path
stringlengths
5
304
repo_name
stringlengths
6
79
content
stringlengths
27
1.05M
js/lessons/lesson2/index.js
leftstick/react-lesson
'use strict'; import React from 'react'; import DocumentLink from 'fw/DocumentLink'; import LessonTitle from 'fw/LessonTitle'; import LessonHelper from 'fw/LessonHelper'; import Preview from 'fw/Preview'; class Lesson2 extends React.Component { constructor(props) { super(props); } render() { return ( <div> <LessonTitle text='alert something while clicking below button' /> <LessonHelper> <DocumentLink link='http://facebook.github.io/react/docs/events.html' text='Read events' /> <DocumentLink link='http://facebook.github.io/react/docs/tags-and-attributes.html' text='Read attributes' /> </LessonHelper> <Preview> <button> Punch me, bitch! </button> </Preview> </div> ); } } module.exports = Lesson2;
src/library/searchSuggestions/index.js
zdizzle6717/tree-machine-records
'use strict'; import React from 'react'; import ReactDOM from 'react-dom'; import classNames from 'classnames'; import {Input} from '../../library/validations'; import {scrollUp, scrollDown} from '../utilities/scrollHelpers'; export default function(Service, method) { let _keyChart = { 9: 'tab', 13: 'enter', 27: 'escape', 38: 'up', 40: 'down' }; let _skipSearch = false; let _selectedSuggestion = null; function configureSuggestion(displayKeys, suggestion) { let formattedSuggestion = ''; displayKeys.forEach((key, i) => { formattedSuggestion += suggestion[key]; if (i < displayKeys.length -1) { formattedSuggestion += ', ' } }) return formattedSuggestion; } const SearchSuggestions = class SearchSuggestions extends React.Component { constructor() { super(); this.state = { 'element': null, 'inputString': '', 'results': [], 'selectedIndex': -1, 'showSuggestions': false, 'storedInputString': '', 'suggestions': [] }; this.handleInputChange = this.handleInputChange.bind(this); this.onKeyDown = this.onKeyDown.bind(this); this.handleClickSelect = this.handleClickSelect.bind(this); this.handleClickAway = this.handleClickAway.bind(this); this.toggleSuggestions = this.toggleSuggestions.bind(this); } componentDidMount() { let element = ReactDOM.findDOMNode(this); this.setState({ 'element': element }) } handleClickAway() { this.setState({ 'inputString': this.state.storedInputString, 'selectedIndex': -1, 'selectedSuggesetion': null, 'showSuggestions': false, 'suggestions': [] }); } handleInputChange(e) { let value = e.target.value; this.setState({ 'inputString': value, 'storedInputString': value }); if (!_skipSearch) { if (!Service[method]) { throw new Error('Library searchSuggestions: No service was found with the supplied method name'); } Service[method]({"searchQuery": value, "maxResults": this.props.maxResults}).then((response) => { let showSuggestions = false; let suggestions = []; if (response.results.length > 0 && value.length >= this.props.minCharacters) { suggestions = response.results; showSuggestions = true; }; this.setState({ 'showSuggestions': showSuggestions, 'suggestions': suggestions }) }); } else { _skipSearch = false; } e.target.value = e.target.value; e.target.suggestionObject = _selectedSuggestion || null; this.props.handleInputChange(e); } handleClickSelect(e) { let suggestion = this.state.suggestions[e.target.getAttribute('data-index')]; _selectedSuggestion = suggestion; let value = configureSuggestion(this.props.displayKeys, suggestion); _skipSearch = true; let event = new Event('input', { bubbles: true }); let elem = ReactDOM.findDOMNode(this); let input = elem.getElementsByTagName('input')[0]; input.value = configureSuggestion(this.props.displayKeys, suggestion); input.dispatchEvent(event); this.setState({ 'inputString': value, 'selectedIndex': -1, 'showSuggestions': false, 'storedInputString': configureSuggestion(this.props.displayKeys, suggestion), 'suggestions': [] }); } onKeyDown(e) { let key = _keyChart[e.keyCode]; let inputString = this.state.inputString; let suggestions = this.state.suggestions; let selectedIndex = this.state.selectedIndex; let showSuggestions = this.state.showSuggestions; let storedInputString = this.state.storedInputString; if (!key) { _selectedSuggestion = null; this.setState({ 'selectedIndex': -1 }) return; } if (key !== 'tab') { e.preventDefault(); } if (key === 'enter') { if (selectedIndex > -1) { storedInputString = configureSuggestion(this.props.displayKeys, suggestions[selectedIndex]); _selectedSuggestion = suggestions[selectedIndex]; } else { _selectedSuggestion = null; } _skipSearch = true; let event = new Event('input', { bubbles: true }); let elem = ReactDOM.findDOMNode(this); let input = elem.getElementsByTagName('input')[0]; input.value = configureSuggestion(this.props.displayKeys, suggestions[selectedIndex]); input.dispatchEvent(event); selectedIndex = -1; showSuggestions = false; suggestions = []; } if (key === 'escape') { inputString = storedInputString; selectedIndex = -1; showSuggestions = false; suggestions = []; } if (key === 'down') { if (suggestions.length > 0) { scrollDown(this.props.rowCount, this.state.element, selectedIndex, suggestions.length); } selectedIndex = selectedIndex < this.state.suggestions.length - 1 ? selectedIndex + 1 : selectedIndex; } if (key === 'tab') { if (selectedIndex < this.state.suggestions.length - 1) { e.preventDefault(); if (suggestions.length > 0) { scrollDown(this.props.rowCount, this.state.element, selectedIndex, suggestions.length); } selectedIndex++; } else { selectedIndex = -1; suggestions = []; inputString = storedInputString; } } if (key === 'up') { if (suggestions.length > 0) { scrollUp(this.props.rowCount, this.state.element, selectedIndex, suggestions.length); } selectedIndex = selectedIndex > -1 ? selectedIndex - 1 : selectedIndex; if (selectedIndex === -1) { inputString = storedInputString; } } if (selectedIndex > -1 && key !== 'escape') { inputString = configureSuggestion(this.props.displayKeys, suggestions[selectedIndex]) ; } this.setState({ 'inputString': inputString, 'selectedIndex': selectedIndex, 'showSuggestions': showSuggestions, 'storedInputString': storedInputString, 'suggestions': suggestions }); } toggleSuggestions() { this.setState({ 'showSuggestions': !this.state.showSuggestions }) } render() { let suggestionClasses = classNames({ 'search-suggestions': true, 'active': this.state.showSuggestions && this.state.suggestions.length > 0 }); return ( <div className={suggestionClasses} onKeyDown={this.onKeyDown}> <Input type="text" name={this.props.name} value={this.state.inputString} handleInputChange={this.handleInputChange} validate={this.props.validate} autoComplete="off" required={this.props.required}/> { this.state.showSuggestions && this.state.suggestions.length > 0 && <div className="suggestions"> <ul> { this.state.suggestions.map((suggestion, i) => <li key={i} data-index={i} className={i === this.state.selectedIndex ? 'selected' : ''} onClick={this.handleClickSelect}>{configureSuggestion(this.props.displayKeys, suggestion)}</li> ) } </ul> </div> } { this.state.showSuggestions && this.state.suggestions.length > 0 && <div className="clickaway-backdrop" onClick={this.handleClickAway}></div> } </div> ) } } SearchSuggestions.propTypes = { 'displayKeys': React.PropTypes.array.isRequired, 'handleInputChange': React.PropTypes.func.isRequired, 'maxResults': React.PropTypes.number, 'minCharacters': React.PropTypes.number, 'name': React.PropTypes.string.isRequired, 'required': React.PropTypes.bool, 'rowCount': React.PropTypes.number, 'validate': React.PropTypes.string } SearchSuggestions.defaultProps = { 'maxResults': 10, 'minCharacters': 3, 'required': false, 'rowCount': 4 } return SearchSuggestions; }
CoMLle/src/views/Home.js
MOTOMUR/plz_donation
import React, { Component } from 'react' import TextField from 'material-ui/TextField' import RaisedButton from 'material-ui/RaisedButton' import {Tabs, Tab} from 'material-ui/Tabs' import SearchIcon from 'material-ui/svg-icons/action/search' import firebase from 'firebase' import PostRef from './components/PostRef' import VideoRef from './components/VideoRef' import PostRef4LatestUser from './components/PostRef4LatestUser' import VideoRef4LatestUser from './components/VideoRef4LatestUser' import SearchRef from './components/SearchRef' import LocalizedStrings from 'react-localization' let strings = new LocalizedStrings({ en:{ home:"Home", thereIsNoStarredUser:"There is no starred user", type_username4search:"type username for search", search:"search", latestPostedUsers:"Latest Posted Users", starredUsers:"StarredUsers", }, ja: { home:"ホーム", thereIsNoStarredUser:"スターしたユーザーがいません", type_username4search:"ユーザー名で検索", search:"検索", latestPostedUsers:"今投稿したユーザー", starredUsers:"スターユーザー", } }); class Home extends Component { constructor(props) { super(props); this.state = { //logged in user id userId:'', unsub:'', //for tab tabValue:'a', //search state search:'', searchReference:'0', search_users : [], //for star function off_starred_user:'', off_starred_user_posts:'', willStarUser:'', starCount:'', starred_users : [], starred_postsId : [], starred_posts : [], //commet state commentFormShown:false, commentUid:'', commentPostId:'', author:'', //latest user state latest_posts : [], latest_postsId :[], open:false, profile_image:'', } } /*------------refer latest post-------------------------------------------------------------------------------------------------------------------------------*/ referLatestPost(){ const self = this const latestPosts = [] firebase.database().ref('/posts/').limitToLast(30).once('value',function(snapshot){ snapshot.forEach(function(childSnapshot){ latestPosts.push(childSnapshot.val()) }) self.setState({ latest_posts:latestPosts }) }) } /*------------refer starred user-----------------------------------------------------------------------------------------------------------------------------*/ fetchStarredUser(onchange) { const self1 = this const myUserId = self1.state.userId var onValueChange1 = firebase.database().ref('/users/' + myUserId + '/starred_users').on('value', function(snapshot) { const starred_users = []; snapshot.forEach(function(childSnapshot) { starred_users.push(childSnapshot.key) }) self1.setState({ starred_users: starred_users }, function() { if (onchange) onchange(); }); }); this.setState({ off_starred_user: onValueChange1 }) } fetchStarredUserPostsID() { const self = this const postsId = []; const stateStarredUsers = this.state.starred_users for (var i = 0; i < stateStarredUsers.length; i++) { const starredUser = stateStarredUsers[i] firebase.database().ref('/users/' + starredUser + '/user_posts/').limitToLast(1).once('value', function(snapshot) { snapshot.forEach(function(childSnapshot) { postsId.push(childSnapshot.key) self.setState({ starred_postsId: postsId },self.fetchPosts); }) }); } } fetchPosts(){ const self = this Promise.all(this.state.starred_postsId.map(function (id) { return firebase.database().ref('/posts/' + id).once('value').then(function (snapshot) { return snapshot.val() }) })).then(function (posts) { self.setState({ starred_posts:posts }) }) } fetchAllStarUser() { const self = this this.fetchStarredUser(function() { self.fetchStarredUserPostsID() }) this.referLatestPost() this.fetchAuthorData4SubmitComment() } /*------------life cicle method-------------------------------------------------------------------------------------------------------------------*/ componentDidMount(){ const self=this var unsub = firebase.auth().onAuthStateChanged(function(user){ if(user){ self.setState({ userId : firebase.auth().currentUser.uid },self.fetchAllStarUser); }else { self.props.history.push('/login') } }) this.setState({unsub}); } fetchAuthorData4SubmitComment(){ const self =this firebase.database().ref('/users/'+this.state.userId).once("value").then(function(snapshot){ if(snapshot.val() === null){ self.props.history.push('makeMyPage') }else{ self.setState({ author:snapshot.val().user, profile_image:snapshot.val().profile_image, }) } }) } componentWillUnmount() { const self = this this.state.unsub(); firebase.database().ref('/users/'+this.state.userId+'/starred_users/').off('value', self.state.off_starred_user) firebase.database().ref('/posts/').off('value', self.state.off_starred_user_posts) } /*------------search reference method------------------------------------------------------------------------------------------------------------------------------*/ handleChange_search = (event) => { this.setState({ search: event.target.value, }) } handleSearch = (event) =>{ const self = this firebase.database().ref('/users/').orderByChild('user').startAt(self.state.search).endAt(self.state.search+"\uf8ff").on("value",function(snapshot) { const search_users =[] snapshot.forEach(function(childSnapshot) { search_users.push(childSnapshot.val()) }) self.setState({ search_users:search_users, }) }) this.setState({searchReference:'1'}); } handleChange_Tab = (value) => { this.setState({ tabValue: value, }); }; herfUserPage=(val)=>{ this.props.history.push('/userPage/' + val) } render () { return ( <div> <div style={{backgroundColor: '',}} > <div> <TextField id="search" floatingLabelText={strings.type_username4search} value={this.state.search} onChange={this.handleChange_search} /> <RaisedButton label={strings.search} secondary={true} icon={<SearchIcon/>} onClick={this.handleSearch} /> </div> </div> <div> <div style={{overflowX: 'scroll'}} > <div style={{ display: 'inline-block', whiteSpace: 'nowrap',}} > { this.state.searchReference === '0' ? <div></div> :<ul>{ this.state.search_users.map( function(searchRef){ return( <SearchRef searchRef={searchRef} myuid={this.state.userId} /> ) }.bind(this) ) }</ul> } </div> </div> </div> <div> <Tabs value={this.state.tabValue} onChange={this.handleChange_Tab}> <Tab label={strings.starredUsers} value="a"> <div style={{overflowX: 'scroll'}} > <div style={{ display: 'inline-block', whiteSpace: 'nowrap',}} > { this.state.starred_posts.length === 0 ? <div><h>{strings.thereIsNoStarredUser}</h></div> : <ul>{ this.state.starred_posts.slice().map( function(starred_post){ if(starred_post.postType === 'text'){ return( <PostRef key={starred_post.uid} post={starred_post} myuid={this.state.userId} author={this.state.author} profile_image={this.state.profile_image} herfUserPage={this.herfUserPage} /> ) } if(starred_post.postType === 'Youtube'){ return( <VideoRef key={starred_post.uid} post={starred_post} myuid={this.state.userId} author={this.state.author} profile_image={this.state.profile_image} herfUserPage={this.herfUserPage} /> ) } }.bind(this) ) }</ul> } </div> </div> </Tab> <Tab label={strings.latestPostedUsers} value="b"> <div style={{overflowX: 'scroll'}} > <div style={{ display: 'inline-block', whiteSpace: 'nowrap',}} > { this.state.tabValue==='a' ?<div></div> :<ul>{ this.state.latest_posts.slice().reverse().map( function(latest_post){ if(latest_post.postType === 'text'){ return( <PostRef4LatestUser key={latest_post.postId} post={latest_post} myuid={this.state.userId} herfUserPage={this.herfUserPage} /> ) } if(latest_post.postType === 'Youtube'){ return( <VideoRef4LatestUser key={latest_post.postId} post={latest_post} myuid={this.state.userId} herfUserPage={this.herfUserPage} /> ) } }.bind(this) ) }</ul> } </div> </div> </Tab> </Tabs> </div> </div> ) } } export default Home
node_modules/react-dom/lib/ReactInputSelection.js
jongschneider/lyndaProject
/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var ReactDOMSelection = require('./ReactDOMSelection'); var containsNode = require('fbjs/lib/containsNode'); var focusNode = require('fbjs/lib/focusNode'); var getActiveElement = require('fbjs/lib/getActiveElement'); function isInDocument(node) { return containsNode(document.documentElement, node); } /** * @ReactInputSelection: React input selection module. Based on Selection.js, * but modified to be suitable for react and has a couple of bug fixes (doesn't * assume buttons have range selections allowed). * Input selection module for React. */ var ReactInputSelection = { hasSelectionCapabilities: function (elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true'); }, getSelectionInformation: function () { var focusedElem = getActiveElement(); return { focusedElem: focusedElem, selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null }; }, /** * @restoreSelection: If any selection information was potentially lost, * restore it. This is useful when performing operations that could remove dom * nodes and place them back in, resulting in focus being lost. */ restoreSelection: function (priorSelectionInformation) { var curFocusedElem = getActiveElement(); var priorFocusedElem = priorSelectionInformation.focusedElem; var priorSelectionRange = priorSelectionInformation.selectionRange; if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) { ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange); } focusNode(priorFocusedElem); } }, /** * @getSelection: Gets the selection bounds of a focused textarea, input or * contentEditable node. * -@input: Look up selection bounds of this input * -@return {start: selectionStart, end: selectionEnd} */ getSelection: function (input) { var selection; if ('selectionStart' in input) { // Modern browser with input or textarea. selection = { start: input.selectionStart, end: input.selectionEnd }; } else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') { // IE8 input. var range = document.selection.createRange(); // There can only be one selection per document in IE, so it must // be in our element. if (range.parentElement() === input) { selection = { start: -range.moveStart('character', -input.value.length), end: -range.moveEnd('character', -input.value.length) }; } } else { // Content editable or old IE textarea. selection = ReactDOMSelection.getOffsets(input); } return selection || { start: 0, end: 0 }; }, /** * @setSelection: Sets the selection bounds of a textarea or input and focuses * the input. * -@input Set selection bounds of this input or textarea * -@offsets Object of same form that is returned from get* */ setSelection: function (input, offsets) { var start = offsets.start; var end = offsets.end; if (end === undefined) { end = start; } if ('selectionStart' in input) { input.selectionStart = start; input.selectionEnd = Math.min(end, input.value.length); } else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') { var range = input.createTextRange(); range.collapse(true); range.moveStart('character', start); range.moveEnd('character', end - start); range.select(); } else { ReactDOMSelection.setOffsets(input, offsets); } } }; module.exports = ReactInputSelection;
src/js/components/icons/base/CloudSoftware.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-cloud-software`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'cloud-software'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M8,23 L16,23 L16,12 L8,12 L8,23 Z M8,16 L16,16 M12,12 L12,16 M6,6 L6,5 C6,2 7.5,1 10,1 L14,1 C16.5,1 18,2.5 18,5 L18,6 C21,6 23,8 23,11 C23,14 21,16 18,16 M14,6 L6,6 C3,6 1,7.5 1,11 C1,14.5 3,16 6,16"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'CloudSoftware'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
hw8-frontend/src/components/article/articleView.js
lanyangyang025/COMP531
import React from 'react' import { connect } from 'react-redux' import {Article} from './article' import { searchKeyword,showComments,addArticle } from './articleActions' //the content of all the articles const ArticleView = ({articles,dispatch, username}) => { let keyword, text, newImage, count=0 return( <div className="row"> <div className="col-sm-8"> <div className="panel panel-default text-left"> <div className="panel-body"> <div className="form-group col-sm-12"> <textarea className="form-control" id="post" rows="4" placeholder="share..." ref={ (node) => { text = node }} ></textarea><br/> <p><input type="file" id='uploadFile_1' accept="image/*" onChange={(e) => newImage = e.target.files[0]} /></p> </div> <button id='post_button' className="btn btn-primary btn-sm col-sm-offset-4" onClick={() => {dispatch(addArticle(text.value, newImage)); document.getElementById('post').value=''; document.getElementById('uploadFile_1').value='';}}>{' Post '}</button> <button className="btn btn-primary btn-sm col-sm-offset-3" onClick={()=>{document.getElementById('post').value=''}}>Cancel</button> </div> </div> </div> <div className="col-sm-8"> <div className="col-sm-11"> <input className="form-control" type="search" placeholder="search here" id="article_search" ref={ (node) => { keyword = node }} onChange={() => { dispatch(searchKeyword(keyword.value)) }}/> </div> </div> <div className="col-sm-8 row"> <div className="panel panel-default text-left"> <div className="panel-body"> { articles.sort((a,b) => { if (a.date < b.date){ return 1 } if (a.date > b.date) return -1 return 0 }).map( article => <Article count={count++} article={article} _id={article._id} key={article._id} author={article.author} date={article.date} text={article.text} img={article.img} comments={article.comments} dispatch={dispatch} username={username}/> ) } </div> </div> </div> </div> ) }; export default connect( (state) => { const keyword = state.articleReducer.searchKeyword; let articles = Object.keys(state.articleReducer.articles).map((id) => state.articleReducer.articles[id]); if (keyword && keyword.length > 0) { articles=articles.filter((a) => { return a.text.toLowerCase().indexOf(keyword.toLowerCase()) >= 0 || a.author.toLowerCase().indexOf(keyword.toLowerCase()) >= 0 }) } return { articles, username: state.profileReducer.username || localStorage.getItem("login_username") } } )(ArticleView)
ajax/libs/forerunnerdb/1.3.542/fdb-core.min.js
sashberd/cdnjs
!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("../lib/Core");a("../lib/Shim.IE8");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":4,"../lib/Shim.IE8":29}],2:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=new e,g=function(a,b,c){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c,d,e){this._store=[],this._keys=[],void 0!==c&&this.primaryKey(c),void 0!==b&&this.index(b),void 0!==d&&this.compareFunc(d),void 0!==e&&this.hashFunc(e),void 0!==a&&this.data(a)},d.addModule("BinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),d.mixin(g.prototype,"Mixin.Common"),d.synthesize(g.prototype,"compareFunc"),d.synthesize(g.prototype,"hashFunc"),d.synthesize(g.prototype,"indexDir"),d.synthesize(g.prototype,"primaryKey"),d.synthesize(g.prototype,"keys"),d.synthesize(g.prototype,"index",function(a){return void 0!==a&&(this.debug()&&console.log("Setting index",a,f.parse(a,!0)),this.keys(f.parse(a,!0))),this.$super.call(this,a)}),g.prototype.clear=function(){delete this._data,delete this._left,delete this._right,this._store=[]},g.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},g.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},g.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),this}return!1},g.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.value?e=this.sortAsc(f.get(a,d.path),f.get(b,d.path)):-1===d.value&&(e=this.sortDesc(f.get(a,d.path),f.get(b,d.path))),this.debug()&&console.log("Compared %s with %s order %d in path %s and result was %d",f.get(a,d.path),f.get(b,d.path),d.value,d.path,e),0!==e)return this.debug()&&console.log("Retuning result %d",e),e;return this.debug()&&console.log("Retuning result %d",e),e},g.prototype._hashFunc=function(a){return a[this._keys[0].path]},g.prototype.removeChildNode=function(a){this._left===a?delete this._left:this._right===a&&delete this._right},g.prototype.nodeBranch=function(a){return this._left===a?"left":this._right===a?"right":void 0},g.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this.debug()&&console.log("Inserting",a),this._data?(b=this._compareFunc(this._data,a),0===b?(this.debug()&&console.log("Data is equal (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):-1===b?(this.debug()&&console.log("Data is greater (currrent, new)",this._data,a),this._right?this._right.insert(a):(this._right=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._right._parent=this),!0):1===b?(this.debug()&&console.log("Data is less (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):!1):(this.debug()&&console.log("Node has no data, setting data",a),this.data(a),!0)},g.prototype.remove=function(a){var b,c,d,e=this.primaryKey();if(a instanceof Array){for(c=[],d=0;d<a.length;d++)this.remove(a[d])&&c.push(a[d]);return c}return this.debug()&&console.log("Removing",a),this._data[e]===a[e]?this._remove(this):(b=this._compareFunc(this._data,a),-1===b&&this._right?this._right.remove(a):1===b&&this._left?this._left.remove(a):!1)},g.prototype._remove=function(a){var b,c;return this._left?(b=this._left,c=this._right,this._left=b._left,this._right=b._right,this._data=b._data,this._store=b._store,c&&(b.rightMost()._right=c)):this._right?(c=this._right,this._left=c._left,this._right=c._right,this._data=c._data,this._store=c._store):this.clear(),!0},g.prototype.leftMost=function(){return this._left?this._left.leftMost():this},g.prototype.rightMost=function(){return this._right?this._right.rightMost():this},g.prototype.lookup=function(a,b,c){var d=this._compareFunc(this._data,a);return c=c||[],0===d&&(this._left&&this._left.lookup(a,b,c),c.push(this._data),this._right&&this._right.lookup(a,b,c)),-1===d&&this._right&&this._right.lookup(a,b,c),1===d&&this._left&&this._left.lookup(a,b,c),c},g.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},g.prototype.startsWith=function(a,b,c,d){var e,g,h=f.get(this._data,a),i=h.substr(0,b.length);return c=c||new RegExp("^"+b),d=d||[],void 0===d._visited&&(d._visited=0),d._visited++,g=this.sortAsc(h,b),e=i===b,0===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),-1===g&&(e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),1===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data)),d},g.prototype.findRange=function(a,b,c,d,f,g){f=f||[],g=g||new e(b),this._left&&this._left.findRange(a,b,c,d,f,g);var h=g.value(this._data),i=this.sortAsc(h,c),j=this.sortAsc(h,d);if(!(0!==i&&1!==i||0!==j&&-1!==j))switch(a){case"hash":f.push(this._hash);break;case"data":f.push(this._data);break;default:f.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,f,g),f},g.prototype.match=function(a,b,c){var d,e,g,h=[],i=0;for(d=f.parseArr(this._index,{verbose:!0}),e=f.parseArr(a,c&&c.pathOptions?c.pathOptions:{ignore:/\$/,verbose:!0}),g=0;g<d.length;g++)e[g]===d[g]&&(i++,h.push(e[g]));return{matchedKeys:h,totalKeyCount:e.length,score:i}},d.finishModule("BinaryTree"),b.exports=g},{"./Path":25,"./Shared":28}],3:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n,o;d=a("./Shared");var p=function(a){this.init.apply(this,arguments)};p.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._options.db&&this.db(this._options.db),this._metaData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[],async:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._deferredCalls=!0,this.subsetOf(this)},d.addModule("Collection",p),d.mixin(p.prototype,"Mixin.Common"),d.mixin(p.prototype,"Mixin.Events"),d.mixin(p.prototype,"Mixin.ChainReactor"),d.mixin(p.prototype,"Mixin.CRUD"),d.mixin(p.prototype,"Mixin.Constants"),d.mixin(p.prototype,"Mixin.Triggers"),d.mixin(p.prototype,"Mixin.Sorting"),d.mixin(p.prototype,"Mixin.Matching"),d.mixin(p.prototype,"Mixin.Updating"),d.mixin(p.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Index2d"),l=a("./Crc"),e=d.modules.Db,m=a("./Overload"),n=a("./ReactorIO"),o=new h,p.prototype.crc=l,d.synthesize(p.prototype,"deferredCalls"),d.synthesize(p.prototype,"state"),d.synthesize(p.prototype,"name"),d.synthesize(p.prototype,"metaData"),d.synthesize(p.prototype,"capped"),d.synthesize(p.prototype,"cappedSize"),p.prototype._asyncPending=function(a){this._deferQueue.async.push(a)},p.prototype._asyncComplete=function(a){for(var b=this._deferQueue.async.indexOf(a);b>-1;)this._deferQueue.async.splice(b,1),b=this._deferQueue.async.indexOf(a);0===this._deferQueue.async.length&&this.deferEmit("ready")},p.prototype.data=function(){return this._data},p.prototype.drop=function(a){var b;if(this.isDropped())return a&&a(!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,delete this._listeners,a&&a(!1,!0),!0}return a&&a(!1,!0),!1},p.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",a,{oldData:b})}return this}return this._primaryKey},p.prototype._onInsert=function(a,b){this.emit("insert",a,b)},p.prototype._onUpdate=function(a){this.emit("update",a)},p.prototype._onRemove=function(a){this.emit("remove",a)},p.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=new Date)},d.synthesize(p.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(p.prototype,"mongoEmulation"),p.prototype.setData=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},p.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: "+d[this._primaryKey]}else h.set(d[k],d);e=this.jStringify(d),i.set(d[k],e),j.set(e,d)}},p.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},p.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.deferEmit("change",{type:"truncate"}),this},p.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(this._deferredCalls&&a.length>f)return this._deferQueue.upsert=e.concat(a),this._asyncPending("upsert"),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b(),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(),{}},p.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},p.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},p.prototype.update=function(a,b,c){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:e},c),g.time("Resolve chains"),this._onUpdate(e),this._onChange(),this.deferEmit("change",{type:"update",data:e}))),g.stop(),e||[]},p.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},p.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)[0]},p.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q,r,s,t=!1,u=!1;for(s in b)if(b.hasOwnProperty(s)){if(g=!1,"$"===s.substr(0,1))switch(s){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)u=this.updateObject(a,b.$each[j],c,d,e),u&&(t=!0);t=t||u;break;case"$replace":g=!0,n=b.$replace,o=this.primaryKey();for(m in a)a.hasOwnProperty(m)&&m!==o&&void 0===n[m]&&(this._updateUnset(a,m),t=!0);for(m in n)n.hasOwnProperty(m)&&m!==o&&(this._updateOverwrite(a,m,n[m]),t=!0);break;default:g=!0,u=this.updateObject(a,b[s],c,d,e,s),t=t||u}if(this._isPositionalKey(s)&&(g=!0,s=s.substr(0,s.length-2),p=new h(e+"."+s),a[s]&&a[s]instanceof Array&&a[s].length)){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],p.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)u=this.updateObject(a[s][i[j]],b[s+".$"],c,d,e+"."+s,f),t=t||u}if(!g)if(f||"object"!=typeof b[s])switch(f){case"$inc":var v=!0;b[s]>0?b.$max&&a[s]>=b.$max&&(v=!1):b[s]<0&&b.$min&&a[s]<=b.$min&&(v=!1),v&&(this._updateIncrement(a,s,b[s]),t=!0);break;case"$cast":switch(b[s]){case"array":a[s]instanceof Array||(this._updateProperty(a,s,b.$data||[]),t=!0);break;case"object":(!(a[s]instanceof Object)||a[s]instanceof Array)&&(this._updateProperty(a,s,b.$data||{}),t=!0);break;case"number":"number"!=typeof a[s]&&(this._updateProperty(a,s,Number(a[s])),t=!0);break;case"string":"string"!=typeof a[s]&&(this._updateProperty(a,s,String(a[s])),t=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[s]}break;case"$push":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+s+")";if(void 0!==b[s].$position&&b[s].$each instanceof Array)for(l=b[s].$position,k=b[s].$each.length,j=0;k>j;j++)this._updateSplicePush(a[s],l+j,b[s].$each[j]);else if(b[s].$each instanceof Array)for(k=b[s].$each.length,j=0;k>j;j++)this._updatePush(a[s],b[s].$each[j]);else this._updatePush(a[s],b[s]);t=!0;break;case"$pull":if(a[s]instanceof Array){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],b[s],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[s],i[k]),t=!0}break;case"$pullAll":if(a[s]instanceof Array){if(!(b[s]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+s+")";if(i=a[s],k=i.length,k>0)for(;k--;){for(l=0;l<b[s].length;l++)i[k]===b[s][l]&&(this._updatePull(a[s],k),k--,t=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+s+")";var w,x,y,z,A=a[s],B=A.length,C=!0,D=d&&d.$addToSet;for(b[s].$key?(y=!1,z=new h(b[s].$key),x=z.value(b[s])[0],delete b[s].$key):D&&D.key?(y=!1,z=new h(D.key),x=z.value(b[s])[0]):(x=this.jStringify(b[s]),y=!0),w=0;B>w;w++)if(y){if(this.jStringify(A[w])===x){C=!1;break}}else if(x===z.value(A[w])[0]){C=!1;break}C&&(this._updatePush(a[s],b[s]),t=!0);break;case"$splicePush":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+s+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[s].length&&(l=a[s].length),this._updateSplicePush(a[s],l,b[s]),t=!0;break;case"$move":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+s+")";for(j=0;j<a[s].length;j++)if(this._match(a[s][j],b[s],d,"",{})){var E=b.$index;if(void 0===E)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[s],j,E),t=!0;break}break;case"$mul":this._updateMultiply(a,s,b[s]),t=!0;break;case"$rename":this._updateRename(a,s,b[s]),t=!0;break;case"$overwrite":this._updateOverwrite(a,s,b[s]),t=!0;break;case"$unset":this._updateUnset(a,s),t=!0;break;case"$clear":this._updateClear(a,s),t=!0;break;case"$pop":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+s+")";this._updatePop(a[s],b[s])&&(t=!0);break;case"$toggle":this._updateProperty(a,s,!a[s]),t=!0;break;default:a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}else if(null!==a[s]&&"object"==typeof a[s])if(q=a[s]instanceof Array,r=b[s]instanceof Array,q||r)if(!r&&q)for(j=0;j<a[s].length;j++)u=this.updateObject(a[s][j],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0);else u=this.updateObject(a[s],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}return t},p.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},p.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c(!1,g),g}if(g=[],d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e),g.push(a)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);g.length&&(l.chainSend("remove",{query:a,dataSet:g},b),(!b||b&&!b.noEmit)&&this._onRemove(g),this._onChange(),this.deferEmit("change",{type:"remove",data:g}))}return c&&c(!1,g),g},p.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)[0]},p.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b(c),this._asyncComplete(a);this.isProcessingQueue()||this.deferEmit("queuesComplete")},p.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},p.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},p.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(this._deferredCalls&&a.length>h)return this._deferQueue.insert=g.concat(a),this._asyncPending("insert"),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c(e),this._onChange(),this.deferEmit("change",{type:"insert",data:i}),e},p.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this,h=this.capped(),i=this.cappedSize();if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a),h&&g._data.length>i&&g.removeById(g._data[0][g._primaryKey]),g.chainSend("insert",a,{index:b})},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return"Trigger cancelled operation";e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},p.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},p.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},p.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},p.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.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},p.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)},p.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},p.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},p.prototype.subset=function(a,b){var c=this.find(a,b);return(new p).subsetOf(this).primaryKey(this._primaryKey).setData(c)},d.synthesize(p.prototype,"subsetOf"),p.prototype.isSubsetOf=function(a){return this._subsetOf===a},p.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},p.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},p.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new p,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},p.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},p.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},p.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c("Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.call(this,a,b,c)},p.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{};var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K=this._metrics.create("find"),L=this.primaryKey(),M=this,N=!0,O={},P=[],Q=[],R=[],S={},T={};if(b instanceof Array||(b=this.options(b)),J=function(c){return M._match(c,a,b,"and",S)},K.start(),a){if(a instanceof Array){for(I=this,z=0;z<a.length;z++)I=I.subset(a[z],b&&b[z]?b[z]:{});return I.find()}if(a.$findSub){if(!a.$findSub.$path)throw"$findSub missing $path property!";return this.findSub(a.$findSub.$query,a.$findSub.$path,a.$findSub.$subQuery,a.$findSub.$subOptions)}if(a.$findSubOne){if(!a.$findSubOne.$path)throw"$findSubOne missing $path property!";return this.findSubOne(a.$findSubOne.$query,a.$findSubOne.$path,a.$findSubOne.$subQuery,a.$findSubOne.$subOptions)}if(K.time("analyseQuery"),c=this._analyseQuery(M.decouple(a),b,K),K.time("analyseQuery"),K.data("analysis",c),c.hasJoin&&c.queriesJoin){for(K.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],O[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i),delete a[c.joinQueries[k]];K.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(K.data("index.potential",c.indexMatch),K.data("index.used",c.indexMatch[0].index),K.time("indexLookup"),e=c.indexMatch[0].lookup||[],K.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(N=!1)):K.flag("usedIndex",!1),N&&(e&&e.length?(d=e.length,K.time("tableScan: "+d),e=e.filter(J)):(d=this._data.length,K.time("tableScan: "+d),e=this._data.filter(J)),K.time("tableScan: "+d)),b.$orderBy&&(K.time("sort"),e=this.sort(b.$orderBy,e),K.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(T.page=b.$page,T.pages=Math.ceil(e.length/b.$limit),T.records=e.length,b.$page&&b.$limit>0&&(K.data("cursor",T),e.splice(0,b.$page*b.$limit))),b.$skip&&(T.skip=b.$skip,e.splice(0,b.$skip),K.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(T.limit=b.$limit,e.length=b.$limit,K.data("limit",b.$limit)),b.$decouple&&(K.time("decouple"),e=this.decouple(e),K.time("decouple"),K.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=O[k]?O[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._resolveDynamicQuery(m[n].query,e[x])),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]=M._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 [$multi: 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 P.push(e[x])}K.data("flag.join",!0)}if(P.length){for(K.time("removalQueue"),z=0;z<P.length;z++)y=e.indexOf(P[z]),y>-1&&e.splice(y,1);K.time("removalQueue")}if(b.$transform){for(K.time("transform"),z=0;z<e.length;z++)e.splice(z,1,b.$transform(e[z]));K.time("transform"),K.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(K.time("transformOut"),e=this.transformOut(e),K.time("transformOut")),K.data("results",e.length)}else e=[];if(!b.$aggregate){K.time("scanFields");for(z in b)b.hasOwnProperty(z)&&0!==z.indexOf("$")&&(1===b[z]?Q.push(z):0===b[z]&&R.push(z));if(K.time("scanFields"),Q.length||R.length){for(K.data("flag.limitFields",!0),K.data("limitFields.on",Q),K.data("limitFields.off",R),K.time("limitFields"),z=0;z<e.length;z++){G=e[z];for(A in G)G.hasOwnProperty(A)&&(Q.length&&A!==L&&-1===Q.indexOf(A)&&delete G[A],R.length&&R.indexOf(A)>-1&&delete G[A])}K.time("limitFields")}if(b.$elemMatch){K.data("flag.elemMatch",!0),K.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(M._match(E[B],b.$elemMatch[z],b,"",{})){D.set(e[A],z,[E[B]]);break}K.time("projection-elemMatch")}if(b.$elemsMatch){K.data("flag.elemsMatch",!0),K.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++)M._match(E[B],b.$elemsMatch[z],b,"",{})&&F.push(E[B]);D.set(e[A],z,F)}K.time("projection-elemsMatch")}}return b.$aggregate&&(K.data("flag.aggregate",!0),K.time("aggregate"),H=new h(b.$aggregate),e=H.value(e),K.time("aggregate")),K.stop(),e.__fdbOp=K,e.$cursor=T,e},p.prototype._resolveDynamicQuery=function(a,b){var c,d,e,f,g,i=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?new h(a.substr(3,a.length-3)).value(b):new h(a).value(b),f.length>1?{$in:f}:f[0];c={};for(g in a)if(a.hasOwnProperty(g))switch(d=typeof a[g],e=a[g],d){case"string":"$$."===e.substr(0,3)?c[g]=new h(e.substr(3,e.length-3)).value(b)[0]:c[g]=e;break;case"object":c[g]=i._resolveDynamicQuery(e,b);break;default:c[g]=e}return c},p.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},p.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},p.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},p.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},p.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},p.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformIn(a[b]);return c}return this._transformIn(a)}return a},p.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},p.prototype.sort=function(a,b){var c=this,d=o.parse(a,!0);return d.length&&b.sort(function(a,b){var e,f,g=0;for(e=0;e<d.length;e++)if(f=d[e],1===f.value?g=c.sortAsc(o.get(a,f.path),o.get(b,f.path)):-1===f.value&&(g=c.sortDesc(o.get(a,f.path),o.get(b,f.path))),0!==g)return g;return g}),b},p.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},p.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p,q,r={queriesOn:[this._name],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},s=[],t=[];if(c.time("checkIndexes"),m=new h,n=m.parseArr(a,{ignore:/\$/,verbose:!0}).length){void 0!==a[this._primaryKey]&&(o=typeof a[this._primaryKey],("string"===o||"number"===o||a[this._primaryKey]instanceof Array)&&(c.time("checkIndexMatch: Primary Key"), p=this._primaryIndex.lookup(a,b),r.indexMatch.push({lookup:p,keyData:{matchedKeys:[this._primaryKey],totalKeyCount:n,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key")));for(q in this._indexById)if(this._indexById.hasOwnProperty(q)&&(j=this._indexById[q],k=j.name(),c.time("checkIndexMatch: "+k),i=j.match(a,b),i.score>0&&(l=j.lookup(a,b),r.indexMatch.push({lookup:l,keyData:i,index:j})),c.time("checkIndexMatch: "+k),i.score===n))break;c.time("checkIndexes"),r.indexMatch.length>1&&(c.time("findOptimalIndex"),r.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(r.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(s.push(e),"$as"in b.$join[d][e]?t.push(b.$join[d][e].$as):t.push(e));for(g=0;g<t.length;g++)f=this._queryReferencesCollection(a,t[g],""),f&&(r.joinQueries[s[g]]=f,r.queriesJoin=!0);r.joinsOn=s,r.queriesOn=r.queriesOn.concat(s)}return r},p.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},p.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},p.prototype.findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=this.find(a),k=j.length,l=new p("__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(),m.pathFound||(m.err="No objects found in the parent documents with a matching path of: "+b),d.$stats?m:m.subDocs},p.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},p.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},p.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,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;case"2d":c=new k(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"}:(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()})},p.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},p.prototype.lastOp=function(){return this._metrics.list()},p.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},p.prototype.collateAdd=new m({"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 n(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),p.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new m({"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof p?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=this,c=a.name;if(c){if(this._collection[c])return this._collection[c];if(a&&a.autoCreate===!1){if(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+c+" because it does not exist and auto-create has been disabled!";return}if(this.debug()&&console.log(this.logIdentifier()+" Creating collection "+c),this._collection[c]=this._collection[c]||new p(c,a).db(this),this._collection[c].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[c].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[c].capped(a.capped),this._collection[c].cappedSize(a.size)}return b._collection[c].on("change",function(){b.emit("change",b._collection[c],"collection",c)}),b.emit("create",b._collection[c],"collection",c),this._collection[c]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=p},{"./Crc":5,"./Index2d":8,"./IndexBinaryTree":9,"./IndexHashMap":10,"./KeyValueStore":11,"./Metrics":12,"./Overload":24,"./Path":25,"./ReactorIO":26,"./Shared":28}],4:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b&&b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=i},{"./Db.js":6,"./Metrics.js":12,"./Overload":24,"./Shared":28}],5:[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}},{}],6:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./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.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Collection.js":3,"./Crc.js":5,"./Metrics.js":12,"./Overload":24,"./Shared":28}],7:[function(a,b,c){"use strict";var d,e,f,g;d=[16,8,4,2,1],e="0123456789bcdefghjkmnpqrstuvwxyz",f={right:{even:"bc01fg45238967deuvhjyznpkmstqrwx"},left:{even:"238967debc01fg45kmstqrwxuvhjyznp"},top:{even:"p0r21436x8zb9dcf5h7kjnmqesgutwvy"},bottom:{even:"14365h7k9dcfesgujnmqp0r2twvyx8zb"}},g={right:{even:"bcfguvyz"},left:{even:"0145hjnp"},top:{even:"prxz"},bottom:{even:"028b"}},f.bottom.odd=f.left.even,f.top.odd=f.right.even,f.left.odd=f.bottom.even,f.right.odd=f.top.even,g.bottom.odd=g.left.even,g.top.odd=g.right.even,g.left.odd=g.bottom.even,g.right.odd=g.top.even;var h=function(){};h.prototype.refineInterval=function(a,b,c){b&c?a[0]=(a[0]+a[1])/2:a[1]=(a[0]+a[1])/2},h.prototype.calculateNeighbours=function(a,b){var c;return b&&"object"!==b.type?(c=[],c[4]=a,c[3]=this.calculateAdjacent(a,"left"),c[5]=this.calculateAdjacent(a,"right"),c[1]=this.calculateAdjacent(a,"top"),c[7]=this.calculateAdjacent(a,"bottom"),c[0]=this.calculateAdjacent(c[3],"top"),c[2]=this.calculateAdjacent(c[5],"top"),c[6]=this.calculateAdjacent(c[3],"bottom"),c[8]=this.calculateAdjacent(c[5],"bottom")):(c={center:a,left:this.calculateAdjacent(a,"left"),right:this.calculateAdjacent(a,"right"),top:this.calculateAdjacent(a,"top"),bottom:this.calculateAdjacent(a,"bottom")},c.topLeft=this.calculateAdjacent(c.left,"top"),c.topRight=this.calculateAdjacent(c.right,"top"),c.bottomLeft=this.calculateAdjacent(c.left,"bottom"),c.bottomRight=this.calculateAdjacent(c.right,"bottom")),c},h.prototype.calculateAdjacent=function(a,b){a=a.toLowerCase();var c=a.charAt(a.length-1),d=a.length%2?"odd":"even",h=a.substring(0,a.length-1);return-1!==g[b][d].indexOf(c)&&(h=this.calculateAdjacent(h,b)),h+e[f[b][d].indexOf(c)]},h.prototype.decode=function(a){var b,c,f,g,h,i,j,k=1,l=[],m=[];for(l[0]=-90,l[1]=90,m[0]=-180,m[1]=180,i=90,j=180,b=0;b<a.length;b++)for(c=a[b],f=e.indexOf(c),g=0;5>g;g++)h=d[g],k?(j/=2,this.refineInterval(m,f,h)):(i/=2,this.refineInterval(l,f,h)),k=!k;return l[2]=(l[0]+l[1])/2,m[2]=(m[0]+m[1])/2,{latitude:l,longitude:m}},h.prototype.encode=function(a,b,c){var f,g=1,h=[],i=[],j=0,k=0,l="";for(c||(c=12),h[0]=-90,h[1]=90,i[0]=-180,i[1]=180;l.length<c;)g?(f=(i[0]+i[1])/2,b>f?(k|=d[j],i[0]=f):i[1]=f):(f=(h[0]+h[1])/2,a>f?(k|=d[j],h[0]=f):h[1]=f),g=!g,4>j?j++:(l+=e[k],j=0,k=0);return l},b.exports=h},{}],8:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=a("./GeoHash"),h=new e,i=new g,j=[5e3,1250,156,39.1,4.89,1.22,.153,.0382,.00477,.00119,149e-6,372e-7],k=function(){this.init.apply(this,arguments)};k.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("Index2d",k),d.mixin(k.prototype,"Mixin.Common"),d.mixin(k.prototype,"Mixin.ChainReactor"),d.mixin(k.prototype,"Mixin.Sorting"),k.prototype.id=function(){return this._id},k.prototype.state=function(){return this._state},k.prototype.size=function(){return this._size},d.synthesize(k.prototype,"data"),d.synthesize(k.prototype,"name"),d.synthesize(k.prototype,"collection"),d.synthesize(k.prototype,"type"),d.synthesize(k.prototype,"unique"),k.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=h.parse(this._keys).length,this):this._keys},k.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},k.prototype.insert=function(a,b){var c,d=this._unique;a=this.decouple(a),d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a);var e,f,g,j,k,l=this._btree.keys();for(k=0;k<l.length;k++)e=h.get(a,l[k].path),e instanceof Array&&(g=e[0],j=e[1],f=i.encode(g,j),h.set(a,l[k].path,f));return this._btree.insert(a)?(this._size++,!0):!1},k.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},k.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},k.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},k.prototype.lookup=function(a,b){var c,d,e,f,g=this._btree.keys();for(f=0;f<g.length;f++)if(c=g[f].path,d=h.get(a,c),"object"==typeof d)return d.$near&&(e=[],e=e.concat(this.near(c,d.$near,b))),d.$geoWithin&&(e=[],e=e.concat(this.geoWithin(c,d.$geoWithin,b))),e;return this._btree.lookup(a,b)},k.prototype.near=function(a,b,c){var d,e,f,g,k,l,m,n,o,p,q,r=this,s=[],t=this._collection.primaryKey();if("km"===b.$distanceUnits){for(m=b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}else if("miles"===b.$distanceUnits){for(m=1.60934*b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}for(d=i.encode(b.$point[0],b.$point[1],l),e=i.calculateNeighbours(d,{type:"array"}),k=[],f=0,q=0;9>q;q++)g=this._btree.startsWith(a,e[q]),f+=g._visited,k=k.concat(g);if(k=this._collection._primaryIndex.lookup(k),k.length){for(n={},q=0;q<k.length;q++)p=h.get(k[q],a),o=n[k[q][t]]=this.distanceBetweenPoints(b.$point[0],b.$point[1],p[0],p[1]),m>=o&&s.push(k[q]);s.sort(function(a,b){return r.sortAsc(n[a[t]],n[b[t]])})}return s},k.prototype.geoWithin=function(a,b,c){return[]},k.prototype.distanceBetweenPoints=function(a,b,c,d){var e=6371,f=this.toRadians(a),g=this.toRadians(c),h=this.toRadians(c-a),i=this.toRadians(d-b),j=Math.sin(h/2)*Math.sin(h/2)+Math.cos(f)*Math.cos(g)*Math.sin(i/2)*Math.sin(i/2),k=2*Math.atan2(Math.sqrt(j),Math.sqrt(1-j));return e*k},k.prototype.toRadians=function(a){return.01747722222222*a},k.prototype.match=function(a,b){return this._btree.match(a,b)},k.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},k.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},k.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("Index2d"),b.exports=k},{"./BinaryTree":2,"./GeoHash":7,"./Path":25,"./Shared":28}],9:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),this._btree.insert(a)?(this._size++,!0):!1},g.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a,b){return this._btree.lookup(a,b)},g.prototype.match=function(a,b){return this._btree.match(a,b)},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexBinaryTree"),b.exports=g},{"./BinaryTree":2,"./Path":25,"./Shared":28}],10:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexHashMap"),b.exports=f},{"./Path":25,"./Shared":28}],11:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e=this._primaryKey,f=typeof a,g=[];if("string"===f||"number"===f)return d=this.get(a),void 0!==d?[d]:[];if("object"===f){if(a instanceof Array){for(c=a.length,g=[],b=0;c>b;b++)d=this.lookup(a[b]),d&&(d instanceof Array?g=g.concat(d):g.push(d));return g}if(a[e])return this.lookup(a[e])}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":28}],12:[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":28}],13:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],14:[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&&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},{}],15:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a&&""!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return h.parse(a)},jStringify:function(a){return h.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,"./Serialiser":27}],16:[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},{}],17:[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}],18:[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.$rootSource||(e.$rootSource=a),e.$currentQuery=b,e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m||"string"!==n&&"number"!==n){if(("string"===m||"number"===m)&&"object"===n&&b instanceof RegExp)b.test(a)||(o=!1);else for(k in b)if(b.hasOwnProperty(k)){if(e.$previousQuery=e.$parent,e.$parent={query:b[k],key:k,parent:e.$previousQuery},f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$eq":return b==c;case"$eeq":return b===c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++)if(this._match(b,i[h],d,"and",e))return!0;return!1}if("object"==typeof c)return this._match(b,c,d,"and",e);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(this._match(b,l[k],d,"and",e))return!1;return!0}if("object"==typeof c)return this._match(b,c,d,"and",e);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;case"$find":case"$findOne":case"$findSub":var r,s,t,u,v,w,x="collection",y={};if(!c.$from)throw a+" missing $from property!";if(c.$fromType&&(x=c.$fromType,!this.db()[x]||"function"!=typeof this.db()[x]))throw a+' cannot operate against $fromType "'+x+'" because the database does not recognise this type of object!';if(r=c.$query||{},s=c.$options||{},"$findSub"===a){if(!c.$path)throw a+" missing $path property!";v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},w=this.db()[x](c.$from).findSub(r,v,t,u)}else w=this.db()[x](c.$from)[a.substr(1)](r,s);return y[e.$parent.parent.key]=w,this._match(b,y,d,"and",e)}return-1}};b.exports=d},{}],19:[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},{}],20:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],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":28}],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",console.log("Overload: ",a),'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]?(d.verbose&&c.push(f),this._parseArr(a[e],f,c,d)):c.push(f));return c},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.value=function(a,b,c){var d,e,f,g,h,i,j,k,l;if(b&&-1===b.indexOf("."))return[a[b]];if(void 0!==a&&"object"==typeof a){if((!c||c&&!c.skipArrCheck)&&a instanceof Array){for(j=[],k=0;k<a.length;k++)j.push(this.get(a[k],b));return j}for(i=[],void 0!==b&&(b=this.clean(b),d=b.split(".")),e=d||this._pathParts,f=e.length,g=a,k=0;f>k;k++){if(g=g[e[k]],h instanceof Array){for(l=0;l<h.length;l++)i=i.concat(this.value(h,l+"."+e[k],{skipArrCheck:!0}));return i}if(!g||"object"!=typeof g)break;h=g}return[g]}return[]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":28}],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)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this),delete this._listeners),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":28}],27:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){this._encoder=[],this._decoder={},this.registerEncoder("$date",function(a){return a instanceof Date?a.toISOString():void 0}),this.registerDecoder("$date",function(a){return new Date(a)}),this.registerEncoder("$regexp",function(a){return a instanceof RegExp?{source:a.source,params:""+(a.global?"g":"")+(a.ignoreCase?"i":"")}:void 0}),this.registerDecoder("$regexp",function(a){var b=typeof a;return"object"===b?new RegExp(a.source,a.params):"string"===b?new RegExp(a):void 0})},d.prototype.registerEncoder=function(a,b){this._encoder.push(function(c){var d,e=b(c);return void 0!==e&&(d={},d[a]=e),d})},d.prototype.registerDecoder=function(a,b){this._decoder[a]=b},d.prototype._encode=function(a){for(var b,c=this._encoder.length;c--&&!b;)b=this._encoder[c](a);return b},d.prototype.parse=function(a){return this._parse(JSON.parse(a))},d.prototype._parse=function(a,b){var c;if("object"==typeof a&&null!==a){b=a instanceof Array?b||[]:b||{};for(c in a)if(a.hasOwnProperty(c)){if("$"===c.substr(0,1)&&this._decoder[c])return this._decoder[c](a[c]);b[c]=this._parse(a[c],b[c])}}else b=a;return b},d.prototype.stringify=function(a){return JSON.stringify(this._stringify(a))},d.prototype._stringify=function(a,b){var c,d;if("object"==typeof a&&null!==a){if(c=this._encode(a))return c;b=a instanceof Array?b||[]:b||{};for(d in a)a.hasOwnProperty(d)&&(b[d]=this._stringify(a[d],b[d]))}else b=a;return b},b.exports=d},{}],28:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.542",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"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":13,"./Mixin.ChainReactor":14,"./Mixin.Common":15,"./Mixin.Constants":16,"./Mixin.Events":17,"./Mixin.Matching":18,"./Mixin.Sorting":19,"./Mixin.Tags":20,"./Mixin.Triggers":21,"./Mixin.Updating":22,"./Overload":24}],29:[function(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;c>f;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);e>c;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}]},{},[1]);
src/containers/Page/signin.js
EncontrAR/backoffice
import React from 'react'; import { Link, Redirect } from 'react-router-dom'; import { connect } from 'react-redux'; import { message } from 'antd'; import Input from '../../components/uielements/input'; import Button from '../../components/uielements/button'; import authActions from '../../redux/auth/actions'; import IntlMessages from '../../components/utility/intlMessages'; const { login, clearMsg } = authActions; class SignIn extends React.Component { constructor(props) { super(props) this.state = { redirectToReferrer: false } } componentWillReceiveProps(nextProps) { if (nextProps.loginFailure) { message.error('El usuario y/o contraseña son inválidos.') this.props.clearMsg() } } handleInput(field, e) { this.setState({ [field]: e.target.value }) } handleLogin = () => { this.props.login(this.state.email, this.state.password) }; render() { const from = { pathname: '/admin/campaigns' }; if (this.props.isLoggedIn) { return <Redirect to={from} />; } return ( <div className="isoSignInPage"> <div className="isoLoginContent"> <div className="isoLogoWrapper"> <Link to="/signin"> <IntlMessages id="page.signInTitle" /> </Link> </div> <div className="isoSignInForm"> <div className="isoInputWrapper"> <Input size="large" placeholder="Email" onChange={this.handleInput.bind(this, 'email')} /> </div> <div className="isoInputWrapper"> <Input size="large" type="password" placeholder="Contraseña" onChange={this.handleInput.bind(this, 'password')} /> </div> <div className="isoInputWrapper isoLeftRightComponent"> <Button type="primary" onClick={this.handleLogin}> Ingresar </Button> </div> </div> </div> </div> ); } }; SignIn.defaultProps = { isLoggedIn: false } function mapStateToProps(state) { const { loginSuccess, loginFailure } = state.Auth return { isLoggedIn: loginSuccess, loginFailure: loginFailure } } export default connect(mapStateToProps, { login, clearMsg } )(SignIn)
ajax/libs/yui/3.9.0pr3/datatable-core/datatable-core.js
pvnr0082t/cdnjs
YUI.add('datatable-core', function (Y, NAME) { /** The core implementation of the `DataTable` and `DataTable.Base` Widgets. @module datatable @submodule datatable-core @since 3.5.0 **/ var INVALID = Y.Attribute.INVALID_VALUE, Lang = Y.Lang, isFunction = Lang.isFunction, isObject = Lang.isObject, isArray = Lang.isArray, isString = Lang.isString, isNumber = Lang.isNumber, toArray = Y.Array, keys = Y.Object.keys, Table; /** _API docs for this extension are included in the DataTable class._ Class extension providing the core API and structure for the DataTable Widget. Use this class extension with Widget or another Base-based superclass to create the basic DataTable model API and composing class structure. @class DataTable.Core @for DataTable @since 3.5.0 **/ Table = Y.namespace('DataTable').Core = function () {}; Table.ATTRS = { /** Columns to include in the rendered table. If omitted, the attributes on the configured `recordType` or the first item in the `data` collection will be used as a source. This attribute takes an array of strings or objects (mixing the two is fine). Each string or object is considered a column to be rendered. Strings are converted to objects, so `columns: ['first', 'last']` becomes `columns: [{ key: 'first' }, { key: 'last' }]`. DataTable.Core only concerns itself with a few properties of columns. These properties are: * `key` - Used to identify the record field/attribute containing content for this column. Also used to create a default Model if no `recordType` or `data` are provided during construction. If `name` is not specified, this is assigned to the `_id` property (with added incrementer if the key is used by multiple columns). * `children` - Traversed to initialize nested column objects * `name` - Used in place of, or in addition to, the `key`. Useful for columns that aren't bound to a field/attribute in the record data. This is assigned to the `_id` property. * `id` - For backward compatibility. Implementers can specify the id of the header cell. This should be avoided, if possible, to avoid the potential for creating DOM elements with duplicate IDs. * `field` - For backward compatibility. Implementers should use `name`. * `_id` - Assigned unique-within-this-instance id for a column. By order of preference, assumes the value of `name`, `key`, `id`, or `_yuid`. This is used by the rendering views as well as feature module as a means to identify a specific column without ambiguity (such as multiple columns using the same `key`. * `_yuid` - Guid stamp assigned to the column object. * `_parent` - Assigned to all child columns, referencing their parent column. @attribute columns @type {Object[]|String[]} @default (from `recordType` ATTRS or first item in the `data`) @since 3.5.0 **/ columns: { // TODO: change to setter to clone input array/objects validator: isArray, setter: '_setColumns', getter: '_getColumns' }, /** Model subclass to use as the `model` for the ModelList stored in the `data` attribute. If not provided, it will try really hard to figure out what to use. The following attempts will be made to set a default value: 1. If the `data` attribute is set with a ModelList instance and its `model` property is set, that will be used. 2. If the `data` attribute is set with a ModelList instance, and its `model` property is unset, but it is populated, the `ATTRS` of the `constructor of the first item will be used. 3. If the `data` attribute is set with a non-empty array, a Model subclass will be generated using the keys of the first item as its `ATTRS` (see the `_createRecordClass` method). 4. If the `columns` attribute is set, a Model subclass will be generated using the columns defined with a `key`. This is least desirable because columns can be duplicated or nested in a way that's not parsable. 5. If neither `data` nor `columns` is set or populated, a change event subscriber will listen for the first to be changed and try all over again. @attribute recordType @type {Function} @default (see description) @since 3.5.0 **/ recordType: { getter: '_getRecordType', setter: '_setRecordType' }, /** The collection of data records to display. This attribute is a pass through to a `data` property, which is a ModelList instance. If this attribute is passed a ModelList or subclass, it will be assigned to the property directly. If an array of objects is passed, a new ModelList will be created using the configured `recordType` as its `model` property and seeded with the array. Retrieving this attribute will return the ModelList stored in the `data` property. @attribute data @type {ModelList|Object[]} @default `new ModelList()` @since 3.5.0 **/ data: { valueFn: '_initData', setter : '_setData', lazyAdd: false }, /** Content for the `<table summary="ATTRIBUTE VALUE HERE">`. Values assigned to this attribute will be HTML escaped for security. @attribute summary @type {String} @default '' (empty string) @since 3.5.0 **/ //summary: {}, /** HTML content of an optional `<caption>` element to appear above the table. Leave this config unset or set to a falsy value to remove the caption. @attribute caption @type HTML @default '' (empty string) @since 3.5.0 **/ //caption: {}, /** Deprecated as of 3.5.0. Passes through to the `data` attribute. WARNING: `get('recordset')` will NOT return a Recordset instance as of 3.5.0. This is a break in backward compatibility. @attribute recordset @type {Object[]|Recordset} @deprecated Use the `data` attribute @since 3.5.0 **/ recordset: { setter: '_setRecordset', getter: '_getRecordset', lazyAdd: false }, /** Deprecated as of 3.5.0. Passes through to the `columns` attribute. WARNING: `get('columnset')` will NOT return a Columnset instance as of 3.5.0. This is a break in backward compatibility. @attribute columnset @type {Object[]} @deprecated Use the `columns` attribute @since 3.5.0 **/ columnset: { setter: '_setColumnset', getter: '_getColumnset', lazyAdd: false } }; Y.mix(Table.prototype, { // -- Instance properties ------------------------------------------------- /** The ModelList that manages the table's data. @property data @type {ModelList} @default undefined (initially unset) @since 3.5.0 **/ //data: null, // -- Public methods ------------------------------------------------------ /** Gets the column configuration object for the given key, name, or index. For nested columns, `name` can be an array of indexes, each identifying the index of that column in the respective parent's "children" array. If you pass a column object, it will be returned. For columns with keys, you can also fetch the column with `instance.get('columns.foo')`. @method getColumn @param {String|Number|Number[]} name Key, "name", index, or index array to identify the column @return {Object} the column configuration object @since 3.5.0 **/ getColumn: function (name) { var col, columns, i, len, cols; if (isObject(name) && !isArray(name)) { // TODO: support getting a column from a DOM node - this will cross // the line into the View logic, so it should be relayed // Assume an object passed in is already a column def col = name; } else { col = this.get('columns.' + name); } if (col) { return col; } columns = this.get('columns'); if (isNumber(name) || isArray(name)) { name = toArray(name); cols = columns; for (i = 0, len = name.length - 1; cols && i < len; ++i) { cols = cols[name[i]] && cols[name[i]].children; } return (cols && cols[name[i]]) || null; } return null; }, /** Returns the Model associated to the record `id`, `clientId`, or index (not row index). If none of those yield a Model from the `data` ModelList, the arguments will be passed to the `view` instance's `getRecord` method if it has one. If no Model can be found, `null` is returned. @method getRecord @param {Number|String|Node} seed Record `id`, `clientId`, index, Node, or identifier for a row or child element @return {Model} @since 3.5.0 **/ getRecord: function (seed) { var record = this.data.getById(seed) || this.data.getByClientId(seed); if (!record) { if (isNumber(seed)) { record = this.data.item(seed); } // TODO: this should be split out to base somehow if (!record && this.view && this.view.getRecord) { record = this.view.getRecord.apply(this.view, arguments); } } return record || null; }, // -- Protected and private properties and methods ------------------------ /** This tells `Y.Base` that it should create ad-hoc attributes for config properties passed to DataTable's constructor. This is useful for setting configurations on the DataTable that are intended for the rendering View(s). @property _allowAdHocAttrs @type Boolean @default true @protected @since 3.6.0 **/ _allowAdHocAttrs: true, /** A map of column key to column configuration objects parsed from the `columns` attribute. @property _columnMap @type {Object} @default undefined (initially unset) @protected @since 3.5.0 **/ //_columnMap: null, /** The Node instance of the table containing the data rows. This is set when the table is rendered. It may also be set by progressive enhancement, though this extension does not provide the logic to parse from source. @property _tableNode @type {Node} @default undefined (initially unset) @protected @since 3.5.0 **/ //_tableNode: null, /** Updates the `_columnMap` property in response to changes in the `columns` attribute. @method _afterColumnsChange @param {EventFacade} e The `columnsChange` event object @protected @since 3.5.0 **/ _afterColumnsChange: function (e) { this._setColumnMap(e.newVal); }, /** Updates the `modelList` attributes of the rendered views in response to the `data` attribute being assigned a new ModelList. @method _afterDataChange @param {EventFacade} e the `dataChange` event @protected @since 3.5.0 **/ _afterDataChange: function (e) { var modelList = e.newVal; this.data = e.newVal; if (!this.get('columns') && modelList.size()) { // TODO: this will cause a re-render twice because the Views are // subscribed to columnsChange this._initColumns(); } }, /** Assigns to the new recordType as the model for the data ModelList @method _afterRecordTypeChange @param {EventFacade} e recordTypeChange event @protected @since 3.6.0 **/ _afterRecordTypeChange: function (e) { var data = this.data.toJSON(); this.data.model = e.newVal; this.data.reset(data); if (!this.get('columns') && data) { if (data.length) { this._initColumns(); } else { this.set('columns', keys(e.newVal.ATTRS)); } } }, /** Creates a Model subclass from an array of attribute names or an object of attribute definitions. This is used to generate a class suitable to represent the data passed to the `data` attribute if no `recordType` is set. @method _createRecordClass @param {String[]|Object} attrs Names assigned to the Model subclass's `ATTRS` or its entire `ATTRS` definition object @return {Model} @protected @since 3.5.0 **/ _createRecordClass: function (attrs) { var ATTRS, i, len; if (isArray(attrs)) { ATTRS = {}; for (i = 0, len = attrs.length; i < len; ++i) { ATTRS[attrs[i]] = {}; } } else if (isObject(attrs)) { ATTRS = attrs; } return Y.Base.create('record', Y.Model, [], null, { ATTRS: ATTRS }); }, /** Tears down the instance. @method destructor @protected @since 3.6.0 **/ destructor: function () { new Y.EventHandle(Y.Object.values(this._eventHandles)).detach(); }, /** The getter for the `columns` attribute. Returns the array of column configuration objects if `instance.get('columns')` is called, or the specific column object if `instance.get('columns.columnKey')` is called. @method _getColumns @param {Object[]} columns The full array of column objects @param {String} name The attribute name requested (e.g. 'columns' or 'columns.foo'); @protected @since 3.5.0 **/ _getColumns: function (columns, name) { // Workaround for an attribute oddity (ticket #2529254) // getter is expected to return an object if get('columns.foo') is called. // Note 'columns.' is 8 characters return name.length > 8 ? this._columnMap : columns; }, /** Relays the `get()` request for the deprecated `columnset` attribute to the `columns` attribute. THIS BREAKS BACKWARD COMPATIBILITY. 3.4.1 and prior implementations will expect a Columnset instance returned from `get('columnset')`. @method _getColumnset @param {Object} ignored The current value stored in the `columnset` state @param {String} name The attribute name requested (e.g. 'columnset' or 'columnset.foo'); @deprecated This will be removed with the `columnset` attribute in a future version. @protected @since 3.5.0 **/ _getColumnset: function (_, name) { return this.get(name.replace(/^columnset/, 'columns')); }, /** Returns the Model class of the instance's `data` attribute ModelList. If not set, returns the explicitly configured value. @method _getRecordType @param {Model} val The currently configured value @return {Model} **/ _getRecordType: function (val) { // Prefer the value stored in the attribute because the attribute // change event defaultFn sets e.newVal = this.get('recordType') // before notifying the after() subs. But if this getter returns // this.data.model, then after() subs would get e.newVal === previous // model before _afterRecordTypeChange can set // this.data.model = e.newVal return val || (this.data && this.data.model); }, /** Initializes the `_columnMap` property from the configured `columns` attribute. If `columns` is not set, but there are records in the `data` ModelList, use `ATTRS` of that class. @method _initColumns @protected @since 3.5.0 **/ _initColumns: function () { var columns = this.get('columns') || [], item; // Default column definition from the configured recordType if (!columns.length && this.data.size()) { // TODO: merge superclass attributes up to Model? item = this.data.item(0); if (item.toJSON) { item = item.toJSON(); } this.set('columns', keys(item)); } this._setColumnMap(columns); }, /** Sets up the change event subscriptions to maintain internal state. @method _initCoreEvents @protected @since 3.6.0 **/ _initCoreEvents: function () { this._eventHandles.coreAttrChanges = this.after({ columnsChange : Y.bind('_afterColumnsChange', this), recordTypeChange: Y.bind('_afterRecordTypeChange', this), dataChange : Y.bind('_afterDataChange', this) }); }, /** Defaults the `data` attribute to an empty ModelList if not set during construction. Uses the configured `recordType` for the ModelList's `model` proeprty if set. @method _initData @protected @return {ModelList} @since 3.6.0 **/ _initData: function () { var recordType = this.get('recordType'), // TODO: LazyModelList if recordType doesn't have complex ATTRS modelList = new Y.ModelList(); if (recordType) { modelList.model = recordType; } return modelList; }, /** Initializes the instance's `data` property from the value of the `data` attribute. If the attribute value is a ModelList, it is assigned directly to `this.data`. If it is an array, a ModelList is created, its `model` property is set to the configured `recordType` class, and it is seeded with the array data. This ModelList is then assigned to `this.data`. @method _initDataProperty @param {Array|ModelList|ArrayList} data Collection of data to populate the DataTable @protected @since 3.6.0 **/ _initDataProperty: function (data) { var recordType; if (!this.data) { recordType = this.get('recordType'); if (data && data.each && data.toJSON) { this.data = data; if (recordType) { this.data.model = recordType; } } else { // TODO: customize the ModelList or read the ModelList class // from a configuration option? this.data = new Y.ModelList(); if (recordType) { this.data.model = recordType; } } // TODO: Replace this with an event relay for specific events. // Using bubbling causes subscription conflicts with the models' // aggregated change event and 'change' events from DOM elements // inside the table (via Widget UI event). this.data.addTarget(this); } }, /** Initializes the columns, `recordType` and data ModelList. @method initializer @param {Object} config Configuration object passed to constructor @protected @since 3.5.0 **/ initializer: function (config) { var data = config.data, columns = config.columns, recordType; // Referencing config.data to allow _setData to be more stringent // about its behavior this._initDataProperty(data); // Default columns from recordType ATTRS if recordType is supplied at // construction. If no recordType is supplied, but the data is // supplied as a non-empty array, use the keys of the first item // as the columns. if (!columns) { recordType = (config.recordType || config.data === this.data) && this.get('recordType'); if (recordType) { columns = keys(recordType.ATTRS); } else if (isArray(data) && data.length) { columns = keys(data[0]); } if (columns) { this.set('columns', columns); } } this._initColumns(); this._eventHandles = {}; this._initCoreEvents(); }, /** Iterates the array of column configurations to capture all columns with a `key` property. An map is built with column keys as the property name and the corresponding column object as the associated value. This map is then assigned to the instance's `_columnMap` property. @method _setColumnMap @param {Object[]|String[]} columns The array of column config objects @protected @since 3.6.0 **/ _setColumnMap: function (columns) { var map = {}; function process(cols) { var i, len, col, key; for (i = 0, len = cols.length; i < len; ++i) { col = cols[i]; key = col.key; // First in wins for multiple columns with the same key // because the first call to genId (in _setColumns) will // return the same key, which will then be overwritten by the // subsequent same-keyed column. So table.getColumn(key) would // return the last same-keyed column. if (key && !map[key]) { map[key] = col; } //TODO: named columns can conflict with keyed columns map[col._id] = col; if (col.children) { process(col.children); } } } process(columns); this._columnMap = map; }, /** Translates string columns into objects with that string as the value of its `key` property. All columns are assigned a `_yuid` stamp and `_id` property corresponding to the column's configured `name` or `key` property with any spaces replaced with dashes. If the same `name` or `key` appears in multiple columns, subsequent appearances will have their `_id` appended with an incrementing number (e.g. if column "foo" is included in the `columns` attribute twice, the first will get `_id` of "foo", and the second an `_id` of "foo1"). Columns that are children of other columns will have the `_parent` property added, assigned the column object to which they belong. @method _setColumns @param {null|Object[]|String[]} val Array of config objects or strings @return {null|Object[]} @protected **/ _setColumns: function (val) { var keys = {}, known = [], knownCopies = [], arrayIndex = Y.Array.indexOf; function copyObj(o) { var copy = {}, key, val, i; known.push(o); knownCopies.push(copy); for (key in o) { if (o.hasOwnProperty(key)) { val = o[key]; if (isArray(val)) { copy[key] = val.slice(); } else if (isObject(val, true)) { i = arrayIndex(val, known); copy[key] = i === -1 ? copyObj(val) : knownCopies[i]; } else { copy[key] = o[key]; } } } return copy; } function genId(name) { // Sanitize the name for use in generated CSS classes. // TODO: is there more to do for other uses of _id? name = name.replace(/\s+/, '-'); if (keys[name]) { name += (keys[name]++); } else { keys[name] = 1; } return name; } function process(cols, parent) { var columns = [], i, len, col, yuid; for (i = 0, len = cols.length; i < len; ++i) { columns[i] = // chained assignment col = isString(cols[i]) ? { key: cols[i] } : copyObj(cols[i]); yuid = Y.stamp(col); // For backward compatibility if (!col.id) { // Implementers can shoot themselves in the foot by setting // this config property to a non-unique value col.id = yuid; } if (col.field) { // Field is now known as "name" to avoid confusion with data // fields or schema.resultFields col.name = col.field; } if (parent) { col._parent = parent; } else { delete col._parent; } // Unique id based on the column's configured name or key, // falling back to the yuid. Duplicates will have a counter // added to the end. col._id = genId(col.name || col.key || col.id); if (isArray(col.children)) { col.children = process(col.children, col); } } return columns; } return val && process(val); }, /** Relays attribute assignments of the deprecated `columnset` attribute to the `columns` attribute. If a Columnset is object is passed, its basic object structure is mined. @method _setColumnset @param {Array|Columnset} val The columnset value to relay @deprecated This will be removed with the deprecated `columnset` attribute in a later version. @protected @since 3.5.0 **/ _setColumnset: function (val) { this.set('columns', val); return isArray(val) ? val : INVALID; }, /** Accepts an object with `each` and `getAttrs` (preferably a ModelList or subclass) or an array of data objects. If an array is passes, it will create a ModelList to wrap the data. In doing so, it will set the created ModelList's `model` property to the class in the `recordType` attribute, which will be defaulted if not yet set. If the `data` property is already set with a ModelList, passing an array as the value will call the ModelList's `reset()` method with that array rather than replacing the stored ModelList wholesale. Any non-ModelList-ish and non-array value is invalid. @method _setData @protected @since 3.5.0 **/ _setData: function (val) { if (val === null) { val = []; } if (isArray(val)) { this._initDataProperty(); // silent to prevent subscribers to both reset and dataChange // from reacting to the change twice. // TODO: would it be better to return INVALID to silence the // dataChange event, or even allow both events? this.data.reset(val, { silent: true }); // Return the instance ModelList to avoid storing unprocessed // data in the state and their vivified Model representations in // the instance's data property. Decreases memory consumption. val = this.data; } else if (!val || !val.each || !val.toJSON) { // ModelList/ArrayList duck typing val = INVALID; } return val; }, /** Relays the value assigned to the deprecated `recordset` attribute to the `data` attribute. If a Recordset instance is passed, the raw object data will be culled from it. @method _setRecordset @param {Object[]|Recordset} val The recordset value to relay @deprecated This will be removed with the deprecated `recordset` attribute in a later version. @protected @since 3.5.0 **/ _setRecordset: function (val) { var data; if (val && Y.Recordset && val instanceof Y.Recordset) { data = []; val.each(function (record) { data.push(record.get('data')); }); val = data; } this.set('data', val); return val; }, /** Accepts a Base subclass (preferably a Model subclass). Alternately, it will generate a custom Model subclass from an array of attribute names or an object defining attributes and their respective configurations (it is assigned as the `ATTRS` of the new class). Any other value is invalid. @method _setRecordType @param {Function|String[]|Object} val The Model subclass, array of attribute names, or the `ATTRS` definition for a custom model subclass @return {Function} A Base/Model subclass @protected @since 3.5.0 **/ _setRecordType: function (val) { var modelClass; // Duck type based on known/likely consumed APIs if (isFunction(val) && val.prototype.toJSON && val.prototype.setAttrs) { modelClass = val; } else if (isObject(val)) { modelClass = this._createRecordClass(val); } return modelClass || INVALID; } }); }, '@VERSION@', {"requires": ["escape", "model-list", "node-event-delegate"]});
js/src/Decorators/Link/__test__/linkDecoratorTest.js
andresin87/react-draft-wysiwyg
/* @flow */ import React from 'react'; import { expect, assert } from 'chai'; import { shallow, mount } from 'enzyme'; import LinkDecorator from '..'; describe('LinkDecorator test suite', () => { it('should have a div when rendered', () => { const Link = LinkDecorator.component; expect(shallow(<Link>Link</Link>).node.type).to.equal('span'); }); it('should have state initialized correctly', () => { const Link = LinkDecorator.component; const control = shallow(<Link>Link</Link>); assert.isNotTrue(control.state().showPopOver); }); it('should have 1 child element by default', () => { const Link = LinkDecorator.component; const control = shallow(<Link>Link</Link>); expect(control.children().length).to.equal(1); }); it('should have 2 child element when showPopOver is true', () => { const Link = LinkDecorator.component; const control = mount(<Link>Link</Link>); control.setState({ showPopOver: true }); expect(control.children().length).to.equal(2); }); });
ajax/libs/yasqe/1.3.2/yasqe.min.js
cloudrifles/cdnjs
!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var t;"undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.YASQE=e()}}(function(){var e;return function t(e,i,r){function n(s,a){if(!i[s]){if(!e[s]){var l="function"==typeof require&&require;if(!a&&l)return l(s,!0);if(o)return o(s,!0);throw new Error("Cannot find module '"+s+"'")}var u=i[s]={exports:{}};e[s][0].call(u.exports,function(t){var i=e[s][1][t];return n(i?i:t)},u,u.exports,t,e,i,r)}return i[s].exports}for(var o="function"==typeof require&&require,s=0;s<r.length;s++)n(r[s]);return n}({1:[function(e){$=jquery=e("jquery"),$.deparam=function(e,t){var i={},r={"true":!0,"false":!1,"null":null};return $.each(e.replace(/\+/g," ").split("&"),function(e,n){var o,s=n.split("="),a=decodeURIComponent(s[0]),l=i,u=0,p=a.split("]["),c=p.length-1;if(/\[/.test(p[0])&&/\]$/.test(p[c])?(p[c]=p[c].replace(/\]$/,""),p=p.shift().split("[").concat(p),c=p.length-1):c=0,2===s.length)if(o=decodeURIComponent(s[1]),t&&(o=o&&!isNaN(o)?+o:"undefined"===o?void 0:void 0!==r[o]?r[o]:o),c)for(;c>=u;u++)a=""===p[u]?l.length:p[u],l=l[a]=c>u?l[a]||(p[u+1]&&isNaN(p[u+1])?{}:[]):o;else $.isArray(i[a])?i[a].push(o):i[a]=void 0!==i[a]?[i[a],o]:o;else a&&(i[a]=t?void 0:"")}),i}},{jquery:9}],2:[function(t,i,r){!function(n){"object"==typeof r&&"object"==typeof i?n(t("codemirror")):"function"==typeof e&&e.amd?e(["codemirror"],n):n(CodeMirror)}(function(e){"use strict";e.defineMode("sparql11",function(e){function t(){var e,t,i="<[^<>\"'|{}^\\\x00- ]*>",r="[A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]",n=r+"|_",o="("+n+"|-|[0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040])",s="("+n+"|[0-9])("+n+"|[0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040])*",a="\\?"+s,l="\\$"+s,p="("+r+")((("+o+")|\\.)*("+o+"))?",c="[0-9A-Fa-f]",d="(%"+c+c+")",E="(\\\\[_~\\.\\-!\\$&'\\(\\)\\*\\+,;=/\\?#@%])",h="("+d+"|"+E+")";"sparql11"==u?(e="("+n+"|:|[0-9]|"+h+")(("+o+"|\\.|:|"+h+")*("+o+"|:|"+h+"))?",t="_:("+n+"|[0-9])(("+o+"|\\.)*"+o+")?"):(e="("+n+"|[0-9])((("+o+")|\\.)*("+o+"))?",t="_:"+e);var f="("+p+")?:",m=f+e,g="@[a-zA-Z]+(-[a-zA-Z0-9]+)*",v="[eE][\\+-]?[0-9]+",x="[0-9]+",N="(([0-9]+\\.[0-9]*)|(\\.[0-9]+))",L="(([0-9]+\\.[0-9]*"+v+")|(\\.[0-9]+"+v+")|([0-9]+"+v+"))",T="\\+"+x,I="\\+"+N,y="\\+"+L,A="-"+x,S="-"+N,C="-"+L,R="\\\\[tbnrf\\\\\"']",b="'(([^\\x27\\x5C\\x0A\\x0D])|"+R+")*'",O='"(([^\\x22\\x5C\\x0A\\x0D])|'+R+')*"',P="'''(('|'')?([^'\\\\]|"+R+"))*'''",D='"""(("|"")?([^"\\\\]|'+R+'))*"""',_="[\\x20\\x09\\x0D\\x0A]",M="#([^\\n\\r]*[\\n\\r]|[^\\n\\r]*$)",w="("+_+"|("+M+"))*",G="\\("+w+"\\)",k="\\["+w+"\\]",B={terminal:[{name:"WS",regex:new RegExp("^"+_+"+"),style:"ws"},{name:"COMMENT",regex:new RegExp("^"+M),style:"comment"},{name:"IRI_REF",regex:new RegExp("^"+i),style:"variable-3"},{name:"VAR1",regex:new RegExp("^"+a),style:"atom"},{name:"VAR2",regex:new RegExp("^"+l),style:"atom"},{name:"LANGTAG",regex:new RegExp("^"+g),style:"meta"},{name:"DOUBLE",regex:new RegExp("^"+L),style:"number"},{name:"DECIMAL",regex:new RegExp("^"+N),style:"number"},{name:"INTEGER",regex:new RegExp("^"+x),style:"number"},{name:"DOUBLE_POSITIVE",regex:new RegExp("^"+y),style:"number"},{name:"DECIMAL_POSITIVE",regex:new RegExp("^"+I),style:"number"},{name:"INTEGER_POSITIVE",regex:new RegExp("^"+T),style:"number"},{name:"DOUBLE_NEGATIVE",regex:new RegExp("^"+C),style:"number"},{name:"DECIMAL_NEGATIVE",regex:new RegExp("^"+S),style:"number"},{name:"INTEGER_NEGATIVE",regex:new RegExp("^"+A),style:"number"},{name:"STRING_LITERAL_LONG1",regex:new RegExp("^"+P),style:"string"},{name:"STRING_LITERAL_LONG2",regex:new RegExp("^"+D),style:"string"},{name:"STRING_LITERAL1",regex:new RegExp("^"+b),style:"string"},{name:"STRING_LITERAL2",regex:new RegExp("^"+O),style:"string"},{name:"NIL",regex:new RegExp("^"+G),style:"punc"},{name:"ANON",regex:new RegExp("^"+k),style:"punc"},{name:"PNAME_LN",regex:new RegExp("^"+m),style:"string-2"},{name:"PNAME_NS",regex:new RegExp("^"+f),style:"string-2"},{name:"BLANK_NODE_LABEL",regex:new RegExp("^"+t),style:"string-2"}]};return B}function i(e){var t=[],i=o[e];if(void 0!=i)for(var r in i)t.push(r.toString());else t.push(e);return t}function r(e,t){function r(){for(var t=null,i=0;i<E.length;++i)if(t=e.match(E[i].regex,!0,!1))return{cat:E[i].name,style:E[i].style,text:t[0]};return(t=e.match(s,!0,!1))?{cat:e.current().toUpperCase(),style:"keyword",text:t[0]}:(t=e.match(a,!0,!1))?{cat:e.current(),style:"punc",text:t[0]}:(t=e.match(/^.[A-Za-z0-9]*/,!0,!1),{cat:"<invalid_token>",style:"error",text:t[0]})}function n(){var i=e.column();t.errorStartPos=i,t.errorEndPos=i+c.text.length}function l(e){null==t.queryType&&("SELECT"==e||"CONSTRUCT"==e||"ASK"==e||"DESCRIBE"==e)&&(t.queryType=e)}function u(e){"disallowVars"==e?t.allowVars=!1:"allowVars"==e?t.allowVars=!0:"disallowBnodes"==e?t.allowBnodes=!1:"allowBnodes"==e?t.allowBnodes=!0:"storeProperty"==e&&(t.storeProperty=!0)}function p(e){return(t.allowVars||"var"!=e)&&(t.allowBnodes||"blankNode"!=e&&"blankNodePropertyList"!=e&&"blankNodePropertyListPath"!=e)}0==e.pos&&(t.possibleCurrent=t.possibleNext);var c=r();if("<invalid_token>"==c.cat)return 1==t.OK&&(t.OK=!1,n()),t.complete=!1,c.style;if("WS"==c.cat||"COMMENT"==c.cat)return t.possibleCurrent=t.possibleNext,c.style;for(var d,h=!1,f=c.cat;t.stack.length>0&&f&&t.OK&&!h;)if(d=t.stack.pop(),o[d]){var m=o[d][f];if(void 0!=m&&p(d)){for(var g=m.length-1;g>=0;--g)t.stack.push(m[g]);u(d)}else t.OK=!1,t.complete=!1,n(),t.stack.push(d)}else if(d==f){h=!0,l(d);for(var v=!0,x=t.stack.length;x>0;--x){var N=o[t.stack[x-1]];N&&N.$||(v=!1)}t.complete=v,t.storeProperty&&"punc"!=f.cat&&(t.lastProperty=c.text,t.storeProperty=!1)}else t.OK=!1,t.complete=!1,n();return!h&&t.OK&&(t.OK=!1,t.complete=!1,n()),t.possibleCurrent=t.possibleNext,t.possibleNext=i(t.stack[t.stack.length-1]),c.style}function n(t,i){var r=0,n=t.stack.length-1;if(/^[\}\]\)]/.test(i)){for(var o=i.substr(0,1);n>=0;--n)if(t.stack[n]==o){--n;break}}else{var s=h[t.stack[n]];s&&(r+=s,--n)}for(;n>=0;--n){var s=f[t.stack[n]];s&&(r+=s)}return r*e.indentUnit}var o=(e.indentUnit,{"*[&&,valueLogical]":{"&&":["[&&,valueLogical]","*[&&,valueLogical]"],AS:[],")":[],",":[],"||":[],";":[]},"*[,,expression]":{",":["[,,expression]","*[,,expression]"],")":[]},"*[,,objectPath]":{",":["[,,objectPath]","*[,,objectPath]"],".":[],";":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[,,object]":{",":["[,,object]","*[,,object]"],".":[],";":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"*[/,pathEltOrInverse]":{"/":["[/,pathEltOrInverse]","*[/,pathEltOrInverse]"],"|":[],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"*[;,?[or([verbPath,verbSimple]),objectList]]":{";":["[;,?[or([verbPath,verbSimple]),objectList]]","*[;,?[or([verbPath,verbSimple]),objectList]]"],".":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[;,?[verb,objectList]]":{";":["[;,?[verb,objectList]]","*[;,?[verb,objectList]]"],".":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"*[UNION,groupGraphPattern]":{UNION:["[UNION,groupGraphPattern]","*[UNION,groupGraphPattern]"],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],".":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[graphPatternNotTriples,?.,?triplesBlock]":{"{":["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],OPTIONAL:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],MINUS:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],GRAPH:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],SERVICE:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],FILTER:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],BIND:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],VALUES:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],"}":[]},"*[quadsNotTriples,?.,?triplesTemplate]":{GRAPH:["[quadsNotTriples,?.,?triplesTemplate]","*[quadsNotTriples,?.,?triplesTemplate]"],"}":[]},"*[|,pathOneInPropertySet]":{"|":["[|,pathOneInPropertySet]","*[|,pathOneInPropertySet]"],")":[]},"*[|,pathSequence]":{"|":["[|,pathSequence]","*[|,pathSequence]"],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"*[||,conditionalAndExpression]":{"||":["[||,conditionalAndExpression]","*[||,conditionalAndExpression]"],AS:[],")":[],",":[],";":[]},"*dataBlockValue":{UNDEF:["dataBlockValue","*dataBlockValue"],IRI_REF:["dataBlockValue","*dataBlockValue"],TRUE:["dataBlockValue","*dataBlockValue"],FALSE:["dataBlockValue","*dataBlockValue"],PNAME_LN:["dataBlockValue","*dataBlockValue"],PNAME_NS:["dataBlockValue","*dataBlockValue"],STRING_LITERAL1:["dataBlockValue","*dataBlockValue"],STRING_LITERAL2:["dataBlockValue","*dataBlockValue"],STRING_LITERAL_LONG1:["dataBlockValue","*dataBlockValue"],STRING_LITERAL_LONG2:["dataBlockValue","*dataBlockValue"],INTEGER:["dataBlockValue","*dataBlockValue"],DECIMAL:["dataBlockValue","*dataBlockValue"],DOUBLE:["dataBlockValue","*dataBlockValue"],INTEGER_POSITIVE:["dataBlockValue","*dataBlockValue"],DECIMAL_POSITIVE:["dataBlockValue","*dataBlockValue"],DOUBLE_POSITIVE:["dataBlockValue","*dataBlockValue"],INTEGER_NEGATIVE:["dataBlockValue","*dataBlockValue"],DECIMAL_NEGATIVE:["dataBlockValue","*dataBlockValue"],DOUBLE_NEGATIVE:["dataBlockValue","*dataBlockValue"],"}":[],")":[]},"*datasetClause":{FROM:["datasetClause","*datasetClause"],WHERE:[],"{":[]},"*describeDatasetClause":{FROM:["describeDatasetClause","*describeDatasetClause"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],WHERE:[],"{":[],VALUES:[],$:[]},"*graphNode":{"(":["graphNode","*graphNode"],"[":["graphNode","*graphNode"],VAR1:["graphNode","*graphNode"],VAR2:["graphNode","*graphNode"],NIL:["graphNode","*graphNode"],IRI_REF:["graphNode","*graphNode"],TRUE:["graphNode","*graphNode"],FALSE:["graphNode","*graphNode"],BLANK_NODE_LABEL:["graphNode","*graphNode"],ANON:["graphNode","*graphNode"],PNAME_LN:["graphNode","*graphNode"],PNAME_NS:["graphNode","*graphNode"],STRING_LITERAL1:["graphNode","*graphNode"],STRING_LITERAL2:["graphNode","*graphNode"],STRING_LITERAL_LONG1:["graphNode","*graphNode"],STRING_LITERAL_LONG2:["graphNode","*graphNode"],INTEGER:["graphNode","*graphNode"],DECIMAL:["graphNode","*graphNode"],DOUBLE:["graphNode","*graphNode"],INTEGER_POSITIVE:["graphNode","*graphNode"],DECIMAL_POSITIVE:["graphNode","*graphNode"],DOUBLE_POSITIVE:["graphNode","*graphNode"],INTEGER_NEGATIVE:["graphNode","*graphNode"],DECIMAL_NEGATIVE:["graphNode","*graphNode"],DOUBLE_NEGATIVE:["graphNode","*graphNode"],")":[]},"*graphNodePath":{"(":["graphNodePath","*graphNodePath"],"[":["graphNodePath","*graphNodePath"],VAR1:["graphNodePath","*graphNodePath"],VAR2:["graphNodePath","*graphNodePath"],NIL:["graphNodePath","*graphNodePath"],IRI_REF:["graphNodePath","*graphNodePath"],TRUE:["graphNodePath","*graphNodePath"],FALSE:["graphNodePath","*graphNodePath"],BLANK_NODE_LABEL:["graphNodePath","*graphNodePath"],ANON:["graphNodePath","*graphNodePath"],PNAME_LN:["graphNodePath","*graphNodePath"],PNAME_NS:["graphNodePath","*graphNodePath"],STRING_LITERAL1:["graphNodePath","*graphNodePath"],STRING_LITERAL2:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath","*graphNodePath"],INTEGER:["graphNodePath","*graphNodePath"],DECIMAL:["graphNodePath","*graphNodePath"],DOUBLE:["graphNodePath","*graphNodePath"],INTEGER_POSITIVE:["graphNodePath","*graphNodePath"],DECIMAL_POSITIVE:["graphNodePath","*graphNodePath"],DOUBLE_POSITIVE:["graphNodePath","*graphNodePath"],INTEGER_NEGATIVE:["graphNodePath","*graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath","*graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath","*graphNodePath"],")":[]},"*groupCondition":{"(":["groupCondition","*groupCondition"],STR:["groupCondition","*groupCondition"],LANG:["groupCondition","*groupCondition"],LANGMATCHES:["groupCondition","*groupCondition"],DATATYPE:["groupCondition","*groupCondition"],BOUND:["groupCondition","*groupCondition"],IRI:["groupCondition","*groupCondition"],URI:["groupCondition","*groupCondition"],BNODE:["groupCondition","*groupCondition"],RAND:["groupCondition","*groupCondition"],ABS:["groupCondition","*groupCondition"],CEIL:["groupCondition","*groupCondition"],FLOOR:["groupCondition","*groupCondition"],ROUND:["groupCondition","*groupCondition"],CONCAT:["groupCondition","*groupCondition"],STRLEN:["groupCondition","*groupCondition"],UCASE:["groupCondition","*groupCondition"],LCASE:["groupCondition","*groupCondition"],ENCODE_FOR_URI:["groupCondition","*groupCondition"],CONTAINS:["groupCondition","*groupCondition"],STRSTARTS:["groupCondition","*groupCondition"],STRENDS:["groupCondition","*groupCondition"],STRBEFORE:["groupCondition","*groupCondition"],STRAFTER:["groupCondition","*groupCondition"],YEAR:["groupCondition","*groupCondition"],MONTH:["groupCondition","*groupCondition"],DAY:["groupCondition","*groupCondition"],HOURS:["groupCondition","*groupCondition"],MINUTES:["groupCondition","*groupCondition"],SECONDS:["groupCondition","*groupCondition"],TIMEZONE:["groupCondition","*groupCondition"],TZ:["groupCondition","*groupCondition"],NOW:["groupCondition","*groupCondition"],UUID:["groupCondition","*groupCondition"],STRUUID:["groupCondition","*groupCondition"],MD5:["groupCondition","*groupCondition"],SHA1:["groupCondition","*groupCondition"],SHA256:["groupCondition","*groupCondition"],SHA384:["groupCondition","*groupCondition"],SHA512:["groupCondition","*groupCondition"],COALESCE:["groupCondition","*groupCondition"],IF:["groupCondition","*groupCondition"],STRLANG:["groupCondition","*groupCondition"],STRDT:["groupCondition","*groupCondition"],SAMETERM:["groupCondition","*groupCondition"],ISIRI:["groupCondition","*groupCondition"],ISURI:["groupCondition","*groupCondition"],ISBLANK:["groupCondition","*groupCondition"],ISLITERAL:["groupCondition","*groupCondition"],ISNUMERIC:["groupCondition","*groupCondition"],VAR1:["groupCondition","*groupCondition"],VAR2:["groupCondition","*groupCondition"],SUBSTR:["groupCondition","*groupCondition"],REPLACE:["groupCondition","*groupCondition"],REGEX:["groupCondition","*groupCondition"],EXISTS:["groupCondition","*groupCondition"],NOT:["groupCondition","*groupCondition"],IRI_REF:["groupCondition","*groupCondition"],PNAME_LN:["groupCondition","*groupCondition"],PNAME_NS:["groupCondition","*groupCondition"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],HAVING:[],$:[],"}":[]},"*havingCondition":{"(":["havingCondition","*havingCondition"],STR:["havingCondition","*havingCondition"],LANG:["havingCondition","*havingCondition"],LANGMATCHES:["havingCondition","*havingCondition"],DATATYPE:["havingCondition","*havingCondition"],BOUND:["havingCondition","*havingCondition"],IRI:["havingCondition","*havingCondition"],URI:["havingCondition","*havingCondition"],BNODE:["havingCondition","*havingCondition"],RAND:["havingCondition","*havingCondition"],ABS:["havingCondition","*havingCondition"],CEIL:["havingCondition","*havingCondition"],FLOOR:["havingCondition","*havingCondition"],ROUND:["havingCondition","*havingCondition"],CONCAT:["havingCondition","*havingCondition"],STRLEN:["havingCondition","*havingCondition"],UCASE:["havingCondition","*havingCondition"],LCASE:["havingCondition","*havingCondition"],ENCODE_FOR_URI:["havingCondition","*havingCondition"],CONTAINS:["havingCondition","*havingCondition"],STRSTARTS:["havingCondition","*havingCondition"],STRENDS:["havingCondition","*havingCondition"],STRBEFORE:["havingCondition","*havingCondition"],STRAFTER:["havingCondition","*havingCondition"],YEAR:["havingCondition","*havingCondition"],MONTH:["havingCondition","*havingCondition"],DAY:["havingCondition","*havingCondition"],HOURS:["havingCondition","*havingCondition"],MINUTES:["havingCondition","*havingCondition"],SECONDS:["havingCondition","*havingCondition"],TIMEZONE:["havingCondition","*havingCondition"],TZ:["havingCondition","*havingCondition"],NOW:["havingCondition","*havingCondition"],UUID:["havingCondition","*havingCondition"],STRUUID:["havingCondition","*havingCondition"],MD5:["havingCondition","*havingCondition"],SHA1:["havingCondition","*havingCondition"],SHA256:["havingCondition","*havingCondition"],SHA384:["havingCondition","*havingCondition"],SHA512:["havingCondition","*havingCondition"],COALESCE:["havingCondition","*havingCondition"],IF:["havingCondition","*havingCondition"],STRLANG:["havingCondition","*havingCondition"],STRDT:["havingCondition","*havingCondition"],SAMETERM:["havingCondition","*havingCondition"],ISIRI:["havingCondition","*havingCondition"],ISURI:["havingCondition","*havingCondition"],ISBLANK:["havingCondition","*havingCondition"],ISLITERAL:["havingCondition","*havingCondition"],ISNUMERIC:["havingCondition","*havingCondition"],SUBSTR:["havingCondition","*havingCondition"],REPLACE:["havingCondition","*havingCondition"],REGEX:["havingCondition","*havingCondition"],EXISTS:["havingCondition","*havingCondition"],NOT:["havingCondition","*havingCondition"],IRI_REF:["havingCondition","*havingCondition"],PNAME_LN:["havingCondition","*havingCondition"],PNAME_NS:["havingCondition","*havingCondition"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],$:[],"}":[]},"*or([[ (,*dataBlockValue,)],NIL])":{"(":["or([[ (,*dataBlockValue,)],NIL])","*or([[ (,*dataBlockValue,)],NIL])"],NIL:["or([[ (,*dataBlockValue,)],NIL])","*or([[ (,*dataBlockValue,)],NIL])"],"}":[]},"*or([[*,unaryExpression],[/,unaryExpression]])":{"*":["or([[*,unaryExpression],[/,unaryExpression]])","*or([[*,unaryExpression],[/,unaryExpression]])"],"/":["or([[*,unaryExpression],[/,unaryExpression]])","*or([[*,unaryExpression],[/,unaryExpression]])"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],";":[]},"*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])":{"+":["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"-":["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],";":[]},"*or([var,[ (,expression,AS,var,)]])":{"(":["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR1:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR2:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],WHERE:[],"{":[],FROM:[]},"*orderCondition":{ASC:["orderCondition","*orderCondition"],DESC:["orderCondition","*orderCondition"],VAR1:["orderCondition","*orderCondition"],VAR2:["orderCondition","*orderCondition"],"(":["orderCondition","*orderCondition"],STR:["orderCondition","*orderCondition"],LANG:["orderCondition","*orderCondition"],LANGMATCHES:["orderCondition","*orderCondition"],DATATYPE:["orderCondition","*orderCondition"],BOUND:["orderCondition","*orderCondition"],IRI:["orderCondition","*orderCondition"],URI:["orderCondition","*orderCondition"],BNODE:["orderCondition","*orderCondition"],RAND:["orderCondition","*orderCondition"],ABS:["orderCondition","*orderCondition"],CEIL:["orderCondition","*orderCondition"],FLOOR:["orderCondition","*orderCondition"],ROUND:["orderCondition","*orderCondition"],CONCAT:["orderCondition","*orderCondition"],STRLEN:["orderCondition","*orderCondition"],UCASE:["orderCondition","*orderCondition"],LCASE:["orderCondition","*orderCondition"],ENCODE_FOR_URI:["orderCondition","*orderCondition"],CONTAINS:["orderCondition","*orderCondition"],STRSTARTS:["orderCondition","*orderCondition"],STRENDS:["orderCondition","*orderCondition"],STRBEFORE:["orderCondition","*orderCondition"],STRAFTER:["orderCondition","*orderCondition"],YEAR:["orderCondition","*orderCondition"],MONTH:["orderCondition","*orderCondition"],DAY:["orderCondition","*orderCondition"],HOURS:["orderCondition","*orderCondition"],MINUTES:["orderCondition","*orderCondition"],SECONDS:["orderCondition","*orderCondition"],TIMEZONE:["orderCondition","*orderCondition"],TZ:["orderCondition","*orderCondition"],NOW:["orderCondition","*orderCondition"],UUID:["orderCondition","*orderCondition"],STRUUID:["orderCondition","*orderCondition"],MD5:["orderCondition","*orderCondition"],SHA1:["orderCondition","*orderCondition"],SHA256:["orderCondition","*orderCondition"],SHA384:["orderCondition","*orderCondition"],SHA512:["orderCondition","*orderCondition"],COALESCE:["orderCondition","*orderCondition"],IF:["orderCondition","*orderCondition"],STRLANG:["orderCondition","*orderCondition"],STRDT:["orderCondition","*orderCondition"],SAMETERM:["orderCondition","*orderCondition"],ISIRI:["orderCondition","*orderCondition"],ISURI:["orderCondition","*orderCondition"],ISBLANK:["orderCondition","*orderCondition"],ISLITERAL:["orderCondition","*orderCondition"],ISNUMERIC:["orderCondition","*orderCondition"],SUBSTR:["orderCondition","*orderCondition"],REPLACE:["orderCondition","*orderCondition"],REGEX:["orderCondition","*orderCondition"],EXISTS:["orderCondition","*orderCondition"],NOT:["orderCondition","*orderCondition"],IRI_REF:["orderCondition","*orderCondition"],PNAME_LN:["orderCondition","*orderCondition"],PNAME_NS:["orderCondition","*orderCondition"],VALUES:[],LIMIT:[],OFFSET:[],$:[],"}":[]},"*prefixDecl":{PREFIX:["prefixDecl","*prefixDecl"],$:[],CONSTRUCT:[],DESCRIBE:[],ASK:[],INSERT:[],DELETE:[],SELECT:[],LOAD:[],CLEAR:[],DROP:[],ADD:[],MOVE:[],COPY:[],CREATE:[],WITH:[]},"*usingClause":{USING:["usingClause","*usingClause"],WHERE:[]},"*var":{VAR1:["var","*var"],VAR2:["var","*var"],")":[]},"*varOrIRIref":{VAR1:["varOrIRIref","*varOrIRIref"],VAR2:["varOrIRIref","*varOrIRIref"],IRI_REF:["varOrIRIref","*varOrIRIref"],PNAME_LN:["varOrIRIref","*varOrIRIref"],PNAME_NS:["varOrIRIref","*varOrIRIref"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],WHERE:[],"{":[],FROM:[],VALUES:[],$:[]},"+graphNode":{"(":["graphNode","*graphNode"],"[":["graphNode","*graphNode"],VAR1:["graphNode","*graphNode"],VAR2:["graphNode","*graphNode"],NIL:["graphNode","*graphNode"],IRI_REF:["graphNode","*graphNode"],TRUE:["graphNode","*graphNode"],FALSE:["graphNode","*graphNode"],BLANK_NODE_LABEL:["graphNode","*graphNode"],ANON:["graphNode","*graphNode"],PNAME_LN:["graphNode","*graphNode"],PNAME_NS:["graphNode","*graphNode"],STRING_LITERAL1:["graphNode","*graphNode"],STRING_LITERAL2:["graphNode","*graphNode"],STRING_LITERAL_LONG1:["graphNode","*graphNode"],STRING_LITERAL_LONG2:["graphNode","*graphNode"],INTEGER:["graphNode","*graphNode"],DECIMAL:["graphNode","*graphNode"],DOUBLE:["graphNode","*graphNode"],INTEGER_POSITIVE:["graphNode","*graphNode"],DECIMAL_POSITIVE:["graphNode","*graphNode"],DOUBLE_POSITIVE:["graphNode","*graphNode"],INTEGER_NEGATIVE:["graphNode","*graphNode"],DECIMAL_NEGATIVE:["graphNode","*graphNode"],DOUBLE_NEGATIVE:["graphNode","*graphNode"]},"+graphNodePath":{"(":["graphNodePath","*graphNodePath"],"[":["graphNodePath","*graphNodePath"],VAR1:["graphNodePath","*graphNodePath"],VAR2:["graphNodePath","*graphNodePath"],NIL:["graphNodePath","*graphNodePath"],IRI_REF:["graphNodePath","*graphNodePath"],TRUE:["graphNodePath","*graphNodePath"],FALSE:["graphNodePath","*graphNodePath"],BLANK_NODE_LABEL:["graphNodePath","*graphNodePath"],ANON:["graphNodePath","*graphNodePath"],PNAME_LN:["graphNodePath","*graphNodePath"],PNAME_NS:["graphNodePath","*graphNodePath"],STRING_LITERAL1:["graphNodePath","*graphNodePath"],STRING_LITERAL2:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath","*graphNodePath"],INTEGER:["graphNodePath","*graphNodePath"],DECIMAL:["graphNodePath","*graphNodePath"],DOUBLE:["graphNodePath","*graphNodePath"],INTEGER_POSITIVE:["graphNodePath","*graphNodePath"],DECIMAL_POSITIVE:["graphNodePath","*graphNodePath"],DOUBLE_POSITIVE:["graphNodePath","*graphNodePath"],INTEGER_NEGATIVE:["graphNodePath","*graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath","*graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath","*graphNodePath"]},"+groupCondition":{"(":["groupCondition","*groupCondition"],STR:["groupCondition","*groupCondition"],LANG:["groupCondition","*groupCondition"],LANGMATCHES:["groupCondition","*groupCondition"],DATATYPE:["groupCondition","*groupCondition"],BOUND:["groupCondition","*groupCondition"],IRI:["groupCondition","*groupCondition"],URI:["groupCondition","*groupCondition"],BNODE:["groupCondition","*groupCondition"],RAND:["groupCondition","*groupCondition"],ABS:["groupCondition","*groupCondition"],CEIL:["groupCondition","*groupCondition"],FLOOR:["groupCondition","*groupCondition"],ROUND:["groupCondition","*groupCondition"],CONCAT:["groupCondition","*groupCondition"],STRLEN:["groupCondition","*groupCondition"],UCASE:["groupCondition","*groupCondition"],LCASE:["groupCondition","*groupCondition"],ENCODE_FOR_URI:["groupCondition","*groupCondition"],CONTAINS:["groupCondition","*groupCondition"],STRSTARTS:["groupCondition","*groupCondition"],STRENDS:["groupCondition","*groupCondition"],STRBEFORE:["groupCondition","*groupCondition"],STRAFTER:["groupCondition","*groupCondition"],YEAR:["groupCondition","*groupCondition"],MONTH:["groupCondition","*groupCondition"],DAY:["groupCondition","*groupCondition"],HOURS:["groupCondition","*groupCondition"],MINUTES:["groupCondition","*groupCondition"],SECONDS:["groupCondition","*groupCondition"],TIMEZONE:["groupCondition","*groupCondition"],TZ:["groupCondition","*groupCondition"],NOW:["groupCondition","*groupCondition"],UUID:["groupCondition","*groupCondition"],STRUUID:["groupCondition","*groupCondition"],MD5:["groupCondition","*groupCondition"],SHA1:["groupCondition","*groupCondition"],SHA256:["groupCondition","*groupCondition"],SHA384:["groupCondition","*groupCondition"],SHA512:["groupCondition","*groupCondition"],COALESCE:["groupCondition","*groupCondition"],IF:["groupCondition","*groupCondition"],STRLANG:["groupCondition","*groupCondition"],STRDT:["groupCondition","*groupCondition"],SAMETERM:["groupCondition","*groupCondition"],ISIRI:["groupCondition","*groupCondition"],ISURI:["groupCondition","*groupCondition"],ISBLANK:["groupCondition","*groupCondition"],ISLITERAL:["groupCondition","*groupCondition"],ISNUMERIC:["groupCondition","*groupCondition"],VAR1:["groupCondition","*groupCondition"],VAR2:["groupCondition","*groupCondition"],SUBSTR:["groupCondition","*groupCondition"],REPLACE:["groupCondition","*groupCondition"],REGEX:["groupCondition","*groupCondition"],EXISTS:["groupCondition","*groupCondition"],NOT:["groupCondition","*groupCondition"],IRI_REF:["groupCondition","*groupCondition"],PNAME_LN:["groupCondition","*groupCondition"],PNAME_NS:["groupCondition","*groupCondition"]},"+havingCondition":{"(":["havingCondition","*havingCondition"],STR:["havingCondition","*havingCondition"],LANG:["havingCondition","*havingCondition"],LANGMATCHES:["havingCondition","*havingCondition"],DATATYPE:["havingCondition","*havingCondition"],BOUND:["havingCondition","*havingCondition"],IRI:["havingCondition","*havingCondition"],URI:["havingCondition","*havingCondition"],BNODE:["havingCondition","*havingCondition"],RAND:["havingCondition","*havingCondition"],ABS:["havingCondition","*havingCondition"],CEIL:["havingCondition","*havingCondition"],FLOOR:["havingCondition","*havingCondition"],ROUND:["havingCondition","*havingCondition"],CONCAT:["havingCondition","*havingCondition"],STRLEN:["havingCondition","*havingCondition"],UCASE:["havingCondition","*havingCondition"],LCASE:["havingCondition","*havingCondition"],ENCODE_FOR_URI:["havingCondition","*havingCondition"],CONTAINS:["havingCondition","*havingCondition"],STRSTARTS:["havingCondition","*havingCondition"],STRENDS:["havingCondition","*havingCondition"],STRBEFORE:["havingCondition","*havingCondition"],STRAFTER:["havingCondition","*havingCondition"],YEAR:["havingCondition","*havingCondition"],MONTH:["havingCondition","*havingCondition"],DAY:["havingCondition","*havingCondition"],HOURS:["havingCondition","*havingCondition"],MINUTES:["havingCondition","*havingCondition"],SECONDS:["havingCondition","*havingCondition"],TIMEZONE:["havingCondition","*havingCondition"],TZ:["havingCondition","*havingCondition"],NOW:["havingCondition","*havingCondition"],UUID:["havingCondition","*havingCondition"],STRUUID:["havingCondition","*havingCondition"],MD5:["havingCondition","*havingCondition"],SHA1:["havingCondition","*havingCondition"],SHA256:["havingCondition","*havingCondition"],SHA384:["havingCondition","*havingCondition"],SHA512:["havingCondition","*havingCondition"],COALESCE:["havingCondition","*havingCondition"],IF:["havingCondition","*havingCondition"],STRLANG:["havingCondition","*havingCondition"],STRDT:["havingCondition","*havingCondition"],SAMETERM:["havingCondition","*havingCondition"],ISIRI:["havingCondition","*havingCondition"],ISURI:["havingCondition","*havingCondition"],ISBLANK:["havingCondition","*havingCondition"],ISLITERAL:["havingCondition","*havingCondition"],ISNUMERIC:["havingCondition","*havingCondition"],SUBSTR:["havingCondition","*havingCondition"],REPLACE:["havingCondition","*havingCondition"],REGEX:["havingCondition","*havingCondition"],EXISTS:["havingCondition","*havingCondition"],NOT:["havingCondition","*havingCondition"],IRI_REF:["havingCondition","*havingCondition"],PNAME_LN:["havingCondition","*havingCondition"],PNAME_NS:["havingCondition","*havingCondition"]},"+or([var,[ (,expression,AS,var,)]])":{"(":["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR1:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR2:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"]},"+orderCondition":{ASC:["orderCondition","*orderCondition"],DESC:["orderCondition","*orderCondition"],VAR1:["orderCondition","*orderCondition"],VAR2:["orderCondition","*orderCondition"],"(":["orderCondition","*orderCondition"],STR:["orderCondition","*orderCondition"],LANG:["orderCondition","*orderCondition"],LANGMATCHES:["orderCondition","*orderCondition"],DATATYPE:["orderCondition","*orderCondition"],BOUND:["orderCondition","*orderCondition"],IRI:["orderCondition","*orderCondition"],URI:["orderCondition","*orderCondition"],BNODE:["orderCondition","*orderCondition"],RAND:["orderCondition","*orderCondition"],ABS:["orderCondition","*orderCondition"],CEIL:["orderCondition","*orderCondition"],FLOOR:["orderCondition","*orderCondition"],ROUND:["orderCondition","*orderCondition"],CONCAT:["orderCondition","*orderCondition"],STRLEN:["orderCondition","*orderCondition"],UCASE:["orderCondition","*orderCondition"],LCASE:["orderCondition","*orderCondition"],ENCODE_FOR_URI:["orderCondition","*orderCondition"],CONTAINS:["orderCondition","*orderCondition"],STRSTARTS:["orderCondition","*orderCondition"],STRENDS:["orderCondition","*orderCondition"],STRBEFORE:["orderCondition","*orderCondition"],STRAFTER:["orderCondition","*orderCondition"],YEAR:["orderCondition","*orderCondition"],MONTH:["orderCondition","*orderCondition"],DAY:["orderCondition","*orderCondition"],HOURS:["orderCondition","*orderCondition"],MINUTES:["orderCondition","*orderCondition"],SECONDS:["orderCondition","*orderCondition"],TIMEZONE:["orderCondition","*orderCondition"],TZ:["orderCondition","*orderCondition"],NOW:["orderCondition","*orderCondition"],UUID:["orderCondition","*orderCondition"],STRUUID:["orderCondition","*orderCondition"],MD5:["orderCondition","*orderCondition"],SHA1:["orderCondition","*orderCondition"],SHA256:["orderCondition","*orderCondition"],SHA384:["orderCondition","*orderCondition"],SHA512:["orderCondition","*orderCondition"],COALESCE:["orderCondition","*orderCondition"],IF:["orderCondition","*orderCondition"],STRLANG:["orderCondition","*orderCondition"],STRDT:["orderCondition","*orderCondition"],SAMETERM:["orderCondition","*orderCondition"],ISIRI:["orderCondition","*orderCondition"],ISURI:["orderCondition","*orderCondition"],ISBLANK:["orderCondition","*orderCondition"],ISLITERAL:["orderCondition","*orderCondition"],ISNUMERIC:["orderCondition","*orderCondition"],SUBSTR:["orderCondition","*orderCondition"],REPLACE:["orderCondition","*orderCondition"],REGEX:["orderCondition","*orderCondition"],EXISTS:["orderCondition","*orderCondition"],NOT:["orderCondition","*orderCondition"],IRI_REF:["orderCondition","*orderCondition"],PNAME_LN:["orderCondition","*orderCondition"],PNAME_NS:["orderCondition","*orderCondition"]},"+varOrIRIref":{VAR1:["varOrIRIref","*varOrIRIref"],VAR2:["varOrIRIref","*varOrIRIref"],IRI_REF:["varOrIRIref","*varOrIRIref"],PNAME_LN:["varOrIRIref","*varOrIRIref"],PNAME_NS:["varOrIRIref","*varOrIRIref"]},"?.":{".":["."],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?DISTINCT":{DISTINCT:["DISTINCT"],"!":[],"+":[],"-":[],VAR1:[],VAR2:[],"(":[],STR:[],LANG:[],LANGMATCHES:[],DATATYPE:[],BOUND:[],IRI:[],URI:[],BNODE:[],RAND:[],ABS:[],CEIL:[],FLOOR:[],ROUND:[],CONCAT:[],STRLEN:[],UCASE:[],LCASE:[],ENCODE_FOR_URI:[],CONTAINS:[],STRSTARTS:[],STRENDS:[],STRBEFORE:[],STRAFTER:[],YEAR:[],MONTH:[],DAY:[],HOURS:[],MINUTES:[],SECONDS:[],TIMEZONE:[],TZ:[],NOW:[],UUID:[],STRUUID:[],MD5:[],SHA1:[],SHA256:[],SHA384:[],SHA512:[],COALESCE:[],IF:[],STRLANG:[],STRDT:[],SAMETERM:[],ISIRI:[],ISURI:[],ISBLANK:[],ISLITERAL:[],ISNUMERIC:[],TRUE:[],FALSE:[],COUNT:[],SUM:[],MIN:[],MAX:[],AVG:[],SAMPLE:[],GROUP_CONCAT:[],SUBSTR:[],REPLACE:[],REGEX:[],EXISTS:[],NOT:[],IRI_REF:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],PNAME_LN:[],PNAME_NS:[],"*":[]},"?GRAPH":{GRAPH:["GRAPH"],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT":{SILENT:["SILENT"],VAR1:[],VAR2:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT_1":{SILENT:["SILENT"],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT_2":{SILENT:["SILENT"],GRAPH:[],DEFAULT:[],NAMED:[],ALL:[]},"?SILENT_3":{SILENT:["SILENT"],GRAPH:[]},"?SILENT_4":{SILENT:["SILENT"],DEFAULT:[],GRAPH:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?WHERE":{WHERE:["WHERE"],"{":[]},"?[,,expression]":{",":["[,,expression]"],")":[]},"?[.,?constructTriples]":{".":["[.,?constructTriples]"],"}":[]},"?[.,?triplesBlock]":{".":["[.,?triplesBlock]"],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?[.,?triplesTemplate]":{".":["[.,?triplesTemplate]"],"}":[],GRAPH:[]},"?[;,SEPARATOR,=,string]":{";":["[;,SEPARATOR,=,string]"],")":[]},"?[;,update]":{";":["[;,update]"],$:[]},"?[AS,var]":{AS:["[AS,var]"],")":[]},"?[INTO,graphRef]":{INTO:["[INTO,graphRef]"],";":[],$:[]},"?[or([verbPath,verbSimple]),objectList]":{VAR1:["[or([verbPath,verbSimple]),objectList]"],VAR2:["[or([verbPath,verbSimple]),objectList]"],"^":["[or([verbPath,verbSimple]),objectList]"],a:["[or([verbPath,verbSimple]),objectList]"],"!":["[or([verbPath,verbSimple]),objectList]"],"(":["[or([verbPath,verbSimple]),objectList]"],IRI_REF:["[or([verbPath,verbSimple]),objectList]"],PNAME_LN:["[or([verbPath,verbSimple]),objectList]"],PNAME_NS:["[or([verbPath,verbSimple]),objectList]"],";":[],".":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?[pathOneInPropertySet,*[|,pathOneInPropertySet]]":{a:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],"^":["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],IRI_REF:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],PNAME_LN:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],PNAME_NS:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],")":[]},"?[update1,?[;,update]]":{INSERT:["[update1,?[;,update]]"],DELETE:["[update1,?[;,update]]"],LOAD:["[update1,?[;,update]]"],CLEAR:["[update1,?[;,update]]"],DROP:["[update1,?[;,update]]"],ADD:["[update1,?[;,update]]"],MOVE:["[update1,?[;,update]]"],COPY:["[update1,?[;,update]]"],CREATE:["[update1,?[;,update]]"],WITH:["[update1,?[;,update]]"],$:[]},"?[verb,objectList]":{a:["[verb,objectList]"],VAR1:["[verb,objectList]"],VAR2:["[verb,objectList]"],IRI_REF:["[verb,objectList]"],PNAME_LN:["[verb,objectList]"],PNAME_NS:["[verb,objectList]"],";":[],".":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"?argList":{NIL:["argList"],"(":["argList"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],"*":[],"/":[],";":[]},"?baseDecl":{BASE:["baseDecl"],$:[],CONSTRUCT:[],DESCRIBE:[],ASK:[],INSERT:[],DELETE:[],SELECT:[],LOAD:[],CLEAR:[],DROP:[],ADD:[],MOVE:[],COPY:[],CREATE:[],WITH:[],PREFIX:[]},"?constructTriples":{VAR1:["constructTriples"],VAR2:["constructTriples"],NIL:["constructTriples"],"(":["constructTriples"],"[":["constructTriples"],IRI_REF:["constructTriples"],TRUE:["constructTriples"],FALSE:["constructTriples"],BLANK_NODE_LABEL:["constructTriples"],ANON:["constructTriples"],PNAME_LN:["constructTriples"],PNAME_NS:["constructTriples"],STRING_LITERAL1:["constructTriples"],STRING_LITERAL2:["constructTriples"],STRING_LITERAL_LONG1:["constructTriples"],STRING_LITERAL_LONG2:["constructTriples"],INTEGER:["constructTriples"],DECIMAL:["constructTriples"],DOUBLE:["constructTriples"],INTEGER_POSITIVE:["constructTriples"],DECIMAL_POSITIVE:["constructTriples"],DOUBLE_POSITIVE:["constructTriples"],INTEGER_NEGATIVE:["constructTriples"],DECIMAL_NEGATIVE:["constructTriples"],DOUBLE_NEGATIVE:["constructTriples"],"}":[]},"?groupClause":{GROUP:["groupClause"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],HAVING:[],$:[],"}":[]},"?havingClause":{HAVING:["havingClause"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],$:[],"}":[]},"?insertClause":{INSERT:["insertClause"],WHERE:[],USING:[]},"?limitClause":{LIMIT:["limitClause"],VALUES:[],$:[],"}":[]},"?limitOffsetClauses":{LIMIT:["limitOffsetClauses"],OFFSET:["limitOffsetClauses"],VALUES:[],$:[],"}":[]},"?offsetClause":{OFFSET:["offsetClause"],VALUES:[],$:[],"}":[]},"?or([DISTINCT,REDUCED])":{DISTINCT:["or([DISTINCT,REDUCED])"],REDUCED:["or([DISTINCT,REDUCED])"],"*":[],"(":[],VAR1:[],VAR2:[]},"?or([LANGTAG,[^^,iriRef]])":{LANGTAG:["or([LANGTAG,[^^,iriRef]])"],"^^":["or([LANGTAG,[^^,iriRef]])"],UNDEF:[],IRI_REF:[],TRUE:[],FALSE:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],a:[],VAR1:[],VAR2:[],"^":[],"!":[],"(":[],".":[],";":[],",":[],AS:[],")":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],"*":[],"/":[],"}":[],"[":[],NIL:[],BLANK_NODE_LABEL:[],ANON:[],"]":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"?or([[*,unaryExpression],[/,unaryExpression]])":{"*":["or([[*,unaryExpression],[/,unaryExpression]])"],"/":["or([[*,unaryExpression],[/,unaryExpression]])"],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],";":[]},"?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])":{"=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"!=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"<":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],">":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"<=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],">=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IN:["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOT:["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],AS:[],")":[],",":[],"||":[],"&&":[],";":[]},"?orderClause":{ORDER:["orderClause"],VALUES:[],LIMIT:[],OFFSET:[],$:[],"}":[]},"?pathMod":{"*":["pathMod"],"?":["pathMod"],"+":["pathMod"],"{":["pathMod"],"|":[],"/":[],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"?triplesBlock":{VAR1:["triplesBlock"],VAR2:["triplesBlock"],NIL:["triplesBlock"],"(":["triplesBlock"],"[":["triplesBlock"],IRI_REF:["triplesBlock"],TRUE:["triplesBlock"],FALSE:["triplesBlock"],BLANK_NODE_LABEL:["triplesBlock"],ANON:["triplesBlock"],PNAME_LN:["triplesBlock"],PNAME_NS:["triplesBlock"],STRING_LITERAL1:["triplesBlock"],STRING_LITERAL2:["triplesBlock"],STRING_LITERAL_LONG1:["triplesBlock"],STRING_LITERAL_LONG2:["triplesBlock"],INTEGER:["triplesBlock"],DECIMAL:["triplesBlock"],DOUBLE:["triplesBlock"],INTEGER_POSITIVE:["triplesBlock"],DECIMAL_POSITIVE:["triplesBlock"],DOUBLE_POSITIVE:["triplesBlock"],INTEGER_NEGATIVE:["triplesBlock"],DECIMAL_NEGATIVE:["triplesBlock"],DOUBLE_NEGATIVE:["triplesBlock"],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?triplesTemplate":{VAR1:["triplesTemplate"],VAR2:["triplesTemplate"],NIL:["triplesTemplate"],"(":["triplesTemplate"],"[":["triplesTemplate"],IRI_REF:["triplesTemplate"],TRUE:["triplesTemplate"],FALSE:["triplesTemplate"],BLANK_NODE_LABEL:["triplesTemplate"],ANON:["triplesTemplate"],PNAME_LN:["triplesTemplate"],PNAME_NS:["triplesTemplate"],STRING_LITERAL1:["triplesTemplate"],STRING_LITERAL2:["triplesTemplate"],STRING_LITERAL_LONG1:["triplesTemplate"],STRING_LITERAL_LONG2:["triplesTemplate"],INTEGER:["triplesTemplate"],DECIMAL:["triplesTemplate"],DOUBLE:["triplesTemplate"],INTEGER_POSITIVE:["triplesTemplate"],DECIMAL_POSITIVE:["triplesTemplate"],DOUBLE_POSITIVE:["triplesTemplate"],INTEGER_NEGATIVE:["triplesTemplate"],DECIMAL_NEGATIVE:["triplesTemplate"],DOUBLE_NEGATIVE:["triplesTemplate"],"}":[],GRAPH:[]},"?whereClause":{WHERE:["whereClause"],"{":["whereClause"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],VALUES:[],$:[]},"[ (,*dataBlockValue,)]":{"(":["(","*dataBlockValue",")"]},"[ (,*var,)]":{"(":["(","*var",")"]},"[ (,expression,)]":{"(":["(","expression",")"]},"[ (,expression,AS,var,)]":{"(":["(","expression","AS","var",")"]},"[!=,numericExpression]":{"!=":["!=","numericExpression"]},"[&&,valueLogical]":{"&&":["&&","valueLogical"]},"[*,unaryExpression]":{"*":["*","unaryExpression"]},"[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]":{WHERE:["*datasetClause","WHERE","{","?triplesTemplate","}","solutionModifier"],FROM:["*datasetClause","WHERE","{","?triplesTemplate","}","solutionModifier"]},"[+,multiplicativeExpression]":{"+":["+","multiplicativeExpression"]},"[,,expression]":{",":[",","expression"]},"[,,integer,}]":{",":[",","integer","}"]},"[,,objectPath]":{",":[",","objectPath"]},"[,,object]":{",":[",","object"]},"[,,or([},[integer,}]])]":{",":[",","or([},[integer,}]])"]},"[-,multiplicativeExpression]":{"-":["-","multiplicativeExpression"]},"[.,?constructTriples]":{".":[".","?constructTriples"]},"[.,?triplesBlock]":{".":[".","?triplesBlock"]},"[.,?triplesTemplate]":{".":[".","?triplesTemplate"]},"[/,pathEltOrInverse]":{"/":["/","pathEltOrInverse"]},"[/,unaryExpression]":{"/":["/","unaryExpression"]},"[;,?[or([verbPath,verbSimple]),objectList]]":{";":[";","?[or([verbPath,verbSimple]),objectList]"]},"[;,?[verb,objectList]]":{";":[";","?[verb,objectList]"]},"[;,SEPARATOR,=,string]":{";":[";","SEPARATOR","=","string"]},"[;,update]":{";":[";","update"]},"[<,numericExpression]":{"<":["<","numericExpression"]},"[<=,numericExpression]":{"<=":["<=","numericExpression"]},"[=,numericExpression]":{"=":["=","numericExpression"]},"[>,numericExpression]":{">":[">","numericExpression"]},"[>=,numericExpression]":{">=":[">=","numericExpression"]},"[AS,var]":{AS:["AS","var"]},"[IN,expressionList]":{IN:["IN","expressionList"]},"[INTO,graphRef]":{INTO:["INTO","graphRef"]},"[NAMED,iriRef]":{NAMED:["NAMED","iriRef"]},"[NOT,IN,expressionList]":{NOT:["NOT","IN","expressionList"]},"[UNION,groupGraphPattern]":{UNION:["UNION","groupGraphPattern"]},"[^^,iriRef]":{"^^":["^^","iriRef"]},"[constructTemplate,*datasetClause,whereClause,solutionModifier]":{"{":["constructTemplate","*datasetClause","whereClause","solutionModifier"]},"[deleteClause,?insertClause]":{DELETE:["deleteClause","?insertClause"]},"[graphPatternNotTriples,?.,?triplesBlock]":{"{":["graphPatternNotTriples","?.","?triplesBlock"],OPTIONAL:["graphPatternNotTriples","?.","?triplesBlock"],MINUS:["graphPatternNotTriples","?.","?triplesBlock"],GRAPH:["graphPatternNotTriples","?.","?triplesBlock"],SERVICE:["graphPatternNotTriples","?.","?triplesBlock"],FILTER:["graphPatternNotTriples","?.","?triplesBlock"],BIND:["graphPatternNotTriples","?.","?triplesBlock"],VALUES:["graphPatternNotTriples","?.","?triplesBlock"]},"[integer,or([[,,or([},[integer,}]])],}])]":{INTEGER:["integer","or([[,,or([},[integer,}]])],}])"]},"[integer,}]":{INTEGER:["integer","}"]},"[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]":{INTEGER_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"]},"[or([verbPath,verbSimple]),objectList]":{VAR1:["or([verbPath,verbSimple])","objectList"],VAR2:["or([verbPath,verbSimple])","objectList"],"^":["or([verbPath,verbSimple])","objectList"],a:["or([verbPath,verbSimple])","objectList"],"!":["or([verbPath,verbSimple])","objectList"],"(":["or([verbPath,verbSimple])","objectList"],IRI_REF:["or([verbPath,verbSimple])","objectList"],PNAME_LN:["or([verbPath,verbSimple])","objectList"],PNAME_NS:["or([verbPath,verbSimple])","objectList"]},"[pathOneInPropertySet,*[|,pathOneInPropertySet]]":{a:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],"^":["pathOneInPropertySet","*[|,pathOneInPropertySet]"],IRI_REF:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],PNAME_LN:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],PNAME_NS:["pathOneInPropertySet","*[|,pathOneInPropertySet]"]},"[quadsNotTriples,?.,?triplesTemplate]":{GRAPH:["quadsNotTriples","?.","?triplesTemplate"]},"[update1,?[;,update]]":{INSERT:["update1","?[;,update]"],DELETE:["update1","?[;,update]"],LOAD:["update1","?[;,update]"],CLEAR:["update1","?[;,update]"],DROP:["update1","?[;,update]"],ADD:["update1","?[;,update]"],MOVE:["update1","?[;,update]"],COPY:["update1","?[;,update]"],CREATE:["update1","?[;,update]"],WITH:["update1","?[;,update]"]},"[verb,objectList]":{a:["verb","objectList"],VAR1:["verb","objectList"],VAR2:["verb","objectList"],IRI_REF:["verb","objectList"],PNAME_LN:["verb","objectList"],PNAME_NS:["verb","objectList"]},"[|,pathOneInPropertySet]":{"|":["|","pathOneInPropertySet"]},"[|,pathSequence]":{"|":["|","pathSequence"]},"[||,conditionalAndExpression]":{"||":["||","conditionalAndExpression"]},add:{ADD:["ADD","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},additiveExpression:{"!":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"+":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"-":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],VAR1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],VAR2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"(":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LANG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LANGMATCHES:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DATATYPE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],BOUND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IRI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],URI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],BNODE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],RAND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ABS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CEIL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],FLOOR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ROUND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CONCAT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRLEN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],UCASE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LCASE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ENCODE_FOR_URI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CONTAINS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRSTARTS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRENDS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRBEFORE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRAFTER:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],YEAR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MONTH:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DAY:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],HOURS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MINUTES:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SECONDS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TIMEZONE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TZ:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],NOW:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],UUID:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRUUID:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MD5:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA256:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA384:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA512:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],COALESCE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IF:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRLANG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRDT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SAMETERM:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISIRI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISURI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISBLANK:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISLITERAL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISNUMERIC:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TRUE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],FALSE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],COUNT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SUM:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MIN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MAX:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],AVG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SAMPLE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],GROUP_CONCAT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SUBSTR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],REPLACE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],REGEX:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],EXISTS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],NOT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IRI_REF:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL_LONG1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL_LONG2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],PNAME_LN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],PNAME_NS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"]},aggregate:{COUNT:["COUNT","(","?DISTINCT","or([*,expression])",")"],SUM:["SUM","(","?DISTINCT","expression",")"],MIN:["MIN","(","?DISTINCT","expression",")"],MAX:["MAX","(","?DISTINCT","expression",")"],AVG:["AVG","(","?DISTINCT","expression",")"],SAMPLE:["SAMPLE","(","?DISTINCT","expression",")"],GROUP_CONCAT:["GROUP_CONCAT","(","?DISTINCT","expression","?[;,SEPARATOR,=,string]",")"]},allowBnodes:{"}":[]},allowVars:{"}":[]},argList:{NIL:["NIL"],"(":["(","?DISTINCT","expression","*[,,expression]",")"]},askQuery:{ASK:["ASK","*datasetClause","whereClause","solutionModifier"]},baseDecl:{BASE:["BASE","IRI_REF"]},bind:{BIND:["BIND","(","expression","AS","var",")"]},blankNode:{BLANK_NODE_LABEL:["BLANK_NODE_LABEL"],ANON:["ANON"]},blankNodePropertyList:{"[":["[","propertyListNotEmpty","]"]},blankNodePropertyListPath:{"[":["[","propertyListPathNotEmpty","]"]},booleanLiteral:{TRUE:["TRUE"],FALSE:["FALSE"]},brackettedExpression:{"(":["(","expression",")"]},builtInCall:{STR:["STR","(","expression",")"],LANG:["LANG","(","expression",")"],LANGMATCHES:["LANGMATCHES","(","expression",",","expression",")"],DATATYPE:["DATATYPE","(","expression",")"],BOUND:["BOUND","(","var",")"],IRI:["IRI","(","expression",")"],URI:["URI","(","expression",")"],BNODE:["BNODE","or([[ (,expression,)],NIL])"],RAND:["RAND","NIL"],ABS:["ABS","(","expression",")"],CEIL:["CEIL","(","expression",")"],FLOOR:["FLOOR","(","expression",")"],ROUND:["ROUND","(","expression",")"],CONCAT:["CONCAT","expressionList"],SUBSTR:["substringExpression"],STRLEN:["STRLEN","(","expression",")"],REPLACE:["strReplaceExpression"],UCASE:["UCASE","(","expression",")"],LCASE:["LCASE","(","expression",")"],ENCODE_FOR_URI:["ENCODE_FOR_URI","(","expression",")"],CONTAINS:["CONTAINS","(","expression",",","expression",")"],STRSTARTS:["STRSTARTS","(","expression",",","expression",")"],STRENDS:["STRENDS","(","expression",",","expression",")"],STRBEFORE:["STRBEFORE","(","expression",",","expression",")"],STRAFTER:["STRAFTER","(","expression",",","expression",")"],YEAR:["YEAR","(","expression",")"],MONTH:["MONTH","(","expression",")"],DAY:["DAY","(","expression",")"],HOURS:["HOURS","(","expression",")"],MINUTES:["MINUTES","(","expression",")"],SECONDS:["SECONDS","(","expression",")"],TIMEZONE:["TIMEZONE","(","expression",")"],TZ:["TZ","(","expression",")"],NOW:["NOW","NIL"],UUID:["UUID","NIL"],STRUUID:["STRUUID","NIL"],MD5:["MD5","(","expression",")"],SHA1:["SHA1","(","expression",")"],SHA256:["SHA256","(","expression",")"],SHA384:["SHA384","(","expression",")"],SHA512:["SHA512","(","expression",")"],COALESCE:["COALESCE","expressionList"],IF:["IF","(","expression",",","expression",",","expression",")"],STRLANG:["STRLANG","(","expression",",","expression",")"],STRDT:["STRDT","(","expression",",","expression",")"],SAMETERM:["SAMETERM","(","expression",",","expression",")"],ISIRI:["ISIRI","(","expression",")"],ISURI:["ISURI","(","expression",")"],ISBLANK:["ISBLANK","(","expression",")"],ISLITERAL:["ISLITERAL","(","expression",")"],ISNUMERIC:["ISNUMERIC","(","expression",")"],REGEX:["regexExpression"],EXISTS:["existsFunc"],NOT:["notExistsFunc"]},clear:{CLEAR:["CLEAR","?SILENT_2","graphRefAll"]},collection:{"(":["(","+graphNode",")"]},collectionPath:{"(":["(","+graphNodePath",")"]},conditionalAndExpression:{"!":["valueLogical","*[&&,valueLogical]"],"+":["valueLogical","*[&&,valueLogical]"],"-":["valueLogical","*[&&,valueLogical]"],VAR1:["valueLogical","*[&&,valueLogical]"],VAR2:["valueLogical","*[&&,valueLogical]"],"(":["valueLogical","*[&&,valueLogical]"],STR:["valueLogical","*[&&,valueLogical]"],LANG:["valueLogical","*[&&,valueLogical]"],LANGMATCHES:["valueLogical","*[&&,valueLogical]"],DATATYPE:["valueLogical","*[&&,valueLogical]"],BOUND:["valueLogical","*[&&,valueLogical]"],IRI:["valueLogical","*[&&,valueLogical]"],URI:["valueLogical","*[&&,valueLogical]"],BNODE:["valueLogical","*[&&,valueLogical]"],RAND:["valueLogical","*[&&,valueLogical]"],ABS:["valueLogical","*[&&,valueLogical]"],CEIL:["valueLogical","*[&&,valueLogical]"],FLOOR:["valueLogical","*[&&,valueLogical]"],ROUND:["valueLogical","*[&&,valueLogical]"],CONCAT:["valueLogical","*[&&,valueLogical]"],STRLEN:["valueLogical","*[&&,valueLogical]"],UCASE:["valueLogical","*[&&,valueLogical]"],LCASE:["valueLogical","*[&&,valueLogical]"],ENCODE_FOR_URI:["valueLogical","*[&&,valueLogical]"],CONTAINS:["valueLogical","*[&&,valueLogical]"],STRSTARTS:["valueLogical","*[&&,valueLogical]"],STRENDS:["valueLogical","*[&&,valueLogical]"],STRBEFORE:["valueLogical","*[&&,valueLogical]"],STRAFTER:["valueLogical","*[&&,valueLogical]"],YEAR:["valueLogical","*[&&,valueLogical]"],MONTH:["valueLogical","*[&&,valueLogical]"],DAY:["valueLogical","*[&&,valueLogical]"],HOURS:["valueLogical","*[&&,valueLogical]"],MINUTES:["valueLogical","*[&&,valueLogical]"],SECONDS:["valueLogical","*[&&,valueLogical]"],TIMEZONE:["valueLogical","*[&&,valueLogical]"],TZ:["valueLogical","*[&&,valueLogical]"],NOW:["valueLogical","*[&&,valueLogical]"],UUID:["valueLogical","*[&&,valueLogical]"],STRUUID:["valueLogical","*[&&,valueLogical]"],MD5:["valueLogical","*[&&,valueLogical]"],SHA1:["valueLogical","*[&&,valueLogical]"],SHA256:["valueLogical","*[&&,valueLogical]"],SHA384:["valueLogical","*[&&,valueLogical]"],SHA512:["valueLogical","*[&&,valueLogical]"],COALESCE:["valueLogical","*[&&,valueLogical]"],IF:["valueLogical","*[&&,valueLogical]"],STRLANG:["valueLogical","*[&&,valueLogical]"],STRDT:["valueLogical","*[&&,valueLogical]"],SAMETERM:["valueLogical","*[&&,valueLogical]"],ISIRI:["valueLogical","*[&&,valueLogical]"],ISURI:["valueLogical","*[&&,valueLogical]"],ISBLANK:["valueLogical","*[&&,valueLogical]"],ISLITERAL:["valueLogical","*[&&,valueLogical]"],ISNUMERIC:["valueLogical","*[&&,valueLogical]"],TRUE:["valueLogical","*[&&,valueLogical]"],FALSE:["valueLogical","*[&&,valueLogical]"],COUNT:["valueLogical","*[&&,valueLogical]"],SUM:["valueLogical","*[&&,valueLogical]"],MIN:["valueLogical","*[&&,valueLogical]"],MAX:["valueLogical","*[&&,valueLogical]"],AVG:["valueLogical","*[&&,valueLogical]"],SAMPLE:["valueLogical","*[&&,valueLogical]"],GROUP_CONCAT:["valueLogical","*[&&,valueLogical]"],SUBSTR:["valueLogical","*[&&,valueLogical]"],REPLACE:["valueLogical","*[&&,valueLogical]"],REGEX:["valueLogical","*[&&,valueLogical]"],EXISTS:["valueLogical","*[&&,valueLogical]"],NOT:["valueLogical","*[&&,valueLogical]"],IRI_REF:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL1:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL2:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL_LONG1:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL_LONG2:["valueLogical","*[&&,valueLogical]"],INTEGER:["valueLogical","*[&&,valueLogical]"],DECIMAL:["valueLogical","*[&&,valueLogical]"],DOUBLE:["valueLogical","*[&&,valueLogical]"],INTEGER_POSITIVE:["valueLogical","*[&&,valueLogical]"],DECIMAL_POSITIVE:["valueLogical","*[&&,valueLogical]"],DOUBLE_POSITIVE:["valueLogical","*[&&,valueLogical]"],INTEGER_NEGATIVE:["valueLogical","*[&&,valueLogical]"],DECIMAL_NEGATIVE:["valueLogical","*[&&,valueLogical]"],DOUBLE_NEGATIVE:["valueLogical","*[&&,valueLogical]"],PNAME_LN:["valueLogical","*[&&,valueLogical]"],PNAME_NS:["valueLogical","*[&&,valueLogical]"]},conditionalOrExpression:{"!":["conditionalAndExpression","*[||,conditionalAndExpression]"],"+":["conditionalAndExpression","*[||,conditionalAndExpression]"],"-":["conditionalAndExpression","*[||,conditionalAndExpression]"],VAR1:["conditionalAndExpression","*[||,conditionalAndExpression]"],VAR2:["conditionalAndExpression","*[||,conditionalAndExpression]"],"(":["conditionalAndExpression","*[||,conditionalAndExpression]"],STR:["conditionalAndExpression","*[||,conditionalAndExpression]"],LANG:["conditionalAndExpression","*[||,conditionalAndExpression]"],LANGMATCHES:["conditionalAndExpression","*[||,conditionalAndExpression]"],DATATYPE:["conditionalAndExpression","*[||,conditionalAndExpression]"],BOUND:["conditionalAndExpression","*[||,conditionalAndExpression]"],IRI:["conditionalAndExpression","*[||,conditionalAndExpression]"],URI:["conditionalAndExpression","*[||,conditionalAndExpression]"],BNODE:["conditionalAndExpression","*[||,conditionalAndExpression]"],RAND:["conditionalAndExpression","*[||,conditionalAndExpression]"],ABS:["conditionalAndExpression","*[||,conditionalAndExpression]"],CEIL:["conditionalAndExpression","*[||,conditionalAndExpression]"],FLOOR:["conditionalAndExpression","*[||,conditionalAndExpression]"],ROUND:["conditionalAndExpression","*[||,conditionalAndExpression]"],CONCAT:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRLEN:["conditionalAndExpression","*[||,conditionalAndExpression]"],UCASE:["conditionalAndExpression","*[||,conditionalAndExpression]"],LCASE:["conditionalAndExpression","*[||,conditionalAndExpression]"],ENCODE_FOR_URI:["conditionalAndExpression","*[||,conditionalAndExpression]"],CONTAINS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRSTARTS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRENDS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRBEFORE:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRAFTER:["conditionalAndExpression","*[||,conditionalAndExpression]"],YEAR:["conditionalAndExpression","*[||,conditionalAndExpression]"],MONTH:["conditionalAndExpression","*[||,conditionalAndExpression]"],DAY:["conditionalAndExpression","*[||,conditionalAndExpression]"],HOURS:["conditionalAndExpression","*[||,conditionalAndExpression]"],MINUTES:["conditionalAndExpression","*[||,conditionalAndExpression]"],SECONDS:["conditionalAndExpression","*[||,conditionalAndExpression]"],TIMEZONE:["conditionalAndExpression","*[||,conditionalAndExpression]"],TZ:["conditionalAndExpression","*[||,conditionalAndExpression]"],NOW:["conditionalAndExpression","*[||,conditionalAndExpression]"],UUID:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRUUID:["conditionalAndExpression","*[||,conditionalAndExpression]"],MD5:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA1:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA256:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA384:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA512:["conditionalAndExpression","*[||,conditionalAndExpression]"],COALESCE:["conditionalAndExpression","*[||,conditionalAndExpression]"],IF:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRLANG:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRDT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SAMETERM:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISIRI:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISURI:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISBLANK:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISLITERAL:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISNUMERIC:["conditionalAndExpression","*[||,conditionalAndExpression]"],TRUE:["conditionalAndExpression","*[||,conditionalAndExpression]"],FALSE:["conditionalAndExpression","*[||,conditionalAndExpression]"],COUNT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SUM:["conditionalAndExpression","*[||,conditionalAndExpression]"],MIN:["conditionalAndExpression","*[||,conditionalAndExpression]"],MAX:["conditionalAndExpression","*[||,conditionalAndExpression]"],AVG:["conditionalAndExpression","*[||,conditionalAndExpression]"],SAMPLE:["conditionalAndExpression","*[||,conditionalAndExpression]"],GROUP_CONCAT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SUBSTR:["conditionalAndExpression","*[||,conditionalAndExpression]"],REPLACE:["conditionalAndExpression","*[||,conditionalAndExpression]"],REGEX:["conditionalAndExpression","*[||,conditionalAndExpression]"],EXISTS:["conditionalAndExpression","*[||,conditionalAndExpression]"],NOT:["conditionalAndExpression","*[||,conditionalAndExpression]"],IRI_REF:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL1:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL2:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL_LONG1:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL_LONG2:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],PNAME_LN:["conditionalAndExpression","*[||,conditionalAndExpression]"],PNAME_NS:["conditionalAndExpression","*[||,conditionalAndExpression]"]},constraint:{"(":["brackettedExpression"],STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["functionCall"],PNAME_LN:["functionCall"],PNAME_NS:["functionCall"]},constructQuery:{CONSTRUCT:["CONSTRUCT","or([[constructTemplate,*datasetClause,whereClause,solutionModifier],[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]])"]},constructTemplate:{"{":["{","?constructTriples","}"]},constructTriples:{VAR1:["triplesSameSubject","?[.,?constructTriples]"],VAR2:["triplesSameSubject","?[.,?constructTriples]"],NIL:["triplesSameSubject","?[.,?constructTriples]"],"(":["triplesSameSubject","?[.,?constructTriples]"],"[":["triplesSameSubject","?[.,?constructTriples]"],IRI_REF:["triplesSameSubject","?[.,?constructTriples]"],TRUE:["triplesSameSubject","?[.,?constructTriples]"],FALSE:["triplesSameSubject","?[.,?constructTriples]"],BLANK_NODE_LABEL:["triplesSameSubject","?[.,?constructTriples]"],ANON:["triplesSameSubject","?[.,?constructTriples]"],PNAME_LN:["triplesSameSubject","?[.,?constructTriples]"],PNAME_NS:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL1:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL2:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL_LONG1:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL_LONG2:["triplesSameSubject","?[.,?constructTriples]"],INTEGER:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE:["triplesSameSubject","?[.,?constructTriples]"],INTEGER_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],INTEGER_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"]},copy:{COPY:["COPY","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},create:{CREATE:["CREATE","?SILENT_3","graphRef"]},dataBlock:{NIL:["or([inlineDataOneVar,inlineDataFull])"],"(":["or([inlineDataOneVar,inlineDataFull])"],VAR1:["or([inlineDataOneVar,inlineDataFull])"],VAR2:["or([inlineDataOneVar,inlineDataFull])"]},dataBlockValue:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],UNDEF:["UNDEF"]},datasetClause:{FROM:["FROM","or([defaultGraphClause,namedGraphClause])"]},defaultGraphClause:{IRI_REF:["sourceSelector"],PNAME_LN:["sourceSelector"],PNAME_NS:["sourceSelector"]},delete1:{DATA:["DATA","quadDataNoBnodes"],WHERE:["WHERE","quadPatternNoBnodes"],"{":["quadPatternNoBnodes","?insertClause","*usingClause","WHERE","groupGraphPattern"]},deleteClause:{DELETE:["DELETE","quadPattern"]},describeDatasetClause:{FROM:["FROM","or([defaultGraphClause,namedGraphClause])"]},describeQuery:{DESCRIBE:["DESCRIBE","or([+varOrIRIref,*])","*describeDatasetClause","?whereClause","solutionModifier"]},disallowBnodes:{"}":[],GRAPH:[],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},disallowVars:{"}":[],GRAPH:[],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},drop:{DROP:["DROP","?SILENT_2","graphRefAll"]},existsFunc:{EXISTS:["EXISTS","groupGraphPattern"]},expression:{"!":["conditionalOrExpression"],"+":["conditionalOrExpression"],"-":["conditionalOrExpression"],VAR1:["conditionalOrExpression"],VAR2:["conditionalOrExpression"],"(":["conditionalOrExpression"],STR:["conditionalOrExpression"],LANG:["conditionalOrExpression"],LANGMATCHES:["conditionalOrExpression"],DATATYPE:["conditionalOrExpression"],BOUND:["conditionalOrExpression"],IRI:["conditionalOrExpression"],URI:["conditionalOrExpression"],BNODE:["conditionalOrExpression"],RAND:["conditionalOrExpression"],ABS:["conditionalOrExpression"],CEIL:["conditionalOrExpression"],FLOOR:["conditionalOrExpression"],ROUND:["conditionalOrExpression"],CONCAT:["conditionalOrExpression"],STRLEN:["conditionalOrExpression"],UCASE:["conditionalOrExpression"],LCASE:["conditionalOrExpression"],ENCODE_FOR_URI:["conditionalOrExpression"],CONTAINS:["conditionalOrExpression"],STRSTARTS:["conditionalOrExpression"],STRENDS:["conditionalOrExpression"],STRBEFORE:["conditionalOrExpression"],STRAFTER:["conditionalOrExpression"],YEAR:["conditionalOrExpression"],MONTH:["conditionalOrExpression"],DAY:["conditionalOrExpression"],HOURS:["conditionalOrExpression"],MINUTES:["conditionalOrExpression"],SECONDS:["conditionalOrExpression"],TIMEZONE:["conditionalOrExpression"],TZ:["conditionalOrExpression"],NOW:["conditionalOrExpression"],UUID:["conditionalOrExpression"],STRUUID:["conditionalOrExpression"],MD5:["conditionalOrExpression"],SHA1:["conditionalOrExpression"],SHA256:["conditionalOrExpression"],SHA384:["conditionalOrExpression"],SHA512:["conditionalOrExpression"],COALESCE:["conditionalOrExpression"],IF:["conditionalOrExpression"],STRLANG:["conditionalOrExpression"],STRDT:["conditionalOrExpression"],SAMETERM:["conditionalOrExpression"],ISIRI:["conditionalOrExpression"],ISURI:["conditionalOrExpression"],ISBLANK:["conditionalOrExpression"],ISLITERAL:["conditionalOrExpression"],ISNUMERIC:["conditionalOrExpression"],TRUE:["conditionalOrExpression"],FALSE:["conditionalOrExpression"],COUNT:["conditionalOrExpression"],SUM:["conditionalOrExpression"],MIN:["conditionalOrExpression"],MAX:["conditionalOrExpression"],AVG:["conditionalOrExpression"],SAMPLE:["conditionalOrExpression"],GROUP_CONCAT:["conditionalOrExpression"],SUBSTR:["conditionalOrExpression"],REPLACE:["conditionalOrExpression"],REGEX:["conditionalOrExpression"],EXISTS:["conditionalOrExpression"],NOT:["conditionalOrExpression"],IRI_REF:["conditionalOrExpression"],STRING_LITERAL1:["conditionalOrExpression"],STRING_LITERAL2:["conditionalOrExpression"],STRING_LITERAL_LONG1:["conditionalOrExpression"],STRING_LITERAL_LONG2:["conditionalOrExpression"],INTEGER:["conditionalOrExpression"],DECIMAL:["conditionalOrExpression"],DOUBLE:["conditionalOrExpression"],INTEGER_POSITIVE:["conditionalOrExpression"],DECIMAL_POSITIVE:["conditionalOrExpression"],DOUBLE_POSITIVE:["conditionalOrExpression"],INTEGER_NEGATIVE:["conditionalOrExpression"],DECIMAL_NEGATIVE:["conditionalOrExpression"],DOUBLE_NEGATIVE:["conditionalOrExpression"],PNAME_LN:["conditionalOrExpression"],PNAME_NS:["conditionalOrExpression"]},expressionList:{NIL:["NIL"],"(":["(","expression","*[,,expression]",")"]},filter:{FILTER:["FILTER","constraint"]},functionCall:{IRI_REF:["iriRef","argList"],PNAME_LN:["iriRef","argList"],PNAME_NS:["iriRef","argList"]},graphGraphPattern:{GRAPH:["GRAPH","varOrIRIref","groupGraphPattern"]},graphNode:{VAR1:["varOrTerm"],VAR2:["varOrTerm"],NIL:["varOrTerm"],IRI_REF:["varOrTerm"],TRUE:["varOrTerm"],FALSE:["varOrTerm"],BLANK_NODE_LABEL:["varOrTerm"],ANON:["varOrTerm"],PNAME_LN:["varOrTerm"],PNAME_NS:["varOrTerm"],STRING_LITERAL1:["varOrTerm"],STRING_LITERAL2:["varOrTerm"],STRING_LITERAL_LONG1:["varOrTerm"],STRING_LITERAL_LONG2:["varOrTerm"],INTEGER:["varOrTerm"],DECIMAL:["varOrTerm"],DOUBLE:["varOrTerm"],INTEGER_POSITIVE:["varOrTerm"],DECIMAL_POSITIVE:["varOrTerm"],DOUBLE_POSITIVE:["varOrTerm"],INTEGER_NEGATIVE:["varOrTerm"],DECIMAL_NEGATIVE:["varOrTerm"],DOUBLE_NEGATIVE:["varOrTerm"],"(":["triplesNode"],"[":["triplesNode"]},graphNodePath:{VAR1:["varOrTerm"],VAR2:["varOrTerm"],NIL:["varOrTerm"],IRI_REF:["varOrTerm"],TRUE:["varOrTerm"],FALSE:["varOrTerm"],BLANK_NODE_LABEL:["varOrTerm"],ANON:["varOrTerm"],PNAME_LN:["varOrTerm"],PNAME_NS:["varOrTerm"],STRING_LITERAL1:["varOrTerm"],STRING_LITERAL2:["varOrTerm"],STRING_LITERAL_LONG1:["varOrTerm"],STRING_LITERAL_LONG2:["varOrTerm"],INTEGER:["varOrTerm"],DECIMAL:["varOrTerm"],DOUBLE:["varOrTerm"],INTEGER_POSITIVE:["varOrTerm"],DECIMAL_POSITIVE:["varOrTerm"],DOUBLE_POSITIVE:["varOrTerm"],INTEGER_NEGATIVE:["varOrTerm"],DECIMAL_NEGATIVE:["varOrTerm"],DOUBLE_NEGATIVE:["varOrTerm"],"(":["triplesNodePath"],"[":["triplesNodePath"]},graphOrDefault:{DEFAULT:["DEFAULT"],IRI_REF:["?GRAPH","iriRef"],PNAME_LN:["?GRAPH","iriRef"],PNAME_NS:["?GRAPH","iriRef"],GRAPH:["?GRAPH","iriRef"]},graphPatternNotTriples:{"{":["groupOrUnionGraphPattern"],OPTIONAL:["optionalGraphPattern"],MINUS:["minusGraphPattern"],GRAPH:["graphGraphPattern"],SERVICE:["serviceGraphPattern"],FILTER:["filter"],BIND:["bind"],VALUES:["inlineData"]},graphRef:{GRAPH:["GRAPH","iriRef"]},graphRefAll:{GRAPH:["graphRef"],DEFAULT:["DEFAULT"],NAMED:["NAMED"],ALL:["ALL"]},graphTerm:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],BLANK_NODE_LABEL:["blankNode"],ANON:["blankNode"],NIL:["NIL"]},groupClause:{GROUP:["GROUP","BY","+groupCondition"]},groupCondition:{STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["functionCall"],PNAME_LN:["functionCall"],PNAME_NS:["functionCall"],"(":["(","expression","?[AS,var]",")"],VAR1:["var"],VAR2:["var"]},groupGraphPattern:{"{":["{","or([subSelect,groupGraphPatternSub])","}"]},groupGraphPatternSub:{"{":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],OPTIONAL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],MINUS:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],GRAPH:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],SERVICE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],FILTER:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],BIND:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VALUES:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VAR1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VAR2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],NIL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"(":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"[":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],IRI_REF:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],TRUE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],FALSE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],BLANK_NODE_LABEL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],ANON:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],PNAME_LN:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],PNAME_NS:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL_LONG1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL_LONG2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"}":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"]},groupOrUnionGraphPattern:{"{":["groupGraphPattern","*[UNION,groupGraphPattern]"]},havingClause:{HAVING:["HAVING","+havingCondition"]},havingCondition:{"(":["constraint"],STR:["constraint"],LANG:["constraint"],LANGMATCHES:["constraint"],DATATYPE:["constraint"],BOUND:["constraint"],IRI:["constraint"],URI:["constraint"],BNODE:["constraint"],RAND:["constraint"],ABS:["constraint"],CEIL:["constraint"],FLOOR:["constraint"],ROUND:["constraint"],CONCAT:["constraint"],STRLEN:["constraint"],UCASE:["constraint"],LCASE:["constraint"],ENCODE_FOR_URI:["constraint"],CONTAINS:["constraint"],STRSTARTS:["constraint"],STRENDS:["constraint"],STRBEFORE:["constraint"],STRAFTER:["constraint"],YEAR:["constraint"],MONTH:["constraint"],DAY:["constraint"],HOURS:["constraint"],MINUTES:["constraint"],SECONDS:["constraint"],TIMEZONE:["constraint"],TZ:["constraint"],NOW:["constraint"],UUID:["constraint"],STRUUID:["constraint"],MD5:["constraint"],SHA1:["constraint"],SHA256:["constraint"],SHA384:["constraint"],SHA512:["constraint"],COALESCE:["constraint"],IF:["constraint"],STRLANG:["constraint"],STRDT:["constraint"],SAMETERM:["constraint"],ISIRI:["constraint"],ISURI:["constraint"],ISBLANK:["constraint"],ISLITERAL:["constraint"],ISNUMERIC:["constraint"],SUBSTR:["constraint"],REPLACE:["constraint"],REGEX:["constraint"],EXISTS:["constraint"],NOT:["constraint"],IRI_REF:["constraint"],PNAME_LN:["constraint"],PNAME_NS:["constraint"]},inlineData:{VALUES:["VALUES","dataBlock"]},inlineDataFull:{NIL:["or([NIL,[ (,*var,)]])","{","*or([[ (,*dataBlockValue,)],NIL])","}"],"(":["or([NIL,[ (,*var,)]])","{","*or([[ (,*dataBlockValue,)],NIL])","}"]},inlineDataOneVar:{VAR1:["var","{","*dataBlockValue","}"],VAR2:["var","{","*dataBlockValue","}"]},insert1:{DATA:["DATA","quadData"],"{":["quadPattern","*usingClause","WHERE","groupGraphPattern"]},insertClause:{INSERT:["INSERT","quadPattern"]},integer:{INTEGER:["INTEGER"]},iriRef:{IRI_REF:["IRI_REF"],PNAME_LN:["prefixedName"],PNAME_NS:["prefixedName"]},iriRefOrFunction:{IRI_REF:["iriRef","?argList"],PNAME_LN:["iriRef","?argList"],PNAME_NS:["iriRef","?argList"]},limitClause:{LIMIT:["LIMIT","INTEGER"]},limitOffsetClauses:{LIMIT:["limitClause","?offsetClause"],OFFSET:["offsetClause","?limitClause"]},load:{LOAD:["LOAD","?SILENT_1","iriRef","?[INTO,graphRef]"]},minusGraphPattern:{MINUS:["MINUS","groupGraphPattern"]},modify:{WITH:["WITH","iriRef","or([[deleteClause,?insertClause],insertClause])","*usingClause","WHERE","groupGraphPattern"]},move:{MOVE:["MOVE","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},multiplicativeExpression:{"!":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"+":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"-":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],VAR1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],VAR2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"(":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LANG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LANGMATCHES:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DATATYPE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],BOUND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IRI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],URI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],BNODE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],RAND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ABS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CEIL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],FLOOR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ROUND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CONCAT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRLEN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],UCASE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LCASE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ENCODE_FOR_URI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CONTAINS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRSTARTS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRENDS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRBEFORE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRAFTER:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],YEAR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MONTH:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DAY:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],HOURS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MINUTES:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SECONDS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TIMEZONE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TZ:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],NOW:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],UUID:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRUUID:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MD5:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA256:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA384:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA512:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],COALESCE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IF:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRLANG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRDT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SAMETERM:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISIRI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISURI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISBLANK:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISLITERAL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISNUMERIC:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TRUE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],FALSE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],COUNT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SUM:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MIN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MAX:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],AVG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SAMPLE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],GROUP_CONCAT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SUBSTR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],REPLACE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],REGEX:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],EXISTS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],NOT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IRI_REF:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL_LONG1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL_LONG2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],PNAME_LN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],PNAME_NS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"]},namedGraphClause:{NAMED:["NAMED","sourceSelector"]},notExistsFunc:{NOT:["NOT","EXISTS","groupGraphPattern"]},numericExpression:{"!":["additiveExpression"],"+":["additiveExpression"],"-":["additiveExpression"],VAR1:["additiveExpression"],VAR2:["additiveExpression"],"(":["additiveExpression"],STR:["additiveExpression"],LANG:["additiveExpression"],LANGMATCHES:["additiveExpression"],DATATYPE:["additiveExpression"],BOUND:["additiveExpression"],IRI:["additiveExpression"],URI:["additiveExpression"],BNODE:["additiveExpression"],RAND:["additiveExpression"],ABS:["additiveExpression"],CEIL:["additiveExpression"],FLOOR:["additiveExpression"],ROUND:["additiveExpression"],CONCAT:["additiveExpression"],STRLEN:["additiveExpression"],UCASE:["additiveExpression"],LCASE:["additiveExpression"],ENCODE_FOR_URI:["additiveExpression"],CONTAINS:["additiveExpression"],STRSTARTS:["additiveExpression"],STRENDS:["additiveExpression"],STRBEFORE:["additiveExpression"],STRAFTER:["additiveExpression"],YEAR:["additiveExpression"],MONTH:["additiveExpression"],DAY:["additiveExpression"],HOURS:["additiveExpression"],MINUTES:["additiveExpression"],SECONDS:["additiveExpression"],TIMEZONE:["additiveExpression"],TZ:["additiveExpression"],NOW:["additiveExpression"],UUID:["additiveExpression"],STRUUID:["additiveExpression"],MD5:["additiveExpression"],SHA1:["additiveExpression"],SHA256:["additiveExpression"],SHA384:["additiveExpression"],SHA512:["additiveExpression"],COALESCE:["additiveExpression"],IF:["additiveExpression"],STRLANG:["additiveExpression"],STRDT:["additiveExpression"],SAMETERM:["additiveExpression"],ISIRI:["additiveExpression"],ISURI:["additiveExpression"],ISBLANK:["additiveExpression"],ISLITERAL:["additiveExpression"],ISNUMERIC:["additiveExpression"],TRUE:["additiveExpression"],FALSE:["additiveExpression"],COUNT:["additiveExpression"],SUM:["additiveExpression"],MIN:["additiveExpression"],MAX:["additiveExpression"],AVG:["additiveExpression"],SAMPLE:["additiveExpression"],GROUP_CONCAT:["additiveExpression"],SUBSTR:["additiveExpression"],REPLACE:["additiveExpression"],REGEX:["additiveExpression"],EXISTS:["additiveExpression"],NOT:["additiveExpression"],IRI_REF:["additiveExpression"],STRING_LITERAL1:["additiveExpression"],STRING_LITERAL2:["additiveExpression"],STRING_LITERAL_LONG1:["additiveExpression"],STRING_LITERAL_LONG2:["additiveExpression"],INTEGER:["additiveExpression"],DECIMAL:["additiveExpression"],DOUBLE:["additiveExpression"],INTEGER_POSITIVE:["additiveExpression"],DECIMAL_POSITIVE:["additiveExpression"],DOUBLE_POSITIVE:["additiveExpression"],INTEGER_NEGATIVE:["additiveExpression"],DECIMAL_NEGATIVE:["additiveExpression"],DOUBLE_NEGATIVE:["additiveExpression"],PNAME_LN:["additiveExpression"],PNAME_NS:["additiveExpression"]},numericLiteral:{INTEGER:["numericLiteralUnsigned"],DECIMAL:["numericLiteralUnsigned"],DOUBLE:["numericLiteralUnsigned"],INTEGER_POSITIVE:["numericLiteralPositive"],DECIMAL_POSITIVE:["numericLiteralPositive"],DOUBLE_POSITIVE:["numericLiteralPositive"],INTEGER_NEGATIVE:["numericLiteralNegative"],DECIMAL_NEGATIVE:["numericLiteralNegative"],DOUBLE_NEGATIVE:["numericLiteralNegative"]},numericLiteralNegative:{INTEGER_NEGATIVE:["INTEGER_NEGATIVE"],DECIMAL_NEGATIVE:["DECIMAL_NEGATIVE"],DOUBLE_NEGATIVE:["DOUBLE_NEGATIVE"]},numericLiteralPositive:{INTEGER_POSITIVE:["INTEGER_POSITIVE"],DECIMAL_POSITIVE:["DECIMAL_POSITIVE"],DOUBLE_POSITIVE:["DOUBLE_POSITIVE"]},numericLiteralUnsigned:{INTEGER:["INTEGER"],DECIMAL:["DECIMAL"],DOUBLE:["DOUBLE"]},object:{"(":["graphNode"],"[":["graphNode"],VAR1:["graphNode"],VAR2:["graphNode"],NIL:["graphNode"],IRI_REF:["graphNode"],TRUE:["graphNode"],FALSE:["graphNode"],BLANK_NODE_LABEL:["graphNode"],ANON:["graphNode"],PNAME_LN:["graphNode"],PNAME_NS:["graphNode"],STRING_LITERAL1:["graphNode"],STRING_LITERAL2:["graphNode"],STRING_LITERAL_LONG1:["graphNode"],STRING_LITERAL_LONG2:["graphNode"],INTEGER:["graphNode"],DECIMAL:["graphNode"],DOUBLE:["graphNode"],INTEGER_POSITIVE:["graphNode"],DECIMAL_POSITIVE:["graphNode"],DOUBLE_POSITIVE:["graphNode"],INTEGER_NEGATIVE:["graphNode"],DECIMAL_NEGATIVE:["graphNode"],DOUBLE_NEGATIVE:["graphNode"]},objectList:{"(":["object","*[,,object]"],"[":["object","*[,,object]"],VAR1:["object","*[,,object]"],VAR2:["object","*[,,object]"],NIL:["object","*[,,object]"],IRI_REF:["object","*[,,object]"],TRUE:["object","*[,,object]"],FALSE:["object","*[,,object]"],BLANK_NODE_LABEL:["object","*[,,object]"],ANON:["object","*[,,object]"],PNAME_LN:["object","*[,,object]"],PNAME_NS:["object","*[,,object]"],STRING_LITERAL1:["object","*[,,object]"],STRING_LITERAL2:["object","*[,,object]"],STRING_LITERAL_LONG1:["object","*[,,object]"],STRING_LITERAL_LONG2:["object","*[,,object]"],INTEGER:["object","*[,,object]"],DECIMAL:["object","*[,,object]"],DOUBLE:["object","*[,,object]"],INTEGER_POSITIVE:["object","*[,,object]"],DECIMAL_POSITIVE:["object","*[,,object]"],DOUBLE_POSITIVE:["object","*[,,object]"],INTEGER_NEGATIVE:["object","*[,,object]"],DECIMAL_NEGATIVE:["object","*[,,object]"],DOUBLE_NEGATIVE:["object","*[,,object]"]},objectListPath:{"(":["objectPath","*[,,objectPath]"],"[":["objectPath","*[,,objectPath]"],VAR1:["objectPath","*[,,objectPath]"],VAR2:["objectPath","*[,,objectPath]"],NIL:["objectPath","*[,,objectPath]"],IRI_REF:["objectPath","*[,,objectPath]"],TRUE:["objectPath","*[,,objectPath]"],FALSE:["objectPath","*[,,objectPath]"],BLANK_NODE_LABEL:["objectPath","*[,,objectPath]"],ANON:["objectPath","*[,,objectPath]"],PNAME_LN:["objectPath","*[,,objectPath]"],PNAME_NS:["objectPath","*[,,objectPath]"],STRING_LITERAL1:["objectPath","*[,,objectPath]"],STRING_LITERAL2:["objectPath","*[,,objectPath]"],STRING_LITERAL_LONG1:["objectPath","*[,,objectPath]"],STRING_LITERAL_LONG2:["objectPath","*[,,objectPath]"],INTEGER:["objectPath","*[,,objectPath]"],DECIMAL:["objectPath","*[,,objectPath]"],DOUBLE:["objectPath","*[,,objectPath]"],INTEGER_POSITIVE:["objectPath","*[,,objectPath]"],DECIMAL_POSITIVE:["objectPath","*[,,objectPath]"],DOUBLE_POSITIVE:["objectPath","*[,,objectPath]"],INTEGER_NEGATIVE:["objectPath","*[,,objectPath]"],DECIMAL_NEGATIVE:["objectPath","*[,,objectPath]"],DOUBLE_NEGATIVE:["objectPath","*[,,objectPath]"]},objectPath:{"(":["graphNodePath"],"[":["graphNodePath"],VAR1:["graphNodePath"],VAR2:["graphNodePath"],NIL:["graphNodePath"],IRI_REF:["graphNodePath"],TRUE:["graphNodePath"],FALSE:["graphNodePath"],BLANK_NODE_LABEL:["graphNodePath"],ANON:["graphNodePath"],PNAME_LN:["graphNodePath"],PNAME_NS:["graphNodePath"],STRING_LITERAL1:["graphNodePath"],STRING_LITERAL2:["graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath"],INTEGER:["graphNodePath"],DECIMAL:["graphNodePath"],DOUBLE:["graphNodePath"],INTEGER_POSITIVE:["graphNodePath"],DECIMAL_POSITIVE:["graphNodePath"],DOUBLE_POSITIVE:["graphNodePath"],INTEGER_NEGATIVE:["graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath"]},offsetClause:{OFFSET:["OFFSET","INTEGER"]},optionalGraphPattern:{OPTIONAL:["OPTIONAL","groupGraphPattern"]},"or([*,expression])":{"*":["*"],"!":["expression"],"+":["expression"],"-":["expression"],VAR1:["expression"],VAR2:["expression"],"(":["expression"],STR:["expression"],LANG:["expression"],LANGMATCHES:["expression"],DATATYPE:["expression"],BOUND:["expression"],IRI:["expression"],URI:["expression"],BNODE:["expression"],RAND:["expression"],ABS:["expression"],CEIL:["expression"],FLOOR:["expression"],ROUND:["expression"],CONCAT:["expression"],STRLEN:["expression"],UCASE:["expression"],LCASE:["expression"],ENCODE_FOR_URI:["expression"],CONTAINS:["expression"],STRSTARTS:["expression"],STRENDS:["expression"],STRBEFORE:["expression"],STRAFTER:["expression"],YEAR:["expression"],MONTH:["expression"],DAY:["expression"],HOURS:["expression"],MINUTES:["expression"],SECONDS:["expression"],TIMEZONE:["expression"],TZ:["expression"],NOW:["expression"],UUID:["expression"],STRUUID:["expression"],MD5:["expression"],SHA1:["expression"],SHA256:["expression"],SHA384:["expression"],SHA512:["expression"],COALESCE:["expression"],IF:["expression"],STRLANG:["expression"],STRDT:["expression"],SAMETERM:["expression"],ISIRI:["expression"],ISURI:["expression"],ISBLANK:["expression"],ISLITERAL:["expression"],ISNUMERIC:["expression"],TRUE:["expression"],FALSE:["expression"],COUNT:["expression"],SUM:["expression"],MIN:["expression"],MAX:["expression"],AVG:["expression"],SAMPLE:["expression"],GROUP_CONCAT:["expression"],SUBSTR:["expression"],REPLACE:["expression"],REGEX:["expression"],EXISTS:["expression"],NOT:["expression"],IRI_REF:["expression"],STRING_LITERAL1:["expression"],STRING_LITERAL2:["expression"],STRING_LITERAL_LONG1:["expression"],STRING_LITERAL_LONG2:["expression"],INTEGER:["expression"],DECIMAL:["expression"],DOUBLE:["expression"],INTEGER_POSITIVE:["expression"],DECIMAL_POSITIVE:["expression"],DOUBLE_POSITIVE:["expression"],INTEGER_NEGATIVE:["expression"],DECIMAL_NEGATIVE:["expression"],DOUBLE_NEGATIVE:["expression"],PNAME_LN:["expression"],PNAME_NS:["expression"]},"or([+or([var,[ (,expression,AS,var,)]]),*])":{"(":["+or([var,[ (,expression,AS,var,)]])"],VAR1:["+or([var,[ (,expression,AS,var,)]])"],VAR2:["+or([var,[ (,expression,AS,var,)]])"],"*":["*"]},"or([+varOrIRIref,*])":{VAR1:["+varOrIRIref"],VAR2:["+varOrIRIref"],IRI_REF:["+varOrIRIref"],PNAME_LN:["+varOrIRIref"],PNAME_NS:["+varOrIRIref"],"*":["*"]},"or([ASC,DESC])":{ASC:["ASC"],DESC:["DESC"]},"or([DISTINCT,REDUCED])":{DISTINCT:["DISTINCT"],REDUCED:["REDUCED"]},"or([LANGTAG,[^^,iriRef]])":{LANGTAG:["LANGTAG"],"^^":["[^^,iriRef]"]},"or([NIL,[ (,*var,)]])":{NIL:["NIL"],"(":["[ (,*var,)]"]},"or([[ (,*dataBlockValue,)],NIL])":{"(":["[ (,*dataBlockValue,)]"],NIL:["NIL"]},"or([[ (,expression,)],NIL])":{"(":["[ (,expression,)]"],NIL:["NIL"]},"or([[*,unaryExpression],[/,unaryExpression]])":{"*":["[*,unaryExpression]"],"/":["[/,unaryExpression]"]},"or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])":{"+":["[+,multiplicativeExpression]"],"-":["[-,multiplicativeExpression]"],INTEGER_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DECIMAL_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DOUBLE_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],INTEGER_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DECIMAL_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DOUBLE_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"]},"or([[,,or([},[integer,}]])],}])":{",":["[,,or([},[integer,}]])]"],"}":["}"]},"or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])":{"=":["[=,numericExpression]"],"!=":["[!=,numericExpression]"],"<":["[<,numericExpression]"],">":["[>,numericExpression]"],"<=":["[<=,numericExpression]"],">=":["[>=,numericExpression]"],IN:["[IN,expressionList]"],NOT:["[NOT,IN,expressionList]"]},"or([[constructTemplate,*datasetClause,whereClause,solutionModifier],[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]])":{"{":["[constructTemplate,*datasetClause,whereClause,solutionModifier]"],WHERE:["[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]"],FROM:["[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]"]},"or([[deleteClause,?insertClause],insertClause])":{DELETE:["[deleteClause,?insertClause]"],INSERT:["insertClause"]},"or([[integer,or([[,,or([},[integer,}]])],}])],[,,integer,}]])":{INTEGER:["[integer,or([[,,or([},[integer,}]])],}])]"],",":["[,,integer,}]"]},"or([defaultGraphClause,namedGraphClause])":{IRI_REF:["defaultGraphClause"],PNAME_LN:["defaultGraphClause"],PNAME_NS:["defaultGraphClause"],NAMED:["namedGraphClause"]},"or([inlineDataOneVar,inlineDataFull])":{VAR1:["inlineDataOneVar"],VAR2:["inlineDataOneVar"],NIL:["inlineDataFull"],"(":["inlineDataFull"]},"or([iriRef,[NAMED,iriRef]])":{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],NAMED:["[NAMED,iriRef]"]},"or([iriRef,a])":{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],a:["a"]},"or([numericLiteralPositive,numericLiteralNegative])":{INTEGER_POSITIVE:["numericLiteralPositive"],DECIMAL_POSITIVE:["numericLiteralPositive"],DOUBLE_POSITIVE:["numericLiteralPositive"],INTEGER_NEGATIVE:["numericLiteralNegative"],DECIMAL_NEGATIVE:["numericLiteralNegative"],DOUBLE_NEGATIVE:["numericLiteralNegative"]},"or([queryAll,updateAll])":{CONSTRUCT:["queryAll"],DESCRIBE:["queryAll"],ASK:["queryAll"],SELECT:["queryAll"],INSERT:["updateAll"],DELETE:["updateAll"],LOAD:["updateAll"],CLEAR:["updateAll"],DROP:["updateAll"],ADD:["updateAll"],MOVE:["updateAll"],COPY:["updateAll"],CREATE:["updateAll"],WITH:["updateAll"],$:["updateAll"]},"or([selectQuery,constructQuery,describeQuery,askQuery])":{SELECT:["selectQuery"],CONSTRUCT:["constructQuery"],DESCRIBE:["describeQuery"],ASK:["askQuery"]},"or([subSelect,groupGraphPatternSub])":{SELECT:["subSelect"],"{":["groupGraphPatternSub"],OPTIONAL:["groupGraphPatternSub"],MINUS:["groupGraphPatternSub"],GRAPH:["groupGraphPatternSub"],SERVICE:["groupGraphPatternSub"],FILTER:["groupGraphPatternSub"],BIND:["groupGraphPatternSub"],VALUES:["groupGraphPatternSub"],VAR1:["groupGraphPatternSub"],VAR2:["groupGraphPatternSub"],NIL:["groupGraphPatternSub"],"(":["groupGraphPatternSub"],"[":["groupGraphPatternSub"],IRI_REF:["groupGraphPatternSub"],TRUE:["groupGraphPatternSub"],FALSE:["groupGraphPatternSub"],BLANK_NODE_LABEL:["groupGraphPatternSub"],ANON:["groupGraphPatternSub"],PNAME_LN:["groupGraphPatternSub"],PNAME_NS:["groupGraphPatternSub"],STRING_LITERAL1:["groupGraphPatternSub"],STRING_LITERAL2:["groupGraphPatternSub"],STRING_LITERAL_LONG1:["groupGraphPatternSub"],STRING_LITERAL_LONG2:["groupGraphPatternSub"],INTEGER:["groupGraphPatternSub"],DECIMAL:["groupGraphPatternSub"],DOUBLE:["groupGraphPatternSub"],INTEGER_POSITIVE:["groupGraphPatternSub"],DECIMAL_POSITIVE:["groupGraphPatternSub"],DOUBLE_POSITIVE:["groupGraphPatternSub"],INTEGER_NEGATIVE:["groupGraphPatternSub"],DECIMAL_NEGATIVE:["groupGraphPatternSub"],DOUBLE_NEGATIVE:["groupGraphPatternSub"],"}":["groupGraphPatternSub"]},"or([var,[ (,expression,AS,var,)]])":{VAR1:["var"],VAR2:["var"],"(":["[ (,expression,AS,var,)]"]},"or([verbPath,verbSimple])":{"^":["verbPath"],a:["verbPath"],"!":["verbPath"],"(":["verbPath"],IRI_REF:["verbPath"],PNAME_LN:["verbPath"],PNAME_NS:["verbPath"],VAR1:["verbSimple"],VAR2:["verbSimple"]},"or([},[integer,}]])":{"}":["}"],INTEGER:["[integer,}]"]},orderClause:{ORDER:["ORDER","BY","+orderCondition"]},orderCondition:{ASC:["or([ASC,DESC])","brackettedExpression"],DESC:["or([ASC,DESC])","brackettedExpression"],"(":["constraint"],STR:["constraint"],LANG:["constraint"],LANGMATCHES:["constraint"],DATATYPE:["constraint"],BOUND:["constraint"],IRI:["constraint"],URI:["constraint"],BNODE:["constraint"],RAND:["constraint"],ABS:["constraint"],CEIL:["constraint"],FLOOR:["constraint"],ROUND:["constraint"],CONCAT:["constraint"],STRLEN:["constraint"],UCASE:["constraint"],LCASE:["constraint"],ENCODE_FOR_URI:["constraint"],CONTAINS:["constraint"],STRSTARTS:["constraint"],STRENDS:["constraint"],STRBEFORE:["constraint"],STRAFTER:["constraint"],YEAR:["constraint"],MONTH:["constraint"],DAY:["constraint"],HOURS:["constraint"],MINUTES:["constraint"],SECONDS:["constraint"],TIMEZONE:["constraint"],TZ:["constraint"],NOW:["constraint"],UUID:["constraint"],STRUUID:["constraint"],MD5:["constraint"],SHA1:["constraint"],SHA256:["constraint"],SHA384:["constraint"],SHA512:["constraint"],COALESCE:["constraint"],IF:["constraint"],STRLANG:["constraint"],STRDT:["constraint"],SAMETERM:["constraint"],ISIRI:["constraint"],ISURI:["constraint"],ISBLANK:["constraint"],ISLITERAL:["constraint"],ISNUMERIC:["constraint"],SUBSTR:["constraint"],REPLACE:["constraint"],REGEX:["constraint"],EXISTS:["constraint"],NOT:["constraint"],IRI_REF:["constraint"],PNAME_LN:["constraint"],PNAME_NS:["constraint"],VAR1:["var"],VAR2:["var"]},path:{"^":["pathAlternative"],a:["pathAlternative"],"!":["pathAlternative"],"(":["pathAlternative"],IRI_REF:["pathAlternative"],PNAME_LN:["pathAlternative"],PNAME_NS:["pathAlternative"]},pathAlternative:{"^":["pathSequence","*[|,pathSequence]"],a:["pathSequence","*[|,pathSequence]"],"!":["pathSequence","*[|,pathSequence]"],"(":["pathSequence","*[|,pathSequence]"],IRI_REF:["pathSequence","*[|,pathSequence]"],PNAME_LN:["pathSequence","*[|,pathSequence]"],PNAME_NS:["pathSequence","*[|,pathSequence]"]},pathElt:{a:["pathPrimary","?pathMod"],"!":["pathPrimary","?pathMod"],"(":["pathPrimary","?pathMod"],IRI_REF:["pathPrimary","?pathMod"],PNAME_LN:["pathPrimary","?pathMod"],PNAME_NS:["pathPrimary","?pathMod"]},pathEltOrInverse:{a:["pathElt"],"!":["pathElt"],"(":["pathElt"],IRI_REF:["pathElt"],PNAME_LN:["pathElt"],PNAME_NS:["pathElt"],"^":["^","pathElt"]},pathMod:{"*":["*"],"?":["?"],"+":["+"],"{":["{","or([[integer,or([[,,or([},[integer,}]])],}])],[,,integer,}]])"]},pathNegatedPropertySet:{a:["pathOneInPropertySet"],"^":["pathOneInPropertySet"],IRI_REF:["pathOneInPropertySet"],PNAME_LN:["pathOneInPropertySet"],PNAME_NS:["pathOneInPropertySet"],"(":["(","?[pathOneInPropertySet,*[|,pathOneInPropertySet]]",")"]},pathOneInPropertySet:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],a:["a"],"^":["^","or([iriRef,a])"]},pathPrimary:{IRI_REF:["storeProperty","iriRef"],PNAME_LN:["storeProperty","iriRef"],PNAME_NS:["storeProperty","iriRef"],a:["storeProperty","a"],"!":["!","pathNegatedPropertySet"],"(":["(","path",")"]},pathSequence:{"^":["pathEltOrInverse","*[/,pathEltOrInverse]"],a:["pathEltOrInverse","*[/,pathEltOrInverse]"],"!":["pathEltOrInverse","*[/,pathEltOrInverse]"],"(":["pathEltOrInverse","*[/,pathEltOrInverse]"],IRI_REF:["pathEltOrInverse","*[/,pathEltOrInverse]"],PNAME_LN:["pathEltOrInverse","*[/,pathEltOrInverse]"],PNAME_NS:["pathEltOrInverse","*[/,pathEltOrInverse]"]},prefixDecl:{PREFIX:["PREFIX","PNAME_NS","IRI_REF"]},prefixedName:{PNAME_LN:["PNAME_LN"],PNAME_NS:["PNAME_NS"]},primaryExpression:{"(":["brackettedExpression"],STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["iriRefOrFunction"],PNAME_LN:["iriRefOrFunction"],PNAME_NS:["iriRefOrFunction"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],VAR1:["var"],VAR2:["var"],COUNT:["aggregate"],SUM:["aggregate"],MIN:["aggregate"],MAX:["aggregate"],AVG:["aggregate"],SAMPLE:["aggregate"],GROUP_CONCAT:["aggregate"]},prologue:{PREFIX:["?baseDecl","*prefixDecl"],BASE:["?baseDecl","*prefixDecl"],$:["?baseDecl","*prefixDecl"],CONSTRUCT:["?baseDecl","*prefixDecl"],DESCRIBE:["?baseDecl","*prefixDecl"],ASK:["?baseDecl","*prefixDecl"],INSERT:["?baseDecl","*prefixDecl"],DELETE:["?baseDecl","*prefixDecl"],SELECT:["?baseDecl","*prefixDecl"],LOAD:["?baseDecl","*prefixDecl"],CLEAR:["?baseDecl","*prefixDecl"],DROP:["?baseDecl","*prefixDecl"],ADD:["?baseDecl","*prefixDecl"],MOVE:["?baseDecl","*prefixDecl"],COPY:["?baseDecl","*prefixDecl"],CREATE:["?baseDecl","*prefixDecl"],WITH:["?baseDecl","*prefixDecl"]},propertyList:{a:["propertyListNotEmpty"],VAR1:["propertyListNotEmpty"],VAR2:["propertyListNotEmpty"],IRI_REF:["propertyListNotEmpty"],PNAME_LN:["propertyListNotEmpty"],PNAME_NS:["propertyListNotEmpty"],".":[],"}":[],GRAPH:[]},propertyListNotEmpty:{a:["verb","objectList","*[;,?[verb,objectList]]"],VAR1:["verb","objectList","*[;,?[verb,objectList]]"],VAR2:["verb","objectList","*[;,?[verb,objectList]]"],IRI_REF:["verb","objectList","*[;,?[verb,objectList]]"],PNAME_LN:["verb","objectList","*[;,?[verb,objectList]]"],PNAME_NS:["verb","objectList","*[;,?[verb,objectList]]"]},propertyListPath:{a:["propertyListNotEmpty"],VAR1:["propertyListNotEmpty"],VAR2:["propertyListNotEmpty"],IRI_REF:["propertyListNotEmpty"],PNAME_LN:["propertyListNotEmpty"],PNAME_NS:["propertyListNotEmpty"],".":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},propertyListPathNotEmpty:{VAR1:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],VAR2:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"^":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],a:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"!":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"(":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],IRI_REF:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],PNAME_LN:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],PNAME_NS:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"]},quadData:{"{":["{","disallowVars","quads","allowVars","}"]},quadDataNoBnodes:{"{":["{","disallowBnodes","disallowVars","quads","allowVars","allowBnodes","}"]},quadPattern:{"{":["{","quads","}"]},quadPatternNoBnodes:{"{":["{","disallowBnodes","quads","allowBnodes","}"]},quads:{GRAPH:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],VAR1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],VAR2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],NIL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"(":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"[":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],IRI_REF:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],TRUE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],FALSE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],BLANK_NODE_LABEL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],ANON:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],PNAME_LN:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],PNAME_NS:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL_LONG1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL_LONG2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"}":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"]},quadsNotTriples:{GRAPH:["GRAPH","varOrIRIref","{","?triplesTemplate","}"]},queryAll:{CONSTRUCT:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],DESCRIBE:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],ASK:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],SELECT:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"]},rdfLiteral:{STRING_LITERAL1:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL2:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL_LONG1:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL_LONG2:["string","?or([LANGTAG,[^^,iriRef]])"]},regexExpression:{REGEX:["REGEX","(","expression",",","expression","?[,,expression]",")"]},relationalExpression:{"!":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"+":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"-":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],VAR1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],VAR2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"(":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LANG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LANGMATCHES:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DATATYPE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],BOUND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IRI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],URI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],BNODE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],RAND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ABS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CEIL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],FLOOR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ROUND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CONCAT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRLEN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],UCASE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LCASE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ENCODE_FOR_URI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CONTAINS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRSTARTS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRENDS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRBEFORE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRAFTER:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],YEAR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MONTH:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DAY:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],HOURS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MINUTES:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SECONDS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TIMEZONE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TZ:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOW:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],UUID:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRUUID:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MD5:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA256:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA384:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA512:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],COALESCE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IF:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRLANG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRDT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SAMETERM:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISIRI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISURI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISBLANK:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISLITERAL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISNUMERIC:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TRUE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],FALSE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],COUNT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SUM:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MIN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MAX:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],AVG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SAMPLE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],GROUP_CONCAT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SUBSTR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],REPLACE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],REGEX:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],EXISTS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IRI_REF:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL_LONG1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL_LONG2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],PNAME_LN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],PNAME_NS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"]},selectClause:{SELECT:["SELECT","?or([DISTINCT,REDUCED])","or([+or([var,[ (,expression,AS,var,)]]),*])"]},selectQuery:{SELECT:["selectClause","*datasetClause","whereClause","solutionModifier"]},serviceGraphPattern:{SERVICE:["SERVICE","?SILENT","varOrIRIref","groupGraphPattern"]},solutionModifier:{LIMIT:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],OFFSET:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],ORDER:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],HAVING:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],GROUP:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],VALUES:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],$:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],"}":["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"]},sourceSelector:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"]},sparql11:{$:["prologue","or([queryAll,updateAll])","$"],CONSTRUCT:["prologue","or([queryAll,updateAll])","$"],DESCRIBE:["prologue","or([queryAll,updateAll])","$"],ASK:["prologue","or([queryAll,updateAll])","$"],INSERT:["prologue","or([queryAll,updateAll])","$"],DELETE:["prologue","or([queryAll,updateAll])","$"],SELECT:["prologue","or([queryAll,updateAll])","$"],LOAD:["prologue","or([queryAll,updateAll])","$"],CLEAR:["prologue","or([queryAll,updateAll])","$"],DROP:["prologue","or([queryAll,updateAll])","$"],ADD:["prologue","or([queryAll,updateAll])","$"],MOVE:["prologue","or([queryAll,updateAll])","$"],COPY:["prologue","or([queryAll,updateAll])","$"],CREATE:["prologue","or([queryAll,updateAll])","$"],WITH:["prologue","or([queryAll,updateAll])","$"],PREFIX:["prologue","or([queryAll,updateAll])","$"],BASE:["prologue","or([queryAll,updateAll])","$"]},storeProperty:{VAR1:[],VAR2:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[],a:[]},strReplaceExpression:{REPLACE:["REPLACE","(","expression",",","expression",",","expression","?[,,expression]",")"]},string:{STRING_LITERAL1:["STRING_LITERAL1"],STRING_LITERAL2:["STRING_LITERAL2"],STRING_LITERAL_LONG1:["STRING_LITERAL_LONG1"],STRING_LITERAL_LONG2:["STRING_LITERAL_LONG2"]},subSelect:{SELECT:["selectClause","whereClause","solutionModifier","valuesClause"]},substringExpression:{SUBSTR:["SUBSTR","(","expression",",","expression","?[,,expression]",")"]},triplesBlock:{VAR1:["triplesSameSubjectPath","?[.,?triplesBlock]"],VAR2:["triplesSameSubjectPath","?[.,?triplesBlock]"],NIL:["triplesSameSubjectPath","?[.,?triplesBlock]"],"(":["triplesSameSubjectPath","?[.,?triplesBlock]"],"[":["triplesSameSubjectPath","?[.,?triplesBlock]"],IRI_REF:["triplesSameSubjectPath","?[.,?triplesBlock]"],TRUE:["triplesSameSubjectPath","?[.,?triplesBlock]"],FALSE:["triplesSameSubjectPath","?[.,?triplesBlock]"],BLANK_NODE_LABEL:["triplesSameSubjectPath","?[.,?triplesBlock]"],ANON:["triplesSameSubjectPath","?[.,?triplesBlock]"],PNAME_LN:["triplesSameSubjectPath","?[.,?triplesBlock]"],PNAME_NS:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL1:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL2:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL_LONG1:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL_LONG2:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"]},triplesNode:{"(":["collection"],"[":["blankNodePropertyList"]},triplesNodePath:{"(":["collectionPath"],"[":["blankNodePropertyListPath"]},triplesSameSubject:{VAR1:["varOrTerm","propertyListNotEmpty"],VAR2:["varOrTerm","propertyListNotEmpty"],NIL:["varOrTerm","propertyListNotEmpty"],IRI_REF:["varOrTerm","propertyListNotEmpty"],TRUE:["varOrTerm","propertyListNotEmpty"],FALSE:["varOrTerm","propertyListNotEmpty"],BLANK_NODE_LABEL:["varOrTerm","propertyListNotEmpty"],ANON:["varOrTerm","propertyListNotEmpty"],PNAME_LN:["varOrTerm","propertyListNotEmpty"],PNAME_NS:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL1:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL2:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL_LONG1:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL_LONG2:["varOrTerm","propertyListNotEmpty"],INTEGER:["varOrTerm","propertyListNotEmpty"],DECIMAL:["varOrTerm","propertyListNotEmpty"],DOUBLE:["varOrTerm","propertyListNotEmpty"],INTEGER_POSITIVE:["varOrTerm","propertyListNotEmpty"],DECIMAL_POSITIVE:["varOrTerm","propertyListNotEmpty"],DOUBLE_POSITIVE:["varOrTerm","propertyListNotEmpty"],INTEGER_NEGATIVE:["varOrTerm","propertyListNotEmpty"],DECIMAL_NEGATIVE:["varOrTerm","propertyListNotEmpty"],DOUBLE_NEGATIVE:["varOrTerm","propertyListNotEmpty"],"(":["triplesNode","propertyList"],"[":["triplesNode","propertyList"]},triplesSameSubjectPath:{VAR1:["varOrTerm","propertyListPathNotEmpty"],VAR2:["varOrTerm","propertyListPathNotEmpty"],NIL:["varOrTerm","propertyListPathNotEmpty"],IRI_REF:["varOrTerm","propertyListPathNotEmpty"],TRUE:["varOrTerm","propertyListPathNotEmpty"],FALSE:["varOrTerm","propertyListPathNotEmpty"],BLANK_NODE_LABEL:["varOrTerm","propertyListPathNotEmpty"],ANON:["varOrTerm","propertyListPathNotEmpty"],PNAME_LN:["varOrTerm","propertyListPathNotEmpty"],PNAME_NS:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL1:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL2:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL_LONG1:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL_LONG2:["varOrTerm","propertyListPathNotEmpty"],INTEGER:["varOrTerm","propertyListPathNotEmpty"],DECIMAL:["varOrTerm","propertyListPathNotEmpty"],DOUBLE:["varOrTerm","propertyListPathNotEmpty"],INTEGER_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],DECIMAL_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],DOUBLE_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],INTEGER_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],DECIMAL_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],DOUBLE_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],"(":["triplesNodePath","propertyListPath"],"[":["triplesNodePath","propertyListPath"]},triplesTemplate:{VAR1:["triplesSameSubject","?[.,?triplesTemplate]"],VAR2:["triplesSameSubject","?[.,?triplesTemplate]"],NIL:["triplesSameSubject","?[.,?triplesTemplate]"],"(":["triplesSameSubject","?[.,?triplesTemplate]"],"[":["triplesSameSubject","?[.,?triplesTemplate]"],IRI_REF:["triplesSameSubject","?[.,?triplesTemplate]"],TRUE:["triplesSameSubject","?[.,?triplesTemplate]"],FALSE:["triplesSameSubject","?[.,?triplesTemplate]"],BLANK_NODE_LABEL:["triplesSameSubject","?[.,?triplesTemplate]"],ANON:["triplesSameSubject","?[.,?triplesTemplate]"],PNAME_LN:["triplesSameSubject","?[.,?triplesTemplate]"],PNAME_NS:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL1:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL2:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL_LONG1:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL_LONG2:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"]},unaryExpression:{"!":["!","primaryExpression"],"+":["+","primaryExpression"],"-":["-","primaryExpression"],VAR1:["primaryExpression"],VAR2:["primaryExpression"],"(":["primaryExpression"],STR:["primaryExpression"],LANG:["primaryExpression"],LANGMATCHES:["primaryExpression"],DATATYPE:["primaryExpression"],BOUND:["primaryExpression"],IRI:["primaryExpression"],URI:["primaryExpression"],BNODE:["primaryExpression"],RAND:["primaryExpression"],ABS:["primaryExpression"],CEIL:["primaryExpression"],FLOOR:["primaryExpression"],ROUND:["primaryExpression"],CONCAT:["primaryExpression"],STRLEN:["primaryExpression"],UCASE:["primaryExpression"],LCASE:["primaryExpression"],ENCODE_FOR_URI:["primaryExpression"],CONTAINS:["primaryExpression"],STRSTARTS:["primaryExpression"],STRENDS:["primaryExpression"],STRBEFORE:["primaryExpression"],STRAFTER:["primaryExpression"],YEAR:["primaryExpression"],MONTH:["primaryExpression"],DAY:["primaryExpression"],HOURS:["primaryExpression"],MINUTES:["primaryExpression"],SECONDS:["primaryExpression"],TIMEZONE:["primaryExpression"],TZ:["primaryExpression"],NOW:["primaryExpression"],UUID:["primaryExpression"],STRUUID:["primaryExpression"],MD5:["primaryExpression"],SHA1:["primaryExpression"],SHA256:["primaryExpression"],SHA384:["primaryExpression"],SHA512:["primaryExpression"],COALESCE:["primaryExpression"],IF:["primaryExpression"],STRLANG:["primaryExpression"],STRDT:["primaryExpression"],SAMETERM:["primaryExpression"],ISIRI:["primaryExpression"],ISURI:["primaryExpression"],ISBLANK:["primaryExpression"],ISLITERAL:["primaryExpression"],ISNUMERIC:["primaryExpression"],TRUE:["primaryExpression"],FALSE:["primaryExpression"],COUNT:["primaryExpression"],SUM:["primaryExpression"],MIN:["primaryExpression"],MAX:["primaryExpression"],AVG:["primaryExpression"],SAMPLE:["primaryExpression"],GROUP_CONCAT:["primaryExpression"],SUBSTR:["primaryExpression"],REPLACE:["primaryExpression"],REGEX:["primaryExpression"],EXISTS:["primaryExpression"],NOT:["primaryExpression"],IRI_REF:["primaryExpression"],STRING_LITERAL1:["primaryExpression"],STRING_LITERAL2:["primaryExpression"],STRING_LITERAL_LONG1:["primaryExpression"],STRING_LITERAL_LONG2:["primaryExpression"],INTEGER:["primaryExpression"],DECIMAL:["primaryExpression"],DOUBLE:["primaryExpression"],INTEGER_POSITIVE:["primaryExpression"],DECIMAL_POSITIVE:["primaryExpression"],DOUBLE_POSITIVE:["primaryExpression"],INTEGER_NEGATIVE:["primaryExpression"],DECIMAL_NEGATIVE:["primaryExpression"],DOUBLE_NEGATIVE:["primaryExpression"],PNAME_LN:["primaryExpression"],PNAME_NS:["primaryExpression"]},update:{INSERT:["prologue","?[update1,?[;,update]]"],DELETE:["prologue","?[update1,?[;,update]]"],LOAD:["prologue","?[update1,?[;,update]]"],CLEAR:["prologue","?[update1,?[;,update]]"],DROP:["prologue","?[update1,?[;,update]]"],ADD:["prologue","?[update1,?[;,update]]"],MOVE:["prologue","?[update1,?[;,update]]"],COPY:["prologue","?[update1,?[;,update]]"],CREATE:["prologue","?[update1,?[;,update]]"],WITH:["prologue","?[update1,?[;,update]]"],PREFIX:["prologue","?[update1,?[;,update]]"],BASE:["prologue","?[update1,?[;,update]]"],$:["prologue","?[update1,?[;,update]]"]},update1:{LOAD:["load"],CLEAR:["clear"],DROP:["drop"],ADD:["add"],MOVE:["move"],COPY:["copy"],CREATE:["create"],INSERT:["INSERT","insert1"],DELETE:["DELETE","delete1"],WITH:["modify"]},updateAll:{INSERT:["?[update1,?[;,update]]"],DELETE:["?[update1,?[;,update]]"],LOAD:["?[update1,?[;,update]]"],CLEAR:["?[update1,?[;,update]]"],DROP:["?[update1,?[;,update]]"],ADD:["?[update1,?[;,update]]"],MOVE:["?[update1,?[;,update]]"],COPY:["?[update1,?[;,update]]"],CREATE:["?[update1,?[;,update]]"],WITH:["?[update1,?[;,update]]"],$:["?[update1,?[;,update]]"]},usingClause:{USING:["USING","or([iriRef,[NAMED,iriRef]])"]},valueLogical:{"!":["relationalExpression"],"+":["relationalExpression"],"-":["relationalExpression"],VAR1:["relationalExpression"],VAR2:["relationalExpression"],"(":["relationalExpression"],STR:["relationalExpression"],LANG:["relationalExpression"],LANGMATCHES:["relationalExpression"],DATATYPE:["relationalExpression"],BOUND:["relationalExpression"],IRI:["relationalExpression"],URI:["relationalExpression"],BNODE:["relationalExpression"],RAND:["relationalExpression"],ABS:["relationalExpression"],CEIL:["relationalExpression"],FLOOR:["relationalExpression"],ROUND:["relationalExpression"],CONCAT:["relationalExpression"],STRLEN:["relationalExpression"],UCASE:["relationalExpression"],LCASE:["relationalExpression"],ENCODE_FOR_URI:["relationalExpression"],CONTAINS:["relationalExpression"],STRSTARTS:["relationalExpression"],STRENDS:["relationalExpression"],STRBEFORE:["relationalExpression"],STRAFTER:["relationalExpression"],YEAR:["relationalExpression"],MONTH:["relationalExpression"],DAY:["relationalExpression"],HOURS:["relationalExpression"],MINUTES:["relationalExpression"],SECONDS:["relationalExpression"],TIMEZONE:["relationalExpression"],TZ:["relationalExpression"],NOW:["relationalExpression"],UUID:["relationalExpression"],STRUUID:["relationalExpression"],MD5:["relationalExpression"],SHA1:["relationalExpression"],SHA256:["relationalExpression"],SHA384:["relationalExpression"],SHA512:["relationalExpression"],COALESCE:["relationalExpression"],IF:["relationalExpression"],STRLANG:["relationalExpression"],STRDT:["relationalExpression"],SAMETERM:["relationalExpression"],ISIRI:["relationalExpression"],ISURI:["relationalExpression"],ISBLANK:["relationalExpression"],ISLITERAL:["relationalExpression"],ISNUMERIC:["relationalExpression"],TRUE:["relationalExpression"],FALSE:["relationalExpression"],COUNT:["relationalExpression"],SUM:["relationalExpression"],MIN:["relationalExpression"],MAX:["relationalExpression"],AVG:["relationalExpression"],SAMPLE:["relationalExpression"],GROUP_CONCAT:["relationalExpression"],SUBSTR:["relationalExpression"],REPLACE:["relationalExpression"],REGEX:["relationalExpression"],EXISTS:["relationalExpression"],NOT:["relationalExpression"],IRI_REF:["relationalExpression"],STRING_LITERAL1:["relationalExpression"],STRING_LITERAL2:["relationalExpression"],STRING_LITERAL_LONG1:["relationalExpression"],STRING_LITERAL_LONG2:["relationalExpression"],INTEGER:["relationalExpression"],DECIMAL:["relationalExpression"],DOUBLE:["relationalExpression"],INTEGER_POSITIVE:["relationalExpression"],DECIMAL_POSITIVE:["relationalExpression"],DOUBLE_POSITIVE:["relationalExpression"],INTEGER_NEGATIVE:["relationalExpression"],DECIMAL_NEGATIVE:["relationalExpression"],DOUBLE_NEGATIVE:["relationalExpression"],PNAME_LN:["relationalExpression"],PNAME_NS:["relationalExpression"]},valuesClause:{VALUES:["VALUES","dataBlock"],$:[],"}":[]},"var":{VAR1:["VAR1"],VAR2:["VAR2"]},varOrIRIref:{VAR1:["var"],VAR2:["var"],IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"]},varOrTerm:{VAR1:["var"],VAR2:["var"],NIL:["graphTerm"],IRI_REF:["graphTerm"],TRUE:["graphTerm"],FALSE:["graphTerm"],BLANK_NODE_LABEL:["graphTerm"],ANON:["graphTerm"],PNAME_LN:["graphTerm"],PNAME_NS:["graphTerm"],STRING_LITERAL1:["graphTerm"],STRING_LITERAL2:["graphTerm"],STRING_LITERAL_LONG1:["graphTerm"],STRING_LITERAL_LONG2:["graphTerm"],INTEGER:["graphTerm"],DECIMAL:["graphTerm"],DOUBLE:["graphTerm"],INTEGER_POSITIVE:["graphTerm"],DECIMAL_POSITIVE:["graphTerm"],DOUBLE_POSITIVE:["graphTerm"],INTEGER_NEGATIVE:["graphTerm"],DECIMAL_NEGATIVE:["graphTerm"],DOUBLE_NEGATIVE:["graphTerm"]},verb:{VAR1:["storeProperty","varOrIRIref"],VAR2:["storeProperty","varOrIRIref"],IRI_REF:["storeProperty","varOrIRIref"],PNAME_LN:["storeProperty","varOrIRIref"],PNAME_NS:["storeProperty","varOrIRIref"],a:["storeProperty","a"]},verbPath:{"^":["path"],a:["path"],"!":["path"],"(":["path"],IRI_REF:["path"],PNAME_LN:["path"],PNAME_NS:["path"]},verbSimple:{VAR1:["var"],VAR2:["var"]},whereClause:{"{":["?WHERE","groupGraphPattern"],WHERE:["?WHERE","groupGraphPattern"]}}),s=/^(GROUP_CONCAT|DATATYPE|BASE|PREFIX|SELECT|CONSTRUCT|DESCRIBE|ASK|FROM|NAMED|ORDER|BY|LIMIT|ASC|DESC|OFFSET|DISTINCT|REDUCED|WHERE|GRAPH|OPTIONAL|UNION|FILTER|GROUP|HAVING|AS|VALUES|LOAD|CLEAR|DROP|CREATE|MOVE|COPY|SILENT|INSERT|DELETE|DATA|WITH|TO|USING|NAMED|MINUS|BIND|LANGMATCHES|LANG|BOUND|SAMETERM|ISIRI|ISURI|ISBLANK|ISLITERAL|REGEX|TRUE|FALSE|UNDEF|ADD|DEFAULT|ALL|SERVICE|INTO|IN|NOT|IRI|URI|BNODE|RAND|ABS|CEIL|FLOOR|ROUND|CONCAT|STRLEN|UCASE|LCASE|ENCODE_FOR_URI|CONTAINS|STRSTARTS|STRENDS|STRBEFORE|STRAFTER|YEAR|MONTH|DAY|HOURS|MINUTES|SECONDS|TIMEZONE|TZ|NOW|UUID|STRUUID|MD5|SHA1|SHA256|SHA384|SHA512|COALESCE|IF|STRLANG|STRDT|ISNUMERIC|SUBSTR|REPLACE|EXISTS|COUNT|SUM|MIN|MAX|AVG|SAMPLE|SEPARATOR|STR)/i,a=/^(\*|a|\.|\{|\}|,|\(|\)|;|\[|\]|\|\||&&|=|!=|!|<=|>=|<|>|\+|-|\/|\^\^|\?|\||\^)/,l=null,u="sparql11",p="sparql11",c=!0,d=t(),E=d.terminal,h={"*[,, object]":3,"*[(,),object]":3,"*[(,),objectPath]":3,"*[/,pathEltOrInverse]":2,object:2,objectPath:2,objectList:2,objectListPath:2,storeProperty:2,pathMod:2,"?pathMod":2,propertyListNotEmpty:1,propertyList:1,propertyListPath:1,propertyListPathNotEmpty:1,"?[verb,objectList]":1,"?[or([verbPath, verbSimple]),objectList]":1},f={"}":1,"]":0,")":1,"{":-1,"(":-1,"*[;,?[or([verbPath,verbSimple]),objectList]]":1}; return{token:r,startState:function(){return{tokenize:r,OK:!0,complete:c,errorStartPos:null,errorEndPos:null,queryType:l,possibleCurrent:i(p),possibleNext:i(p),allowVars:!0,allowBnodes:!0,storeProperty:!1,lastProperty:"",stack:[p]}},indent:n,electricChars:"}])"}}),e.defineMIME("application/x-sparql-query","sparql11")})},{codemirror:8}],3:[function(e,t){t.exports=Trie=function(){this.words=0,this.prefixes=0,this.children=[]},Trie.prototype={insert:function(e,t){if(0!=e.length){var i,r,n=this;if(void 0===t&&(t=0),t===e.length)return void n.words++;n.prefixes++,i=e[t],void 0===n.children[i]&&(n.children[i]=new Trie),r=n.children[i],r.insert(e,t+1)}},remove:function(e,t){if(0!=e.length){var i,r,n=this;if(void 0===t&&(t=0),void 0!==n){if(t===e.length)return void n.words--;n.prefixes--,i=e[t],r=n.children[i],r.remove(e,t+1)}}},update:function(e,t){0!=e.length&&0!=t.length&&(this.remove(e),this.insert(t))},countWord:function(e,t){if(0==e.length)return 0;var i,r,n=this,o=0;return void 0===t&&(t=0),t===e.length?n.words:(i=e[t],r=n.children[i],void 0!==r&&(o=r.countWord(e,t+1)),o)},countPrefix:function(e,t){if(0==e.length)return 0;var i,r,n=this,o=0;if(void 0===t&&(t=0),t===e.length)return n.prefixes;var i=e[t];return r=n.children[i],void 0!==r&&(o=r.countPrefix(e,t+1)),o},find:function(e){return 0==e.length?!1:this.countWord(e)>0?!0:!1},getAllWords:function(e){var t,i,r=this,n=[];if(void 0===e&&(e=""),void 0===r)return[];r.words>0&&n.push(e);for(t in r.children)i=r.children[t],n=n.concat(i.getAllWords(e+t));return n},autoComplete:function(e,t){var i,r,n=this;return 0==e.length?void 0===t?n.getAllWords(e):[]:(void 0===t&&(t=0),i=e[t],r=n.children[i],void 0===r?[]:t===e.length-1?r.getAllWords(e):r.autoComplete(e,t+1))}}},{}],4:[function(t,i,r){!function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)}(function(e){function t(e,t,r,n){var o=e.getLineHandle(t.line),l=t.ch-1,u=l>=0&&a[o.text.charAt(l)]||a[o.text.charAt(++l)];if(!u)return null;var p=">"==u.charAt(1)?1:-1;if(r&&p>0!=(l==t.ch))return null;var c=e.getTokenTypeAt(s(t.line,l+1)),d=i(e,s(t.line,l+(p>0?1:0)),p,c||null,n);return null==d?null:{from:s(t.line,l),to:d&&d.pos,match:d&&d.ch==u.charAt(0),forward:p>0}}function i(e,t,i,r,n){for(var o=n&&n.maxScanLineLength||1e4,l=n&&n.maxScanLines||1e3,u=[],p=n&&n.bracketRegex?n.bracketRegex:/[(){}[\]]/,c=i>0?Math.min(t.line+l,e.lastLine()+1):Math.max(e.firstLine()-1,t.line-l),d=t.line;d!=c;d+=i){var E=e.getLine(d);if(E){var h=i>0?0:E.length-1,f=i>0?E.length:-1;if(!(E.length>o))for(d==t.line&&(h=t.ch-(0>i?1:0));h!=f;h+=i){var m=E.charAt(h);if(p.test(m)&&(void 0===r||e.getTokenTypeAt(s(d,h+1))==r)){var g=a[m];if(">"==g.charAt(1)==i>0)u.push(m);else{if(!u.length)return{pos:s(d,h),ch:m};u.pop()}}}}}return d-i==(i>0?e.lastLine():e.firstLine())?!1:null}function r(e,i,r){for(var n=e.state.matchBrackets.maxHighlightLineLength||1e3,a=[],l=e.listSelections(),u=0;u<l.length;u++){var p=l[u].empty()&&t(e,l[u].head,!1,r);if(p&&e.getLine(p.from.line).length<=n){var c=p.match?"CodeMirror-matchingbracket":"CodeMirror-nonmatchingbracket";a.push(e.markText(p.from,s(p.from.line,p.from.ch+1),{className:c})),p.to&&e.getLine(p.to.line).length<=n&&a.push(e.markText(p.to,s(p.to.line,p.to.ch+1),{className:c}))}}if(a.length){o&&e.state.focused&&e.display.input.focus();var d=function(){e.operation(function(){for(var e=0;e<a.length;e++)a[e].clear()})};if(!i)return d;setTimeout(d,800)}}function n(e){e.operation(function(){l&&(l(),l=null),l=r(e,!1,e.state.matchBrackets)})}var o=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<8),s=e.Pos,a={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"},l=null;e.defineOption("matchBrackets",!1,function(t,i,r){r&&r!=e.Init&&t.off("cursorActivity",n),i&&(t.state.matchBrackets="object"==typeof i?i:{},t.on("cursorActivity",n))}),e.defineExtension("matchBrackets",function(){r(this,!0)}),e.defineExtension("findMatchingBracket",function(e,i,r){return t(this,e,i,r)}),e.defineExtension("scanForBracket",function(e,t,r,n){return i(this,e,t,r,n)})})},{"../../lib/codemirror":8}],5:[function(t,i,r){!function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)}(function(e){"use strict";function t(e,t){this.cm=e,this.options=this.buildOptions(t),this.widget=this.onClose=null}function i(e){return"string"==typeof e?e:e.text}function r(e,t){function i(e,i){var n;n="string"!=typeof i?function(e){return i(e,t)}:r.hasOwnProperty(i)?r[i]:i,o[e]=n}var r={Up:function(){t.moveFocus(-1)},Down:function(){t.moveFocus(1)},PageUp:function(){t.moveFocus(-t.menuSize()+1,!0)},PageDown:function(){t.moveFocus(t.menuSize()-1,!0)},Home:function(){t.setFocus(0)},End:function(){t.setFocus(t.length-1)},Enter:t.pick,Tab:t.pick,Esc:t.close},n=e.options.customKeys,o=n?{}:r;if(n)for(var s in n)n.hasOwnProperty(s)&&i(s,n[s]);var a=e.options.extraKeys;if(a)for(var s in a)a.hasOwnProperty(s)&&i(s,a[s]);return o}function n(e,t){for(;t&&t!=e;){if("LI"===t.nodeName.toUpperCase()&&t.parentNode==e)return t;t=t.parentNode}}function o(t,o){this.completion=t,this.data=o;var l=this,u=t.cm,p=this.hints=document.createElement("ul");p.className="CodeMirror-hints",this.selectedHint=o.selectedHint||0;for(var c=o.list,d=0;d<c.length;++d){var E=p.appendChild(document.createElement("li")),h=c[d],f=s+(d!=this.selectedHint?"":" "+a);null!=h.className&&(f=h.className+" "+f),E.className=f,h.render?h.render(E,o,h):E.appendChild(document.createTextNode(h.displayText||i(h))),E.hintId=d}var m=u.cursorCoords(t.options.alignWithWord?o.from:null),g=m.left,v=m.bottom,x=!0;p.style.left=g+"px",p.style.top=v+"px";var N=window.innerWidth||Math.max(document.body.offsetWidth,document.documentElement.offsetWidth),L=window.innerHeight||Math.max(document.body.offsetHeight,document.documentElement.offsetHeight);(t.options.container||document.body).appendChild(p);var T=p.getBoundingClientRect(),I=T.bottom-L;if(I>0){var y=T.bottom-T.top,A=T.top-(m.bottom-m.top);if(A-y>0)p.style.top=(v=A-y)+"px",x=!1;else if(y>L){p.style.height=L-5+"px",p.style.top=(v=m.bottom-T.top)+"px";var S=u.getCursor();o.from.ch!=S.ch&&(m=u.cursorCoords(S),p.style.left=(g=m.left)+"px",T=p.getBoundingClientRect())}}var C=T.left-N;if(C>0&&(T.right-T.left>N&&(p.style.width=N-5+"px",C-=T.right-T.left-N),p.style.left=(g=m.left-C)+"px"),u.addKeyMap(this.keyMap=r(t,{moveFocus:function(e,t){l.changeActive(l.selectedHint+e,t)},setFocus:function(e){l.changeActive(e)},menuSize:function(){return l.screenAmount()},length:c.length,close:function(){t.close()},pick:function(){l.pick()},data:o})),t.options.closeOnUnfocus){var R;u.on("blur",this.onBlur=function(){R=setTimeout(function(){t.close()},100)}),u.on("focus",this.onFocus=function(){clearTimeout(R)})}var b=u.getScrollInfo();return u.on("scroll",this.onScroll=function(){var e=u.getScrollInfo(),i=u.getWrapperElement().getBoundingClientRect(),r=v+b.top-e.top,n=r-(window.pageYOffset||(document.documentElement||document.body).scrollTop);return x||(n+=p.offsetHeight),n<=i.top||n>=i.bottom?t.close():(p.style.top=r+"px",void(p.style.left=g+b.left-e.left+"px"))}),e.on(p,"dblclick",function(e){var t=n(p,e.target||e.srcElement);t&&null!=t.hintId&&(l.changeActive(t.hintId),l.pick())}),e.on(p,"click",function(e){var i=n(p,e.target||e.srcElement);i&&null!=i.hintId&&(l.changeActive(i.hintId),t.options.completeOnSingleClick&&l.pick())}),e.on(p,"mousedown",function(){setTimeout(function(){u.focus()},20)}),e.signal(o,"select",c[0],p.firstChild),!0}var s="CodeMirror-hint",a="CodeMirror-hint-active";e.showHint=function(e,t,i){if(!t)return e.showHint(i);i&&i.async&&(t.async=!0);var r={hint:t};if(i)for(var n in i)r[n]=i[n];return e.showHint(r)},e.defineExtension("showHint",function(i){if(!(this.listSelections().length>1||this.somethingSelected())){this.state.completionActive&&this.state.completionActive.close();var r=this.state.completionActive=new t(this,i),n=r.options.hint;if(n)return e.signal(this,"startCompletion",this),n.async?void n(this,function(e){r.showHints(e)},r.options):r.showHints(n(this,r.options))}}),t.prototype={close:function(){this.active()&&(this.cm.state.completionActive=null,this.widget&&this.widget.close(),this.onClose&&this.onClose(),e.signal(this.cm,"endCompletion",this.cm))},active:function(){return this.cm.state.completionActive==this},pick:function(t,r){var n=t.list[r];n.hint?n.hint(this.cm,t,n):this.cm.replaceRange(i(n),n.from||t.from,n.to||t.to,"complete"),e.signal(t,"pick",n),this.close()},showHints:function(e){return e&&e.list.length&&this.active()?void(this.options.completeSingle&&1==e.list.length?this.pick(e,0):this.showWidget(e)):this.close()},showWidget:function(t){function i(){l||(l=!0,p.close(),p.cm.off("cursorActivity",a),t&&e.signal(t,"close"))}function r(){if(!l){e.signal(t,"update");var i=p.options.hint;i.async?i(p.cm,n,p.options):n(i(p.cm,p.options))}}function n(e){if(t=e,!l){if(!t||!t.list.length)return i();p.widget&&p.widget.close(),p.widget=new o(p,t)}}function s(){u&&(f(u),u=0)}function a(){s();var e=p.cm.getCursor(),t=p.cm.getLine(e.line);e.line!=d.line||t.length-e.ch!=E-d.ch||e.ch<d.ch||p.cm.somethingSelected()||e.ch&&c.test(t.charAt(e.ch-1))?p.close():(u=h(r),p.widget&&p.widget.close())}this.widget=new o(this,t),e.signal(t,"shown");var l,u=0,p=this,c=this.options.closeCharacters,d=this.cm.getCursor(),E=this.cm.getLine(d.line).length,h=window.requestAnimationFrame||function(e){return setTimeout(e,1e3/60)},f=window.cancelAnimationFrame||clearTimeout;this.cm.on("cursorActivity",a),this.onClose=i},buildOptions:function(e){var t=this.cm.options.hintOptions,i={};for(var r in l)i[r]=l[r];if(t)for(var r in t)void 0!==t[r]&&(i[r]=t[r]);if(e)for(var r in e)void 0!==e[r]&&(i[r]=e[r]);return i}},o.prototype={close:function(){if(this.completion.widget==this){this.completion.widget=null,this.hints.parentNode.removeChild(this.hints),this.completion.cm.removeKeyMap(this.keyMap);var e=this.completion.cm;this.completion.options.closeOnUnfocus&&(e.off("blur",this.onBlur),e.off("focus",this.onFocus)),e.off("scroll",this.onScroll)}},pick:function(){this.completion.pick(this.data,this.selectedHint)},changeActive:function(t,i){if(t>=this.data.list.length?t=i?this.data.list.length-1:0:0>t&&(t=i?0:this.data.list.length-1),this.selectedHint!=t){var r=this.hints.childNodes[this.selectedHint];r.className=r.className.replace(" "+a,""),r=this.hints.childNodes[this.selectedHint=t],r.className+=" "+a,r.offsetTop<this.hints.scrollTop?this.hints.scrollTop=r.offsetTop-3:r.offsetTop+r.offsetHeight>this.hints.scrollTop+this.hints.clientHeight&&(this.hints.scrollTop=r.offsetTop+r.offsetHeight-this.hints.clientHeight+3),e.signal(this.data,"select",this.data.list[this.selectedHint],r)}},screenAmount:function(){return Math.floor(this.hints.clientHeight/this.hints.firstChild.offsetHeight)||1}},e.registerHelper("hint","auto",function(t,i){var r,n=t.getHelpers(t.getCursor(),"hint");if(n.length)for(var o=0;o<n.length;o++){var s=n[o](t,i);if(s&&s.list.length)return s}else if(r=t.getHelper(t.getCursor(),"hintWords")){if(r)return e.hint.fromList(t,{words:r})}else if(e.hint.anyword)return e.hint.anyword(t,i)}),e.registerHelper("hint","fromList",function(t,i){for(var r=t.getCursor(),n=t.getTokenAt(r),o=[],s=0;s<i.words.length;s++){var a=i.words[s];a.slice(0,n.string.length)==n.string&&o.push(a)}return o.length?{list:o,from:e.Pos(r.line,n.start),to:e.Pos(r.line,n.end)}:void 0}),e.commands.autocomplete=e.showHint;var l={hint:e.hint.auto,completeSingle:!0,alignWithWord:!0,closeCharacters:/[\s()\[\]{};:>,]/,closeOnUnfocus:!0,completeOnSingleClick:!1,container:null,customKeys:null,extraKeys:null};e.defineOption("hintOptions",null)})},{"../../lib/codemirror":8}],6:[function(t,i,r){!function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)}(function(e){"use strict";e.runMode=function(t,i,r,n){var o=e.getMode(e.defaults,i),s=/MSIE \d/.test(navigator.userAgent),a=s&&(null==document.documentMode||document.documentMode<9);if(1==r.nodeType){var l=n&&n.tabSize||e.defaults.tabSize,u=r,p=0;u.innerHTML="",r=function(e,t){if("\n"==e)return u.appendChild(document.createTextNode(a?"\r":e)),void(p=0);for(var i="",r=0;;){var n=e.indexOf(" ",r);if(-1==n){i+=e.slice(r),p+=e.length-r;break}p+=n-r,i+=e.slice(r,n);var o=l-p%l;p+=o;for(var s=0;o>s;++s)i+=" ";r=n+1}if(t){var c=u.appendChild(document.createElement("span"));c.className="cm-"+t.replace(/ +/g," cm-"),c.appendChild(document.createTextNode(i))}else u.appendChild(document.createTextNode(i))}}for(var c=e.splitLines(t),d=n&&n.state||e.startState(o),E=0,h=c.length;h>E;++E){E&&r("\n");var f=new e.StringStream(c[E]);for(!f.string&&o.blankLine&&o.blankLine(d);!f.eol();){var m=o.token(f,d);r(f.current(),m,E,f.start,d),f.start=f.pos}}}})},{"../../lib/codemirror":8}],7:[function(t,i,r){!function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)}(function(e){"use strict";function t(e,t,n,o){if(this.atOccurrence=!1,this.doc=e,null==o&&"string"==typeof t&&(o=!1),n=n?e.clipPos(n):r(0,0),this.pos={from:n,to:n},"string"!=typeof t)t.global||(t=new RegExp(t.source,t.ignoreCase?"ig":"g")),this.matches=function(i,n){if(i){t.lastIndex=0;for(var o,s,a=e.getLine(n.line).slice(0,n.ch),l=0;;){t.lastIndex=l;var u=t.exec(a);if(!u)break;if(o=u,s=o.index,l=o.index+(o[0].length||1),l==a.length)break}var p=o&&o[0].length||0;p||(0==s&&0==a.length?o=void 0:s!=e.getLine(n.line).length&&p++)}else{t.lastIndex=n.ch;var a=e.getLine(n.line),o=t.exec(a),p=o&&o[0].length||0,s=o&&o.index;s+p==a.length||p||(p=1)}return o&&p?{from:r(n.line,s),to:r(n.line,s+p),match:o}:void 0};else{var s=t;o&&(t=t.toLowerCase());var a=o?function(e){return e.toLowerCase()}:function(e){return e},l=t.split("\n");if(1==l.length)this.matches=t.length?function(n,o){if(n){var l=e.getLine(o.line).slice(0,o.ch),u=a(l),p=u.lastIndexOf(t);if(p>-1)return p=i(l,u,p),{from:r(o.line,p),to:r(o.line,p+s.length)}}else{var l=e.getLine(o.line).slice(o.ch),u=a(l),p=u.indexOf(t);if(p>-1)return p=i(l,u,p)+o.ch,{from:r(o.line,p),to:r(o.line,p+s.length)}}}:function(){};else{var u=s.split("\n");this.matches=function(t,i){var n=l.length-1;if(t){if(i.line-(l.length-1)<e.firstLine())return;if(a(e.getLine(i.line).slice(0,u[n].length))!=l[l.length-1])return;for(var o=r(i.line,u[n].length),s=i.line-1,p=n-1;p>=1;--p,--s)if(l[p]!=a(e.getLine(s)))return;var c=e.getLine(s),d=c.length-u[0].length;if(a(c.slice(d))!=l[0])return;return{from:r(s,d),to:o}}if(!(i.line+(l.length-1)>e.lastLine())){var c=e.getLine(i.line),d=c.length-u[0].length;if(a(c.slice(d))==l[0]){for(var E=r(i.line,d),s=i.line+1,p=1;n>p;++p,++s)if(l[p]!=a(e.getLine(s)))return;if(e.getLine(s).slice(0,u[n].length)==l[n])return{from:E,to:r(s,u[n].length)}}}}}}}function i(e,t,i){if(e.length==t.length)return i;for(var r=Math.min(i,e.length);;){var n=e.slice(0,r).toLowerCase().length;if(i>n)++r;else{if(!(n>i))return r;--r}}}var r=e.Pos;t.prototype={findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(e){function t(e){var t=r(e,0);return i.pos={from:t,to:t},i.atOccurrence=!1,!1}for(var i=this,n=this.doc.clipPos(e?this.pos.from:this.pos.to);;){if(this.pos=this.matches(e,n))return this.atOccurrence=!0,this.pos.match||!0;if(e){if(!n.line)return t(0);n=r(n.line-1,this.doc.getLine(n.line-1).length)}else{var o=this.doc.lineCount();if(n.line==o-1)return t(o);n=r(n.line+1,0)}}},from:function(){return this.atOccurrence?this.pos.from:void 0},to:function(){return this.atOccurrence?this.pos.to:void 0},replace:function(t){if(this.atOccurrence){var i=e.splitLines(t);this.doc.replaceRange(i,this.pos.from,this.pos.to),this.pos.to=r(this.pos.from.line+i.length-1,i[i.length-1].length+(1==i.length?this.pos.from.ch:0))}}},e.defineExtension("getSearchCursor",function(e,i,r){return new t(this.doc,e,i,r)}),e.defineDocExtension("getSearchCursor",function(e,i,r){return new t(this,e,i,r)}),e.defineExtension("selectMatches",function(t,i){for(var r,n=[],o=this.getSearchCursor(t,this.getCursor("from"),i);(r=o.findNext())&&!(e.cmpPos(o.to(),this.getCursor("to"))>0);)n.push({anchor:o.from(),head:o.to()});n.length&&this.setSelections(n,0)})})},{"../../lib/codemirror":8}],8:[function(t,i,r){!function(t){if("object"==typeof r&&"object"==typeof i)i.exports=t();else{if("function"==typeof e&&e.amd)return e([],t);this.CodeMirror=t()}}(function(){"use strict";function e(i,r){if(!(this instanceof e))return new e(i,r);this.options=r=r||{},no(Ns,r,!1),h(r);var n=r.value;"string"==typeof n&&(n=new Ws(n,r.mode)),this.doc=n;var o=this.display=new t(i,n);o.wrapper.CodeMirror=this,p(this),l(this),r.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),r.autofocus&&!Jo&&Ei(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,draggingText:!1,highlight:new Qn},Bo&&setTimeout(oo(di,this,!0),20),mi(this),No();var s=this;$t(this,function(){s.curOp.forceUpdate=!0,vn(s,n),r.autofocus&&!Jo||ho()==o.input?setTimeout(oo(Ui,s),20):Vi(s);for(var e in Ls)Ls.hasOwnProperty(e)&&Ls[e](s,r[e],Ts);for(var t=0;t<Ss.length;++t)Ss[t](s)})}function t(e,t){var i=this,r=i.input=uo("textarea",null,null,"position: absolute; padding: 0; width: 1px; height: 1em; outline: none");Wo?r.style.width="1000px":r.setAttribute("wrap","off"),Zo&&(r.style.border="1px solid black"),r.setAttribute("autocorrect","off"),r.setAttribute("autocapitalize","off"),r.setAttribute("spellcheck","false"),i.inputDiv=uo("div",[r],null,"overflow: hidden; position: relative; width: 3px; height: 0px;"),i.scrollbarH=uo("div",[uo("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar"),i.scrollbarV=uo("div",[uo("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),i.scrollbarFiller=uo("div",null,"CodeMirror-scrollbar-filler"),i.gutterFiller=uo("div",null,"CodeMirror-gutter-filler"),i.lineDiv=uo("div",null,"CodeMirror-code"),i.selectionDiv=uo("div",null,null,"position: relative; z-index: 1"),i.cursorDiv=uo("div",null,"CodeMirror-cursors"),i.measure=uo("div",null,"CodeMirror-measure"),i.lineMeasure=uo("div",null,"CodeMirror-measure"),i.lineSpace=uo("div",[i.measure,i.lineMeasure,i.selectionDiv,i.cursorDiv,i.lineDiv],null,"position: relative; outline: none"),i.mover=uo("div",[uo("div",[i.lineSpace],"CodeMirror-lines")],null,"position: relative"),i.sizer=uo("div",[i.mover],"CodeMirror-sizer"),i.heightForcer=uo("div",null,null,"position: absolute; height: "+ta+"px; width: 1px;"),i.gutters=uo("div",null,"CodeMirror-gutters"),i.lineGutter=null,i.scroller=uo("div",[i.sizer,i.heightForcer,i.gutters],"CodeMirror-scroll"),i.scroller.setAttribute("tabIndex","-1"),i.wrapper=uo("div",[i.inputDiv,i.scrollbarH,i.scrollbarV,i.scrollbarFiller,i.gutterFiller,i.scroller],"CodeMirror"),Uo&&(i.gutters.style.zIndex=-1,i.scroller.style.paddingRight=0),Zo&&(r.style.width="0px"),Wo||(i.scroller.draggable=!0),Ko&&(i.inputDiv.style.height="1px",i.inputDiv.style.position="absolute"),Uo&&(i.scrollbarH.style.minHeight=i.scrollbarV.style.minWidth="18px"),e.appendChild?e.appendChild(i.wrapper):e(i.wrapper),i.viewFrom=i.viewTo=t.first,i.view=[],i.externalMeasured=null,i.viewOffset=0,i.lastSizeC=0,i.updateLineNumbers=null,i.lineNumWidth=i.lineNumInnerWidth=i.lineNumChars=null,i.prevInput="",i.alignWidgets=!1,i.pollingFast=!1,i.poll=new Qn,i.cachedCharWidth=i.cachedTextHeight=i.cachedPaddingH=null,i.inaccurateSelection=!1,i.maxLine=null,i.maxLineLength=0,i.maxLineChanged=!1,i.wheelDX=i.wheelDY=i.wheelStartX=i.wheelStartY=null,i.shift=!1,i.selForContextMenu=null}function i(t){t.doc.mode=e.getMode(t.options,t.doc.modeOption),r(t)}function r(e){e.doc.iter(function(e){e.stateAfter&&(e.stateAfter=null),e.styles&&(e.styles=null)}),e.doc.frontier=e.doc.first,vt(e,100),e.state.modeGen++,e.curOp&&ii(e)}function n(e){e.options.lineWrapping?(go(e.display.wrapper,"CodeMirror-wrap"),e.display.sizer.style.minWidth=""):(mo(e.display.wrapper,"CodeMirror-wrap"),E(e)),s(e),ii(e),wt(e),setTimeout(function(){m(e)},100)}function o(e){var t=zt(e.display),i=e.options.lineWrapping,r=i&&Math.max(5,e.display.scroller.clientWidth/Xt(e.display)-3);return function(n){if(Wr(e.doc,n))return 0;var o=0;if(n.widgets)for(var s=0;s<n.widgets.length;s++)n.widgets[s].height&&(o+=n.widgets[s].height);return i?o+(Math.ceil(n.text.length/r)||1)*t:o+t}}function s(e){var t=e.doc,i=o(e);t.iter(function(e){var t=i(e);t!=e.height&&Tn(e,t)})}function a(e){var t=Ps[e.options.keyMap],i=t.style;e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-keymap-\S+/g,"")+(i?" cm-keymap-"+i:"")}function l(e){e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+e.options.theme.replace(/(^|\s)\s*/g," cm-s-"),wt(e)}function u(e){p(e),ii(e),setTimeout(function(){v(e)},20)}function p(e){var t=e.display.gutters,i=e.options.gutters;po(t);for(var r=0;r<i.length;++r){var n=i[r],o=t.appendChild(uo("div",null,"CodeMirror-gutter "+n));"CodeMirror-linenumbers"==n&&(e.display.lineGutter=o,o.style.width=(e.display.lineNumWidth||1)+"px")}t.style.display=r?"":"none",c(e)}function c(e){var t=e.display.gutters.offsetWidth;e.display.sizer.style.marginLeft=t+"px",e.display.scrollbarH.style.left=e.options.fixedGutter?t+"px":0}function d(e){if(0==e.height)return 0;for(var t,i=e.text.length,r=e;t=kr(r);){var n=t.find(0,!0);r=n.from.line,i+=n.from.ch-n.to.ch}for(r=e;t=Br(r);){var n=t.find(0,!0);i-=r.text.length-n.from.ch,r=n.to.line,i+=r.text.length-n.to.ch}return i}function E(e){var t=e.display,i=e.doc;t.maxLine=xn(i,i.first),t.maxLineLength=d(t.maxLine),t.maxLineChanged=!0,i.iter(function(e){var i=d(e);i>t.maxLineLength&&(t.maxLineLength=i,t.maxLine=e)})}function h(e){var t=to(e.gutters,"CodeMirror-linenumbers");-1==t&&e.lineNumbers?e.gutters=e.gutters.concat(["CodeMirror-linenumbers"]):t>-1&&!e.lineNumbers&&(e.gutters=e.gutters.slice(0),e.gutters.splice(t,1))}function f(e){var t=e.display.scroller;return{clientHeight:t.clientHeight,barHeight:e.display.scrollbarV.clientHeight,scrollWidth:t.scrollWidth,clientWidth:t.clientWidth,barWidth:e.display.scrollbarH.clientWidth,docHeight:Math.round(e.doc.height+It(e.display))}}function m(e,t){t||(t=f(e));var i=e.display,r=t.docHeight+ta,n=t.scrollWidth>t.clientWidth,o=r>t.clientHeight;if(o?(i.scrollbarV.style.display="block",i.scrollbarV.style.bottom=n?To(i.measure)+"px":"0",i.scrollbarV.firstChild.style.height=Math.max(0,r-t.clientHeight+(t.barHeight||i.scrollbarV.clientHeight))+"px"):(i.scrollbarV.style.display="",i.scrollbarV.firstChild.style.height="0"),n?(i.scrollbarH.style.display="block",i.scrollbarH.style.right=o?To(i.measure)+"px":"0",i.scrollbarH.firstChild.style.width=t.scrollWidth-t.clientWidth+(t.barWidth||i.scrollbarH.clientWidth)+"px"):(i.scrollbarH.style.display="",i.scrollbarH.firstChild.style.width="0"),n&&o?(i.scrollbarFiller.style.display="block",i.scrollbarFiller.style.height=i.scrollbarFiller.style.width=To(i.measure)+"px"):i.scrollbarFiller.style.display="",n&&e.options.coverGutterNextToScrollbar&&e.options.fixedGutter?(i.gutterFiller.style.display="block",i.gutterFiller.style.height=To(i.measure)+"px",i.gutterFiller.style.width=i.gutters.offsetWidth+"px"):i.gutterFiller.style.display="",!e.state.checkedOverlayScrollbar&&t.clientHeight>0){if(0===To(i.measure)){var s=es&&!$o?"12px":"18px";i.scrollbarV.style.minWidth=i.scrollbarH.style.minHeight=s;var a=function(t){jn(t)!=i.scrollbarV&&jn(t)!=i.scrollbarH&&Qt(e,Ni)(t)};Qs(i.scrollbarV,"mousedown",a),Qs(i.scrollbarH,"mousedown",a)}e.state.checkedOverlayScrollbar=!0}}function g(e,t,i){var r=i&&null!=i.top?Math.max(0,i.top):e.scroller.scrollTop;r=Math.floor(r-Tt(e));var n=i&&null!=i.bottom?i.bottom:r+e.wrapper.clientHeight,o=yn(t,r),s=yn(t,n);if(i&&i.ensure){var a=i.ensure.from.line,l=i.ensure.to.line;if(o>a)return{from:a,to:yn(t,An(xn(t,a))+e.wrapper.clientHeight)};if(Math.min(l,t.lastLine())>=s)return{from:yn(t,An(xn(t,l))-e.wrapper.clientHeight),to:l}}return{from:o,to:Math.max(s,o+1)}}function v(e){var t=e.display,i=t.view;if(t.alignWidgets||t.gutters.firstChild&&e.options.fixedGutter){for(var r=L(t)-t.scroller.scrollLeft+e.doc.scrollLeft,n=t.gutters.offsetWidth,o=r+"px",s=0;s<i.length;s++)if(!i[s].hidden){e.options.fixedGutter&&i[s].gutter&&(i[s].gutter.style.left=o);var a=i[s].alignable;if(a)for(var l=0;l<a.length;l++)a[l].style.left=o}e.options.fixedGutter&&(t.gutters.style.left=r+n+"px")}}function x(e){if(!e.options.lineNumbers)return!1;var t=e.doc,i=N(e.options,t.first+t.size-1),r=e.display;if(i.length!=r.lineNumChars){var n=r.measure.appendChild(uo("div",[uo("div",i)],"CodeMirror-linenumber CodeMirror-gutter-elt")),o=n.firstChild.offsetWidth,s=n.offsetWidth-o;return r.lineGutter.style.width="",r.lineNumInnerWidth=Math.max(o,r.lineGutter.offsetWidth-s),r.lineNumWidth=r.lineNumInnerWidth+s,r.lineNumChars=r.lineNumInnerWidth?i.length:-1,r.lineGutter.style.width=r.lineNumWidth+"px",c(e),!0}return!1}function N(e,t){return String(e.lineNumberFormatter(t+e.firstLineNumber))}function L(e){return e.scroller.getBoundingClientRect().left-e.sizer.getBoundingClientRect().left}function T(e,t,i){for(var r,n=e.display.viewFrom,o=e.display.viewTo,s=g(e.display,e.doc,t),a=!0;;a=!1){var l=e.display.scroller.clientWidth;if(!I(e,s,i))break;r=!0,e.display.maxLineChanged&&!e.options.lineWrapping&&y(e);var u=f(e);if(ht(e),A(e,u),m(e,u),Wo&&e.options.lineWrapping&&S(e,u),a&&e.options.lineWrapping&&l!=e.display.scroller.clientWidth)i=!0;else if(i=!1,t&&null!=t.top&&(t={top:Math.min(u.docHeight-ta-u.clientHeight,t.top)}),s=g(e.display,e.doc,t),s.from>=e.display.viewFrom&&s.to<=e.display.viewTo)break}return e.display.updateLineNumbers=null,r&&(qn(e,"update",e),(e.display.viewFrom!=n||e.display.viewTo!=o)&&qn(e,"viewportChange",e,e.display.viewFrom,e.display.viewTo)),r}function I(e,t,i){var r=e.display,n=e.doc;if(!r.wrapper.offsetWidth)return void ni(e);if(!(!i&&t.from>=r.viewFrom&&t.to<=r.viewTo&&0==li(e))){x(e)&&ni(e);var o=b(e),s=n.first+n.size,a=Math.max(t.from-e.options.viewportMargin,n.first),l=Math.min(s,t.to+e.options.viewportMargin);r.viewFrom<a&&a-r.viewFrom<20&&(a=Math.max(n.first,r.viewFrom)),r.viewTo>l&&r.viewTo-l<20&&(l=Math.min(s,r.viewTo)),ss&&(a=Fr(e.doc,a),l=jr(e.doc,l));var u=a!=r.viewFrom||l!=r.viewTo||r.lastSizeC!=r.wrapper.clientHeight;ai(e,a,l),r.viewOffset=An(xn(e.doc,r.viewFrom)),e.display.mover.style.top=r.viewOffset+"px";var p=li(e);if(u||0!=p||i){var c=ho();return p>4&&(r.lineDiv.style.display="none"),O(e,r.updateLineNumbers,o),p>4&&(r.lineDiv.style.display=""),c&&ho()!=c&&c.offsetHeight&&c.focus(),po(r.cursorDiv),po(r.selectionDiv),u&&(r.lastSizeC=r.wrapper.clientHeight,vt(e,400)),C(e),!0}}}function y(e){var t=e.display,i=Rt(e,t.maxLine,t.maxLine.text.length).left;t.maxLineChanged=!1;var r=Math.max(0,i+3),n=Math.max(0,t.sizer.offsetLeft+r+ta-t.scroller.clientWidth);t.sizer.style.minWidth=r+"px",n<e.doc.scrollLeft&&bi(e,Math.min(t.scroller.scrollLeft,n),!0)}function A(e,t){e.display.sizer.style.minHeight=e.display.heightForcer.style.top=t.docHeight+"px",e.display.gutters.style.height=Math.max(t.docHeight,t.clientHeight-ta)+"px"}function S(e,t){e.display.sizer.offsetWidth+e.display.gutters.offsetWidth<e.display.scroller.clientWidth-1&&(e.display.sizer.style.minHeight=e.display.heightForcer.style.top="0px",e.display.gutters.style.height=t.docHeight+"px")}function C(e){for(var t=e.display,i=t.lineDiv.offsetTop,r=0;r<t.view.length;r++){var n,o=t.view[r];if(!o.hidden){if(Uo){var s=o.node.offsetTop+o.node.offsetHeight;n=s-i,i=s}else{var a=o.node.getBoundingClientRect();n=a.bottom-a.top}var l=o.line.height-n;if(2>n&&(n=zt(t)),(l>.001||-.001>l)&&(Tn(o.line,n),R(o.line),o.rest))for(var u=0;u<o.rest.length;u++)R(o.rest[u])}}}function R(e){if(e.widgets)for(var t=0;t<e.widgets.length;++t)e.widgets[t].height=e.widgets[t].node.offsetHeight}function b(e){for(var t=e.display,i={},r={},n=t.gutters.firstChild,o=0;n;n=n.nextSibling,++o)i[e.options.gutters[o]]=n.offsetLeft,r[e.options.gutters[o]]=n.offsetWidth;return{fixedPos:L(t),gutterTotalWidth:t.gutters.offsetWidth,gutterLeft:i,gutterWidth:r,wrapperWidth:t.wrapper.clientWidth}}function O(e,t,i){function r(t){var i=t.nextSibling;return Wo&&es&&e.display.currentWheelTarget==t?t.style.display="none":t.parentNode.removeChild(t),i}for(var n=e.display,o=e.options.lineNumbers,s=n.lineDiv,a=s.firstChild,l=n.view,u=n.viewFrom,p=0;p<l.length;p++){var c=l[p];if(c.hidden);else if(c.node){for(;a!=c.node;)a=r(a);var d=o&&null!=t&&u>=t&&c.lineNumber;c.changes&&(to(c.changes,"gutter")>-1&&(d=!1),P(e,c,u,i)),d&&(po(c.lineNumber),c.lineNumber.appendChild(document.createTextNode(N(e.options,u)))),a=c.node.nextSibling}else{var E=U(e,c,u,i);s.insertBefore(E,a)}u+=c.size}for(;a;)a=r(a)}function P(e,t,i,r){for(var n=0;n<t.changes.length;n++){var o=t.changes[n];"text"==o?w(e,t):"gutter"==o?k(e,t,i,r):"class"==o?G(t):"widget"==o&&B(t,r)}t.changes=null}function D(e){return e.node==e.text&&(e.node=uo("div",null,null,"position: relative"),e.text.parentNode&&e.text.parentNode.replaceChild(e.node,e.text),e.node.appendChild(e.text),Uo&&(e.node.style.zIndex=2)),e.node}function _(e){var t=e.bgClass?e.bgClass+" "+(e.line.bgClass||""):e.line.bgClass;if(t&&(t+=" CodeMirror-linebackground"),e.background)t?e.background.className=t:(e.background.parentNode.removeChild(e.background),e.background=null);else if(t){var i=D(e);e.background=i.insertBefore(uo("div",null,t),i.firstChild)}}function M(e,t){var i=e.display.externalMeasured;return i&&i.line==t.line?(e.display.externalMeasured=null,t.measure=i.measure,i.built):sn(e,t)}function w(e,t){var i=t.text.className,r=M(e,t);t.text==t.node&&(t.node=r.pre),t.text.parentNode.replaceChild(r.pre,t.text),t.text=r.pre,r.bgClass!=t.bgClass||r.textClass!=t.textClass?(t.bgClass=r.bgClass,t.textClass=r.textClass,G(t)):i&&(t.text.className=i)}function G(e){_(e),e.line.wrapClass?D(e).className=e.line.wrapClass:e.node!=e.text&&(e.node.className="");var t=e.textClass?e.textClass+" "+(e.line.textClass||""):e.line.textClass;e.text.className=t||""}function k(e,t,i,r){t.gutter&&(t.node.removeChild(t.gutter),t.gutter=null);var n=t.line.gutterMarkers;if(e.options.lineNumbers||n){var o=D(t),s=t.gutter=o.insertBefore(uo("div",null,"CodeMirror-gutter-wrapper","position: absolute; left: "+(e.options.fixedGutter?r.fixedPos:-r.gutterTotalWidth)+"px"),t.text);if(!e.options.lineNumbers||n&&n["CodeMirror-linenumbers"]||(t.lineNumber=s.appendChild(uo("div",N(e.options,i),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+r.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+e.display.lineNumInnerWidth+"px"))),n)for(var a=0;a<e.options.gutters.length;++a){var l=e.options.gutters[a],u=n.hasOwnProperty(l)&&n[l];u&&s.appendChild(uo("div",[u],"CodeMirror-gutter-elt","left: "+r.gutterLeft[l]+"px; width: "+r.gutterWidth[l]+"px"))}}}function B(e,t){e.alignable&&(e.alignable=null);for(var i,r=e.node.firstChild;r;r=i){var i=r.nextSibling;"CodeMirror-linewidget"==r.className&&e.node.removeChild(r)}V(e,t)}function U(e,t,i,r){var n=M(e,t);return t.text=t.node=n.pre,n.bgClass&&(t.bgClass=n.bgClass),n.textClass&&(t.textClass=n.textClass),G(t),k(e,t,i,r),V(t,r),t.node}function V(e,t){if(H(e.line,e,t,!0),e.rest)for(var i=0;i<e.rest.length;i++)H(e.rest[i],e,t,!1)}function H(e,t,i,r){if(e.widgets)for(var n=D(t),o=0,s=e.widgets;o<s.length;++o){var a=s[o],l=uo("div",[a.node],"CodeMirror-linewidget");a.handleMouseEvents||(l.ignoreEvents=!0),F(a,l,t,i),r&&a.above?n.insertBefore(l,t.gutter||t.text):n.appendChild(l),qn(a,"redraw")}}function F(e,t,i,r){if(e.noHScroll){(i.alignable||(i.alignable=[])).push(t);var n=r.wrapperWidth;t.style.left=r.fixedPos+"px",e.coverGutter||(n-=r.gutterTotalWidth,t.style.paddingLeft=r.gutterTotalWidth+"px"),t.style.width=n+"px"}e.coverGutter&&(t.style.zIndex=5,t.style.position="relative",e.noHScroll||(t.style.marginLeft=-r.gutterTotalWidth+"px"))}function j(e){return as(e.line,e.ch) }function W(e,t){return ls(e,t)<0?t:e}function q(e,t){return ls(e,t)<0?e:t}function z(e,t){this.ranges=e,this.primIndex=t}function X(e,t){this.anchor=e,this.head=t}function Y(e,t){var i=e[t];e.sort(function(e,t){return ls(e.from(),t.from())}),t=to(e,i);for(var r=1;r<e.length;r++){var n=e[r],o=e[r-1];if(ls(o.to(),n.from())>=0){var s=q(o.from(),n.from()),a=W(o.to(),n.to()),l=o.empty()?n.from()==n.head:o.from()==o.head;t>=r&&--t,e.splice(--r,2,new X(l?a:s,l?s:a))}}return new z(e,t)}function K(e,t){return new z([new X(e,t||e)],0)}function $(e,t){return Math.max(e.first,Math.min(t,e.first+e.size-1))}function Q(e,t){if(t.line<e.first)return as(e.first,0);var i=e.first+e.size-1;return t.line>i?as(i,xn(e,i).text.length):Z(t,xn(e,t.line).text.length)}function Z(e,t){var i=e.ch;return null==i||i>t?as(e.line,t):0>i?as(e.line,0):e}function J(e,t){return t>=e.first&&t<e.first+e.size}function et(e,t){for(var i=[],r=0;r<t.length;r++)i[r]=Q(e,t[r]);return i}function tt(e,t,i,r){if(e.cm&&e.cm.display.shift||e.extend){var n=t.anchor;if(r){var o=ls(i,n)<0;o!=ls(r,n)<0?(n=i,i=r):o!=ls(i,r)<0&&(i=r)}return new X(n,i)}return new X(r||i,i)}function it(e,t,i,r){lt(e,new z([tt(e,e.sel.primary(),t,i)],0),r)}function rt(e,t,i){for(var r=[],n=0;n<e.sel.ranges.length;n++)r[n]=tt(e,e.sel.ranges[n],t[n],null);var o=Y(r,e.sel.primIndex);lt(e,o,i)}function nt(e,t,i,r){var n=e.sel.ranges.slice(0);n[t]=i,lt(e,Y(n,e.sel.primIndex),r)}function ot(e,t,i,r){lt(e,K(t,i),r)}function st(e,t){var i={ranges:t.ranges,update:function(t){this.ranges=[];for(var i=0;i<t.length;i++)this.ranges[i]=new X(Q(e,t[i].anchor),Q(e,t[i].head))}};return Js(e,"beforeSelectionChange",e,i),e.cm&&Js(e.cm,"beforeSelectionChange",e.cm,i),i.ranges!=t.ranges?Y(i.ranges,i.ranges.length-1):t}function at(e,t,i){var r=e.history.done,n=eo(r);n&&n.ranges?(r[r.length-1]=t,ut(e,t,i)):lt(e,t,i)}function lt(e,t,i){ut(e,t,i),_n(e,e.sel,e.cm?e.cm.curOp.id:0/0,i)}function ut(e,t,i){(Kn(e,"beforeSelectionChange")||e.cm&&Kn(e.cm,"beforeSelectionChange"))&&(t=st(e,t));var r=i&&i.bias||(ls(t.primary().head,e.sel.primary().head)<0?-1:1);pt(e,dt(e,t,r,!0)),i&&i.scroll===!1||!e.cm||sr(e.cm)}function pt(e,t){t.equals(e.sel)||(e.sel=t,e.cm&&(e.cm.curOp.updateInput=e.cm.curOp.selectionChanged=!0,Yn(e.cm)),qn(e,"cursorActivity",e))}function ct(e){pt(e,dt(e,e.sel,null,!1),ra)}function dt(e,t,i,r){for(var n,o=0;o<t.ranges.length;o++){var s=t.ranges[o],a=Et(e,s.anchor,i,r),l=Et(e,s.head,i,r);(n||a!=s.anchor||l!=s.head)&&(n||(n=t.ranges.slice(0,o)),n[o]=new X(a,l))}return n?Y(n,t.primIndex):t}function Et(e,t,i,r){var n=!1,o=t,s=i||1;e.cantEdit=!1;e:for(;;){var a=xn(e,o.line);if(a.markedSpans)for(var l=0;l<a.markedSpans.length;++l){var u=a.markedSpans[l],p=u.marker;if((null==u.from||(p.inclusiveLeft?u.from<=o.ch:u.from<o.ch))&&(null==u.to||(p.inclusiveRight?u.to>=o.ch:u.to>o.ch))){if(r&&(Js(p,"beforeCursorEnter"),p.explicitlyCleared)){if(a.markedSpans){--l;continue}break}if(!p.atomic)continue;var c=p.find(0>s?-1:1);if(0==ls(c,o)&&(c.ch+=s,c.ch<0?c=c.line>e.first?Q(e,as(c.line-1)):null:c.ch>a.text.length&&(c=c.line<e.first+e.size-1?as(c.line+1,0):null),!c)){if(n)return r?(e.cantEdit=!0,as(e.first,0)):Et(e,t,i,!0);n=!0,c=t,s=-s}o=c;continue e}}return o}}function ht(e){for(var t=e.display,i=e.doc,r=document.createDocumentFragment(),n=document.createDocumentFragment(),o=0;o<i.sel.ranges.length;o++){var s=i.sel.ranges[o],a=s.empty();(a||e.options.showCursorWhenSelecting)&&ft(e,s,r),a||mt(e,s,n)}if(e.options.moveInputWithCursor){var l=Ht(e,i.sel.primary().head,"div"),u=t.wrapper.getBoundingClientRect(),p=t.lineDiv.getBoundingClientRect(),c=Math.max(0,Math.min(t.wrapper.clientHeight-10,l.top+p.top-u.top)),d=Math.max(0,Math.min(t.wrapper.clientWidth-10,l.left+p.left-u.left));t.inputDiv.style.top=c+"px",t.inputDiv.style.left=d+"px"}co(t.cursorDiv,r),co(t.selectionDiv,n)}function ft(e,t,i){var r=Ht(e,t.head,"div"),n=i.appendChild(uo("div"," ","CodeMirror-cursor"));if(n.style.left=r.left+"px",n.style.top=r.top+"px",n.style.height=Math.max(0,r.bottom-r.top)*e.options.cursorHeight+"px",r.other){var o=i.appendChild(uo("div"," ","CodeMirror-cursor CodeMirror-secondarycursor"));o.style.display="",o.style.left=r.other.left+"px",o.style.top=r.other.top+"px",o.style.height=.85*(r.other.bottom-r.other.top)+"px"}}function mt(e,t,i){function r(e,t,i,r){0>t&&(t=0),t=Math.round(t),r=Math.round(r),a.appendChild(uo("div",null,"CodeMirror-selected","position: absolute; left: "+e+"px; top: "+t+"px; width: "+(null==i?p-e:i)+"px; height: "+(r-t)+"px"))}function n(t,i,n){function o(i,r){return Vt(e,as(t,i),"div",c,r)}var a,l,c=xn(s,t),d=c.text.length;return Ao(Sn(c),i||0,null==n?d:n,function(e,t,s){var c,E,h,f=o(e,"left");if(e==t)c=f,E=h=f.left;else{if(c=o(t-1,"right"),"rtl"==s){var m=f;f=c,c=m}E=f.left,h=c.right}null==i&&0==e&&(E=u),c.top-f.top>3&&(r(E,f.top,null,f.bottom),E=u,f.bottom<c.top&&r(E,f.bottom,null,c.top)),null==n&&t==d&&(h=p),(!a||f.top<a.top||f.top==a.top&&f.left<a.left)&&(a=f),(!l||c.bottom>l.bottom||c.bottom==l.bottom&&c.right>l.right)&&(l=c),u+1>E&&(E=u),r(E,c.top,h-E,c.bottom)}),{start:a,end:l}}var o=e.display,s=e.doc,a=document.createDocumentFragment(),l=yt(e.display),u=l.left,p=o.lineSpace.offsetWidth-l.right,c=t.from(),d=t.to();if(c.line==d.line)n(c.line,c.ch,d.ch);else{var E=xn(s,c.line),h=xn(s,d.line),f=Vr(E)==Vr(h),m=n(c.line,c.ch,f?E.text.length+1:null).end,g=n(d.line,f?0:null,d.ch).start;f&&(m.top<g.top-2?(r(m.right,m.top,null,m.bottom),r(u,g.top,g.left,g.bottom)):r(m.right,m.top,g.left-m.right,m.bottom)),m.bottom<g.top&&r(u,m.bottom,null,g.top)}i.appendChild(a)}function gt(e){if(e.state.focused){var t=e.display;clearInterval(t.blinker);var i=!0;t.cursorDiv.style.visibility="",e.options.cursorBlinkRate>0&&(t.blinker=setInterval(function(){t.cursorDiv.style.visibility=(i=!i)?"":"hidden"},e.options.cursorBlinkRate))}}function vt(e,t){e.doc.mode.startState&&e.doc.frontier<e.display.viewTo&&e.state.highlight.set(t,oo(xt,e))}function xt(e){var t=e.doc;if(t.frontier<t.first&&(t.frontier=t.first),!(t.frontier>=e.display.viewTo)){var i=+new Date+e.options.workTime,r=Rs(t.mode,Lt(e,t.frontier));$t(e,function(){t.iter(t.frontier,Math.min(t.first+t.size,e.display.viewTo+500),function(n){if(t.frontier>=e.display.viewFrom){var o=n.styles,s=tn(e,n,r,!0);n.styles=s.styles,s.classes?n.styleClasses=s.classes:n.styleClasses&&(n.styleClasses=null);for(var a=!o||o.length!=n.styles.length,l=0;!a&&l<o.length;++l)a=o[l]!=n.styles[l];a&&ri(e,t.frontier,"text"),n.stateAfter=Rs(t.mode,r)}else nn(e,n.text,r),n.stateAfter=t.frontier%5==0?Rs(t.mode,r):null;return++t.frontier,+new Date>i?(vt(e,e.options.workDelay),!0):void 0})})}}function Nt(e,t,i){for(var r,n,o=e.doc,s=i?-1:t-(e.doc.mode.innerMode?1e3:100),a=t;a>s;--a){if(a<=o.first)return o.first;var l=xn(o,a-1);if(l.stateAfter&&(!i||a<=o.frontier))return a;var u=sa(l.text,null,e.options.tabSize);(null==n||r>u)&&(n=a-1,r=u)}return n}function Lt(e,t,i){var r=e.doc,n=e.display;if(!r.mode.startState)return!0;var o=Nt(e,t,i),s=o>r.first&&xn(r,o-1).stateAfter;return s=s?Rs(r.mode,s):bs(r.mode),r.iter(o,t,function(i){nn(e,i.text,s);var a=o==t-1||o%5==0||o>=n.viewFrom&&o<n.viewTo;i.stateAfter=a?Rs(r.mode,s):null,++o}),i&&(r.frontier=o),s}function Tt(e){return e.lineSpace.offsetTop}function It(e){return e.mover.offsetHeight-e.lineSpace.offsetHeight}function yt(e){if(e.cachedPaddingH)return e.cachedPaddingH;var t=co(e.measure,uo("pre","x")),i=window.getComputedStyle?window.getComputedStyle(t):t.currentStyle,r={left:parseInt(i.paddingLeft),right:parseInt(i.paddingRight)};return isNaN(r.left)||isNaN(r.right)||(e.cachedPaddingH=r),r}function At(e,t,i){var r=e.options.lineWrapping,n=r&&e.display.scroller.clientWidth;if(!t.measure.heights||r&&t.measure.width!=n){var o=t.measure.heights=[];if(r){t.measure.width=n;for(var s=t.text.firstChild.getClientRects(),a=0;a<s.length-1;a++){var l=s[a],u=s[a+1];Math.abs(l.bottom-u.bottom)>2&&o.push((l.bottom+u.top)/2-i.top)}}o.push(i.bottom-i.top)}}function St(e,t,i){if(e.line==t)return{map:e.measure.map,cache:e.measure.cache};for(var r=0;r<e.rest.length;r++)if(e.rest[r]==t)return{map:e.measure.maps[r],cache:e.measure.caches[r]};for(var r=0;r<e.rest.length;r++)if(In(e.rest[r])>i)return{map:e.measure.maps[r],cache:e.measure.caches[r],before:!0}}function Ct(e,t){t=Vr(t);var i=In(t),r=e.display.externalMeasured=new ei(e.doc,t,i);r.lineN=i;var n=r.built=sn(e,r);return r.text=n.pre,co(e.display.lineMeasure,n.pre),r}function Rt(e,t,i,r){return Pt(e,Ot(e,t),i,r)}function bt(e,t){if(t>=e.display.viewFrom&&t<e.display.viewTo)return e.display.view[oi(e,t)];var i=e.display.externalMeasured;return i&&t>=i.lineN&&t<i.lineN+i.size?i:void 0}function Ot(e,t){var i=In(t),r=bt(e,i);r&&!r.text?r=null:r&&r.changes&&P(e,r,i,b(e)),r||(r=Ct(e,t));var n=St(r,t,i);return{line:t,view:r,rect:null,map:n.map,cache:n.cache,before:n.before,hasHeights:!1}}function Pt(e,t,i,r){t.before&&(i=-1);var n,o=i+(r||"");return t.cache.hasOwnProperty(o)?n=t.cache[o]:(t.rect||(t.rect=t.view.text.getBoundingClientRect()),t.hasHeights||(At(e,t.view,t.rect),t.hasHeights=!0),n=Dt(e,t,i,r),n.bogus||(t.cache[o]=n)),{left:n.left,right:n.right,top:n.top,bottom:n.bottom}}function Dt(e,t,i,r){for(var n,o,s,a,l=t.map,u=0;u<l.length;u+=3){var p=l[u],c=l[u+1];if(p>i?(o=0,s=1,a="left"):c>i?(o=i-p,s=o+1):(u==l.length-3||i==c&&l[u+3]>i)&&(s=c-p,o=s-1,i>=c&&(a="right")),null!=o){if(n=l[u+2],p==c&&r==(n.insertLeft?"left":"right")&&(a=r),"left"==r&&0==o)for(;u&&l[u-2]==l[u-3]&&l[u-1].insertLeft;)n=l[(u-=3)+2],a="left";if("right"==r&&o==c-p)for(;u<l.length-3&&l[u+3]==l[u+4]&&!l[u+5].insertLeft;)n=l[(u+=3)+2],a="right";break}}var d;if(3==n.nodeType){for(;o&&lo(t.line.text.charAt(p+o));)--o;for(;c>p+s&&lo(t.line.text.charAt(p+s));)++s;if(Vo&&0==o&&s==c-p)d=n.parentNode.getBoundingClientRect();else if(jo&&e.options.lineWrapping){var E=ua(n,o,s).getClientRects();d=E.length?E["right"==r?E.length-1:0]:ds}else d=ua(n,o,s).getBoundingClientRect()||ds}else{o>0&&(a=r="right");var E;d=e.options.lineWrapping&&(E=n.getClientRects()).length>1?E["right"==r?E.length-1:0]:n.getBoundingClientRect()}if(Vo&&!o&&(!d||!d.left&&!d.right)){var h=n.parentNode.getClientRects()[0];d=h?{left:h.left,right:h.left+Xt(e.display),top:h.top,bottom:h.bottom}:ds}for(var f,m=(d.bottom+d.top)/2-t.rect.top,g=t.view.measure.heights,u=0;u<g.length-1&&!(m<g[u]);u++);f=u?g[u-1]:0,m=g[u];var v={left:("right"==a?d.right:d.left)-t.rect.left,right:("left"==a?d.left:d.right)-t.rect.left,top:f,bottom:m};return d.left||d.right||(v.bogus=!0),v}function _t(e){if(e.measure&&(e.measure.cache={},e.measure.heights=null,e.rest))for(var t=0;t<e.rest.length;t++)e.measure.caches[t]={}}function Mt(e){e.display.externalMeasure=null,po(e.display.lineMeasure);for(var t=0;t<e.display.view.length;t++)_t(e.display.view[t])}function wt(e){Mt(e),e.display.cachedCharWidth=e.display.cachedTextHeight=e.display.cachedPaddingH=null,e.options.lineWrapping||(e.display.maxLineChanged=!0),e.display.lineNumChars=null}function Gt(){return window.pageXOffset||(document.documentElement||document.body).scrollLeft}function kt(){return window.pageYOffset||(document.documentElement||document.body).scrollTop}function Bt(e,t,i,r){if(t.widgets)for(var n=0;n<t.widgets.length;++n)if(t.widgets[n].above){var o=Xr(t.widgets[n]);i.top+=o,i.bottom+=o}if("line"==r)return i;r||(r="local");var s=An(t);if("local"==r?s+=Tt(e.display):s-=e.display.viewOffset,"page"==r||"window"==r){var a=e.display.lineSpace.getBoundingClientRect();s+=a.top+("window"==r?0:kt());var l=a.left+("window"==r?0:Gt());i.left+=l,i.right+=l}return i.top+=s,i.bottom+=s,i}function Ut(e,t,i){if("div"==i)return t;var r=t.left,n=t.top;if("page"==i)r-=Gt(),n-=kt();else if("local"==i||!i){var o=e.display.sizer.getBoundingClientRect();r+=o.left,n+=o.top}var s=e.display.lineSpace.getBoundingClientRect();return{left:r-s.left,top:n-s.top}}function Vt(e,t,i,r,n){return r||(r=xn(e.doc,t.line)),Bt(e,r,Rt(e,r,t.ch,n),i)}function Ht(e,t,i,r,n){function o(t,o){var s=Pt(e,n,t,o?"right":"left");return o?s.left=s.right:s.right=s.left,Bt(e,r,s,i)}function s(e,t){var i=a[t],r=i.level%2;return e==So(i)&&t&&i.level<a[t-1].level?(i=a[--t],e=Co(i)-(i.level%2?0:1),r=!0):e==Co(i)&&t<a.length-1&&i.level<a[t+1].level&&(i=a[++t],e=So(i)-i.level%2,r=!1),r&&e==i.to&&e>i.from?o(e-1):o(e,r)}r=r||xn(e.doc,t.line),n||(n=Ot(e,r));var a=Sn(r),l=t.ch;if(!a)return o(l);var u=_o(a,l),p=s(l,u);return null!=Ta&&(p.other=s(l,Ta)),p}function Ft(e,t){var i=0,t=Q(e.doc,t);e.options.lineWrapping||(i=Xt(e.display)*t.ch);var r=xn(e.doc,t.line),n=An(r)+Tt(e.display);return{left:i,right:i,top:n,bottom:n+r.height}}function jt(e,t,i,r){var n=as(e,t);return n.xRel=r,i&&(n.outside=!0),n}function Wt(e,t,i){var r=e.doc;if(i+=e.display.viewOffset,0>i)return jt(r.first,0,!0,-1);var n=yn(r,i),o=r.first+r.size-1;if(n>o)return jt(r.first+r.size-1,xn(r,o).text.length,!0,1);0>t&&(t=0);for(var s=xn(r,n);;){var a=qt(e,s,n,t,i),l=Br(s),u=l&&l.find(0,!0);if(!l||!(a.ch>u.from.ch||a.ch==u.from.ch&&a.xRel>0))return a;n=In(s=u.to.line)}}function qt(e,t,i,r,n){function o(r){var n=Ht(e,as(i,r),"line",t,u);return a=!0,s>n.bottom?n.left-l:s<n.top?n.left+l:(a=!1,n.left)}var s=n-An(t),a=!1,l=2*e.display.wrapper.clientWidth,u=Ot(e,t),p=Sn(t),c=t.text.length,d=Ro(t),E=bo(t),h=o(d),f=a,m=o(E),g=a;if(r>m)return jt(i,E,g,1);for(;;){if(p?E==d||E==wo(t,d,1):1>=E-d){for(var v=h>r||m-r>=r-h?d:E,x=r-(v==d?h:m);lo(t.text.charAt(v));)++v;var N=jt(i,v,v==d?f:g,-1>x?-1:x>1?1:0);return N}var L=Math.ceil(c/2),T=d+L;if(p){T=d;for(var I=0;L>I;++I)T=wo(t,T,1)}var y=o(T);y>r?(E=T,m=y,(g=a)&&(m+=1e3),c=L):(d=T,h=y,f=a,c-=L)}}function zt(e){if(null!=e.cachedTextHeight)return e.cachedTextHeight;if(null==us){us=uo("pre");for(var t=0;49>t;++t)us.appendChild(document.createTextNode("x")),us.appendChild(uo("br"));us.appendChild(document.createTextNode("x"))}co(e.measure,us);var i=us.offsetHeight/50;return i>3&&(e.cachedTextHeight=i),po(e.measure),i||1}function Xt(e){if(null!=e.cachedCharWidth)return e.cachedCharWidth;var t=uo("span","xxxxxxxxxx"),i=uo("pre",[t]);co(e.measure,i);var r=t.getBoundingClientRect(),n=(r.right-r.left)/10;return n>2&&(e.cachedCharWidth=n),n||10}function Yt(e){e.curOp={viewChanged:!1,startHeight:e.doc.height,forceUpdate:!1,updateInput:null,typing:!1,changeObjs:null,cursorActivityHandlers:null,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,id:++Es},ea++||(Xs=[])}function Kt(e){var t=e.curOp,i=e.doc,r=e.display;if(e.curOp=null,t.updateMaxLine&&E(e),t.viewChanged||t.forceUpdate||null!=t.scrollTop||t.scrollToPos&&(t.scrollToPos.from.line<r.viewFrom||t.scrollToPos.to.line>=r.viewTo)||r.maxLineChanged&&e.options.lineWrapping){var n=T(e,{top:t.scrollTop,ensure:t.scrollToPos},t.forceUpdate);e.display.scroller.offsetHeight&&(e.doc.scrollTop=e.display.scroller.scrollTop)}if(!n&&t.selectionChanged&&ht(e),n||t.startHeight==e.doc.height||m(e),null==r.wheelStartX||null==t.scrollTop&&null==t.scrollLeft&&!t.scrollToPos||(r.wheelStartX=r.wheelStartY=null),null!=t.scrollTop&&r.scroller.scrollTop!=t.scrollTop){var o=Math.max(0,Math.min(r.scroller.scrollHeight-r.scroller.clientHeight,t.scrollTop));r.scroller.scrollTop=r.scrollbarV.scrollTop=i.scrollTop=o}if(null!=t.scrollLeft&&r.scroller.scrollLeft!=t.scrollLeft){var s=Math.max(0,Math.min(r.scroller.scrollWidth-r.scroller.clientWidth,t.scrollLeft));r.scroller.scrollLeft=r.scrollbarH.scrollLeft=i.scrollLeft=s,v(e)}if(t.scrollToPos){var a=ir(e,Q(e.doc,t.scrollToPos.from),Q(e.doc,t.scrollToPos.to),t.scrollToPos.margin);t.scrollToPos.isCursor&&e.state.focused&&tr(e,a)}t.selectionChanged&&gt(e),e.state.focused&&t.updateInput&&di(e,t.typing);var l=t.maybeHiddenMarkers,u=t.maybeUnhiddenMarkers;if(l)for(var p=0;p<l.length;++p)l[p].lines.length||Js(l[p],"hide");if(u)for(var p=0;p<u.length;++p)u[p].lines.length&&Js(u[p],"unhide");var c;if(--ea||(c=Xs,Xs=null),t.changeObjs&&Js(e,"changes",e,t.changeObjs),c)for(var p=0;p<c.length;++p)c[p]();if(t.cursorActivityHandlers)for(var p=0;p<t.cursorActivityHandlers.length;p++)t.cursorActivityHandlers[p](e)}function $t(e,t){if(e.curOp)return t();Yt(e);try{return t()}finally{Kt(e)}}function Qt(e,t){return function(){if(e.curOp)return t.apply(e,arguments);Yt(e);try{return t.apply(e,arguments)}finally{Kt(e)}}}function Zt(e){return function(){if(this.curOp)return e.apply(this,arguments);Yt(this);try{return e.apply(this,arguments)}finally{Kt(this)}}}function Jt(e){return function(){var t=this.cm;if(!t||t.curOp)return e.apply(this,arguments);Yt(t);try{return e.apply(this,arguments)}finally{Kt(t)}}}function ei(e,t,i){this.line=t,this.rest=Hr(t),this.size=this.rest?In(eo(this.rest))-i+1:1,this.node=this.text=null,this.hidden=Wr(e,t)}function ti(e,t,i){for(var r,n=[],o=t;i>o;o=r){var s=new ei(e.doc,xn(e.doc,o),o);r=o+s.size,n.push(s)}return n}function ii(e,t,i,r){null==t&&(t=e.doc.first),null==i&&(i=e.doc.first+e.doc.size),r||(r=0);var n=e.display;if(r&&i<n.viewTo&&(null==n.updateLineNumbers||n.updateLineNumbers>t)&&(n.updateLineNumbers=t),e.curOp.viewChanged=!0,t>=n.viewTo)ss&&Fr(e.doc,t)<n.viewTo&&ni(e);else if(i<=n.viewFrom)ss&&jr(e.doc,i+r)>n.viewFrom?ni(e):(n.viewFrom+=r,n.viewTo+=r);else if(t<=n.viewFrom&&i>=n.viewTo)ni(e);else if(t<=n.viewFrom){var o=si(e,i,i+r,1);o?(n.view=n.view.slice(o.index),n.viewFrom=o.lineN,n.viewTo+=r):ni(e)}else if(i>=n.viewTo){var o=si(e,t,t,-1);o?(n.view=n.view.slice(0,o.index),n.viewTo=o.lineN):ni(e)}else{var s=si(e,t,t,-1),a=si(e,i,i+r,1);s&&a?(n.view=n.view.slice(0,s.index).concat(ti(e,s.lineN,a.lineN)).concat(n.view.slice(a.index)),n.viewTo+=r):ni(e)}var l=n.externalMeasured;l&&(i<l.lineN?l.lineN+=r:t<l.lineN+l.size&&(n.externalMeasured=null))}function ri(e,t,i){e.curOp.viewChanged=!0;var r=e.display,n=e.display.externalMeasured;if(n&&t>=n.lineN&&t<n.lineN+n.size&&(r.externalMeasured=null),!(t<r.viewFrom||t>=r.viewTo)){var o=r.view[oi(e,t)];if(null!=o.node){var s=o.changes||(o.changes=[]);-1==to(s,i)&&s.push(i)}}}function ni(e){e.display.viewFrom=e.display.viewTo=e.doc.first,e.display.view=[],e.display.viewOffset=0}function oi(e,t){if(t>=e.display.viewTo)return null;if(t-=e.display.viewFrom,0>t)return null;for(var i=e.display.view,r=0;r<i.length;r++)if(t-=i[r].size,0>t)return r}function si(e,t,i,r){var n,o=oi(e,t),s=e.display.view;if(!ss||i==e.doc.first+e.doc.size)return{index:o,lineN:i};for(var a=0,l=e.display.viewFrom;o>a;a++)l+=s[a].size;if(l!=t){if(r>0){if(o==s.length-1)return null;n=l+s[o].size-t,o++}else n=l-t;t+=n,i+=n}for(;Fr(e.doc,i)!=i;){if(o==(0>r?0:s.length-1))return null;i+=r*s[o-(0>r?1:0)].size,o+=r}return{index:o,lineN:i}}function ai(e,t,i){var r=e.display,n=r.view;0==n.length||t>=r.viewTo||i<=r.viewFrom?(r.view=ti(e,t,i),r.viewFrom=t):(r.viewFrom>t?r.view=ti(e,t,r.viewFrom).concat(r.view):r.viewFrom<t&&(r.view=r.view.slice(oi(e,t))),r.viewFrom=t,r.viewTo<i?r.view=r.view.concat(ti(e,r.viewTo,i)):r.viewTo>i&&(r.view=r.view.slice(0,oi(e,i)))),r.viewTo=i}function li(e){for(var t=e.display.view,i=0,r=0;r<t.length;r++){var n=t[r];n.hidden||n.node&&!n.changes||++i}return i}function ui(e){e.display.pollingFast||e.display.poll.set(e.options.pollInterval,function(){ci(e),e.state.focused&&ui(e)})}function pi(e){function t(){var r=ci(e);r||i?(e.display.pollingFast=!1,ui(e)):(i=!0,e.display.poll.set(60,t))}var i=!1;e.display.pollingFast=!0,e.display.poll.set(20,t)}function ci(e){var t=e.display.input,i=e.display.prevInput,r=e.doc;if(!e.state.focused||xa(t)&&!i||fi(e)||e.options.disableInput)return!1;e.state.pasteIncoming&&e.state.fakedLastChar&&(t.value=t.value.substring(0,t.value.length-1),e.state.fakedLastChar=!1);var n=t.value;if(n==i&&!e.somethingSelected())return!1;if(jo&&!Vo&&e.display.inputHasSelection===n)return di(e),!1;var o=!e.curOp;o&&Yt(e),e.display.shift=!1,8203!=n.charCodeAt(0)||r.sel!=e.display.selForContextMenu||i||(i="​");for(var s=0,a=Math.min(i.length,n.length);a>s&&i.charCodeAt(s)==n.charCodeAt(s);)++s;for(var l=n.slice(s),u=va(l),p=e.state.pasteIncoming&&u.length>1&&r.sel.ranges.length==u.length,c=r.sel.ranges.length-1;c>=0;c--){var d=r.sel.ranges[c],E=d.from(),h=d.to();s<i.length?E=as(E.line,E.ch-(i.length-s)):e.state.overwrite&&d.empty()&&!e.state.pasteIncoming&&(h=as(h.line,Math.min(xn(r,h.line).text.length,h.ch+eo(u).length)));var f=e.curOp.updateInput,m={from:E,to:h,text:p?[u[c]]:u,origin:e.state.pasteIncoming?"paste":e.state.cutIncoming?"cut":"+input"};if(Yi(e.doc,m),qn(e,"inputRead",e,m),l&&!e.state.pasteIncoming&&e.options.electricChars&&e.options.smartIndent&&d.head.ch<100&&(!c||r.sel.ranges[c-1].head.line!=d.head.line)){var g=e.getModeAt(d.head);if(g.electricChars){for(var v=0;v<g.electricChars.length;v++)if(l.indexOf(g.electricChars.charAt(v))>-1){lr(e,d.head.line,"smart");break}}else if(g.electricInput){var x=xs(m);g.electricInput.test(xn(r,x.line).text.slice(0,x.ch))&&lr(e,d.head.line,"smart")}}}return sr(e),e.curOp.updateInput=f,e.curOp.typing=!0,n.length>1e3||n.indexOf("\n")>-1?t.value=e.display.prevInput="":e.display.prevInput=n,o&&Kt(e),e.state.pasteIncoming=e.state.cutIncoming=!1,!0}function di(e,t){var i,r,n=e.doc;if(e.somethingSelected()){e.display.prevInput="";var o=n.sel.primary();i=Na&&(o.to().line-o.from().line>100||(r=e.getSelection()).length>1e3);var s=i?"-":r||e.getSelection();e.display.input.value=s,e.state.focused&&la(e.display.input),jo&&!Vo&&(e.display.inputHasSelection=s)}else t||(e.display.prevInput=e.display.input.value="",jo&&!Vo&&(e.display.inputHasSelection=null));e.display.inaccurateSelection=i}function Ei(e){"nocursor"==e.options.readOnly||Jo&&ho()==e.display.input||e.display.input.focus()}function hi(e){e.state.focused||(Ei(e),Ui(e))}function fi(e){return e.options.readOnly||e.doc.cantEdit}function mi(e){function t(){e.state.focused&&setTimeout(oo(Ei,e),0)}function i(t){Xn(e,t)||$s(t)}function r(t){if(e.somethingSelected())n.inaccurateSelection&&(n.prevInput="",n.inaccurateSelection=!1,n.input.value=e.getSelection(),la(n.input));else{for(var i="",r=[],o=0;o<e.doc.sel.ranges.length;o++){var s=e.doc.sel.ranges[o].head.line,a={anchor:as(s,0),head:as(s+1,0)};r.push(a),i+=e.getRange(a.anchor,a.head)}"cut"==t.type?e.setSelections(r,null,ra):(n.prevInput="",n.input.value=i,la(n.input))}"cut"==t.type&&(e.state.cutIncoming=!0)}var n=e.display;Qs(n.scroller,"mousedown",Qt(e,Ni)),Bo?Qs(n.scroller,"dblclick",Qt(e,function(t){if(!Xn(e,t)){var i=xi(e,t);if(i&&!Ai(e,t)&&!vi(e.display,t)){Ys(t);var r=Er(e,i);it(e.doc,r.anchor,r.head)}}})):Qs(n.scroller,"dblclick",function(t){Xn(e,t)||Ys(t)}),Qs(n.lineSpace,"selectstart",function(e){vi(n,e)||Ys(e)}),ns||Qs(n.scroller,"contextmenu",function(t){Hi(e,t)}),Qs(n.scroller,"scroll",function(){n.scroller.clientHeight&&(Ri(e,n.scroller.scrollTop),bi(e,n.scroller.scrollLeft,!0),Js(e,"scroll",e))}),Qs(n.scrollbarV,"scroll",function(){n.scroller.clientHeight&&Ri(e,n.scrollbarV.scrollTop)}),Qs(n.scrollbarH,"scroll",function(){n.scroller.clientHeight&&bi(e,n.scrollbarH.scrollLeft)}),Qs(n.scroller,"mousewheel",function(t){Oi(e,t)}),Qs(n.scroller,"DOMMouseScroll",function(t){Oi(e,t)}),Qs(n.scrollbarH,"mousedown",t),Qs(n.scrollbarV,"mousedown",t),Qs(n.wrapper,"scroll",function(){n.wrapper.scrollTop=n.wrapper.scrollLeft=0}),Qs(n.input,"keyup",Qt(e,ki)),Qs(n.input,"input",function(){jo&&!Vo&&e.display.inputHasSelection&&(e.display.inputHasSelection=null),pi(e)}),Qs(n.input,"keydown",Qt(e,wi)),Qs(n.input,"keypress",Qt(e,Bi)),Qs(n.input,"focus",oo(Ui,e)),Qs(n.input,"blur",oo(Vi,e)),e.options.dragDrop&&(Qs(n.scroller,"dragstart",function(t){Ci(e,t)}),Qs(n.scroller,"dragenter",i),Qs(n.scroller,"dragover",i),Qs(n.scroller,"drop",Qt(e,Si))),Qs(n.scroller,"paste",function(t){vi(n,t)||(e.state.pasteIncoming=!0,Ei(e),pi(e))}),Qs(n.input,"paste",function(){if(Wo&&!e.state.fakedLastChar&&!(new Date-e.state.lastMiddleDown<200)){var t=n.input.selectionStart,i=n.input.selectionEnd;n.input.value+="$",n.input.selectionStart=t,n.input.selectionEnd=i,e.state.fakedLastChar=!0}e.state.pasteIncoming=!0,pi(e)}),Qs(n.input,"cut",r),Qs(n.input,"copy",r),Ko&&Qs(n.sizer,"mouseup",function(){ho()==n.input&&n.input.blur(),Ei(e)})}function gi(e){var t=e.display;t.cachedCharWidth=t.cachedTextHeight=t.cachedPaddingH=null,e.setSize()}function vi(e,t){for(var i=jn(t);i!=e.wrapper;i=i.parentNode)if(!i||i.ignoreEvents||i.parentNode==e.sizer&&i!=e.mover)return!0}function xi(e,t,i,r){var n=e.display;if(!i){var o=jn(t);if(o==n.scrollbarH||o==n.scrollbarV||o==n.scrollbarFiller||o==n.gutterFiller)return null}var s,a,l=n.lineSpace.getBoundingClientRect();try{s=t.clientX-l.left,a=t.clientY-l.top}catch(t){return null}var u,p=Wt(e,s,a);if(r&&1==p.xRel&&(u=xn(e.doc,p.line).text).length==p.ch){var c=sa(u,u.length,e.options.tabSize)-u.length;p=as(p.line,Math.max(0,Math.round((s-yt(e.display).left)/Xt(e.display))-c))}return p}function Ni(e){if(!Xn(this,e)){var t=this,i=t.display;if(i.shift=e.shiftKey,vi(i,e))return void(Wo||(i.scroller.draggable=!1,setTimeout(function(){i.scroller.draggable=!0},100)));if(!Ai(t,e)){var r=xi(t,e);switch(window.focus(),Wn(e)){case 1:r?Li(t,e,r):jn(e)==i.scroller&&Ys(e);break;case 2:Wo&&(t.state.lastMiddleDown=+new Date),r&&it(t.doc,r),setTimeout(oo(Ei,t),20),Ys(e);break;case 3:ns&&Hi(t,e)}}}}function Li(e,t,i){setTimeout(oo(hi,e),0);var r,n=+new Date;cs&&cs.time>n-400&&0==ls(cs.pos,i)?r="triple":ps&&ps.time>n-400&&0==ls(ps.pos,i)?(r="double",cs={time:n,pos:i}):(r="single",ps={time:n,pos:i});var o=e.doc.sel,s=es?t.metaKey:t.ctrlKey;e.options.dragDrop&&ga&&!fi(e)&&"single"==r&&o.contains(i)>-1&&o.somethingSelected()?Ti(e,t,i,s):Ii(e,t,i,r,s)}function Ti(e,t,i,r){var n=e.display,o=Qt(e,function(s){Wo&&(n.scroller.draggable=!1),e.state.draggingText=!1,Zs(document,"mouseup",o),Zs(n.scroller,"drop",o),Math.abs(t.clientX-s.clientX)+Math.abs(t.clientY-s.clientY)<10&&(Ys(s),r||it(e.doc,i),Ei(e),Bo&&!Vo&&setTimeout(function(){document.body.focus(),Ei(e)},20))});Wo&&(n.scroller.draggable=!0),e.state.draggingText=o,n.scroller.dragDrop&&n.scroller.dragDrop(),Qs(document,"mouseup",o),Qs(n.scroller,"drop",o)}function Ii(e,t,i,r,n){function o(t){if(0!=ls(f,t))if(f=t,"rect"==r){for(var n=[],o=e.options.tabSize,s=sa(xn(u,i.line).text,i.ch,o),a=sa(xn(u,t.line).text,t.ch,o),l=Math.min(s,a),E=Math.max(s,a),h=Math.min(i.line,t.line),m=Math.min(e.lastLine(),Math.max(i.line,t.line));m>=h;h++){var g=xn(u,h).text,v=Zn(g,l,o);l==E?n.push(new X(as(h,v),as(h,v))):g.length>v&&n.push(new X(as(h,v),as(h,Zn(g,E,o))))}n.length||n.push(new X(i,i)),lt(u,Y(d.ranges.slice(0,c).concat(n),c),{origin:"*mouse",scroll:!1}),e.scrollIntoView(t)}else{var x=p,N=x.anchor,L=t;if("single"!=r){if("double"==r)var T=Er(e,t);else var T=new X(as(t.line,0),Q(u,as(t.line+1,0)));ls(T.anchor,N)>0?(L=T.head,N=q(x.from(),T.anchor)):(L=T.anchor,N=W(x.to(),T.head))}var n=d.ranges.slice(0);n[c]=new X(Q(u,N),L),lt(u,Y(n,c),na)}}function s(t){var i=++v,n=xi(e,t,!0,"rect"==r);if(n)if(0!=ls(n,f)){hi(e),o(n);var a=g(l,u);(n.line>=a.to||n.line<a.from)&&setTimeout(Qt(e,function(){v==i&&s(t)}),150)}else{var p=t.clientY<m.top?-20:t.clientY>m.bottom?20:0;p&&setTimeout(Qt(e,function(){v==i&&(l.scroller.scrollTop+=p,s(t))}),50)}}function a(t){v=1/0,Ys(t),Ei(e),Zs(document,"mousemove",x),Zs(document,"mouseup",N),u.history.lastSelOrigin=null}var l=e.display,u=e.doc;Ys(t);var p,c,d=u.sel;if(n&&!t.shiftKey?(c=u.sel.contains(i),p=c>-1?u.sel.ranges[c]:new X(i,i)):p=u.sel.primary(),t.altKey)r="rect",n||(p=new X(i,i)),i=xi(e,t,!0,!0),c=-1;else if("double"==r){var E=Er(e,i);p=e.display.shift||u.extend?tt(u,p,E.anchor,E.head):E}else if("triple"==r){var h=new X(as(i.line,0),Q(u,as(i.line+1,0)));p=e.display.shift||u.extend?tt(u,p,h.anchor,h.head):h}else p=tt(u,p,i);n?c>-1?nt(u,c,p,na):(c=u.sel.ranges.length,lt(u,Y(u.sel.ranges.concat([p]),c),{scroll:!1,origin:"*mouse"})):(c=0,lt(u,new z([p],0),na),d=u.sel);var f=i,m=l.wrapper.getBoundingClientRect(),v=0,x=Qt(e,function(e){(jo&&!Ho?e.buttons:Wn(e))?s(e):a(e)}),N=Qt(e,a);Qs(document,"mousemove",x),Qs(document,"mouseup",N)}function yi(e,t,i,r,n){try{var o=t.clientX,s=t.clientY}catch(t){return!1}if(o>=Math.floor(e.display.gutters.getBoundingClientRect().right))return!1;r&&Ys(t);var a=e.display,l=a.lineDiv.getBoundingClientRect();if(s>l.bottom||!Kn(e,i))return Fn(t);s-=l.top-a.viewOffset;for(var u=0;u<e.options.gutters.length;++u){var p=a.gutters.childNodes[u];if(p&&p.getBoundingClientRect().right>=o){var c=yn(e.doc,s),d=e.options.gutters[u];return n(e,i,e,c,d,t),Fn(t)}}}function Ai(e,t){return yi(e,t,"gutterClick",!0,qn)}function Si(e){var t=this;if(!Xn(t,e)&&!vi(t.display,e)){Ys(e),jo&&(hs=+new Date);var i=xi(t,e,!0),r=e.dataTransfer.files;if(i&&!fi(t))if(r&&r.length&&window.FileReader&&window.File)for(var n=r.length,o=Array(n),s=0,a=function(e,r){var a=new FileReader;a.onload=Qt(t,function(){if(o[r]=a.result,++s==n){i=Q(t.doc,i);var e={from:i,to:i,text:va(o.join("\n")),origin:"paste"};Yi(t.doc,e),at(t.doc,K(i,xs(e)))}}),a.readAsText(e)},l=0;n>l;++l)a(r[l],l);else{if(t.state.draggingText&&t.doc.sel.contains(i)>-1)return t.state.draggingText(e),void setTimeout(oo(Ei,t),20);try{var o=e.dataTransfer.getData("Text");if(o){if(t.state.draggingText&&!(es?e.metaKey:e.ctrlKey))var u=t.listSelections();if(ut(t.doc,K(i,i)),u)for(var l=0;l<u.length;++l)er(t.doc,"",u[l].anchor,u[l].head,"drag");t.replaceSelection(o,"around","paste"),Ei(t)}}catch(e){}}}}function Ci(e,t){if(jo&&(!e.state.draggingText||+new Date-hs<100))return void $s(t);if(!Xn(e,t)&&!vi(e.display,t)&&(t.dataTransfer.setData("Text",e.getSelection()),t.dataTransfer.setDragImage&&!Yo)){var i=uo("img",null,null,"position: fixed; left: 0; top: 0;");i.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",Xo&&(i.width=i.height=1,e.display.wrapper.appendChild(i),i._top=i.offsetTop),t.dataTransfer.setDragImage(i,0,0),Xo&&i.parentNode.removeChild(i)}}function Ri(e,t){Math.abs(e.doc.scrollTop-t)<2||(e.doc.scrollTop=t,ko||T(e,{top:t}),e.display.scroller.scrollTop!=t&&(e.display.scroller.scrollTop=t),e.display.scrollbarV.scrollTop!=t&&(e.display.scrollbarV.scrollTop=t),ko&&T(e),vt(e,100))}function bi(e,t,i){(i?t==e.doc.scrollLeft:Math.abs(e.doc.scrollLeft-t)<2)||(t=Math.min(t,e.display.scroller.scrollWidth-e.display.scroller.clientWidth),e.doc.scrollLeft=t,v(e),e.display.scroller.scrollLeft!=t&&(e.display.scroller.scrollLeft=t),e.display.scrollbarH.scrollLeft!=t&&(e.display.scrollbarH.scrollLeft=t))}function Oi(e,t){var i=t.wheelDeltaX,r=t.wheelDeltaY;null==i&&t.detail&&t.axis==t.HORIZONTAL_AXIS&&(i=t.detail),null==r&&t.detail&&t.axis==t.VERTICAL_AXIS?r=t.detail:null==r&&(r=t.wheelDelta);var n=e.display,o=n.scroller;if(i&&o.scrollWidth>o.clientWidth||r&&o.scrollHeight>o.clientHeight){if(r&&es&&Wo)e:for(var s=t.target,a=n.view;s!=o;s=s.parentNode)for(var l=0;l<a.length;l++)if(a[l].node==s){e.display.currentWheelTarget=s;break e}if(i&&!ko&&!Xo&&null!=ms)return r&&Ri(e,Math.max(0,Math.min(o.scrollTop+r*ms,o.scrollHeight-o.clientHeight))),bi(e,Math.max(0,Math.min(o.scrollLeft+i*ms,o.scrollWidth-o.clientWidth))),Ys(t),void(n.wheelStartX=null);if(r&&null!=ms){var u=r*ms,p=e.doc.scrollTop,c=p+n.wrapper.clientHeight;0>u?p=Math.max(0,p+u-50):c=Math.min(e.doc.height,c+u+50),T(e,{top:p,bottom:c})}20>fs&&(null==n.wheelStartX?(n.wheelStartX=o.scrollLeft,n.wheelStartY=o.scrollTop,n.wheelDX=i,n.wheelDY=r,setTimeout(function(){if(null!=n.wheelStartX){var e=o.scrollLeft-n.wheelStartX,t=o.scrollTop-n.wheelStartY,i=t&&n.wheelDY&&t/n.wheelDY||e&&n.wheelDX&&e/n.wheelDX;n.wheelStartX=n.wheelStartY=null,i&&(ms=(ms*fs+i)/(fs+1),++fs)}},200)):(n.wheelDX+=i,n.wheelDY+=r))}}function Pi(e,t,i){if("string"==typeof t&&(t=Os[t],!t))return!1;e.display.pollingFast&&ci(e)&&(e.display.pollingFast=!1);var r=e.display.shift,n=!1;try{fi(e)&&(e.state.suppressEdits=!0),i&&(e.display.shift=!1),n=t(e)!=ia}finally{e.display.shift=r,e.state.suppressEdits=!1}return n}function Di(e){var t=e.state.keyMaps.slice(0);return e.options.extraKeys&&t.push(e.options.extraKeys),t.push(e.options.keyMap),t}function _i(e,t){var i=fr(e.options.keyMap),r=i.auto;clearTimeout(gs),r&&!_s(t)&&(gs=setTimeout(function(){fr(e.options.keyMap)==i&&(e.options.keyMap=r.call?r.call(null,e):r,a(e))},50));var n=Ms(t,!0),o=!1;if(!n)return!1;var s=Di(e);return o=t.shiftKey?Ds("Shift-"+n,s,function(t){return Pi(e,t,!0) })||Ds(n,s,function(t){return("string"==typeof t?/^go[A-Z]/.test(t):t.motion)?Pi(e,t):void 0}):Ds(n,s,function(t){return Pi(e,t)}),o&&(Ys(t),gt(e),qn(e,"keyHandled",e,n,t)),o}function Mi(e,t,i){var r=Ds("'"+i+"'",Di(e),function(t){return Pi(e,t,!0)});return r&&(Ys(t),gt(e),qn(e,"keyHandled",e,"'"+i+"'",t)),r}function wi(e){var t=this;if(hi(t),!Xn(t,e)){Bo&&27==e.keyCode&&(e.returnValue=!1);var i=e.keyCode;t.display.shift=16==i||e.shiftKey;var r=_i(t,e);Xo&&(vs=r?i:null,!r&&88==i&&!Na&&(es?e.metaKey:e.ctrlKey)&&t.replaceSelection("",null,"cut")),18!=i||/\bCodeMirror-crosshair\b/.test(t.display.lineDiv.className)||Gi(t)}}function Gi(e){function t(e){18!=e.keyCode&&e.altKey||(mo(i,"CodeMirror-crosshair"),Zs(document,"keyup",t),Zs(document,"mouseover",t))}var i=e.display.lineDiv;go(i,"CodeMirror-crosshair"),Qs(document,"keyup",t),Qs(document,"mouseover",t)}function ki(e){Xn(this,e)||16==e.keyCode&&(this.doc.sel.shift=!1)}function Bi(e){var t=this;if(!Xn(t,e)){var i=e.keyCode,r=e.charCode;if(Xo&&i==vs)return vs=null,void Ys(e);if(!(Xo&&(!e.which||e.which<10)||Ko)||!_i(t,e)){var n=String.fromCharCode(null==r?i:r);Mi(t,e,n)||(jo&&!Vo&&(t.display.inputHasSelection=null),pi(t))}}}function Ui(e){"nocursor"!=e.options.readOnly&&(e.state.focused||(Js(e,"focus",e),e.state.focused=!0,go(e.display.wrapper,"CodeMirror-focused"),e.curOp||e.display.selForContextMenu==e.doc.sel||(di(e),Wo&&setTimeout(oo(di,e,!0),0))),ui(e),gt(e))}function Vi(e){e.state.focused&&(Js(e,"blur",e),e.state.focused=!1,mo(e.display.wrapper,"CodeMirror-focused")),clearInterval(e.display.blinker),setTimeout(function(){e.state.focused||(e.display.shift=!1)},150)}function Hi(e,t){function i(){if(null!=n.input.selectionStart){var t=e.somethingSelected(),i=n.input.value="​"+(t?n.input.value:"");n.prevInput=t?"":"​",n.input.selectionStart=1,n.input.selectionEnd=i.length,n.selForContextMenu=e.doc.sel}}function r(){if(n.inputDiv.style.position="relative",n.input.style.cssText=l,Vo&&(n.scrollbarV.scrollTop=n.scroller.scrollTop=s),ui(e),null!=n.input.selectionStart){(!jo||Vo)&&i();var t=0,r=function(){n.selForContextMenu==e.doc.sel&&0==n.input.selectionStart?Qt(e,Os.selectAll)(e):t++<10?n.detectingSelectAll=setTimeout(r,500):di(e)};n.detectingSelectAll=setTimeout(r,200)}}if(!Xn(e,t,"contextmenu")){var n=e.display;if(!vi(n,t)&&!Fi(e,t)){var o=xi(e,t),s=n.scroller.scrollTop;if(o&&!Xo){var a=e.options.resetSelectionOnContextMenu;a&&-1==e.doc.sel.contains(o)&&Qt(e,lt)(e.doc,K(o),ra);var l=n.input.style.cssText;if(n.inputDiv.style.position="absolute",n.input.style.cssText="position: fixed; width: 30px; height: 30px; top: "+(t.clientY-5)+"px; left: "+(t.clientX-5)+"px; z-index: 1000; background: "+(jo?"rgba(255, 255, 255, .05)":"transparent")+"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);",Ei(e),di(e),e.somethingSelected()||(n.input.value=n.prevInput=" "),n.selForContextMenu=e.doc.sel,clearTimeout(n.detectingSelectAll),jo&&!Vo&&i(),ns){$s(t);var u=function(){Zs(window,"mouseup",u),setTimeout(r,20)};Qs(window,"mouseup",u)}else setTimeout(r,50)}}}}function Fi(e,t){return Kn(e,"gutterContextMenu")?yi(e,t,"gutterContextMenu",!1,Js):!1}function ji(e,t){if(ls(e,t.from)<0)return e;if(ls(e,t.to)<=0)return xs(t);var i=e.line+t.text.length-(t.to.line-t.from.line)-1,r=e.ch;return e.line==t.to.line&&(r+=xs(t).ch-t.to.ch),as(i,r)}function Wi(e,t){for(var i=[],r=0;r<e.sel.ranges.length;r++){var n=e.sel.ranges[r];i.push(new X(ji(n.anchor,t),ji(n.head,t)))}return Y(i,e.sel.primIndex)}function qi(e,t,i){return e.line==t.line?as(i.line,e.ch-t.ch+i.ch):as(i.line+(e.line-t.line),e.ch)}function zi(e,t,i){for(var r=[],n=as(e.first,0),o=n,s=0;s<t.length;s++){var a=t[s],l=qi(a.from,n,o),u=qi(xs(a),n,o);if(n=a.to,o=u,"around"==i){var p=e.sel.ranges[s],c=ls(p.head,p.anchor)<0;r[s]=new X(c?u:l,c?l:u)}else r[s]=new X(l,l)}return new z(r,e.sel.primIndex)}function Xi(e,t,i){var r={canceled:!1,from:t.from,to:t.to,text:t.text,origin:t.origin,cancel:function(){this.canceled=!0}};return i&&(r.update=function(t,i,r,n){t&&(this.from=Q(e,t)),i&&(this.to=Q(e,i)),r&&(this.text=r),void 0!==n&&(this.origin=n)}),Js(e,"beforeChange",e,r),e.cm&&Js(e.cm,"beforeChange",e.cm,r),r.canceled?null:{from:r.from,to:r.to,text:r.text,origin:r.origin}}function Yi(e,t,i){if(e.cm){if(!e.cm.curOp)return Qt(e.cm,Yi)(e,t,i);if(e.cm.state.suppressEdits)return}if(!(Kn(e,"beforeChange")||e.cm&&Kn(e.cm,"beforeChange"))||(t=Xi(e,t,!0))){var r=os&&!i&&Or(e,t.from,t.to);if(r)for(var n=r.length-1;n>=0;--n)Ki(e,{from:r[n].from,to:r[n].to,text:n?[""]:t.text});else Ki(e,t)}}function Ki(e,t){if(1!=t.text.length||""!=t.text[0]||0!=ls(t.from,t.to)){var i=Wi(e,t);Pn(e,t,i,e.cm?e.cm.curOp.id:0/0),Zi(e,t,i,Cr(e,t));var r=[];gn(e,function(e,i){i||-1!=to(r,e.history)||(Hn(e.history,t),r.push(e.history)),Zi(e,t,null,Cr(e,t))})}}function $i(e,t,i){if(!e.cm||!e.cm.state.suppressEdits){for(var r,n=e.history,o=e.sel,s="undo"==t?n.done:n.undone,a="undo"==t?n.undone:n.done,l=0;l<s.length&&(r=s[l],i?!r.ranges||r.equals(e.sel):r.ranges);l++);if(l!=s.length){for(n.lastOrigin=n.lastSelOrigin=null;r=s.pop(),r.ranges;){if(Mn(r,a),i&&!r.equals(e.sel))return void lt(e,r,{clearRedo:!1});o=r}var u=[];Mn(o,a),a.push({changes:u,generation:n.generation}),n.generation=r.generation||++n.maxGeneration;for(var p=Kn(e,"beforeChange")||e.cm&&Kn(e.cm,"beforeChange"),l=r.changes.length-1;l>=0;--l){var c=r.changes[l];if(c.origin=t,p&&!Xi(e,c,!1))return void(s.length=0);u.push(Rn(e,c));var d=l?Wi(e,c,null):eo(s);Zi(e,c,d,br(e,c)),!l&&e.cm&&e.cm.scrollIntoView(c);var E=[];gn(e,function(e,t){t||-1!=to(E,e.history)||(Hn(e.history,c),E.push(e.history)),Zi(e,c,null,br(e,c))})}}}}function Qi(e,t){if(0!=t&&(e.first+=t,e.sel=new z(io(e.sel.ranges,function(e){return new X(as(e.anchor.line+t,e.anchor.ch),as(e.head.line+t,e.head.ch))}),e.sel.primIndex),e.cm)){ii(e.cm,e.first,e.first-t,t);for(var i=e.cm.display,r=i.viewFrom;r<i.viewTo;r++)ri(e.cm,r,"gutter")}}function Zi(e,t,i,r){if(e.cm&&!e.cm.curOp)return Qt(e.cm,Zi)(e,t,i,r);if(t.to.line<e.first)return void Qi(e,t.text.length-1-(t.to.line-t.from.line));if(!(t.from.line>e.lastLine())){if(t.from.line<e.first){var n=t.text.length-1-(e.first-t.from.line);Qi(e,n),t={from:as(e.first,0),to:as(t.to.line+n,t.to.ch),text:[eo(t.text)],origin:t.origin}}var o=e.lastLine();t.to.line>o&&(t={from:t.from,to:as(o,xn(e,o).text.length),text:[t.text[0]],origin:t.origin}),t.removed=Nn(e,t.from,t.to),i||(i=Wi(e,t,null)),e.cm?Ji(e.cm,t,r):hn(e,t,r),ut(e,i,ra)}}function Ji(e,t,i){var r=e.doc,n=e.display,s=t.from,a=t.to,l=!1,u=s.line;e.options.lineWrapping||(u=In(Vr(xn(r,s.line))),r.iter(u,a.line+1,function(e){return e==n.maxLine?(l=!0,!0):void 0})),r.sel.contains(t.from,t.to)>-1&&Yn(e),hn(r,t,i,o(e)),e.options.lineWrapping||(r.iter(u,s.line+t.text.length,function(e){var t=d(e);t>n.maxLineLength&&(n.maxLine=e,n.maxLineLength=t,n.maxLineChanged=!0,l=!1)}),l&&(e.curOp.updateMaxLine=!0)),r.frontier=Math.min(r.frontier,s.line),vt(e,400);var p=t.text.length-(a.line-s.line)-1;s.line!=a.line||1!=t.text.length||En(e.doc,t)?ii(e,s.line,a.line+1,p):ri(e,s.line,"text");var c=Kn(e,"changes"),E=Kn(e,"change");if(E||c){var h={from:s,to:a,text:t.text,removed:t.removed,origin:t.origin};E&&qn(e,"change",e,h),c&&(e.curOp.changeObjs||(e.curOp.changeObjs=[])).push(h)}e.display.selForContextMenu=null}function er(e,t,i,r,n){if(r||(r=i),ls(r,i)<0){var o=r;r=i,i=o}"string"==typeof t&&(t=va(t)),Yi(e,{from:i,to:r,text:t,origin:n})}function tr(e,t){var i=e.display,r=i.sizer.getBoundingClientRect(),n=null;if(t.top+r.top<0?n=!0:t.bottom+r.top>(window.innerHeight||document.documentElement.clientHeight)&&(n=!1),null!=n&&!Qo){var o=uo("div","​",null,"position: absolute; top: "+(t.top-i.viewOffset-Tt(e.display))+"px; height: "+(t.bottom-t.top+ta)+"px; left: "+t.left+"px; width: 2px;");e.display.lineSpace.appendChild(o),o.scrollIntoView(n),e.display.lineSpace.removeChild(o)}}function ir(e,t,i,r){for(null==r&&(r=0);;){var n=!1,o=Ht(e,t),s=i&&i!=t?Ht(e,i):o,a=nr(e,Math.min(o.left,s.left),Math.min(o.top,s.top)-r,Math.max(o.left,s.left),Math.max(o.bottom,s.bottom)+r),l=e.doc.scrollTop,u=e.doc.scrollLeft;if(null!=a.scrollTop&&(Ri(e,a.scrollTop),Math.abs(e.doc.scrollTop-l)>1&&(n=!0)),null!=a.scrollLeft&&(bi(e,a.scrollLeft),Math.abs(e.doc.scrollLeft-u)>1&&(n=!0)),!n)return o}}function rr(e,t,i,r,n){var o=nr(e,t,i,r,n);null!=o.scrollTop&&Ri(e,o.scrollTop),null!=o.scrollLeft&&bi(e,o.scrollLeft)}function nr(e,t,i,r,n){var o=e.display,s=zt(e.display);0>i&&(i=0);var a=e.curOp&&null!=e.curOp.scrollTop?e.curOp.scrollTop:o.scroller.scrollTop,l=o.scroller.clientHeight-ta,u={},p=e.doc.height+It(o),c=s>i,d=n>p-s;if(a>i)u.scrollTop=c?0:i;else if(n>a+l){var E=Math.min(i,(d?p:n)-l);E!=a&&(u.scrollTop=E)}var h=e.curOp&&null!=e.curOp.scrollLeft?e.curOp.scrollLeft:o.scroller.scrollLeft,f=o.scroller.clientWidth-ta;t+=o.gutters.offsetWidth,r+=o.gutters.offsetWidth;var m=o.gutters.offsetWidth,g=m+10>t;return h+m>t||g?(g&&(t=0),u.scrollLeft=Math.max(0,t-10-m)):r>f+h-3&&(u.scrollLeft=r+10-f),u}function or(e,t,i){(null!=t||null!=i)&&ar(e),null!=t&&(e.curOp.scrollLeft=(null==e.curOp.scrollLeft?e.doc.scrollLeft:e.curOp.scrollLeft)+t),null!=i&&(e.curOp.scrollTop=(null==e.curOp.scrollTop?e.doc.scrollTop:e.curOp.scrollTop)+i)}function sr(e){ar(e);var t=e.getCursor(),i=t,r=t;e.options.lineWrapping||(i=t.ch?as(t.line,t.ch-1):t,r=as(t.line,t.ch+1)),e.curOp.scrollToPos={from:i,to:r,margin:e.options.cursorScrollMargin,isCursor:!0}}function ar(e){var t=e.curOp.scrollToPos;if(t){e.curOp.scrollToPos=null;var i=Ft(e,t.from),r=Ft(e,t.to),n=nr(e,Math.min(i.left,r.left),Math.min(i.top,r.top)-t.margin,Math.max(i.right,r.right),Math.max(i.bottom,r.bottom)+t.margin);e.scrollTo(n.scrollLeft,n.scrollTop)}}function lr(e,t,i,r){var n,o=e.doc;null==i&&(i="add"),"smart"==i&&(e.doc.mode.indent?n=Lt(e,t):i="prev");var s=e.options.tabSize,a=xn(o,t),l=sa(a.text,null,s);a.stateAfter&&(a.stateAfter=null);var u,p=a.text.match(/^\s*/)[0];if(r||/\S/.test(a.text)){if("smart"==i&&(u=e.doc.mode.indent(n,a.text.slice(p.length),a.text),u==ia)){if(!r)return;i="prev"}}else u=0,i="not";"prev"==i?u=t>o.first?sa(xn(o,t-1).text,null,s):0:"add"==i?u=l+e.options.indentUnit:"subtract"==i?u=l-e.options.indentUnit:"number"==typeof i&&(u=l+i),u=Math.max(0,u);var c="",d=0;if(e.options.indentWithTabs)for(var E=Math.floor(u/s);E;--E)d+=s,c+=" ";if(u>d&&(c+=Jn(u-d)),c!=p)er(e.doc,c,as(t,0),as(t,p.length),"+input");else for(var E=0;E<o.sel.ranges.length;E++){var h=o.sel.ranges[E];if(h.head.line==t&&h.head.ch<p.length){var d=as(t,p.length);nt(o,E,new X(d,d));break}}a.stateAfter=null}function ur(e,t,i,r){var n=t,o=t,s=e.doc;return"number"==typeof t?o=xn(s,$(s,t)):n=In(t),null==n?null:(r(o,n)&&ri(e,n,i),o)}function pr(e,t){for(var i=e.doc.sel.ranges,r=[],n=0;n<i.length;n++){for(var o=t(i[n]);r.length&&ls(o.from,eo(r).to)<=0;){var s=r.pop();if(ls(s.from,o.from)<0){o.from=s.from;break}}r.push(o)}$t(e,function(){for(var t=r.length-1;t>=0;t--)er(e.doc,"",r[t].from,r[t].to,"+delete");sr(e)})}function cr(e,t,i,r,n){function o(){var t=a+i;return t<e.first||t>=e.first+e.size?c=!1:(a=t,p=xn(e,t))}function s(e){var t=(n?wo:Go)(p,l,i,!0);if(null==t){if(e||!o())return c=!1;l=n?(0>i?bo:Ro)(p):0>i?p.text.length:0}else l=t;return!0}var a=t.line,l=t.ch,u=i,p=xn(e,a),c=!0;if("char"==r)s();else if("column"==r)s(!0);else if("word"==r||"group"==r)for(var d=null,E="group"==r,h=e.cm&&e.cm.getHelper(t,"wordChars"),f=!0;!(0>i)||s(!f);f=!1){var m=p.text.charAt(l)||"\n",g=so(m,h)?"w":E&&"\n"==m?"n":!E||/\s/.test(m)?null:"p";if(!E||f||g||(g="s"),d&&d!=g){0>i&&(i=1,s());break}if(g&&(d=g),i>0&&!s(!f))break}var v=Et(e,as(a,l),u,!0);return c||(v.hitSide=!0),v}function dr(e,t,i,r){var n,o=e.doc,s=t.left;if("page"==r){var a=Math.min(e.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight);n=t.top+i*(a-(0>i?1.5:.5)*zt(e.display))}else"line"==r&&(n=i>0?t.bottom+3:t.top-3);for(;;){var l=Wt(e,s,n);if(!l.outside)break;if(0>i?0>=n:n>=o.height){l.hitSide=!0;break}n+=5*i}return l}function Er(e,t){var i=e.doc,r=xn(i,t.line).text,n=t.ch,o=t.ch;if(r){var s=e.getHelper(t,"wordChars");(t.xRel<0||o==r.length)&&n?--n:++o;for(var a=r.charAt(n),l=so(a,s)?function(e){return so(e,s)}:/\s/.test(a)?function(e){return/\s/.test(e)}:function(e){return!/\s/.test(e)&&!so(e)};n>0&&l(r.charAt(n-1));)--n;for(;o<r.length&&l(r.charAt(o));)++o}return new X(as(t.line,n),as(t.line,o))}function hr(t,i,r,n){e.defaults[t]=i,r&&(Ls[t]=n?function(e,t,i){i!=Ts&&r(e,t,i)}:r)}function fr(e){return"string"==typeof e?Ps[e]:e}function mr(e,t,i,r,n){if(r&&r.shared)return gr(e,t,i,r,n);if(e.cm&&!e.cm.curOp)return Qt(e.cm,mr)(e,t,i,r,n);var o=new Gs(e,n),s=ls(t,i);if(r&&no(r,o,!1),s>0||0==s&&o.clearWhenEmpty!==!1)return o;if(o.replacedWith&&(o.collapsed=!0,o.widgetNode=uo("span",[o.replacedWith],"CodeMirror-widget"),r.handleMouseEvents||(o.widgetNode.ignoreEvents=!0),r.insertLeft&&(o.widgetNode.insertLeft=!0)),o.collapsed){if(Ur(e,t.line,t,i,o)||t.line!=i.line&&Ur(e,i.line,t,i,o))throw new Error("Inserting collapsed marker partially overlapping an existing one");ss=!0}o.addToHistory&&Pn(e,{from:t,to:i,origin:"markText"},e.sel,0/0);var a,l=t.line,u=e.cm;if(e.iter(l,i.line+1,function(e){u&&o.collapsed&&!u.options.lineWrapping&&Vr(e)==u.display.maxLine&&(a=!0),o.collapsed&&l!=t.line&&Tn(e,0),yr(e,new Lr(o,l==t.line?t.ch:null,l==i.line?i.ch:null)),++l}),o.collapsed&&e.iter(t.line,i.line+1,function(t){Wr(e,t)&&Tn(t,0)}),o.clearOnEnter&&Qs(o,"beforeCursorEnter",function(){o.clear()}),o.readOnly&&(os=!0,(e.history.done.length||e.history.undone.length)&&e.clearHistory()),o.collapsed&&(o.id=++ks,o.atomic=!0),u){if(a&&(u.curOp.updateMaxLine=!0),o.collapsed)ii(u,t.line,i.line+1);else if(o.className||o.title||o.startStyle||o.endStyle)for(var p=t.line;p<=i.line;p++)ri(u,p,"text");o.atomic&&ct(u.doc),qn(u,"markerAdded",u,o)}return o}function gr(e,t,i,r,n){r=no(r),r.shared=!1;var o=[mr(e,t,i,r,n)],s=o[0],a=r.widgetNode;return gn(e,function(e){a&&(r.widgetNode=a.cloneNode(!0)),o.push(mr(e,Q(e,t),Q(e,i),r,n));for(var l=0;l<e.linked.length;++l)if(e.linked[l].isParent)return;s=eo(o)}),new Bs(o,s)}function vr(e){return e.findMarks(as(e.first,0),e.clipPos(as(e.lastLine())),function(e){return e.parent})}function xr(e,t){for(var i=0;i<t.length;i++){var r=t[i],n=r.find(),o=e.clipPos(n.from),s=e.clipPos(n.to);if(ls(o,s)){var a=mr(e,o,s,r.primary,r.primary.type);r.markers.push(a),a.parent=r}}}function Nr(e){for(var t=0;t<e.length;t++){var i=e[t],r=[i.primary.doc];gn(i.primary.doc,function(e){r.push(e)});for(var n=0;n<i.markers.length;n++){var o=i.markers[n];-1==to(r,o.doc)&&(o.parent=null,i.markers.splice(n--,1))}}}function Lr(e,t,i){this.marker=e,this.from=t,this.to=i}function Tr(e,t){if(e)for(var i=0;i<e.length;++i){var r=e[i];if(r.marker==t)return r}}function Ir(e,t){for(var i,r=0;r<e.length;++r)e[r]!=t&&(i||(i=[])).push(e[r]);return i}function yr(e,t){e.markedSpans=e.markedSpans?e.markedSpans.concat([t]):[t],t.marker.attachLine(e)}function Ar(e,t,i){if(e)for(var r,n=0;n<e.length;++n){var o=e[n],s=o.marker,a=null==o.from||(s.inclusiveLeft?o.from<=t:o.from<t);if(a||o.from==t&&"bookmark"==s.type&&(!i||!o.marker.insertLeft)){var l=null==o.to||(s.inclusiveRight?o.to>=t:o.to>t);(r||(r=[])).push(new Lr(s,o.from,l?null:o.to))}}return r}function Sr(e,t,i){if(e)for(var r,n=0;n<e.length;++n){var o=e[n],s=o.marker,a=null==o.to||(s.inclusiveRight?o.to>=t:o.to>t);if(a||o.from==t&&"bookmark"==s.type&&(!i||o.marker.insertLeft)){var l=null==o.from||(s.inclusiveLeft?o.from<=t:o.from<t);(r||(r=[])).push(new Lr(s,l?null:o.from-t,null==o.to?null:o.to-t))}}return r}function Cr(e,t){var i=J(e,t.from.line)&&xn(e,t.from.line).markedSpans,r=J(e,t.to.line)&&xn(e,t.to.line).markedSpans;if(!i&&!r)return null;var n=t.from.ch,o=t.to.ch,s=0==ls(t.from,t.to),a=Ar(i,n,s),l=Sr(r,o,s),u=1==t.text.length,p=eo(t.text).length+(u?n:0);if(a)for(var c=0;c<a.length;++c){var d=a[c];if(null==d.to){var E=Tr(l,d.marker);E?u&&(d.to=null==E.to?null:E.to+p):d.to=n}}if(l)for(var c=0;c<l.length;++c){var d=l[c];if(null!=d.to&&(d.to+=p),null==d.from){var E=Tr(a,d.marker);E||(d.from=p,u&&(a||(a=[])).push(d))}else d.from+=p,u&&(a||(a=[])).push(d)}a&&(a=Rr(a)),l&&l!=a&&(l=Rr(l));var h=[a];if(!u){var f,m=t.text.length-2;if(m>0&&a)for(var c=0;c<a.length;++c)null==a[c].to&&(f||(f=[])).push(new Lr(a[c].marker,null,null));for(var c=0;m>c;++c)h.push(f);h.push(l)}return h}function Rr(e){for(var t=0;t<e.length;++t){var i=e[t];null!=i.from&&i.from==i.to&&i.marker.clearWhenEmpty!==!1&&e.splice(t--,1)}return e.length?e:null}function br(e,t){var i=kn(e,t),r=Cr(e,t);if(!i)return r;if(!r)return i;for(var n=0;n<i.length;++n){var o=i[n],s=r[n];if(o&&s)e:for(var a=0;a<s.length;++a){for(var l=s[a],u=0;u<o.length;++u)if(o[u].marker==l.marker)continue e;o.push(l)}else s&&(i[n]=s)}return i}function Or(e,t,i){var r=null;if(e.iter(t.line,i.line+1,function(e){if(e.markedSpans)for(var t=0;t<e.markedSpans.length;++t){var i=e.markedSpans[t].marker;!i.readOnly||r&&-1!=to(r,i)||(r||(r=[])).push(i)}}),!r)return null;for(var n=[{from:t,to:i}],o=0;o<r.length;++o)for(var s=r[o],a=s.find(0),l=0;l<n.length;++l){var u=n[l];if(!(ls(u.to,a.from)<0||ls(u.from,a.to)>0)){var p=[l,1],c=ls(u.from,a.from),d=ls(u.to,a.to);(0>c||!s.inclusiveLeft&&!c)&&p.push({from:u.from,to:a.from}),(d>0||!s.inclusiveRight&&!d)&&p.push({from:a.to,to:u.to}),n.splice.apply(n,p),l+=p.length-1}}return n}function Pr(e){var t=e.markedSpans;if(t){for(var i=0;i<t.length;++i)t[i].marker.detachLine(e);e.markedSpans=null}}function Dr(e,t){if(t){for(var i=0;i<t.length;++i)t[i].marker.attachLine(e);e.markedSpans=t}}function _r(e){return e.inclusiveLeft?-1:0}function Mr(e){return e.inclusiveRight?1:0}function wr(e,t){var i=e.lines.length-t.lines.length;if(0!=i)return i;var r=e.find(),n=t.find(),o=ls(r.from,n.from)||_r(e)-_r(t);if(o)return-o;var s=ls(r.to,n.to)||Mr(e)-Mr(t);return s?s:t.id-e.id}function Gr(e,t){var i,r=ss&&e.markedSpans;if(r)for(var n,o=0;o<r.length;++o)n=r[o],n.marker.collapsed&&null==(t?n.from:n.to)&&(!i||wr(i,n.marker)<0)&&(i=n.marker);return i}function kr(e){return Gr(e,!0)}function Br(e){return Gr(e,!1)}function Ur(e,t,i,r,n){var o=xn(e,t),s=ss&&o.markedSpans;if(s)for(var a=0;a<s.length;++a){var l=s[a];if(l.marker.collapsed){var u=l.marker.find(0),p=ls(u.from,i)||_r(l.marker)-_r(n),c=ls(u.to,r)||Mr(l.marker)-Mr(n);if(!(p>=0&&0>=c||0>=p&&c>=0)&&(0>=p&&(ls(u.to,i)||Mr(l.marker)-_r(n))>0||p>=0&&(ls(u.from,r)||_r(l.marker)-Mr(n))<0))return!0}}}function Vr(e){for(var t;t=kr(e);)e=t.find(-1,!0).line;return e}function Hr(e){for(var t,i;t=Br(e);)e=t.find(1,!0).line,(i||(i=[])).push(e);return i}function Fr(e,t){var i=xn(e,t),r=Vr(i);return i==r?t:In(r)}function jr(e,t){if(t>e.lastLine())return t;var i,r=xn(e,t);if(!Wr(e,r))return t;for(;i=Br(r);)r=i.find(1,!0).line;return In(r)+1}function Wr(e,t){var i=ss&&t.markedSpans;if(i)for(var r,n=0;n<i.length;++n)if(r=i[n],r.marker.collapsed){if(null==r.from)return!0;if(!r.marker.widgetNode&&0==r.from&&r.marker.inclusiveLeft&&qr(e,t,r))return!0}}function qr(e,t,i){if(null==i.to){var r=i.marker.find(1,!0);return qr(e,r.line,Tr(r.line.markedSpans,i.marker))}if(i.marker.inclusiveRight&&i.to==t.text.length)return!0;for(var n,o=0;o<t.markedSpans.length;++o)if(n=t.markedSpans[o],n.marker.collapsed&&!n.marker.widgetNode&&n.from==i.to&&(null==n.to||n.to!=i.from)&&(n.marker.inclusiveLeft||i.marker.inclusiveRight)&&qr(e,t,n))return!0}function zr(e,t,i){An(t)<(e.curOp&&e.curOp.scrollTop||e.doc.scrollTop)&&or(e,null,i)}function Xr(e){return null!=e.height?e.height:(Eo(document.body,e.node)||co(e.cm.display.measure,uo("div",[e.node],null,"position: relative")),e.height=e.node.offsetHeight)}function Yr(e,t,i,r){var n=new Us(e,i,r);return n.noHScroll&&(e.display.alignWidgets=!0),ur(e,t,"widget",function(t){var i=t.widgets||(t.widgets=[]);if(null==n.insertAt?i.push(n):i.splice(Math.min(i.length-1,Math.max(0,n.insertAt)),0,n),n.line=t,!Wr(e.doc,t)){var r=An(t)<e.doc.scrollTop;Tn(t,t.height+Xr(n)),r&&or(e,null,n.height),e.curOp.forceUpdate=!0}return!0}),n}function Kr(e,t,i,r){e.text=t,e.stateAfter&&(e.stateAfter=null),e.styles&&(e.styles=null),null!=e.order&&(e.order=null),Pr(e),Dr(e,i);var n=r?r(e):1;n!=e.height&&Tn(e,n)}function $r(e){e.parent=null,Pr(e)}function Qr(e,t){if(e)for(;;){var i=e.match(/(?:^|\s+)line-(background-)?(\S+)/);if(!i)break;e=e.slice(0,i.index)+e.slice(i.index+i[0].length);var r=i[1]?"bgClass":"textClass";null==t[r]?t[r]=i[2]:new RegExp("(?:^|s)"+i[2]+"(?:$|s)").test(t[r])||(t[r]+=" "+i[2])}return e}function Zr(t,i){if(t.blankLine)return t.blankLine(i);if(t.innerMode){var r=e.innerMode(t,i);return r.mode.blankLine?r.mode.blankLine(r.state):void 0}}function Jr(e,t,i){for(var r=0;10>r;r++){var n=e.token(t,i);if(t.pos>t.start)return n}throw new Error("Mode "+e.name+" failed to advance stream.")}function en(t,i,r,n,o,s,a){var l=r.flattenSpans;null==l&&(l=t.options.flattenSpans);var u,p=0,c=null,d=new ws(i,t.options.tabSize);for(""==i&&Qr(Zr(r,n),s);!d.eol();){if(d.pos>t.options.maxHighlightLength?(l=!1,a&&nn(t,i,n,d.pos),d.pos=i.length,u=null):u=Qr(Jr(r,d,n),s),t.options.addModeClass){var E=e.innerMode(r,n).mode.name;E&&(u="m-"+(u?E+" "+u:E))}l&&c==u||(p<d.start&&o(d.start,c),p=d.start,c=u),d.start=d.pos}for(;p<d.pos;){var h=Math.min(d.pos,p+5e4);o(h,c),p=h}}function tn(e,t,i,r){var n=[e.state.modeGen],o={};en(e,t.text,e.doc.mode,i,function(e,t){n.push(e,t)},o,r);for(var s=0;s<e.state.overlays.length;++s){var a=e.state.overlays[s],l=1,u=0;en(e,t.text,a.mode,!0,function(e,t){for(var i=l;e>u;){var r=n[l];r>e&&n.splice(l,1,e,n[l+1],r),l+=2,u=Math.min(e,r)}if(t)if(a.opaque)n.splice(i,l-i,e,"cm-overlay "+t),l=i+2;else for(;l>i;i+=2){var o=n[i+1];n[i+1]=(o?o+" ":"")+"cm-overlay "+t}},o)}return{styles:n,classes:o.bgClass||o.textClass?o:null}}function rn(e,t){if(!t.styles||t.styles[0]!=e.state.modeGen){var i=tn(e,t,t.stateAfter=Lt(e,In(t)));t.styles=i.styles,i.classes?t.styleClasses=i.classes:t.styleClasses&&(t.styleClasses=null)}return t.styles}function nn(e,t,i,r){var n=e.doc.mode,o=new ws(t,e.options.tabSize);for(o.start=o.pos=r||0,""==t&&Zr(n,i);!o.eol()&&o.pos<=e.options.maxHighlightLength;)Jr(n,o,i),o.start=o.pos}function on(e,t){if(!e||/^\s*$/.test(e))return null;var i=t.addModeClass?Fs:Hs;return i[e]||(i[e]=e.replace(/\S+/g,"cm-$&"))}function sn(e,t){var i=uo("span",null,null,Wo?"padding-right: .1px":null),r={pre:uo("pre",[i]),content:i,col:0,pos:0,cm:e};t.measure={};for(var n=0;n<=(t.rest?t.rest.length:0);n++){var o,s=n?t.rest[n-1]:t.line;r.pos=0,r.addToken=ln,(jo||Wo)&&e.getOption("lineWrapping")&&(r.addToken=un(r.addToken)),yo(e.display.measure)&&(o=Sn(s))&&(r.addToken=pn(r.addToken,o)),r.map=[],dn(s,r,rn(e,s)),s.styleClasses&&(s.styleClasses.bgClass&&(r.bgClass=vo(s.styleClasses.bgClass,r.bgClass||"")),s.styleClasses.textClass&&(r.textClass=vo(s.styleClasses.textClass,r.textClass||""))),0==r.map.length&&r.map.push(0,0,r.content.appendChild(Io(e.display.measure))),0==n?(t.measure.map=r.map,t.measure.cache={}):((t.measure.maps||(t.measure.maps=[])).push(r.map),(t.measure.caches||(t.measure.caches=[])).push({}))}return Js(e,"renderLine",e,t.line,r.pre),r.pre.className&&(r.textClass=vo(r.pre.className,r.textClass||"")),r}function an(e){var t=uo("span","•","cm-invalidchar");return t.title="\\u"+e.charCodeAt(0).toString(16),t}function ln(e,t,i,r,n,o){if(t){var s=e.cm.options.specialChars,a=!1;if(s.test(t))for(var l=document.createDocumentFragment(),u=0;;){s.lastIndex=u;var p=s.exec(t),c=p?p.index-u:t.length-u;if(c){var d=document.createTextNode(t.slice(u,u+c));l.appendChild(Vo?uo("span",[d]):d),e.map.push(e.pos,e.pos+c,d),e.col+=c,e.pos+=c}if(!p)break;if(u+=c+1," "==p[0]){var E=e.cm.options.tabSize,h=E-e.col%E,d=l.appendChild(uo("span",Jn(h),"cm-tab"));e.col+=h}else{var d=e.cm.options.specialCharPlaceholder(p[0]);l.appendChild(Vo?uo("span",[d]):d),e.col+=1}e.map.push(e.pos,e.pos+1,d),e.pos++}else{e.col+=t.length;var l=document.createTextNode(t);e.map.push(e.pos,e.pos+t.length,l),Vo&&(a=!0),e.pos+=t.length}if(i||r||n||a){var f=i||"";r&&(f+=r),n&&(f+=n);var m=uo("span",[l],f);return o&&(m.title=o),e.content.appendChild(m)}e.content.appendChild(l)}}function un(e){function t(e){for(var t=" ",i=0;i<e.length-2;++i)t+=i%2?" ":" ";return t+=" "}return function(i,r,n,o,s,a){e(i,r.replace(/ {3,}/g,t),n,o,s,a)}}function pn(e,t){return function(i,r,n,o,s,a){n=n?n+" cm-force-border":"cm-force-border";for(var l=i.pos,u=l+r.length;;){for(var p=0;p<t.length;p++){var c=t[p];if(c.to>l&&c.from<=l)break}if(c.to>=u)return e(i,r,n,o,s,a);e(i,r.slice(0,c.to-l),n,o,null,a),o=null,r=r.slice(c.to-l),l=c.to}}}function cn(e,t,i,r){var n=!r&&i.widgetNode;n&&(e.map.push(e.pos,e.pos+t,n),e.content.appendChild(n)),e.pos+=t}function dn(e,t,i){var r=e.markedSpans,n=e.text,o=0;if(r)for(var s,a,l,u,p,c,d=n.length,E=0,h=1,f="",m=0;;){if(m==E){a=l=u=p="",c=null,m=1/0;for(var g=[],v=0;v<r.length;++v){var x=r[v],N=x.marker;x.from<=E&&(null==x.to||x.to>E)?(null!=x.to&&m>x.to&&(m=x.to,l=""),N.className&&(a+=" "+N.className),N.startStyle&&x.from==E&&(u+=" "+N.startStyle),N.endStyle&&x.to==m&&(l+=" "+N.endStyle),N.title&&!p&&(p=N.title),N.collapsed&&(!c||wr(c.marker,N)<0)&&(c=x)):x.from>E&&m>x.from&&(m=x.from),"bookmark"==N.type&&x.from==E&&N.widgetNode&&g.push(N)}if(c&&(c.from||0)==E&&(cn(t,(null==c.to?d+1:c.to)-E,c.marker,null==c.from),null==c.to))return;if(!c&&g.length)for(var v=0;v<g.length;++v)cn(t,0,g[v])}if(E>=d)break;for(var L=Math.min(d,m);;){if(f){var T=E+f.length;if(!c){var I=T>L?f.slice(0,L-E):f;t.addToken(t,I,s?s+a:a,u,E+I.length==m?l:"",p)}if(T>=L){f=f.slice(L-E),E=L;break}E=T,u=""}f=n.slice(o,o=i[h++]),s=on(i[h++],t.cm.options)}}else for(var h=1;h<i.length;h+=2)t.addToken(t,n.slice(o,o=i[h]),on(i[h+1],t.cm.options))}function En(e,t){return 0==t.from.ch&&0==t.to.ch&&""==eo(t.text)&&(!e.cm||e.cm.options.wholeLineUpdateBefore)}function hn(e,t,i,r){function n(e){return i?i[e]:null}function o(e,i,n){Kr(e,i,n,r),qn(e,"change",e,t)}var s=t.from,a=t.to,l=t.text,u=xn(e,s.line),p=xn(e,a.line),c=eo(l),d=n(l.length-1),E=a.line-s.line;if(En(e,t)){for(var h=0,f=[];h<l.length-1;++h)f.push(new Vs(l[h],n(h),r));o(p,p.text,d),E&&e.remove(s.line,E),f.length&&e.insert(s.line,f)}else if(u==p)if(1==l.length)o(u,u.text.slice(0,s.ch)+c+u.text.slice(a.ch),d);else{for(var f=[],h=1;h<l.length-1;++h)f.push(new Vs(l[h],n(h),r));f.push(new Vs(c+u.text.slice(a.ch),d,r)),o(u,u.text.slice(0,s.ch)+l[0],n(0)),e.insert(s.line+1,f)}else if(1==l.length)o(u,u.text.slice(0,s.ch)+l[0]+p.text.slice(a.ch),n(0)),e.remove(s.line+1,E);else{o(u,u.text.slice(0,s.ch)+l[0],n(0)),o(p,c+p.text.slice(a.ch),d);for(var h=1,f=[];h<l.length-1;++h)f.push(new Vs(l[h],n(h),r));E>1&&e.remove(s.line+1,E-1),e.insert(s.line+1,f)}qn(e,"change",e,t)}function fn(e){this.lines=e,this.parent=null;for(var t=0,i=0;t<e.length;++t)e[t].parent=this,i+=e[t].height;this.height=i}function mn(e){this.children=e;for(var t=0,i=0,r=0;r<e.length;++r){var n=e[r];t+=n.chunkSize(),i+=n.height,n.parent=this}this.size=t,this.height=i,this.parent=null}function gn(e,t,i){function r(e,n,o){if(e.linked)for(var s=0;s<e.linked.length;++s){var a=e.linked[s];if(a.doc!=n){var l=o&&a.sharedHist;(!i||l)&&(t(a.doc,l),r(a.doc,e,l))}}}r(e,null,!0)}function vn(e,t){if(t.cm)throw new Error("This document is already in use.");e.doc=t,t.cm=e,s(e),i(e),e.options.lineWrapping||E(e),e.options.mode=t.modeOption,ii(e)}function xn(e,t){if(t-=e.first,0>t||t>=e.size)throw new Error("There is no line "+(t+e.first)+" in the document.");for(var i=e;!i.lines;)for(var r=0;;++r){var n=i.children[r],o=n.chunkSize();if(o>t){i=n;break}t-=o}return i.lines[t]}function Nn(e,t,i){var r=[],n=t.line;return e.iter(t.line,i.line+1,function(e){var o=e.text;n==i.line&&(o=o.slice(0,i.ch)),n==t.line&&(o=o.slice(t.ch)),r.push(o),++n}),r}function Ln(e,t,i){var r=[];return e.iter(t,i,function(e){r.push(e.text)}),r}function Tn(e,t){var i=t-e.height;if(i)for(var r=e;r;r=r.parent)r.height+=i}function In(e){if(null==e.parent)return null;for(var t=e.parent,i=to(t.lines,e),r=t.parent;r;t=r,r=r.parent)for(var n=0;r.children[n]!=t;++n)i+=r.children[n].chunkSize();return i+t.first}function yn(e,t){var i=e.first;e:do{for(var r=0;r<e.children.length;++r){var n=e.children[r],o=n.height;if(o>t){e=n;continue e}t-=o,i+=n.chunkSize()}return i}while(!e.lines);for(var r=0;r<e.lines.length;++r){var s=e.lines[r],a=s.height;if(a>t)break;t-=a}return i+r}function An(e){e=Vr(e);for(var t=0,i=e.parent,r=0;r<i.lines.length;++r){var n=i.lines[r];if(n==e)break;t+=n.height}for(var o=i.parent;o;i=o,o=i.parent)for(var r=0;r<o.children.length;++r){var s=o.children[r];if(s==i)break;t+=s.height}return t}function Sn(e){var t=e.order;return null==t&&(t=e.order=Ia(e.text)),t}function Cn(e){this.done=[],this.undone=[],this.undoDepth=1/0,this.lastModTime=this.lastSelTime=0,this.lastOp=null,this.lastOrigin=this.lastSelOrigin=null,this.generation=this.maxGeneration=e||1}function Rn(e,t){var i={from:j(t.from),to:xs(t),text:Nn(e,t.from,t.to)};return wn(e,i,t.from.line,t.to.line+1),gn(e,function(e){wn(e,i,t.from.line,t.to.line+1)},!0),i}function bn(e){for(;e.length;){var t=eo(e);if(!t.ranges)break;e.pop()}}function On(e,t){return t?(bn(e.done),eo(e.done)):e.done.length&&!eo(e.done).ranges?eo(e.done):e.done.length>1&&!e.done[e.done.length-2].ranges?(e.done.pop(),eo(e.done)):void 0}function Pn(e,t,i,r){var n=e.history;n.undone.length=0;var o,s=+new Date;if((n.lastOp==r||n.lastOrigin==t.origin&&t.origin&&("+"==t.origin.charAt(0)&&e.cm&&n.lastModTime>s-e.cm.options.historyEventDelay||"*"==t.origin.charAt(0)))&&(o=On(n,n.lastOp==r))){var a=eo(o.changes);0==ls(t.from,t.to)&&0==ls(t.from,a.to)?a.to=xs(t):o.changes.push(Rn(e,t))}else{var l=eo(n.done);for(l&&l.ranges||Mn(e.sel,n.done),o={changes:[Rn(e,t)],generation:n.generation},n.done.push(o);n.done.length>n.undoDepth;)n.done.shift(),n.done[0].ranges||n.done.shift()}n.done.push(i),n.generation=++n.maxGeneration,n.lastModTime=n.lastSelTime=s,n.lastOp=r,n.lastOrigin=n.lastSelOrigin=t.origin,a||Js(e,"historyAdded")}function Dn(e,t,i,r){var n=t.charAt(0);return"*"==n||"+"==n&&i.ranges.length==r.ranges.length&&i.somethingSelected()==r.somethingSelected()&&new Date-e.history.lastSelTime<=(e.cm?e.cm.options.historyEventDelay:500)}function _n(e,t,i,r){var n=e.history,o=r&&r.origin;i==n.lastOp||o&&n.lastSelOrigin==o&&(n.lastModTime==n.lastSelTime&&n.lastOrigin==o||Dn(e,o,eo(n.done),t))?n.done[n.done.length-1]=t:Mn(t,n.done),n.lastSelTime=+new Date,n.lastSelOrigin=o,n.lastOp=i,r&&r.clearRedo!==!1&&bn(n.undone)}function Mn(e,t){var i=eo(t);i&&i.ranges&&i.equals(e)||t.push(e)}function wn(e,t,i,r){var n=t["spans_"+e.id],o=0;e.iter(Math.max(e.first,i),Math.min(e.first+e.size,r),function(i){i.markedSpans&&((n||(n=t["spans_"+e.id]={}))[o]=i.markedSpans),++o})}function Gn(e){if(!e)return null;for(var t,i=0;i<e.length;++i)e[i].marker.explicitlyCleared?t||(t=e.slice(0,i)):t&&t.push(e[i]);return t?t.length?t:null:e}function kn(e,t){var i=t["spans_"+e.id];if(!i)return null;for(var r=0,n=[];r<t.text.length;++r)n.push(Gn(i[r]));return n}function Bn(e,t,i){for(var r=0,n=[];r<e.length;++r){var o=e[r];if(o.ranges)n.push(i?z.prototype.deepCopy.call(o):o);else{var s=o.changes,a=[];n.push({changes:a});for(var l=0;l<s.length;++l){var u,p=s[l];if(a.push({from:p.from,to:p.to,text:p.text}),t)for(var c in p)(u=c.match(/^spans_(\d+)$/))&&to(t,Number(u[1]))>-1&&(eo(a)[c]=p[c],delete p[c])}}}return n}function Un(e,t,i,r){i<e.line?e.line+=r:t<e.line&&(e.line=t,e.ch=0)}function Vn(e,t,i,r){for(var n=0;n<e.length;++n){var o=e[n],s=!0;if(o.ranges){o.copied||(o=e[n]=o.deepCopy(),o.copied=!0);for(var a=0;a<o.ranges.length;a++)Un(o.ranges[a].anchor,t,i,r),Un(o.ranges[a].head,t,i,r)}else{for(var a=0;a<o.changes.length;++a){var l=o.changes[a];if(i<l.from.line)l.from=as(l.from.line+r,l.from.ch),l.to=as(l.to.line+r,l.to.ch);else if(t<=l.to.line){s=!1;break}}s||(e.splice(0,n+1),n=0)}}}function Hn(e,t){var i=t.from.line,r=t.to.line,n=t.text.length-(r-i)-1;Vn(e.done,i,r,n),Vn(e.undone,i,r,n)}function Fn(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function jn(e){return e.target||e.srcElement}function Wn(e){var t=e.which;return null==t&&(1&e.button?t=1:2&e.button?t=3:4&e.button&&(t=2)),es&&e.ctrlKey&&1==t&&(t=3),t }function qn(e,t){function i(e){return function(){e.apply(null,n)}}var r=e._handlers&&e._handlers[t];if(r){var n=Array.prototype.slice.call(arguments,2);Xs||(++ea,Xs=[],setTimeout(zn,0));for(var o=0;o<r.length;++o)Xs.push(i(r[o]))}}function zn(){--ea;var e=Xs;Xs=null;for(var t=0;t<e.length;++t)e[t]()}function Xn(e,t,i){return Js(e,i||t.type,e,t),Fn(t)||t.codemirrorIgnore}function Yn(e){var t=e._handlers&&e._handlers.cursorActivity;if(t)for(var i=e.curOp.cursorActivityHandlers||(e.curOp.cursorActivityHandlers=[]),r=0;r<t.length;++r)-1==to(i,t[r])&&i.push(t[r])}function Kn(e,t){var i=e._handlers&&e._handlers[t];return i&&i.length>0}function $n(e){e.prototype.on=function(e,t){Qs(this,e,t)},e.prototype.off=function(e,t){Zs(this,e,t)}}function Qn(){this.id=null}function Zn(e,t,i){for(var r=0,n=0;;){var o=e.indexOf(" ",r);-1==o&&(o=e.length);var s=o-r;if(o==e.length||n+s>=t)return r+Math.min(s,t-n);if(n+=o-r,n+=i-n%i,r=o+1,n>=t)return r}}function Jn(e){for(;aa.length<=e;)aa.push(eo(aa)+" ");return aa[e]}function eo(e){return e[e.length-1]}function to(e,t){for(var i=0;i<e.length;++i)if(e[i]==t)return i;return-1}function io(e,t){for(var i=[],r=0;r<e.length;r++)i[r]=t(e[r],r);return i}function ro(e,t){var i;if(Object.create)i=Object.create(e);else{var r=function(){};r.prototype=e,i=new r}return t&&no(t,i),i}function no(e,t,i){t||(t={});for(var r in e)!e.hasOwnProperty(r)||i===!1&&t.hasOwnProperty(r)||(t[r]=e[r]);return t}function oo(e){var t=Array.prototype.slice.call(arguments,1);return function(){return e.apply(null,t)}}function so(e,t){return t?t.source.indexOf("\\w")>-1&&ca(e)?!0:t.test(e):ca(e)}function ao(e){for(var t in e)if(e.hasOwnProperty(t)&&e[t])return!1;return!0}function lo(e){return e.charCodeAt(0)>=768&&da.test(e)}function uo(e,t,i,r){var n=document.createElement(e);if(i&&(n.className=i),r&&(n.style.cssText=r),"string"==typeof t)n.appendChild(document.createTextNode(t));else if(t)for(var o=0;o<t.length;++o)n.appendChild(t[o]);return n}function po(e){for(var t=e.childNodes.length;t>0;--t)e.removeChild(e.firstChild);return e}function co(e,t){return po(e).appendChild(t)}function Eo(e,t){if(e.contains)return e.contains(t);for(;t=t.parentNode;)if(t==e)return!0}function ho(){return document.activeElement}function fo(e){return new RegExp("\\b"+e+"\\b\\s*")}function mo(e,t){var i=fo(t);i.test(e.className)&&(e.className=e.className.replace(i,""))}function go(e,t){fo(t).test(e.className)||(e.className+=" "+t)}function vo(e,t){for(var i=e.split(" "),r=0;r<i.length;r++)i[r]&&!fo(i[r]).test(t)&&(t+=" "+i[r]);return t}function xo(e){if(document.body.getElementsByClassName)for(var t=document.body.getElementsByClassName("CodeMirror"),i=0;i<t.length;i++){var r=t[i].CodeMirror;r&&e(r)}}function No(){ma||(Lo(),ma=!0)}function Lo(){var e;Qs(window,"resize",function(){null==e&&(e=setTimeout(function(){e=null,Ea=null,xo(gi)},100))}),Qs(window,"blur",function(){xo(Vi)})}function To(e){if(null!=Ea)return Ea;var t=uo("div",null,null,"width: 50px; height: 50px; overflow-x: scroll");return co(e,t),t.offsetWidth&&(Ea=t.offsetHeight-t.clientHeight),Ea||0}function Io(e){if(null==ha){var t=uo("span","​");co(e,uo("span",[t,document.createTextNode("x")])),0!=e.firstChild.offsetHeight&&(ha=t.offsetWidth<=1&&t.offsetHeight>2&&!Uo)}return ha?uo("span","​"):uo("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px")}function yo(e){if(null!=fa)return fa;var t=co(e,document.createTextNode("AخA")),i=ua(t,0,1).getBoundingClientRect();if(i.left==i.right)return!1;var r=ua(t,1,2).getBoundingClientRect();return fa=r.right-i.right<3}function Ao(e,t,i,r){if(!e)return r(t,i,"ltr");for(var n=!1,o=0;o<e.length;++o){var s=e[o];(s.from<i&&s.to>t||t==i&&s.to==t)&&(r(Math.max(s.from,t),Math.min(s.to,i),1==s.level?"rtl":"ltr"),n=!0)}n||r(t,i,"ltr")}function So(e){return e.level%2?e.to:e.from}function Co(e){return e.level%2?e.from:e.to}function Ro(e){var t=Sn(e);return t?So(t[0]):0}function bo(e){var t=Sn(e);return t?Co(eo(t)):e.text.length}function Oo(e,t){var i=xn(e.doc,t),r=Vr(i);r!=i&&(t=In(r));var n=Sn(r),o=n?n[0].level%2?bo(r):Ro(r):0;return as(t,o)}function Po(e,t){for(var i,r=xn(e.doc,t);i=Br(r);)r=i.find(1,!0).line,t=null;var n=Sn(r),o=n?n[0].level%2?Ro(r):bo(r):r.text.length;return as(null==t?In(r):t,o)}function Do(e,t,i){var r=e[0].level;return t==r?!0:i==r?!1:i>t}function _o(e,t){Ta=null;for(var i,r=0;r<e.length;++r){var n=e[r];if(n.from<t&&n.to>t)return r;if(n.from==t||n.to==t){if(null!=i)return Do(e,n.level,e[i].level)?(n.from!=n.to&&(Ta=i),r):(n.from!=n.to&&(Ta=r),i);i=r}}return i}function Mo(e,t,i,r){if(!r)return t+i;do t+=i;while(t>0&&lo(e.text.charAt(t)));return t}function wo(e,t,i,r){var n=Sn(e);if(!n)return Go(e,t,i,r);for(var o=_o(n,t),s=n[o],a=Mo(e,t,s.level%2?-i:i,r);;){if(a>s.from&&a<s.to)return a;if(a==s.from||a==s.to)return _o(n,a)==o?a:(s=n[o+=i],i>0==s.level%2?s.to:s.from);if(s=n[o+=i],!s)return null;a=i>0==s.level%2?Mo(e,s.to,-1,r):Mo(e,s.from,1,r)}}function Go(e,t,i,r){var n=t+i;if(r)for(;n>0&&lo(e.text.charAt(n));)n+=i;return 0>n||n>e.text.length?null:n}var ko=/gecko\/\d/i.test(navigator.userAgent),Bo=/MSIE \d/.test(navigator.userAgent),Uo=Bo&&(null==document.documentMode||document.documentMode<8),Vo=Bo&&(null==document.documentMode||document.documentMode<9),Ho=Bo&&(null==document.documentMode||document.documentMode<10),Fo=/Trident\/([7-9]|\d{2,})\./.test(navigator.userAgent),jo=Bo||Fo,Wo=/WebKit\//.test(navigator.userAgent),qo=Wo&&/Qt\/\d+\.\d+/.test(navigator.userAgent),zo=/Chrome\//.test(navigator.userAgent),Xo=/Opera\//.test(navigator.userAgent),Yo=/Apple Computer/.test(navigator.vendor),Ko=/KHTML\//.test(navigator.userAgent),$o=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent),Qo=/PhantomJS/.test(navigator.userAgent),Zo=/AppleWebKit/.test(navigator.userAgent)&&/Mobile\/\w+/.test(navigator.userAgent),Jo=Zo||/Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent),es=Zo||/Mac/.test(navigator.platform),ts=/win/i.test(navigator.platform),is=Xo&&navigator.userAgent.match(/Version\/(\d*\.\d*)/);is&&(is=Number(is[1])),is&&is>=15&&(Xo=!1,Wo=!0);var rs=es&&(qo||Xo&&(null==is||12.11>is)),ns=ko||jo&&!Vo,os=!1,ss=!1,as=e.Pos=function(e,t){return this instanceof as?(this.line=e,void(this.ch=t)):new as(e,t)},ls=e.cmpPos=function(e,t){return e.line-t.line||e.ch-t.ch};z.prototype={primary:function(){return this.ranges[this.primIndex]},equals:function(e){if(e==this)return!0;if(e.primIndex!=this.primIndex||e.ranges.length!=this.ranges.length)return!1;for(var t=0;t<this.ranges.length;t++){var i=this.ranges[t],r=e.ranges[t];if(0!=ls(i.anchor,r.anchor)||0!=ls(i.head,r.head))return!1}return!0},deepCopy:function(){for(var e=[],t=0;t<this.ranges.length;t++)e[t]=new X(j(this.ranges[t].anchor),j(this.ranges[t].head));return new z(e,this.primIndex)},somethingSelected:function(){for(var e=0;e<this.ranges.length;e++)if(!this.ranges[e].empty())return!0;return!1},contains:function(e,t){t||(t=e);for(var i=0;i<this.ranges.length;i++){var r=this.ranges[i];if(ls(t,r.from())>=0&&ls(e,r.to())<=0)return i}return-1}},X.prototype={from:function(){return q(this.anchor,this.head)},to:function(){return W(this.anchor,this.head)},empty:function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch}};var us,ps,cs,ds={left:0,right:0,top:0,bottom:0},Es=0,hs=0,fs=0,ms=null;jo?ms=-.53:ko?ms=15:zo?ms=-.7:Yo&&(ms=-1/3);var gs,vs=null,xs=e.changeEnd=function(e){return e.text?as(e.from.line+e.text.length-1,eo(e.text).length+(1==e.text.length?e.from.ch:0)):e.to};e.prototype={constructor:e,focus:function(){window.focus(),Ei(this),pi(this)},setOption:function(e,t){var i=this.options,r=i[e];(i[e]!=t||"mode"==e)&&(i[e]=t,Ls.hasOwnProperty(e)&&Qt(this,Ls[e])(this,t,r))},getOption:function(e){return this.options[e]},getDoc:function(){return this.doc},addKeyMap:function(e,t){this.state.keyMaps[t?"push":"unshift"](e)},removeKeyMap:function(e){for(var t=this.state.keyMaps,i=0;i<t.length;++i)if(t[i]==e||"string"!=typeof t[i]&&t[i].name==e)return t.splice(i,1),!0},addOverlay:Zt(function(t,i){var r=t.token?t:e.getMode(this.options,t);if(r.startState)throw new Error("Overlays may not be stateful.");this.state.overlays.push({mode:r,modeSpec:t,opaque:i&&i.opaque}),this.state.modeGen++,ii(this)}),removeOverlay:Zt(function(e){for(var t=this.state.overlays,i=0;i<t.length;++i){var r=t[i].modeSpec;if(r==e||"string"==typeof e&&r.name==e)return t.splice(i,1),this.state.modeGen++,void ii(this)}}),indentLine:Zt(function(e,t,i){"string"!=typeof t&&"number"!=typeof t&&(t=null==t?this.options.smartIndent?"smart":"prev":t?"add":"subtract"),J(this.doc,e)&&lr(this,e,t,i)}),indentSelection:Zt(function(e){for(var t=this.doc.sel.ranges,i=-1,r=0;r<t.length;r++){var n=t[r];if(n.empty())n.head.line>i&&(lr(this,n.head.line,e,!0),i=n.head.line,r==this.doc.sel.primIndex&&sr(this));else{var o=Math.max(i,n.from().line),s=n.to();i=Math.min(this.lastLine(),s.line-(s.ch?0:1))+1;for(var a=o;i>a;++a)lr(this,a,e)}}}),getTokenAt:function(e,t){var i=this.doc;e=Q(i,e);for(var r=Lt(this,e.line,t),n=this.doc.mode,o=xn(i,e.line),s=new ws(o.text,this.options.tabSize);s.pos<e.ch&&!s.eol();){s.start=s.pos;var a=Jr(n,s,r)}return{start:s.start,end:s.pos,string:s.current(),type:a||null,state:r}},getTokenTypeAt:function(e){e=Q(this.doc,e);var t,i=rn(this,xn(this.doc,e.line)),r=0,n=(i.length-1)/2,o=e.ch;if(0==o)t=i[2];else for(;;){var s=r+n>>1;if((s?i[2*s-1]:0)>=o)n=s;else{if(!(i[2*s+1]<o)){t=i[2*s+2];break}r=s+1}}var a=t?t.indexOf("cm-overlay "):-1;return 0>a?t:0==a?null:t.slice(0,a-1)},getModeAt:function(t){var i=this.doc.mode;return i.innerMode?e.innerMode(i,this.getTokenAt(t).state).mode:i},getHelper:function(e,t){return this.getHelpers(e,t)[0]},getHelpers:function(e,t){var i=[];if(!Cs.hasOwnProperty(t))return Cs;var r=Cs[t],n=this.getModeAt(e);if("string"==typeof n[t])r[n[t]]&&i.push(r[n[t]]);else if(n[t])for(var o=0;o<n[t].length;o++){var s=r[n[t][o]];s&&i.push(s)}else n.helperType&&r[n.helperType]?i.push(r[n.helperType]):r[n.name]&&i.push(r[n.name]);for(var o=0;o<r._global.length;o++){var a=r._global[o];a.pred(n,this)&&-1==to(i,a.val)&&i.push(a.val)}return i},getStateAfter:function(e,t){var i=this.doc;return e=$(i,null==e?i.first+i.size-1:e),Lt(this,e+1,t)},cursorCoords:function(e,t){var i,r=this.doc.sel.primary();return i=null==e?r.head:"object"==typeof e?Q(this.doc,e):e?r.from():r.to(),Ht(this,i,t||"page")},charCoords:function(e,t){return Vt(this,Q(this.doc,e),t||"page")},coordsChar:function(e,t){return e=Ut(this,e,t||"page"),Wt(this,e.left,e.top)},lineAtHeight:function(e,t){return e=Ut(this,{top:e,left:0},t||"page").top,yn(this.doc,e+this.display.viewOffset)},heightAtLine:function(e,t){var i=!1,r=this.doc.first+this.doc.size-1;e<this.doc.first?e=this.doc.first:e>r&&(e=r,i=!0);var n=xn(this.doc,e);return Bt(this,n,{top:0,left:0},t||"page").top+(i?this.doc.height-An(n):0)},defaultTextHeight:function(){return zt(this.display)},defaultCharWidth:function(){return Xt(this.display)},setGutterMarker:Zt(function(e,t,i){return ur(this,e,"gutter",function(e){var r=e.gutterMarkers||(e.gutterMarkers={});return r[t]=i,!i&&ao(r)&&(e.gutterMarkers=null),!0})}),clearGutter:Zt(function(e){var t=this,i=t.doc,r=i.first;i.iter(function(i){i.gutterMarkers&&i.gutterMarkers[e]&&(i.gutterMarkers[e]=null,ri(t,r,"gutter"),ao(i.gutterMarkers)&&(i.gutterMarkers=null)),++r})}),addLineClass:Zt(function(e,t,i){return ur(this,e,"class",function(e){var r="text"==t?"textClass":"background"==t?"bgClass":"wrapClass";if(e[r]){if(new RegExp("(?:^|\\s)"+i+"(?:$|\\s)").test(e[r]))return!1;e[r]+=" "+i}else e[r]=i;return!0})}),removeLineClass:Zt(function(e,t,i){return ur(this,e,"class",function(e){var r="text"==t?"textClass":"background"==t?"bgClass":"wrapClass",n=e[r];if(!n)return!1;if(null==i)e[r]=null;else{var o=n.match(new RegExp("(?:^|\\s+)"+i+"(?:$|\\s+)"));if(!o)return!1;var s=o.index+o[0].length;e[r]=n.slice(0,o.index)+(o.index&&s!=n.length?" ":"")+n.slice(s)||null}return!0})}),addLineWidget:Zt(function(e,t,i){return Yr(this,e,t,i)}),removeLineWidget:function(e){e.clear()},lineInfo:function(e){if("number"==typeof e){if(!J(this.doc,e))return null;var t=e;if(e=xn(this.doc,e),!e)return null}else{var t=In(e);if(null==t)return null}return{line:t,handle:e,text:e.text,gutterMarkers:e.gutterMarkers,textClass:e.textClass,bgClass:e.bgClass,wrapClass:e.wrapClass,widgets:e.widgets}},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(e,t,i,r,n){var o=this.display;e=Ht(this,Q(this.doc,e));var s=e.bottom,a=e.left;if(t.style.position="absolute",o.sizer.appendChild(t),"over"==r)s=e.top;else if("above"==r||"near"==r){var l=Math.max(o.wrapper.clientHeight,this.doc.height),u=Math.max(o.sizer.clientWidth,o.lineSpace.clientWidth);("above"==r||e.bottom+t.offsetHeight>l)&&e.top>t.offsetHeight?s=e.top-t.offsetHeight:e.bottom+t.offsetHeight<=l&&(s=e.bottom),a+t.offsetWidth>u&&(a=u-t.offsetWidth)}t.style.top=s+"px",t.style.left=t.style.right="","right"==n?(a=o.sizer.clientWidth-t.offsetWidth,t.style.right="0px"):("left"==n?a=0:"middle"==n&&(a=(o.sizer.clientWidth-t.offsetWidth)/2),t.style.left=a+"px"),i&&rr(this,a,s,a+t.offsetWidth,s+t.offsetHeight)},triggerOnKeyDown:Zt(wi),triggerOnKeyPress:Zt(Bi),triggerOnKeyUp:Zt(ki),execCommand:function(e){return Os.hasOwnProperty(e)?Os[e](this):void 0},findPosH:function(e,t,i,r){var n=1;0>t&&(n=-1,t=-t);for(var o=0,s=Q(this.doc,e);t>o&&(s=cr(this.doc,s,n,i,r),!s.hitSide);++o);return s},moveH:Zt(function(e,t){var i=this;i.extendSelectionsBy(function(r){return i.display.shift||i.doc.extend||r.empty()?cr(i.doc,r.head,e,t,i.options.rtlMoveVisually):0>e?r.from():r.to()},oa)}),deleteH:Zt(function(e,t){var i=this.doc.sel,r=this.doc;i.somethingSelected()?r.replaceSelection("",null,"+delete"):pr(this,function(i){var n=cr(r,i.head,e,t,!1);return 0>e?{from:n,to:i.head}:{from:i.head,to:n}})}),findPosV:function(e,t,i,r){var n=1,o=r;0>t&&(n=-1,t=-t);for(var s=0,a=Q(this.doc,e);t>s;++s){var l=Ht(this,a,"div");if(null==o?o=l.left:l.left=o,a=dr(this,l,n,i),a.hitSide)break}return a},moveV:Zt(function(e,t){var i=this,r=this.doc,n=[],o=!i.display.shift&&!r.extend&&r.sel.somethingSelected();if(r.extendSelectionsBy(function(s){if(o)return 0>e?s.from():s.to();var a=Ht(i,s.head,"div");null!=s.goalColumn&&(a.left=s.goalColumn),n.push(a.left);var l=dr(i,a,e,t);return"page"==t&&s==r.sel.primary()&&or(i,null,Vt(i,l,"div").top-a.top),l},oa),n.length)for(var s=0;s<r.sel.ranges.length;s++)r.sel.ranges[s].goalColumn=n[s]}),toggleOverwrite:function(e){(null==e||e!=this.state.overwrite)&&((this.state.overwrite=!this.state.overwrite)?go(this.display.cursorDiv,"CodeMirror-overwrite"):mo(this.display.cursorDiv,"CodeMirror-overwrite"),Js(this,"overwriteToggle",this,this.state.overwrite))},hasFocus:function(){return ho()==this.display.input},scrollTo:Zt(function(e,t){(null!=e||null!=t)&&ar(this),null!=e&&(this.curOp.scrollLeft=e),null!=t&&(this.curOp.scrollTop=t)}),getScrollInfo:function(){var e=this.display.scroller,t=ta;return{left:e.scrollLeft,top:e.scrollTop,height:e.scrollHeight-t,width:e.scrollWidth-t,clientHeight:e.clientHeight-t,clientWidth:e.clientWidth-t}},scrollIntoView:Zt(function(e,t){if(null==e?(e={from:this.doc.sel.primary().head,to:null},null==t&&(t=this.options.cursorScrollMargin)):"number"==typeof e?e={from:as(e,0),to:null}:null==e.from&&(e={from:e,to:null}),e.to||(e.to=e.from),e.margin=t||0,null!=e.from.line)ar(this),this.curOp.scrollToPos=e;else{var i=nr(this,Math.min(e.from.left,e.to.left),Math.min(e.from.top,e.to.top)-e.margin,Math.max(e.from.right,e.to.right),Math.max(e.from.bottom,e.to.bottom)+e.margin);this.scrollTo(i.scrollLeft,i.scrollTop)}}),setSize:Zt(function(e,t){function i(e){return"number"==typeof e||/^\d+$/.test(String(e))?e+"px":e}null!=e&&(this.display.wrapper.style.width=i(e)),null!=t&&(this.display.wrapper.style.height=i(t)),this.options.lineWrapping&&Mt(this),this.curOp.forceUpdate=!0,Js(this,"refresh",this)}),operation:function(e){return $t(this,e)},refresh:Zt(function(){var e=this.display.cachedTextHeight;ii(this),this.curOp.forceUpdate=!0,wt(this),this.scrollTo(this.doc.scrollLeft,this.doc.scrollTop),c(this),(null==e||Math.abs(e-zt(this.display))>.5)&&s(this),Js(this,"refresh",this)}),swapDoc:Zt(function(e){var t=this.doc;return t.cm=null,vn(this,e),wt(this),di(this),this.scrollTo(e.scrollLeft,e.scrollTop),qn(this,"swapDoc",this,t),t}),getInputField:function(){return this.display.input},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}},$n(e);var Ns=e.defaults={},Ls=e.optionHandlers={},Ts=e.Init={toString:function(){return"CodeMirror.Init"}};hr("value","",function(e,t){e.setValue(t)},!0),hr("mode",null,function(e,t){e.doc.modeOption=t,i(e)},!0),hr("indentUnit",2,i,!0),hr("indentWithTabs",!1),hr("smartIndent",!0),hr("tabSize",4,function(e){r(e),wt(e),ii(e)},!0),hr("specialChars",/[\t\u0000-\u0019\u00ad\u200b\u2028\u2029\ufeff]/g,function(e,t){e.options.specialChars=new RegExp(t.source+(t.test(" ")?"":"| "),"g"),e.refresh()},!0),hr("specialCharPlaceholder",an,function(e){e.refresh()},!0),hr("electricChars",!0),hr("rtlMoveVisually",!ts),hr("wholeLineUpdateBefore",!0),hr("theme","default",function(e){l(e),u(e)},!0),hr("keyMap","default",a),hr("extraKeys",null),hr("lineWrapping",!1,n,!0),hr("gutters",[],function(e){h(e.options),u(e)},!0),hr("fixedGutter",!0,function(e,t){e.display.gutters.style.left=t?L(e.display)+"px":"0",e.refresh()},!0),hr("coverGutterNextToScrollbar",!1,m,!0),hr("lineNumbers",!1,function(e){h(e.options),u(e)},!0),hr("firstLineNumber",1,u,!0),hr("lineNumberFormatter",function(e){return e},u,!0),hr("showCursorWhenSelecting",!1,ht,!0),hr("resetSelectionOnContextMenu",!0),hr("readOnly",!1,function(e,t){"nocursor"==t?(Vi(e),e.display.input.blur(),e.display.disabled=!0):(e.display.disabled=!1,t||di(e))}),hr("disableInput",!1,function(e,t){t||di(e)},!0),hr("dragDrop",!0),hr("cursorBlinkRate",530),hr("cursorScrollMargin",0),hr("cursorHeight",1),hr("workTime",100),hr("workDelay",100),hr("flattenSpans",!0,r,!0),hr("addModeClass",!1,r,!0),hr("pollInterval",100),hr("undoDepth",200,function(e,t){e.doc.history.undoDepth=t}),hr("historyEventDelay",1250),hr("viewportMargin",10,function(e){e.refresh()},!0),hr("maxHighlightLength",1e4,r,!0),hr("moveInputWithCursor",!0,function(e,t){t||(e.display.inputDiv.style.top=e.display.inputDiv.style.left=0)}),hr("tabindex",null,function(e,t){e.display.input.tabIndex=t||""}),hr("autofocus",null);var Is=e.modes={},ys=e.mimeModes={};e.defineMode=function(t,i){if(e.defaults.mode||"null"==t||(e.defaults.mode=t),arguments.length>2){i.dependencies=[];for(var r=2;r<arguments.length;++r)i.dependencies.push(arguments[r])}Is[t]=i},e.defineMIME=function(e,t){ys[e]=t},e.resolveMode=function(t){if("string"==typeof t&&ys.hasOwnProperty(t))t=ys[t];else if(t&&"string"==typeof t.name&&ys.hasOwnProperty(t.name)){var i=ys[t.name];"string"==typeof i&&(i={name:i}),t=ro(i,t),t.name=i.name}else if("string"==typeof t&&/^[\w\-]+\/[\w\-]+\+xml$/.test(t))return e.resolveMode("application/xml");return"string"==typeof t?{name:t}:t||{name:"null"}},e.getMode=function(t,i){var i=e.resolveMode(i),r=Is[i.name];if(!r)return e.getMode(t,"text/plain");var n=r(t,i);if(As.hasOwnProperty(i.name)){var o=As[i.name];for(var s in o)o.hasOwnProperty(s)&&(n.hasOwnProperty(s)&&(n["_"+s]=n[s]),n[s]=o[s])}if(n.name=i.name,i.helperType&&(n.helperType=i.helperType),i.modeProps)for(var s in i.modeProps)n[s]=i.modeProps[s];return n},e.defineMode("null",function(){return{token:function(e){e.skipToEnd()}}}),e.defineMIME("text/plain","null");var As=e.modeExtensions={};e.extendMode=function(e,t){var i=As.hasOwnProperty(e)?As[e]:As[e]={};no(t,i)},e.defineExtension=function(t,i){e.prototype[t]=i},e.defineDocExtension=function(e,t){Ws.prototype[e]=t},e.defineOption=hr;var Ss=[];e.defineInitHook=function(e){Ss.push(e)};var Cs=e.helpers={};e.registerHelper=function(t,i,r){Cs.hasOwnProperty(t)||(Cs[t]=e[t]={_global:[]}),Cs[t][i]=r},e.registerGlobalHelper=function(t,i,r,n){e.registerHelper(t,i,n),Cs[t]._global.push({pred:r,val:n})};var Rs=e.copyState=function(e,t){if(t===!0)return t;if(e.copyState)return e.copyState(t);var i={};for(var r in t){var n=t[r];n instanceof Array&&(n=n.concat([])),i[r]=n}return i},bs=e.startState=function(e,t,i){return e.startState?e.startState(t,i):!0};e.innerMode=function(e,t){for(;e.innerMode;){var i=e.innerMode(t);if(!i||i.mode==e)break;t=i.state,e=i.mode}return i||{mode:e,state:t}};var Os=e.commands={selectAll:function(e){e.setSelection(as(e.firstLine(),0),as(e.lastLine()),ra)},singleSelection:function(e){e.setSelection(e.getCursor("anchor"),e.getCursor("head"),ra)},killLine:function(e){pr(e,function(t){if(t.empty()){var i=xn(e.doc,t.head.line).text.length;return t.head.ch==i&&t.head.line<e.lastLine()?{from:t.head,to:as(t.head.line+1,0)}:{from:t.head,to:as(t.head.line,i)}}return{from:t.from(),to:t.to()}})},deleteLine:function(e){pr(e,function(t){return{from:as(t.from().line,0),to:Q(e.doc,as(t.to().line+1,0))}})},delLineLeft:function(e){pr(e,function(e){return{from:as(e.from().line,0),to:e.from()}})},undo:function(e){e.undo()},redo:function(e){e.redo()},undoSelection:function(e){e.undoSelection()},redoSelection:function(e){e.redoSelection()},goDocStart:function(e){e.extendSelection(as(e.firstLine(),0))},goDocEnd:function(e){e.extendSelection(as(e.lastLine()))},goLineStart:function(e){e.extendSelectionsBy(function(t){return Oo(e,t.head.line)},oa)},goLineStartSmart:function(e){e.extendSelectionsBy(function(t){var i=Oo(e,t.head.line),r=e.getLineHandle(i.line),n=Sn(r);if(!n||0==n[0].level){var o=Math.max(0,r.text.search(/\S/)),s=t.head.line==i.line&&t.head.ch<=o&&t.head.ch;return as(i.line,s?0:o)}return i},oa)},goLineEnd:function(e){e.extendSelectionsBy(function(t){return Po(e,t.head.line)},oa)},goLineRight:function(e){e.extendSelectionsBy(function(t){var i=e.charCoords(t.head,"div").top+5;return e.coordsChar({left:e.display.lineDiv.offsetWidth+100,top:i},"div")},oa)},goLineLeft:function(e){e.extendSelectionsBy(function(t){var i=e.charCoords(t.head,"div").top+5;return e.coordsChar({left:0,top:i},"div")},oa)},goLineUp:function(e){e.moveV(-1,"line")},goLineDown:function(e){e.moveV(1,"line")},goPageUp:function(e){e.moveV(-1,"page")},goPageDown:function(e){e.moveV(1,"page")},goCharLeft:function(e){e.moveH(-1,"char")},goCharRight:function(e){e.moveH(1,"char")},goColumnLeft:function(e){e.moveH(-1,"column")},goColumnRight:function(e){e.moveH(1,"column")},goWordLeft:function(e){e.moveH(-1,"word")},goGroupRight:function(e){e.moveH(1,"group")},goGroupLeft:function(e){e.moveH(-1,"group")},goWordRight:function(e){e.moveH(1,"word")},delCharBefore:function(e){e.deleteH(-1,"char")},delCharAfter:function(e){e.deleteH(1,"char")},delWordBefore:function(e){e.deleteH(-1,"word")},delWordAfter:function(e){e.deleteH(1,"word")},delGroupBefore:function(e){e.deleteH(-1,"group")},delGroupAfter:function(e){e.deleteH(1,"group")},indentAuto:function(e){e.indentSelection("smart")},indentMore:function(e){e.indentSelection("add")},indentLess:function(e){e.indentSelection("subtract")},insertTab:function(e){e.replaceSelection(" ")},insertSoftTab:function(e){for(var t=[],i=e.listSelections(),r=e.options.tabSize,n=0;n<i.length;n++){var o=i[n].from(),s=sa(e.getLine(o.line),o.ch,r);t.push(new Array(r-s%r+1).join(" "))}e.replaceSelections(t)},defaultTab:function(e){e.somethingSelected()?e.indentSelection("add"):e.execCommand("insertTab")},transposeChars:function(e){$t(e,function(){for(var t=e.listSelections(),i=[],r=0;r<t.length;r++){var n=t[r].head,o=xn(e.doc,n.line).text;if(o)if(n.ch==o.length&&(n=new as(n.line,n.ch-1)),n.ch>0)n=new as(n.line,n.ch+1),e.replaceRange(o.charAt(n.ch-1)+o.charAt(n.ch-2),as(n.line,n.ch-2),n,"+transpose");else if(n.line>e.doc.first){var s=xn(e.doc,n.line-1).text;s&&e.replaceRange(o.charAt(0)+"\n"+s.charAt(s.length-1),as(n.line-1,s.length-1),as(n.line,1),"+transpose")}i.push(new X(n,n))}e.setSelections(i)})},newlineAndIndent:function(e){$t(e,function(){for(var t=e.listSelections().length,i=0;t>i;i++){var r=e.listSelections()[i];e.replaceRange("\n",r.anchor,r.head,"+input"),e.indentLine(r.from().line+1,null,!0),sr(e)}})},toggleOverwrite:function(e){e.toggleOverwrite()}},Ps=e.keyMap={};Ps.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"},Ps.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-Up":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Down":"goDocEnd","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"},Ps.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineStart","Cmd-Right":"goLineEnd","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delLineLeft","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection",fallthrough:["basic","emacsy"]},Ps.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars"},Ps["default"]=es?Ps.macDefault:Ps.pcDefault;var Ds=e.lookupKey=function(e,t,i){function r(t){t=fr(t);var n=t[e];if(n===!1)return"stop";if(null!=n&&i(n))return!0;if(t.nofallthrough)return"stop";var o=t.fallthrough;if(null==o)return!1;if("[object Array]"!=Object.prototype.toString.call(o))return r(o);for(var s=0;s<o.length;++s){var a=r(o[s]);if(a)return a}return!1}for(var n=0;n<t.length;++n){var o=r(t[n]);if(o)return"stop"!=o}},_s=e.isModifierKey=function(e){var t=La[e.keyCode];return"Ctrl"==t||"Alt"==t||"Shift"==t||"Mod"==t},Ms=e.keyName=function(e,t){if(Xo&&34==e.keyCode&&e["char"])return!1;var i=La[e.keyCode];return null==i||e.altGraphKey?!1:(e.altKey&&(i="Alt-"+i),(rs?e.metaKey:e.ctrlKey)&&(i="Ctrl-"+i),(rs?e.ctrlKey:e.metaKey)&&(i="Cmd-"+i),!t&&e.shiftKey&&(i="Shift-"+i),i)};e.fromTextArea=function(t,i){function r(){t.value=u.getValue()}if(i||(i={}),i.value=t.value,!i.tabindex&&t.tabindex&&(i.tabindex=t.tabindex),!i.placeholder&&t.placeholder&&(i.placeholder=t.placeholder),null==i.autofocus){var n=ho();i.autofocus=n==t||null!=t.getAttribute("autofocus")&&n==document.body}if(t.form&&(Qs(t.form,"submit",r),!i.leaveSubmitMethodAlone)){var o=t.form,s=o.submit;try{var a=o.submit=function(){r(),o.submit=s,o.submit(),o.submit=a}}catch(l){}}t.style.display="none";var u=e(function(e){t.parentNode.insertBefore(e,t.nextSibling)},i);return u.save=r,u.getTextArea=function(){return t},u.toTextArea=function(){r(),t.parentNode.removeChild(u.getWrapperElement()),t.style.display="",t.form&&(Zs(t.form,"submit",r),"function"==typeof t.form.submit&&(t.form.submit=s))},u};var ws=e.StringStream=function(e,t){this.pos=this.start=0,this.string=e,this.tabSize=t||8,this.lastColumnPos=this.lastColumnValue=0,this.lineStart=0};ws.prototype={eol:function(){return this.pos>=this.string.length},sol:function(){return this.pos==this.lineStart},peek:function(){return this.string.charAt(this.pos)||void 0},next:function(){return this.pos<this.string.length?this.string.charAt(this.pos++):void 0},eat:function(e){var t=this.string.charAt(this.pos);if("string"==typeof e)var i=t==e;else var i=t&&(e.test?e.test(t):e(t));return i?(++this.pos,t):void 0},eatWhile:function(e){for(var t=this.pos;this.eat(e););return this.pos>t},eatSpace:function(){for(var e=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e},skipToEnd:function(){this.pos=this.string.length},skipTo:function(e){var t=this.string.indexOf(e,this.pos);return t>-1?(this.pos=t,!0):void 0},backUp:function(e){this.pos-=e},column:function(){return this.lastColumnPos<this.start&&(this.lastColumnValue=sa(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue),this.lastColumnPos=this.start),this.lastColumnValue-(this.lineStart?sa(this.string,this.lineStart,this.tabSize):0)},indentation:function(){return sa(this.string,null,this.tabSize)-(this.lineStart?sa(this.string,this.lineStart,this.tabSize):0)},match:function(e,t,i){if("string"!=typeof e){var r=this.string.slice(this.pos).match(e);return r&&r.index>0?null:(r&&t!==!1&&(this.pos+=r[0].length),r)}var n=function(e){return i?e.toLowerCase():e},o=this.string.substr(this.pos,e.length);return n(o)==n(e)?(t!==!1&&(this.pos+=e.length),!0):void 0},current:function(){return this.string.slice(this.start,this.pos)},hideFirstChars:function(e,t){this.lineStart+=e;try{return t()}finally{this.lineStart-=e}}};var Gs=e.TextMarker=function(e,t){this.lines=[],this.type=t,this.doc=e};$n(Gs),Gs.prototype.clear=function(){if(!this.explicitlyCleared){var e=this.doc.cm,t=e&&!e.curOp;if(t&&Yt(e),Kn(this,"clear")){var i=this.find();i&&qn(this,"clear",i.from,i.to)}for(var r=null,n=null,o=0;o<this.lines.length;++o){var s=this.lines[o],a=Tr(s.markedSpans,this);e&&!this.collapsed?ri(e,In(s),"text"):e&&(null!=a.to&&(n=In(s)),null!=a.from&&(r=In(s))),s.markedSpans=Ir(s.markedSpans,a),null==a.from&&this.collapsed&&!Wr(this.doc,s)&&e&&Tn(s,zt(e.display))}if(e&&this.collapsed&&!e.options.lineWrapping)for(var o=0;o<this.lines.length;++o){var l=Vr(this.lines[o]),u=d(l);u>e.display.maxLineLength&&(e.display.maxLine=l,e.display.maxLineLength=u,e.display.maxLineChanged=!0)}null!=r&&e&&this.collapsed&&ii(e,r,n+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,e&&ct(e.doc)),e&&qn(e,"markerCleared",e,this),t&&Kt(e),this.parent&&this.parent.clear()}},Gs.prototype.find=function(e,t){null==e&&"bookmark"==this.type&&(e=1);for(var i,r,n=0;n<this.lines.length;++n){var o=this.lines[n],s=Tr(o.markedSpans,this);if(null!=s.from&&(i=as(t?o:In(o),s.from),-1==e))return i;if(null!=s.to&&(r=as(t?o:In(o),s.to),1==e))return r}return i&&{from:i,to:r}},Gs.prototype.changed=function(){var e=this.find(-1,!0),t=this,i=this.doc.cm;e&&i&&$t(i,function(){var r=e.line,n=In(e.line),o=bt(i,n);if(o&&(_t(o),i.curOp.selectionChanged=i.curOp.forceUpdate=!0),i.curOp.updateMaxLine=!0,!Wr(t.doc,r)&&null!=t.height){var s=t.height;t.height=null;var a=Xr(t)-s;a&&Tn(r,r.height+a)}})},Gs.prototype.attachLine=function(e){if(!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;t.maybeHiddenMarkers&&-1!=to(t.maybeHiddenMarkers,this)||(t.maybeUnhiddenMarkers||(t.maybeUnhiddenMarkers=[])).push(this)}this.lines.push(e)},Gs.prototype.detachLine=function(e){if(this.lines.splice(to(this.lines,e),1),!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;(t.maybeHiddenMarkers||(t.maybeHiddenMarkers=[])).push(this)}};var ks=0,Bs=e.SharedTextMarker=function(e,t){this.markers=e,this.primary=t;for(var i=0;i<e.length;++i)e[i].parent=this};$n(Bs),Bs.prototype.clear=function(){if(!this.explicitlyCleared){this.explicitlyCleared=!0;for(var e=0;e<this.markers.length;++e)this.markers[e].clear();qn(this,"clear")}},Bs.prototype.find=function(e,t){return this.primary.find(e,t) };var Us=e.LineWidget=function(e,t,i){if(i)for(var r in i)i.hasOwnProperty(r)&&(this[r]=i[r]);this.cm=e,this.node=t};$n(Us),Us.prototype.clear=function(){var e=this.cm,t=this.line.widgets,i=this.line,r=In(i);if(null!=r&&t){for(var n=0;n<t.length;++n)t[n]==this&&t.splice(n--,1);t.length||(i.widgets=null);var o=Xr(this);$t(e,function(){zr(e,i,-o),ri(e,r,"widget"),Tn(i,Math.max(0,i.height-o))})}},Us.prototype.changed=function(){var e=this.height,t=this.cm,i=this.line;this.height=null;var r=Xr(this)-e;r&&$t(t,function(){t.curOp.forceUpdate=!0,zr(t,i,r),Tn(i,i.height+r)})};var Vs=e.Line=function(e,t,i){this.text=e,Dr(this,t),this.height=i?i(this):1};$n(Vs),Vs.prototype.lineNo=function(){return In(this)};var Hs={},Fs={};fn.prototype={chunkSize:function(){return this.lines.length},removeInner:function(e,t){for(var i=e,r=e+t;r>i;++i){var n=this.lines[i];this.height-=n.height,$r(n),qn(n,"delete")}this.lines.splice(e,t)},collapse:function(e){e.push.apply(e,this.lines)},insertInner:function(e,t,i){this.height+=i,this.lines=this.lines.slice(0,e).concat(t).concat(this.lines.slice(e));for(var r=0;r<t.length;++r)t[r].parent=this},iterN:function(e,t,i){for(var r=e+t;r>e;++e)if(i(this.lines[e]))return!0}},mn.prototype={chunkSize:function(){return this.size},removeInner:function(e,t){this.size-=t;for(var i=0;i<this.children.length;++i){var r=this.children[i],n=r.chunkSize();if(n>e){var o=Math.min(t,n-e),s=r.height;if(r.removeInner(e,o),this.height-=s-r.height,n==o&&(this.children.splice(i--,1),r.parent=null),0==(t-=o))break;e=0}else e-=n}if(this.size-t<25&&(this.children.length>1||!(this.children[0]instanceof fn))){var a=[];this.collapse(a),this.children=[new fn(a)],this.children[0].parent=this}},collapse:function(e){for(var t=0;t<this.children.length;++t)this.children[t].collapse(e)},insertInner:function(e,t,i){this.size+=t.length,this.height+=i;for(var r=0;r<this.children.length;++r){var n=this.children[r],o=n.chunkSize();if(o>=e){if(n.insertInner(e,t,i),n.lines&&n.lines.length>50){for(;n.lines.length>50;){var s=n.lines.splice(n.lines.length-25,25),a=new fn(s);n.height-=a.height,this.children.splice(r+1,0,a),a.parent=this}this.maybeSpill()}break}e-=o}},maybeSpill:function(){if(!(this.children.length<=10)){var e=this;do{var t=e.children.splice(e.children.length-5,5),i=new mn(t);if(e.parent){e.size-=i.size,e.height-=i.height;var r=to(e.parent.children,e);e.parent.children.splice(r+1,0,i)}else{var n=new mn(e.children);n.parent=e,e.children=[n,i],e=n}i.parent=e.parent}while(e.children.length>10);e.parent.maybeSpill()}},iterN:function(e,t,i){for(var r=0;r<this.children.length;++r){var n=this.children[r],o=n.chunkSize();if(o>e){var s=Math.min(t,o-e);if(n.iterN(e,s,i))return!0;if(0==(t-=s))break;e=0}else e-=o}}};var js=0,Ws=e.Doc=function(e,t,i){if(!(this instanceof Ws))return new Ws(e,t,i);null==i&&(i=0),mn.call(this,[new fn([new Vs("",null)])]),this.first=i,this.scrollTop=this.scrollLeft=0,this.cantEdit=!1,this.cleanGeneration=1,this.frontier=i;var r=as(i,0);this.sel=K(r),this.history=new Cn(null),this.id=++js,this.modeOption=t,"string"==typeof e&&(e=va(e)),hn(this,{from:r,to:r,text:e}),lt(this,K(r),ra)};Ws.prototype=ro(mn.prototype,{constructor:Ws,iter:function(e,t,i){i?this.iterN(e-this.first,t-e,i):this.iterN(this.first,this.first+this.size,e)},insert:function(e,t){for(var i=0,r=0;r<t.length;++r)i+=t[r].height;this.insertInner(e-this.first,t,i)},remove:function(e,t){this.removeInner(e-this.first,t)},getValue:function(e){var t=Ln(this,this.first,this.first+this.size);return e===!1?t:t.join(e||"\n")},setValue:Jt(function(e){var t=as(this.first,0),i=this.first+this.size-1;Yi(this,{from:t,to:as(i,xn(this,i).text.length),text:va(e),origin:"setValue"},!0),lt(this,K(t))}),replaceRange:function(e,t,i,r){t=Q(this,t),i=i?Q(this,i):t,er(this,e,t,i,r)},getRange:function(e,t,i){var r=Nn(this,Q(this,e),Q(this,t));return i===!1?r:r.join(i||"\n")},getLine:function(e){var t=this.getLineHandle(e);return t&&t.text},getLineHandle:function(e){return J(this,e)?xn(this,e):void 0},getLineNumber:function(e){return In(e)},getLineHandleVisualStart:function(e){return"number"==typeof e&&(e=xn(this,e)),Vr(e)},lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(e){return Q(this,e)},getCursor:function(e){var t,i=this.sel.primary();return t=null==e||"head"==e?i.head:"anchor"==e?i.anchor:"end"==e||"to"==e||e===!1?i.to():i.from()},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:Jt(function(e,t,i){ot(this,Q(this,"number"==typeof e?as(e,t||0):e),null,i)}),setSelection:Jt(function(e,t,i){ot(this,Q(this,e),Q(this,t||e),i)}),extendSelection:Jt(function(e,t,i){it(this,Q(this,e),t&&Q(this,t),i)}),extendSelections:Jt(function(e,t){rt(this,et(this,e,t))}),extendSelectionsBy:Jt(function(e,t){rt(this,io(this.sel.ranges,e),t)}),setSelections:Jt(function(e,t,i){if(e.length){for(var r=0,n=[];r<e.length;r++)n[r]=new X(Q(this,e[r].anchor),Q(this,e[r].head));null==t&&(t=Math.min(e.length-1,this.sel.primIndex)),lt(this,Y(n,t),i)}}),addSelection:Jt(function(e,t,i){var r=this.sel.ranges.slice(0);r.push(new X(Q(this,e),Q(this,t||e))),lt(this,Y(r,r.length-1),i)}),getSelection:function(e){for(var t,i=this.sel.ranges,r=0;r<i.length;r++){var n=Nn(this,i[r].from(),i[r].to());t=t?t.concat(n):n}return e===!1?t:t.join(e||"\n")},getSelections:function(e){for(var t=[],i=this.sel.ranges,r=0;r<i.length;r++){var n=Nn(this,i[r].from(),i[r].to());e!==!1&&(n=n.join(e||"\n")),t[r]=n}return t},replaceSelection:function(e,t,i){for(var r=[],n=0;n<this.sel.ranges.length;n++)r[n]=e;this.replaceSelections(r,t,i||"+input")},replaceSelections:Jt(function(e,t,i){for(var r=[],n=this.sel,o=0;o<n.ranges.length;o++){var s=n.ranges[o];r[o]={from:s.from(),to:s.to(),text:va(e[o]),origin:i}}for(var a=t&&"end"!=t&&zi(this,r,t),o=r.length-1;o>=0;o--)Yi(this,r[o]);a?at(this,a):this.cm&&sr(this.cm)}),undo:Jt(function(){$i(this,"undo")}),redo:Jt(function(){$i(this,"redo")}),undoSelection:Jt(function(){$i(this,"undo",!0)}),redoSelection:Jt(function(){$i(this,"redo",!0)}),setExtending:function(e){this.extend=e},getExtending:function(){return this.extend},historySize:function(){for(var e=this.history,t=0,i=0,r=0;r<e.done.length;r++)e.done[r].ranges||++t;for(var r=0;r<e.undone.length;r++)e.undone[r].ranges||++i;return{undo:t,redo:i}},clearHistory:function(){this.history=new Cn(this.history.maxGeneration)},markClean:function(){this.cleanGeneration=this.changeGeneration(!0)},changeGeneration:function(e){return e&&(this.history.lastOp=this.history.lastOrigin=null),this.history.generation},isClean:function(e){return this.history.generation==(e||this.cleanGeneration)},getHistory:function(){return{done:Bn(this.history.done),undone:Bn(this.history.undone)}},setHistory:function(e){var t=this.history=new Cn(this.history.maxGeneration);t.done=Bn(e.done.slice(0),null,!0),t.undone=Bn(e.undone.slice(0),null,!0)},markText:function(e,t,i){return mr(this,Q(this,e),Q(this,t),i,"range")},setBookmark:function(e,t){var i={replacedWith:t&&(null==t.nodeType?t.widget:t),insertLeft:t&&t.insertLeft,clearWhenEmpty:!1,shared:t&&t.shared};return e=Q(this,e),mr(this,e,e,i,"bookmark")},findMarksAt:function(e){e=Q(this,e);var t=[],i=xn(this,e.line).markedSpans;if(i)for(var r=0;r<i.length;++r){var n=i[r];(null==n.from||n.from<=e.ch)&&(null==n.to||n.to>=e.ch)&&t.push(n.marker.parent||n.marker)}return t},findMarks:function(e,t,i){e=Q(this,e),t=Q(this,t);var r=[],n=e.line;return this.iter(e.line,t.line+1,function(o){var s=o.markedSpans;if(s)for(var a=0;a<s.length;a++){var l=s[a];n==e.line&&e.ch>l.to||null==l.from&&n!=e.line||n==t.line&&l.from>t.ch||i&&!i(l.marker)||r.push(l.marker.parent||l.marker)}++n}),r},getAllMarks:function(){var e=[];return this.iter(function(t){var i=t.markedSpans;if(i)for(var r=0;r<i.length;++r)null!=i[r].from&&e.push(i[r].marker)}),e},posFromIndex:function(e){var t,i=this.first;return this.iter(function(r){var n=r.text.length+1;return n>e?(t=e,!0):(e-=n,void++i)}),Q(this,as(i,t))},indexFromPos:function(e){e=Q(this,e);var t=e.ch;return e.line<this.first||e.ch<0?0:(this.iter(this.first,e.line,function(e){t+=e.text.length+1}),t)},copy:function(e){var t=new Ws(Ln(this,this.first,this.first+this.size),this.modeOption,this.first);return t.scrollTop=this.scrollTop,t.scrollLeft=this.scrollLeft,t.sel=this.sel,t.extend=!1,e&&(t.history.undoDepth=this.history.undoDepth,t.setHistory(this.getHistory())),t},linkedDoc:function(e){e||(e={});var t=this.first,i=this.first+this.size;null!=e.from&&e.from>t&&(t=e.from),null!=e.to&&e.to<i&&(i=e.to);var r=new Ws(Ln(this,t,i),e.mode||this.modeOption,t);return e.sharedHist&&(r.history=this.history),(this.linked||(this.linked=[])).push({doc:r,sharedHist:e.sharedHist}),r.linked=[{doc:this,isParent:!0,sharedHist:e.sharedHist}],xr(r,vr(this)),r},unlinkDoc:function(t){if(t instanceof e&&(t=t.doc),this.linked)for(var i=0;i<this.linked.length;++i){var r=this.linked[i];if(r.doc==t){this.linked.splice(i,1),t.unlinkDoc(this),Nr(vr(this));break}}if(t.history==this.history){var n=[t.id];gn(t,function(e){n.push(e.id)},!0),t.history=new Cn(null),t.history.done=Bn(this.history.done,n),t.history.undone=Bn(this.history.undone,n)}},iterLinkedDocs:function(e){gn(this,e)},getMode:function(){return this.mode},getEditor:function(){return this.cm}}),Ws.prototype.eachLine=Ws.prototype.iter;var qs="iter insert remove copy getEditor".split(" ");for(var zs in Ws.prototype)Ws.prototype.hasOwnProperty(zs)&&to(qs,zs)<0&&(e.prototype[zs]=function(e){return function(){return e.apply(this.doc,arguments)}}(Ws.prototype[zs]));$n(Ws);var Xs,Ys=e.e_preventDefault=function(e){e.preventDefault?e.preventDefault():e.returnValue=!1},Ks=e.e_stopPropagation=function(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0},$s=e.e_stop=function(e){Ys(e),Ks(e)},Qs=e.on=function(e,t,i){if(e.addEventListener)e.addEventListener(t,i,!1);else if(e.attachEvent)e.attachEvent("on"+t,i);else{var r=e._handlers||(e._handlers={}),n=r[t]||(r[t]=[]);n.push(i)}},Zs=e.off=function(e,t,i){if(e.removeEventListener)e.removeEventListener(t,i,!1);else if(e.detachEvent)e.detachEvent("on"+t,i);else{var r=e._handlers&&e._handlers[t];if(!r)return;for(var n=0;n<r.length;++n)if(r[n]==i){r.splice(n,1);break}}},Js=e.signal=function(e,t){var i=e._handlers&&e._handlers[t];if(i)for(var r=Array.prototype.slice.call(arguments,2),n=0;n<i.length;++n)i[n].apply(null,r)},ea=0,ta=30,ia=e.Pass={toString:function(){return"CodeMirror.Pass"}},ra={scroll:!1},na={origin:"*mouse"},oa={origin:"+move"};Qn.prototype.set=function(e,t){clearTimeout(this.id),this.id=setTimeout(t,e)};var sa=e.countColumn=function(e,t,i,r,n){null==t&&(t=e.search(/[^\s\u00a0]/),-1==t&&(t=e.length));for(var o=r||0,s=n||0;;){var a=e.indexOf(" ",o);if(0>a||a>=t)return s+(t-o);s+=a-o,s+=i-s%i,o=a+1}},aa=[""],la=function(e){e.select()};Zo?la=function(e){e.selectionStart=0,e.selectionEnd=e.value.length}:jo&&(la=function(e){try{e.select()}catch(t){}}),[].indexOf&&(to=function(e,t){return e.indexOf(t)}),[].map&&(io=function(e,t){return e.map(t)});var ua,pa=/[\u00df\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,ca=e.isWordChar=function(e){return/\w/.test(e)||e>"€"&&(e.toUpperCase()!=e.toLowerCase()||pa.test(e))},da=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;ua=document.createRange?function(e,t,i){var r=document.createRange();return r.setEnd(e,i),r.setStart(e,t),r}:function(e,t,i){var r=document.body.createTextRange();return r.moveToElementText(e.parentNode),r.collapse(!0),r.moveEnd("character",i),r.moveStart("character",t),r},Bo&&(ho=function(){try{return document.activeElement}catch(e){return document.body}});var Ea,ha,fa,ma=!1,ga=function(){if(Vo)return!1;var e=uo("div");return"draggable"in e||"dragDrop"in e}(),va=e.splitLines=3!="\n\nb".split(/\n/).length?function(e){for(var t=0,i=[],r=e.length;r>=t;){var n=e.indexOf("\n",t);-1==n&&(n=e.length);var o=e.slice(t,"\r"==e.charAt(n-1)?n-1:n),s=o.indexOf("\r");-1!=s?(i.push(o.slice(0,s)),t+=s+1):(i.push(o),t=n+1)}return i}:function(e){return e.split(/\r\n?|\n/)},xa=window.getSelection?function(e){try{return e.selectionStart!=e.selectionEnd}catch(t){return!1}}:function(e){try{var t=e.ownerDocument.selection.createRange()}catch(i){}return t&&t.parentElement()==e?0!=t.compareEndPoints("StartToEnd",t):!1},Na=function(){var e=uo("div");return"oncopy"in e?!0:(e.setAttribute("oncopy","return;"),"function"==typeof e.oncopy)}(),La={3:"Enter",8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"PrintScrn",45:"Insert",46:"Delete",59:";",61:"=",91:"Mod",92:"Mod",93:"Mod",107:"=",109:"-",127:"Delete",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"};e.keyNames=La,function(){for(var e=0;10>e;e++)La[e+48]=La[e+96]=String(e);for(var e=65;90>=e;e++)La[e]=String.fromCharCode(e);for(var e=1;12>=e;e++)La[e+111]=La[e+63235]="F"+e}();var Ta,Ia=function(){function e(e){return 247>=e?i.charAt(e):e>=1424&&1524>=e?"R":e>=1536&&1773>=e?r.charAt(e-1536):e>=1774&&2220>=e?"r":e>=8192&&8203>=e?"w":8204==e?"b":"L"}function t(e,t,i){this.level=e,this.from=t,this.to=i}var i="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",r="rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm",n=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,o=/[stwN]/,s=/[LRr]/,a=/[Lb1n]/,l=/[1n]/,u="L";return function(i){if(!n.test(i))return!1;for(var r,p=i.length,c=[],d=0;p>d;++d)c.push(r=e(i.charCodeAt(d)));for(var d=0,E=u;p>d;++d){var r=c[d];"m"==r?c[d]=E:E=r}for(var d=0,h=u;p>d;++d){var r=c[d];"1"==r&&"r"==h?c[d]="n":s.test(r)&&(h=r,"r"==r&&(c[d]="R"))}for(var d=1,E=c[0];p-1>d;++d){var r=c[d];"+"==r&&"1"==E&&"1"==c[d+1]?c[d]="1":","!=r||E!=c[d+1]||"1"!=E&&"n"!=E||(c[d]=E),E=r}for(var d=0;p>d;++d){var r=c[d];if(","==r)c[d]="N";else if("%"==r){for(var f=d+1;p>f&&"%"==c[f];++f);for(var m=d&&"!"==c[d-1]||p>f&&"1"==c[f]?"1":"N",g=d;f>g;++g)c[g]=m;d=f-1}}for(var d=0,h=u;p>d;++d){var r=c[d];"L"==h&&"1"==r?c[d]="L":s.test(r)&&(h=r)}for(var d=0;p>d;++d)if(o.test(c[d])){for(var f=d+1;p>f&&o.test(c[f]);++f);for(var v="L"==(d?c[d-1]:u),x="L"==(p>f?c[f]:u),m=v||x?"L":"R",g=d;f>g;++g)c[g]=m;d=f-1}for(var N,L=[],d=0;p>d;)if(a.test(c[d])){var T=d;for(++d;p>d&&a.test(c[d]);++d);L.push(new t(0,T,d))}else{var I=d,y=L.length;for(++d;p>d&&"L"!=c[d];++d);for(var g=I;d>g;)if(l.test(c[g])){g>I&&L.splice(y,0,new t(1,I,g));var A=g;for(++g;d>g&&l.test(c[g]);++g);L.splice(y,0,new t(2,A,g)),I=g}else++g;d>I&&L.splice(y,0,new t(1,I,d))}return 1==L[0].level&&(N=i.match(/^\s+/))&&(L[0].from=N[0].length,L.unshift(new t(0,0,N[0].length))),1==eo(L).level&&(N=i.match(/\s+$/))&&(eo(L).to-=N[0].length,L.push(new t(0,p-N[0].length,p))),L[0].level!=eo(L).level&&L.push(new t(L[0].level,p,p)),L}}();return e.version="4.2.0",e})},{}],9:[function(t,i){!function(e,t){"object"==typeof i&&"object"==typeof i.exports?i.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(t,i){function r(e){var t=e.length,i=ot.type(e);return"function"===i||ot.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===i||0===t||"number"==typeof t&&t>0&&t-1 in e}function n(e,t,i){if(ot.isFunction(t))return ot.grep(e,function(e,r){return!!t.call(e,r,e)!==i});if(t.nodeType)return ot.grep(e,function(e){return e===t!==i});if("string"==typeof t){if(Et.test(t))return ot.filter(t,e,i);t=ot.filter(t,e)}return ot.grep(e,function(e){return ot.inArray(e,t)>=0!==i})}function o(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function s(e){var t=Lt[e]={};return ot.each(e.match(Nt)||[],function(e,i){t[i]=!0}),t}function a(){ft.addEventListener?(ft.removeEventListener("DOMContentLoaded",l,!1),t.removeEventListener("load",l,!1)):(ft.detachEvent("onreadystatechange",l),t.detachEvent("onload",l))}function l(){(ft.addEventListener||"load"===event.type||"complete"===ft.readyState)&&(a(),ot.ready())}function u(e,t,i){if(void 0===i&&1===e.nodeType){var r="data-"+t.replace(St,"-$1").toLowerCase();if(i=e.getAttribute(r),"string"==typeof i){try{i="true"===i?!0:"false"===i?!1:"null"===i?null:+i+""===i?+i:At.test(i)?ot.parseJSON(i):i}catch(n){}ot.data(e,t,i)}else i=void 0}return i}function p(e){var t;for(t in e)if(("data"!==t||!ot.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function c(e,t,i,r){if(ot.acceptData(e)){var n,o,s=ot.expando,a=e.nodeType,l=a?ot.cache:e,u=a?e[s]:e[s]&&s;if(u&&l[u]&&(r||l[u].data)||void 0!==i||"string"!=typeof t)return u||(u=a?e[s]=K.pop()||ot.guid++:s),l[u]||(l[u]=a?{}:{toJSON:ot.noop}),("object"==typeof t||"function"==typeof t)&&(r?l[u]=ot.extend(l[u],t):l[u].data=ot.extend(l[u].data,t)),o=l[u],r||(o.data||(o.data={}),o=o.data),void 0!==i&&(o[ot.camelCase(t)]=i),"string"==typeof t?(n=o[t],null==n&&(n=o[ot.camelCase(t)])):n=o,n}}function d(e,t,i){if(ot.acceptData(e)){var r,n,o=e.nodeType,s=o?ot.cache:e,a=o?e[ot.expando]:ot.expando;if(s[a]){if(t&&(r=i?s[a]:s[a].data)){ot.isArray(t)?t=t.concat(ot.map(t,ot.camelCase)):t in r?t=[t]:(t=ot.camelCase(t),t=t in r?[t]:t.split(" ")),n=t.length;for(;n--;)delete r[t[n]];if(i?!p(r):!ot.isEmptyObject(r))return}(i||(delete s[a].data,p(s[a])))&&(o?ot.cleanData([e],!0):rt.deleteExpando||s!=s.window?delete s[a]:s[a]=null)}}}function E(){return!0}function h(){return!1}function f(){try{return ft.activeElement}catch(e){}}function m(e){var t=kt.split("|"),i=e.createDocumentFragment();if(i.createElement)for(;t.length;)i.createElement(t.pop());return i}function g(e,t){var i,r,n=0,o=typeof e.getElementsByTagName!==yt?e.getElementsByTagName(t||"*"):typeof e.querySelectorAll!==yt?e.querySelectorAll(t||"*"):void 0;if(!o)for(o=[],i=e.childNodes||e;null!=(r=i[n]);n++)!t||ot.nodeName(r,t)?o.push(r):ot.merge(o,g(r,t));return void 0===t||t&&ot.nodeName(e,t)?ot.merge([e],o):o}function v(e){Pt.test(e.type)&&(e.defaultChecked=e.checked)}function x(e,t){return ot.nodeName(e,"table")&&ot.nodeName(11!==t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function N(e){return e.type=(null!==ot.find.attr(e,"type"))+"/"+e.type,e}function L(e){var t=Yt.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function T(e,t){for(var i,r=0;null!=(i=e[r]);r++)ot._data(i,"globalEval",!t||ot._data(t[r],"globalEval"))}function I(e,t){if(1===t.nodeType&&ot.hasData(e)){var i,r,n,o=ot._data(e),s=ot._data(t,o),a=o.events;if(a){delete s.handle,s.events={};for(i in a)for(r=0,n=a[i].length;n>r;r++)ot.event.add(t,i,a[i][r])}s.data&&(s.data=ot.extend({},s.data))}}function y(e,t){var i,r,n;if(1===t.nodeType){if(i=t.nodeName.toLowerCase(),!rt.noCloneEvent&&t[ot.expando]){n=ot._data(t);for(r in n.events)ot.removeEvent(t,r,n.handle);t.removeAttribute(ot.expando)}"script"===i&&t.text!==e.text?(N(t).text=e.text,L(t)):"object"===i?(t.parentNode&&(t.outerHTML=e.outerHTML),rt.html5Clone&&e.innerHTML&&!ot.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===i&&Pt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===i?t.defaultSelected=t.selected=e.defaultSelected:("input"===i||"textarea"===i)&&(t.defaultValue=e.defaultValue)}}function A(e,i){var r,n=ot(i.createElement(e)).appendTo(i.body),o=t.getDefaultComputedStyle&&(r=t.getDefaultComputedStyle(n[0]))?r.display:ot.css(n[0],"display");return n.detach(),o}function S(e){var t=ft,i=ei[e];return i||(i=A(e,t),"none"!==i&&i||(Jt=(Jt||ot("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement),t=(Jt[0].contentWindow||Jt[0].contentDocument).document,t.write(),t.close(),i=A(e,t),Jt.detach()),ei[e]=i),i}function C(e,t){return{get:function(){var i=e();if(null!=i)return i?void delete this.get:(this.get=t).apply(this,arguments)}}}function R(e,t){if(t in e)return t;for(var i=t.charAt(0).toUpperCase()+t.slice(1),r=t,n=Ei.length;n--;)if(t=Ei[n]+i,t in e)return t;return r}function b(e,t){for(var i,r,n,o=[],s=0,a=e.length;a>s;s++)r=e[s],r.style&&(o[s]=ot._data(r,"olddisplay"),i=r.style.display,t?(o[s]||"none"!==i||(r.style.display=""),""===r.style.display&&bt(r)&&(o[s]=ot._data(r,"olddisplay",S(r.nodeName)))):(n=bt(r),(i&&"none"!==i||!n)&&ot._data(r,"olddisplay",n?i:ot.css(r,"display"))));for(s=0;a>s;s++)r=e[s],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[s]||"":"none"));return e}function O(e,t,i){var r=ui.exec(t);return r?Math.max(0,r[1]-(i||0))+(r[2]||"px"):t}function P(e,t,i,r,n){for(var o=i===(r?"border":"content")?4:"width"===t?1:0,s=0;4>o;o+=2)"margin"===i&&(s+=ot.css(e,i+Rt[o],!0,n)),r?("content"===i&&(s-=ot.css(e,"padding"+Rt[o],!0,n)),"margin"!==i&&(s-=ot.css(e,"border"+Rt[o]+"Width",!0,n))):(s+=ot.css(e,"padding"+Rt[o],!0,n),"padding"!==i&&(s+=ot.css(e,"border"+Rt[o]+"Width",!0,n)));return s}function D(e,t,i){var r=!0,n="width"===t?e.offsetWidth:e.offsetHeight,o=ti(e),s=rt.boxSizing&&"border-box"===ot.css(e,"boxSizing",!1,o);if(0>=n||null==n){if(n=ii(e,t,o),(0>n||null==n)&&(n=e.style[t]),ni.test(n))return n;r=s&&(rt.boxSizingReliable()||n===e.style[t]),n=parseFloat(n)||0}return n+P(e,t,i||(s?"border":"content"),r,o)+"px"}function _(e,t,i,r,n){return new _.prototype.init(e,t,i,r,n)}function M(){return setTimeout(function(){hi=void 0}),hi=ot.now()}function w(e,t){var i,r={height:e},n=0;for(t=t?1:0;4>n;n+=2-t)i=Rt[n],r["margin"+i]=r["padding"+i]=e;return t&&(r.opacity=r.width=e),r}function G(e,t,i){for(var r,n=(Ni[t]||[]).concat(Ni["*"]),o=0,s=n.length;s>o;o++)if(r=n[o].call(i,t,e))return r}function k(e,t,i){var r,n,o,s,a,l,u,p,c=this,d={},E=e.style,h=e.nodeType&&bt(e),f=ot._data(e,"fxshow");i.queue||(a=ot._queueHooks(e,"fx"),null==a.unqueued&&(a.unqueued=0,l=a.empty.fire,a.empty.fire=function(){a.unqueued||l()}),a.unqueued++,c.always(function(){c.always(function(){a.unqueued--,ot.queue(e,"fx").length||a.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(i.overflow=[E.overflow,E.overflowX,E.overflowY],u=ot.css(e,"display"),p="none"===u?ot._data(e,"olddisplay")||S(e.nodeName):u,"inline"===p&&"none"===ot.css(e,"float")&&(rt.inlineBlockNeedsLayout&&"inline"!==S(e.nodeName)?E.zoom=1:E.display="inline-block")),i.overflow&&(E.overflow="hidden",rt.shrinkWrapBlocks()||c.always(function(){E.overflow=i.overflow[0],E.overflowX=i.overflow[1],E.overflowY=i.overflow[2]}));for(r in t)if(n=t[r],mi.exec(n)){if(delete t[r],o=o||"toggle"===n,n===(h?"hide":"show")){if("show"!==n||!f||void 0===f[r])continue;h=!0}d[r]=f&&f[r]||ot.style(e,r)}else u=void 0;if(ot.isEmptyObject(d))"inline"===("none"===u?S(e.nodeName):u)&&(E.display=u);else{f?"hidden"in f&&(h=f.hidden):f=ot._data(e,"fxshow",{}),o&&(f.hidden=!h),h?ot(e).show():c.done(function(){ot(e).hide()}),c.done(function(){var t;ot._removeData(e,"fxshow");for(t in d)ot.style(e,t,d[t])});for(r in d)s=G(h?f[r]:0,r,c),r in f||(f[r]=s.start,h&&(s.end=s.start,s.start="width"===r||"height"===r?1:0))}}function B(e,t){var i,r,n,o,s;for(i in e)if(r=ot.camelCase(i),n=t[r],o=e[i],ot.isArray(o)&&(n=o[1],o=e[i]=o[0]),i!==r&&(e[r]=o,delete e[i]),s=ot.cssHooks[r],s&&"expand"in s){o=s.expand(o),delete e[r];for(i in o)i in e||(e[i]=o[i],t[i]=n)}else t[r]=n}function U(e,t,i){var r,n,o=0,s=xi.length,a=ot.Deferred().always(function(){delete l.elem}),l=function(){if(n)return!1;for(var t=hi||M(),i=Math.max(0,u.startTime+u.duration-t),r=i/u.duration||0,o=1-r,s=0,l=u.tweens.length;l>s;s++)u.tweens[s].run(o);return a.notifyWith(e,[u,o,i]),1>o&&l?i:(a.resolveWith(e,[u]),!1)},u=a.promise({elem:e,props:ot.extend({},t),opts:ot.extend(!0,{specialEasing:{}},i),originalProperties:t,originalOptions:i,startTime:hi||M(),duration:i.duration,tweens:[],createTween:function(t,i){var r=ot.Tween(e,u.opts,t,i,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(r),r},stop:function(t){var i=0,r=t?u.tweens.length:0;if(n)return this;for(n=!0;r>i;i++)u.tweens[i].run(1);return t?a.resolveWith(e,[u,t]):a.rejectWith(e,[u,t]),this}}),p=u.props;for(B(p,u.opts.specialEasing);s>o;o++)if(r=xi[o].call(u,e,p,u.opts))return r;return ot.map(p,G,u),ot.isFunction(u.opts.start)&&u.opts.start.call(e,u),ot.fx.timer(ot.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function V(e){return function(t,i){"string"!=typeof t&&(i=t,t="*");var r,n=0,o=t.toLowerCase().match(Nt)||[];if(ot.isFunction(i))for(;r=o[n++];)"+"===r.charAt(0)?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(i)):(e[r]=e[r]||[]).push(i)}}function H(e,t,i,r){function n(a){var l;return o[a]=!0,ot.each(e[a]||[],function(e,a){var u=a(t,i,r);return"string"!=typeof u||s||o[u]?s?!(l=u):void 0:(t.dataTypes.unshift(u),n(u),!1)}),l}var o={},s=e===Wi;return n(t.dataTypes[0])||!o["*"]&&n("*")}function F(e,t){var i,r,n=ot.ajaxSettings.flatOptions||{};for(r in t)void 0!==t[r]&&((n[r]?e:i||(i={}))[r]=t[r]);return i&&ot.extend(!0,e,i),e}function j(e,t,i){for(var r,n,o,s,a=e.contents,l=e.dataTypes;"*"===l[0];)l.shift(),void 0===n&&(n=e.mimeType||t.getResponseHeader("Content-Type"));if(n)for(s in a)if(a[s]&&a[s].test(n)){l.unshift(s);break}if(l[0]in i)o=l[0];else{for(s in i){if(!l[0]||e.converters[s+" "+l[0]]){o=s;break}r||(r=s)}o=o||r}return o?(o!==l[0]&&l.unshift(o),i[o]):void 0}function W(e,t,i,r){var n,o,s,a,l,u={},p=e.dataTypes.slice();if(p[1])for(s in e.converters)u[s.toLowerCase()]=e.converters[s];for(o=p.shift();o;)if(e.responseFields[o]&&(i[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=p.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(s=u[l+" "+o]||u["* "+o],!s)for(n in u)if(a=n.split(" "),a[1]===o&&(s=u[l+" "+a[0]]||u["* "+a[0]])){s===!0?s=u[n]:u[n]!==!0&&(o=a[0],p.unshift(a[1]));break}if(s!==!0)if(s&&e["throws"])t=s(t);else try{t=s(t)}catch(c){return{state:"parsererror",error:s?c:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}function q(e,t,i,r){var n;if(ot.isArray(t))ot.each(t,function(t,n){i||Yi.test(e)?r(e,n):q(e+"["+("object"==typeof n?t:"")+"]",n,i,r)});else if(i||"object"!==ot.type(t))r(e,t);else for(n in t)q(e+"["+n+"]",t[n],i,r)}function z(){try{return new t.XMLHttpRequest}catch(e){}}function X(){try{return new t.ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}function Y(e){return ot.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}var K=[],$=K.slice,Q=K.concat,Z=K.push,J=K.indexOf,et={},tt=et.toString,it=et.hasOwnProperty,rt={},nt="1.11.1",ot=function(e,t){return new ot.fn.init(e,t)},st=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,at=/^-ms-/,lt=/-([\da-z])/gi,ut=function(e,t){return t.toUpperCase()};ot.fn=ot.prototype={jquery:nt,constructor:ot,selector:"",length:0,toArray:function(){return $.call(this)},get:function(e){return null!=e?0>e?this[e+this.length]:this[e]:$.call(this)},pushStack:function(e){var t=ot.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return ot.each(this,e,t)},map:function(e){return this.pushStack(ot.map(this,function(t,i){return e.call(t,i,t)}))},slice:function(){return this.pushStack($.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,i=+e+(0>e?t:0);return this.pushStack(i>=0&&t>i?[this[i]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:Z,sort:K.sort,splice:K.splice},ot.extend=ot.fn.extend=function(){var e,t,i,r,n,o,s=arguments[0]||{},a=1,l=arguments.length,u=!1;for("boolean"==typeof s&&(u=s,s=arguments[a]||{},a++),"object"==typeof s||ot.isFunction(s)||(s={}),a===l&&(s=this,a--);l>a;a++)if(null!=(n=arguments[a]))for(r in n)e=s[r],i=n[r],s!==i&&(u&&i&&(ot.isPlainObject(i)||(t=ot.isArray(i)))?(t?(t=!1,o=e&&ot.isArray(e)?e:[]):o=e&&ot.isPlainObject(e)?e:{},s[r]=ot.extend(u,o,i)):void 0!==i&&(s[r]=i));return s},ot.extend({expando:"jQuery"+(nt+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return"function"===ot.type(e)},isArray:Array.isArray||function(e){return"array"===ot.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!ot.isArray(e)&&e-parseFloat(e)>=0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},isPlainObject:function(e){var t;if(!e||"object"!==ot.type(e)||e.nodeType||ot.isWindow(e))return!1;try{if(e.constructor&&!it.call(e,"constructor")&&!it.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(i){return!1}if(rt.ownLast)for(t in e)return it.call(e,t);for(t in e);return void 0===t||it.call(e,t)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?et[tt.call(e)]||"object":typeof e},globalEval:function(e){e&&ot.trim(e)&&(t.execScript||function(e){t.eval.call(t,e)})(e)},camelCase:function(e){return e.replace(at,"ms-").replace(lt,ut)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,i){var n,o=0,s=e.length,a=r(e);if(i){if(a)for(;s>o&&(n=t.apply(e[o],i),n!==!1);o++);else for(o in e)if(n=t.apply(e[o],i),n===!1)break}else if(a)for(;s>o&&(n=t.call(e[o],o,e[o]),n!==!1);o++);else for(o in e)if(n=t.call(e[o],o,e[o]),n===!1)break;return e},trim:function(e){return null==e?"":(e+"").replace(st,"")},makeArray:function(e,t){var i=t||[];return null!=e&&(r(Object(e))?ot.merge(i,"string"==typeof e?[e]:e):Z.call(i,e)),i},inArray:function(e,t,i){var r;if(t){if(J)return J.call(t,e,i);for(r=t.length,i=i?0>i?Math.max(0,r+i):i:0;r>i;i++)if(i in t&&t[i]===e)return i}return-1},merge:function(e,t){for(var i=+t.length,r=0,n=e.length;i>r;)e[n++]=t[r++]; if(i!==i)for(;void 0!==t[r];)e[n++]=t[r++];return e.length=n,e},grep:function(e,t,i){for(var r,n=[],o=0,s=e.length,a=!i;s>o;o++)r=!t(e[o],o),r!==a&&n.push(e[o]);return n},map:function(e,t,i){var n,o=0,s=e.length,a=r(e),l=[];if(a)for(;s>o;o++)n=t(e[o],o,i),null!=n&&l.push(n);else for(o in e)n=t(e[o],o,i),null!=n&&l.push(n);return Q.apply([],l)},guid:1,proxy:function(e,t){var i,r,n;return"string"==typeof t&&(n=e[t],t=e,e=n),ot.isFunction(e)?(i=$.call(arguments,2),r=function(){return e.apply(t||this,i.concat($.call(arguments)))},r.guid=e.guid=e.guid||ot.guid++,r):void 0},now:function(){return+new Date},support:rt}),ot.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){et["[object "+t+"]"]=t.toLowerCase()});var pt=function(e){function t(e,t,i,r){var n,o,s,a,l,u,c,E,h,f;if((t?t.ownerDocument||t:V)!==D&&P(t),t=t||D,i=i||[],!e||"string"!=typeof e)return i;if(1!==(a=t.nodeType)&&9!==a)return[];if(M&&!r){if(n=vt.exec(e))if(s=n[1]){if(9===a){if(o=t.getElementById(s),!o||!o.parentNode)return i;if(o.id===s)return i.push(o),i}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(s))&&B(t,o)&&o.id===s)return i.push(o),i}else{if(n[2])return J.apply(i,t.getElementsByTagName(e)),i;if((s=n[3])&&L.getElementsByClassName&&t.getElementsByClassName)return J.apply(i,t.getElementsByClassName(s)),i}if(L.qsa&&(!w||!w.test(e))){if(E=c=U,h=t,f=9===a&&e,1===a&&"object"!==t.nodeName.toLowerCase()){for(u=A(e),(c=t.getAttribute("id"))?E=c.replace(Nt,"\\$&"):t.setAttribute("id",E),E="[id='"+E+"'] ",l=u.length;l--;)u[l]=E+d(u[l]);h=xt.test(e)&&p(t.parentNode)||t,f=u.join(",")}if(f)try{return J.apply(i,h.querySelectorAll(f)),i}catch(m){}finally{c||t.removeAttribute("id")}}}return C(e.replace(lt,"$1"),t,i,r)}function i(){function e(i,r){return t.push(i+" ")>T.cacheLength&&delete e[t.shift()],e[i+" "]=r}var t=[];return e}function r(e){return e[U]=!0,e}function n(e){var t=D.createElement("div");try{return!!e(t)}catch(i){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function o(e,t){for(var i=e.split("|"),r=e.length;r--;)T.attrHandle[i[r]]=t}function s(e,t){var i=t&&e,r=i&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||Y)-(~e.sourceIndex||Y);if(r)return r;if(i)for(;i=i.nextSibling;)if(i===t)return-1;return e?1:-1}function a(e){return function(t){var i=t.nodeName.toLowerCase();return"input"===i&&t.type===e}}function l(e){return function(t){var i=t.nodeName.toLowerCase();return("input"===i||"button"===i)&&t.type===e}}function u(e){return r(function(t){return t=+t,r(function(i,r){for(var n,o=e([],i.length,t),s=o.length;s--;)i[n=o[s]]&&(i[n]=!(r[n]=i[n]))})})}function p(e){return e&&typeof e.getElementsByTagName!==X&&e}function c(){}function d(e){for(var t=0,i=e.length,r="";i>t;t++)r+=e[t].value;return r}function E(e,t,i){var r=t.dir,n=i&&"parentNode"===r,o=F++;return t.first?function(t,i,o){for(;t=t[r];)if(1===t.nodeType||n)return e(t,i,o)}:function(t,i,s){var a,l,u=[H,o];if(s){for(;t=t[r];)if((1===t.nodeType||n)&&e(t,i,s))return!0}else for(;t=t[r];)if(1===t.nodeType||n){if(l=t[U]||(t[U]={}),(a=l[r])&&a[0]===H&&a[1]===o)return u[2]=a[2];if(l[r]=u,u[2]=e(t,i,s))return!0}}}function h(e){return e.length>1?function(t,i,r){for(var n=e.length;n--;)if(!e[n](t,i,r))return!1;return!0}:e[0]}function f(e,i,r){for(var n=0,o=i.length;o>n;n++)t(e,i[n],r);return r}function m(e,t,i,r,n){for(var o,s=[],a=0,l=e.length,u=null!=t;l>a;a++)(o=e[a])&&(!i||i(o,r,n))&&(s.push(o),u&&t.push(a));return s}function g(e,t,i,n,o,s){return n&&!n[U]&&(n=g(n)),o&&!o[U]&&(o=g(o,s)),r(function(r,s,a,l){var u,p,c,d=[],E=[],h=s.length,g=r||f(t||"*",a.nodeType?[a]:a,[]),v=!e||!r&&t?g:m(g,d,e,a,l),x=i?o||(r?e:h||n)?[]:s:v;if(i&&i(v,x,a,l),n)for(u=m(x,E),n(u,[],a,l),p=u.length;p--;)(c=u[p])&&(x[E[p]]=!(v[E[p]]=c));if(r){if(o||e){if(o){for(u=[],p=x.length;p--;)(c=x[p])&&u.push(v[p]=c);o(null,x=[],u,l)}for(p=x.length;p--;)(c=x[p])&&(u=o?tt.call(r,c):d[p])>-1&&(r[u]=!(s[u]=c))}}else x=m(x===s?x.splice(h,x.length):x),o?o(null,s,x,l):J.apply(s,x)})}function v(e){for(var t,i,r,n=e.length,o=T.relative[e[0].type],s=o||T.relative[" "],a=o?1:0,l=E(function(e){return e===t},s,!0),u=E(function(e){return tt.call(t,e)>-1},s,!0),p=[function(e,i,r){return!o&&(r||i!==R)||((t=i).nodeType?l(e,i,r):u(e,i,r))}];n>a;a++)if(i=T.relative[e[a].type])p=[E(h(p),i)];else{if(i=T.filter[e[a].type].apply(null,e[a].matches),i[U]){for(r=++a;n>r&&!T.relative[e[r].type];r++);return g(a>1&&h(p),a>1&&d(e.slice(0,a-1).concat({value:" "===e[a-2].type?"*":""})).replace(lt,"$1"),i,r>a&&v(e.slice(a,r)),n>r&&v(e=e.slice(r)),n>r&&d(e))}p.push(i)}return h(p)}function x(e,i){var n=i.length>0,o=e.length>0,s=function(r,s,a,l,u){var p,c,d,E=0,h="0",f=r&&[],g=[],v=R,x=r||o&&T.find.TAG("*",u),N=H+=null==v?1:Math.random()||.1,L=x.length;for(u&&(R=s!==D&&s);h!==L&&null!=(p=x[h]);h++){if(o&&p){for(c=0;d=e[c++];)if(d(p,s,a)){l.push(p);break}u&&(H=N)}n&&((p=!d&&p)&&E--,r&&f.push(p))}if(E+=h,n&&h!==E){for(c=0;d=i[c++];)d(f,g,s,a);if(r){if(E>0)for(;h--;)f[h]||g[h]||(g[h]=Q.call(l));g=m(g)}J.apply(l,g),u&&!r&&g.length>0&&E+i.length>1&&t.uniqueSort(l)}return u&&(H=N,R=v),f};return n?r(s):s}var N,L,T,I,y,A,S,C,R,b,O,P,D,_,M,w,G,k,B,U="sizzle"+-new Date,V=e.document,H=0,F=0,j=i(),W=i(),q=i(),z=function(e,t){return e===t&&(O=!0),0},X="undefined",Y=1<<31,K={}.hasOwnProperty,$=[],Q=$.pop,Z=$.push,J=$.push,et=$.slice,tt=$.indexOf||function(e){for(var t=0,i=this.length;i>t;t++)if(this[t]===e)return t;return-1},it="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",rt="[\\x20\\t\\r\\n\\f]",nt="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",ot=nt.replace("w","w#"),st="\\["+rt+"*("+nt+")(?:"+rt+"*([*^$|!~]?=)"+rt+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+ot+"))|)"+rt+"*\\]",at=":("+nt+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+st+")*)|.*)\\)|)",lt=new RegExp("^"+rt+"+|((?:^|[^\\\\])(?:\\\\.)*)"+rt+"+$","g"),ut=new RegExp("^"+rt+"*,"+rt+"*"),pt=new RegExp("^"+rt+"*([>+~]|"+rt+")"+rt+"*"),ct=new RegExp("="+rt+"*([^\\]'\"]*?)"+rt+"*\\]","g"),dt=new RegExp(at),Et=new RegExp("^"+ot+"$"),ht={ID:new RegExp("^#("+nt+")"),CLASS:new RegExp("^\\.("+nt+")"),TAG:new RegExp("^("+nt.replace("w","w*")+")"),ATTR:new RegExp("^"+st),PSEUDO:new RegExp("^"+at),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+rt+"*(even|odd|(([+-]|)(\\d*)n|)"+rt+"*(?:([+-]|)"+rt+"*(\\d+)|))"+rt+"*\\)|)","i"),bool:new RegExp("^(?:"+it+")$","i"),needsContext:new RegExp("^"+rt+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+rt+"*((?:-\\d)?\\d*)"+rt+"*\\)|)(?=[^-]|$)","i")},ft=/^(?:input|select|textarea|button)$/i,mt=/^h\d$/i,gt=/^[^{]+\{\s*\[native \w/,vt=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,xt=/[+~]/,Nt=/'|\\/g,Lt=new RegExp("\\\\([\\da-f]{1,6}"+rt+"?|("+rt+")|.)","ig"),Tt=function(e,t,i){var r="0x"+t-65536;return r!==r||i?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)};try{J.apply($=et.call(V.childNodes),V.childNodes),$[V.childNodes.length].nodeType}catch(It){J={apply:$.length?function(e,t){Z.apply(e,et.call(t))}:function(e,t){for(var i=e.length,r=0;e[i++]=t[r++];);e.length=i-1}}}L=t.support={},y=t.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},P=t.setDocument=function(e){var t,i=e?e.ownerDocument||e:V,r=i.defaultView;return i!==D&&9===i.nodeType&&i.documentElement?(D=i,_=i.documentElement,M=!y(i),r&&r!==r.top&&(r.addEventListener?r.addEventListener("unload",function(){P()},!1):r.attachEvent&&r.attachEvent("onunload",function(){P()})),L.attributes=n(function(e){return e.className="i",!e.getAttribute("className")}),L.getElementsByTagName=n(function(e){return e.appendChild(i.createComment("")),!e.getElementsByTagName("*").length}),L.getElementsByClassName=gt.test(i.getElementsByClassName)&&n(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),L.getById=n(function(e){return _.appendChild(e).id=U,!i.getElementsByName||!i.getElementsByName(U).length}),L.getById?(T.find.ID=function(e,t){if(typeof t.getElementById!==X&&M){var i=t.getElementById(e);return i&&i.parentNode?[i]:[]}},T.filter.ID=function(e){var t=e.replace(Lt,Tt);return function(e){return e.getAttribute("id")===t}}):(delete T.find.ID,T.filter.ID=function(e){var t=e.replace(Lt,Tt);return function(e){var i=typeof e.getAttributeNode!==X&&e.getAttributeNode("id");return i&&i.value===t}}),T.find.TAG=L.getElementsByTagName?function(e,t){return typeof t.getElementsByTagName!==X?t.getElementsByTagName(e):void 0}:function(e,t){var i,r=[],n=0,o=t.getElementsByTagName(e);if("*"===e){for(;i=o[n++];)1===i.nodeType&&r.push(i);return r}return o},T.find.CLASS=L.getElementsByClassName&&function(e,t){return typeof t.getElementsByClassName!==X&&M?t.getElementsByClassName(e):void 0},G=[],w=[],(L.qsa=gt.test(i.querySelectorAll))&&(n(function(e){e.innerHTML="<select msallowclip=''><option selected=''></option></select>",e.querySelectorAll("[msallowclip^='']").length&&w.push("[*^$]="+rt+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||w.push("\\["+rt+"*(?:value|"+it+")"),e.querySelectorAll(":checked").length||w.push(":checked")}),n(function(e){var t=i.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&w.push("name"+rt+"*[*^$|!~]?="),e.querySelectorAll(":enabled").length||w.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),w.push(",.*:")})),(L.matchesSelector=gt.test(k=_.matches||_.webkitMatchesSelector||_.mozMatchesSelector||_.oMatchesSelector||_.msMatchesSelector))&&n(function(e){L.disconnectedMatch=k.call(e,"div"),k.call(e,"[s!='']:x"),G.push("!=",at)}),w=w.length&&new RegExp(w.join("|")),G=G.length&&new RegExp(G.join("|")),t=gt.test(_.compareDocumentPosition),B=t||gt.test(_.contains)?function(e,t){var i=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(i.contains?i.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},z=t?function(e,t){if(e===t)return O=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r?r:(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1,1&r||!L.sortDetached&&t.compareDocumentPosition(e)===r?e===i||e.ownerDocument===V&&B(V,e)?-1:t===i||t.ownerDocument===V&&B(V,t)?1:b?tt.call(b,e)-tt.call(b,t):0:4&r?-1:1)}:function(e,t){if(e===t)return O=!0,0;var r,n=0,o=e.parentNode,a=t.parentNode,l=[e],u=[t];if(!o||!a)return e===i?-1:t===i?1:o?-1:a?1:b?tt.call(b,e)-tt.call(b,t):0;if(o===a)return s(e,t);for(r=e;r=r.parentNode;)l.unshift(r);for(r=t;r=r.parentNode;)u.unshift(r);for(;l[n]===u[n];)n++;return n?s(l[n],u[n]):l[n]===V?-1:u[n]===V?1:0},i):D},t.matches=function(e,i){return t(e,null,null,i)},t.matchesSelector=function(e,i){if((e.ownerDocument||e)!==D&&P(e),i=i.replace(ct,"='$1']"),!(!L.matchesSelector||!M||G&&G.test(i)||w&&w.test(i)))try{var r=k.call(e,i);if(r||L.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(n){}return t(i,D,null,[e]).length>0},t.contains=function(e,t){return(e.ownerDocument||e)!==D&&P(e),B(e,t)},t.attr=function(e,t){(e.ownerDocument||e)!==D&&P(e);var i=T.attrHandle[t.toLowerCase()],r=i&&K.call(T.attrHandle,t.toLowerCase())?i(e,t,!M):void 0;return void 0!==r?r:L.attributes||!M?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null},t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},t.uniqueSort=function(e){var t,i=[],r=0,n=0;if(O=!L.detectDuplicates,b=!L.sortStable&&e.slice(0),e.sort(z),O){for(;t=e[n++];)t===e[n]&&(r=i.push(n));for(;r--;)e.splice(i[r],1)}return b=null,e},I=t.getText=function(e){var t,i="",r=0,n=e.nodeType;if(n){if(1===n||9===n||11===n){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)i+=I(e)}else if(3===n||4===n)return e.nodeValue}else for(;t=e[r++];)i+=I(t);return i},T=t.selectors={cacheLength:50,createPseudo:r,match:ht,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(Lt,Tt),e[3]=(e[3]||e[4]||e[5]||"").replace(Lt,Tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||t.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&t.error(e[0]),e},PSEUDO:function(e){var t,i=!e[6]&&e[2];return ht.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":i&&dt.test(i)&&(t=A(i,!0))&&(t=i.indexOf(")",i.length-t)-i.length)&&(e[0]=e[0].slice(0,t),e[2]=i.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(Lt,Tt).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=j[e+" "];return t||(t=new RegExp("(^|"+rt+")"+e+"("+rt+"|$)"))&&j(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==X&&e.getAttribute("class")||"")})},ATTR:function(e,i,r){return function(n){var o=t.attr(n,e);return null==o?"!="===i:i?(o+="","="===i?o===r:"!="===i?o!==r:"^="===i?r&&0===o.indexOf(r):"*="===i?r&&o.indexOf(r)>-1:"$="===i?r&&o.slice(-r.length)===r:"~="===i?(" "+o+" ").indexOf(r)>-1:"|="===i?o===r||o.slice(0,r.length+1)===r+"-":!1):!0}},CHILD:function(e,t,i,r,n){var o="nth"!==e.slice(0,3),s="last"!==e.slice(-4),a="of-type"===t;return 1===r&&0===n?function(e){return!!e.parentNode}:function(t,i,l){var u,p,c,d,E,h,f=o!==s?"nextSibling":"previousSibling",m=t.parentNode,g=a&&t.nodeName.toLowerCase(),v=!l&&!a;if(m){if(o){for(;f;){for(c=t;c=c[f];)if(a?c.nodeName.toLowerCase()===g:1===c.nodeType)return!1;h=f="only"===e&&!h&&"nextSibling"}return!0}if(h=[s?m.firstChild:m.lastChild],s&&v){for(p=m[U]||(m[U]={}),u=p[e]||[],E=u[0]===H&&u[1],d=u[0]===H&&u[2],c=E&&m.childNodes[E];c=++E&&c&&c[f]||(d=E=0)||h.pop();)if(1===c.nodeType&&++d&&c===t){p[e]=[H,E,d];break}}else if(v&&(u=(t[U]||(t[U]={}))[e])&&u[0]===H)d=u[1];else for(;(c=++E&&c&&c[f]||(d=E=0)||h.pop())&&((a?c.nodeName.toLowerCase()!==g:1!==c.nodeType)||!++d||(v&&((c[U]||(c[U]={}))[e]=[H,d]),c!==t)););return d-=n,d===r||d%r===0&&d/r>=0}}},PSEUDO:function(e,i){var n,o=T.pseudos[e]||T.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);return o[U]?o(i):o.length>1?(n=[e,e,"",i],T.setFilters.hasOwnProperty(e.toLowerCase())?r(function(e,t){for(var r,n=o(e,i),s=n.length;s--;)r=tt.call(e,n[s]),e[r]=!(t[r]=n[s])}):function(e){return o(e,0,n)}):o}},pseudos:{not:r(function(e){var t=[],i=[],n=S(e.replace(lt,"$1"));return n[U]?r(function(e,t,i,r){for(var o,s=n(e,null,r,[]),a=e.length;a--;)(o=s[a])&&(e[a]=!(t[a]=o))}):function(e,r,o){return t[0]=e,n(t,null,o,i),!i.pop()}}),has:r(function(e){return function(i){return t(e,i).length>0}}),contains:r(function(e){return function(t){return(t.textContent||t.innerText||I(t)).indexOf(e)>-1}}),lang:r(function(e){return Et.test(e||"")||t.error("unsupported lang: "+e),e=e.replace(Lt,Tt).toLowerCase(),function(t){var i;do if(i=M?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return i=i.toLowerCase(),i===e||0===i.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var i=e.location&&e.location.hash;return i&&i.slice(1)===t.id},root:function(e){return e===_},focus:function(e){return e===D.activeElement&&(!D.hasFocus||D.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!T.pseudos.empty(e)},header:function(e){return mt.test(e.nodeName)},input:function(e){return ft.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:u(function(){return[0]}),last:u(function(e,t){return[t-1]}),eq:u(function(e,t,i){return[0>i?i+t:i]}),even:u(function(e,t){for(var i=0;t>i;i+=2)e.push(i);return e}),odd:u(function(e,t){for(var i=1;t>i;i+=2)e.push(i);return e}),lt:u(function(e,t,i){for(var r=0>i?i+t:i;--r>=0;)e.push(r);return e}),gt:u(function(e,t,i){for(var r=0>i?i+t:i;++r<t;)e.push(r);return e})}},T.pseudos.nth=T.pseudos.eq;for(N in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})T.pseudos[N]=a(N);for(N in{submit:!0,reset:!0})T.pseudos[N]=l(N);return c.prototype=T.filters=T.pseudos,T.setFilters=new c,A=t.tokenize=function(e,i){var r,n,o,s,a,l,u,p=W[e+" "];if(p)return i?0:p.slice(0);for(a=e,l=[],u=T.preFilter;a;){(!r||(n=ut.exec(a)))&&(n&&(a=a.slice(n[0].length)||a),l.push(o=[])),r=!1,(n=pt.exec(a))&&(r=n.shift(),o.push({value:r,type:n[0].replace(lt," ")}),a=a.slice(r.length));for(s in T.filter)!(n=ht[s].exec(a))||u[s]&&!(n=u[s](n))||(r=n.shift(),o.push({value:r,type:s,matches:n}),a=a.slice(r.length));if(!r)break}return i?a.length:a?t.error(e):W(e,l).slice(0)},S=t.compile=function(e,t){var i,r=[],n=[],o=q[e+" "];if(!o){for(t||(t=A(e)),i=t.length;i--;)o=v(t[i]),o[U]?r.push(o):n.push(o);o=q(e,x(n,r)),o.selector=e}return o},C=t.select=function(e,t,i,r){var n,o,s,a,l,u="function"==typeof e&&e,c=!r&&A(e=u.selector||e);if(i=i||[],1===c.length){if(o=c[0]=c[0].slice(0),o.length>2&&"ID"===(s=o[0]).type&&L.getById&&9===t.nodeType&&M&&T.relative[o[1].type]){if(t=(T.find.ID(s.matches[0].replace(Lt,Tt),t)||[])[0],!t)return i;u&&(t=t.parentNode),e=e.slice(o.shift().value.length)}for(n=ht.needsContext.test(e)?0:o.length;n--&&(s=o[n],!T.relative[a=s.type]);)if((l=T.find[a])&&(r=l(s.matches[0].replace(Lt,Tt),xt.test(o[0].type)&&p(t.parentNode)||t))){if(o.splice(n,1),e=r.length&&d(o),!e)return J.apply(i,r),i;break}}return(u||S(e,c))(r,t,!M,i,xt.test(e)&&p(t.parentNode)||t),i},L.sortStable=U.split("").sort(z).join("")===U,L.detectDuplicates=!!O,P(),L.sortDetached=n(function(e){return 1&e.compareDocumentPosition(D.createElement("div"))}),n(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||o("type|href|height|width",function(e,t,i){return i?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),L.attributes&&n(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||o("value",function(e,t,i){return i||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue}),n(function(e){return null==e.getAttribute("disabled")})||o(it,function(e,t,i){var r;return i?void 0:e[t]===!0?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),t}(t);ot.find=pt,ot.expr=pt.selectors,ot.expr[":"]=ot.expr.pseudos,ot.unique=pt.uniqueSort,ot.text=pt.getText,ot.isXMLDoc=pt.isXML,ot.contains=pt.contains;var ct=ot.expr.match.needsContext,dt=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,Et=/^.[^:#\[\.,]*$/;ot.filter=function(e,t,i){var r=t[0];return i&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?ot.find.matchesSelector(r,e)?[r]:[]:ot.find.matches(e,ot.grep(t,function(e){return 1===e.nodeType}))},ot.fn.extend({find:function(e){var t,i=[],r=this,n=r.length;if("string"!=typeof e)return this.pushStack(ot(e).filter(function(){for(t=0;n>t;t++)if(ot.contains(r[t],this))return!0}));for(t=0;n>t;t++)ot.find(e,r[t],i);return i=this.pushStack(n>1?ot.unique(i):i),i.selector=this.selector?this.selector+" "+e:e,i},filter:function(e){return this.pushStack(n(this,e||[],!1))},not:function(e){return this.pushStack(n(this,e||[],!0))},is:function(e){return!!n(this,"string"==typeof e&&ct.test(e)?ot(e):e||[],!1).length}});var ht,ft=t.document,mt=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,gt=ot.fn.init=function(e,t){var i,r;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:mt.exec(e),!i||!i[1]&&t)return!t||t.jquery?(t||ht).find(e):this.constructor(t).find(e);if(i[1]){if(t=t instanceof ot?t[0]:t,ot.merge(this,ot.parseHTML(i[1],t&&t.nodeType?t.ownerDocument||t:ft,!0)),dt.test(i[1])&&ot.isPlainObject(t))for(i in t)ot.isFunction(this[i])?this[i](t[i]):this.attr(i,t[i]);return this}if(r=ft.getElementById(i[2]),r&&r.parentNode){if(r.id!==i[2])return ht.find(e);this.length=1,this[0]=r}return this.context=ft,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):ot.isFunction(e)?"undefined"!=typeof ht.ready?ht.ready(e):e(ot):(void 0!==e.selector&&(this.selector=e.selector,this.context=e.context),ot.makeArray(e,this))};gt.prototype=ot.fn,ht=ot(ft);var vt=/^(?:parents|prev(?:Until|All))/,xt={children:!0,contents:!0,next:!0,prev:!0};ot.extend({dir:function(e,t,i){for(var r=[],n=e[t];n&&9!==n.nodeType&&(void 0===i||1!==n.nodeType||!ot(n).is(i));)1===n.nodeType&&r.push(n),n=n[t];return r},sibling:function(e,t){for(var i=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&i.push(e);return i}}),ot.fn.extend({has:function(e){var t,i=ot(e,this),r=i.length;return this.filter(function(){for(t=0;r>t;t++)if(ot.contains(this,i[t]))return!0})},closest:function(e,t){for(var i,r=0,n=this.length,o=[],s=ct.test(e)||"string"!=typeof e?ot(e,t||this.context):0;n>r;r++)for(i=this[r];i&&i!==t;i=i.parentNode)if(i.nodeType<11&&(s?s.index(i)>-1:1===i.nodeType&&ot.find.matchesSelector(i,e))){o.push(i);break}return this.pushStack(o.length>1?ot.unique(o):o)},index:function(e){return e?"string"==typeof e?ot.inArray(this[0],ot(e)):ot.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(ot.unique(ot.merge(this.get(),ot(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),ot.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return ot.dir(e,"parentNode")},parentsUntil:function(e,t,i){return ot.dir(e,"parentNode",i)},next:function(e){return o(e,"nextSibling")},prev:function(e){return o(e,"previousSibling")},nextAll:function(e){return ot.dir(e,"nextSibling")},prevAll:function(e){return ot.dir(e,"previousSibling")},nextUntil:function(e,t,i){return ot.dir(e,"nextSibling",i)},prevUntil:function(e,t,i){return ot.dir(e,"previousSibling",i)},siblings:function(e){return ot.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return ot.sibling(e.firstChild)},contents:function(e){return ot.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:ot.merge([],e.childNodes)}},function(e,t){ot.fn[e]=function(i,r){var n=ot.map(this,t,i);return"Until"!==e.slice(-5)&&(r=i),r&&"string"==typeof r&&(n=ot.filter(r,n)),this.length>1&&(xt[e]||(n=ot.unique(n)),vt.test(e)&&(n=n.reverse())),this.pushStack(n)}});var Nt=/\S+/g,Lt={};ot.Callbacks=function(e){e="string"==typeof e?Lt[e]||s(e):ot.extend({},e);var t,i,r,n,o,a,l=[],u=!e.once&&[],p=function(s){for(i=e.memory&&s,r=!0,o=a||0,a=0,n=l.length,t=!0;l&&n>o;o++)if(l[o].apply(s[0],s[1])===!1&&e.stopOnFalse){i=!1;break}t=!1,l&&(u?u.length&&p(u.shift()):i?l=[]:c.disable())},c={add:function(){if(l){var r=l.length;!function o(t){ot.each(t,function(t,i){var r=ot.type(i);"function"===r?e.unique&&c.has(i)||l.push(i):i&&i.length&&"string"!==r&&o(i)})}(arguments),t?n=l.length:i&&(a=r,p(i))}return this},remove:function(){return l&&ot.each(arguments,function(e,i){for(var r;(r=ot.inArray(i,l,r))>-1;)l.splice(r,1),t&&(n>=r&&n--,o>=r&&o--)}),this},has:function(e){return e?ot.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],n=0,this},disable:function(){return l=u=i=void 0,this},disabled:function(){return!l},lock:function(){return u=void 0,i||c.disable(),this},locked:function(){return!u},fireWith:function(e,i){return!l||r&&!u||(i=i||[],i=[e,i.slice?i.slice():i],t?u.push(i):p(i)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},ot.extend({Deferred:function(e){var t=[["resolve","done",ot.Callbacks("once memory"),"resolved"],["reject","fail",ot.Callbacks("once memory"),"rejected"],["notify","progress",ot.Callbacks("memory")]],i="pending",r={state:function(){return i},always:function(){return n.done(arguments).fail(arguments),this},then:function(){var e=arguments;return ot.Deferred(function(i){ot.each(t,function(t,o){var s=ot.isFunction(e[t])&&e[t];n[o[1]](function(){var e=s&&s.apply(this,arguments);e&&ot.isFunction(e.promise)?e.promise().done(i.resolve).fail(i.reject).progress(i.notify):i[o[0]+"With"](this===r?i.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?ot.extend(e,r):r}},n={};return r.pipe=r.then,ot.each(t,function(e,o){var s=o[2],a=o[3];r[o[1]]=s.add,a&&s.add(function(){i=a},t[1^e][2].disable,t[2][2].lock),n[o[0]]=function(){return n[o[0]+"With"](this===n?r:this,arguments),this},n[o[0]+"With"]=s.fireWith}),r.promise(n),e&&e.call(n,n),n},when:function(e){var t,i,r,n=0,o=$.call(arguments),s=o.length,a=1!==s||e&&ot.isFunction(e.promise)?s:0,l=1===a?e:ot.Deferred(),u=function(e,i,r){return function(n){i[e]=this,r[e]=arguments.length>1?$.call(arguments):n,r===t?l.notifyWith(i,r):--a||l.resolveWith(i,r)}};if(s>1)for(t=new Array(s),i=new Array(s),r=new Array(s);s>n;n++)o[n]&&ot.isFunction(o[n].promise)?o[n].promise().done(u(n,r,o)).fail(l.reject).progress(u(n,i,t)):--a;return a||l.resolveWith(r,o),l.promise()}});var Tt;ot.fn.ready=function(e){return ot.ready.promise().done(e),this},ot.extend({isReady:!1,readyWait:1,holdReady:function(e){e?ot.readyWait++:ot.ready(!0)},ready:function(e){if(e===!0?!--ot.readyWait:!ot.isReady){if(!ft.body)return setTimeout(ot.ready);ot.isReady=!0,e!==!0&&--ot.readyWait>0||(Tt.resolveWith(ft,[ot]),ot.fn.triggerHandler&&(ot(ft).triggerHandler("ready"),ot(ft).off("ready")))}}}),ot.ready.promise=function(e){if(!Tt)if(Tt=ot.Deferred(),"complete"===ft.readyState)setTimeout(ot.ready);else if(ft.addEventListener)ft.addEventListener("DOMContentLoaded",l,!1),t.addEventListener("load",l,!1);else{ft.attachEvent("onreadystatechange",l),t.attachEvent("onload",l);var i=!1;try{i=null==t.frameElement&&ft.documentElement}catch(r){}i&&i.doScroll&&!function n(){if(!ot.isReady){try{i.doScroll("left")}catch(e){return setTimeout(n,50)}a(),ot.ready()}}()}return Tt.promise(e)};var It,yt="undefined";for(It in ot(rt))break;rt.ownLast="0"!==It,rt.inlineBlockNeedsLayout=!1,ot(function(){var e,t,i,r;i=ft.getElementsByTagName("body")[0],i&&i.style&&(t=ft.createElement("div"),r=ft.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",i.appendChild(r).appendChild(t),typeof t.style.zoom!==yt&&(t.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",rt.inlineBlockNeedsLayout=e=3===t.offsetWidth,e&&(i.style.zoom=1)),i.removeChild(r))}),function(){var e=ft.createElement("div");if(null==rt.deleteExpando){rt.deleteExpando=!0;try{delete e.test}catch(t){rt.deleteExpando=!1}}e=null}(),ot.acceptData=function(e){var t=ot.noData[(e.nodeName+" ").toLowerCase()],i=+e.nodeType||1;return 1!==i&&9!==i?!1:!t||t!==!0&&e.getAttribute("classid")===t};var At=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,St=/([A-Z])/g;ot.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?ot.cache[e[ot.expando]]:e[ot.expando],!!e&&!p(e)},data:function(e,t,i){return c(e,t,i)},removeData:function(e,t){return d(e,t)},_data:function(e,t,i){return c(e,t,i,!0)},_removeData:function(e,t){return d(e,t,!0)}}),ot.fn.extend({data:function(e,t){var i,r,n,o=this[0],s=o&&o.attributes;if(void 0===e){if(this.length&&(n=ot.data(o),1===o.nodeType&&!ot._data(o,"parsedAttrs"))){for(i=s.length;i--;)s[i]&&(r=s[i].name,0===r.indexOf("data-")&&(r=ot.camelCase(r.slice(5)),u(o,r,n[r])));ot._data(o,"parsedAttrs",!0)}return n}return"object"==typeof e?this.each(function(){ot.data(this,e)}):arguments.length>1?this.each(function(){ot.data(this,e,t)}):o?u(o,e,ot.data(o,e)):void 0},removeData:function(e){return this.each(function(){ot.removeData(this,e)})}}),ot.extend({queue:function(e,t,i){var r;return e?(t=(t||"fx")+"queue",r=ot._data(e,t),i&&(!r||ot.isArray(i)?r=ot._data(e,t,ot.makeArray(i)):r.push(i)),r||[]):void 0},dequeue:function(e,t){t=t||"fx";var i=ot.queue(e,t),r=i.length,n=i.shift(),o=ot._queueHooks(e,t),s=function(){ot.dequeue(e,t)};"inprogress"===n&&(n=i.shift(),r--),n&&("fx"===t&&i.unshift("inprogress"),delete o.stop,n.call(e,s,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var i=t+"queueHooks";return ot._data(e,i)||ot._data(e,i,{empty:ot.Callbacks("once memory").add(function(){ot._removeData(e,t+"queue"),ot._removeData(e,i)})})}}),ot.fn.extend({queue:function(e,t){var i=2;return"string"!=typeof e&&(t=e,e="fx",i--),arguments.length<i?ot.queue(this[0],e):void 0===t?this:this.each(function(){var i=ot.queue(this,e,t);ot._queueHooks(this,e),"fx"===e&&"inprogress"!==i[0]&&ot.dequeue(this,e)})},dequeue:function(e){return this.each(function(){ot.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var i,r=1,n=ot.Deferred(),o=this,s=this.length,a=function(){--r||n.resolveWith(o,[o])};for("string"!=typeof e&&(t=e,e=void 0),e=e||"fx";s--;)i=ot._data(o[s],e+"queueHooks"),i&&i.empty&&(r++,i.empty.add(a));return a(),n.promise(t)}});var Ct=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,Rt=["Top","Right","Bottom","Left"],bt=function(e,t){return e=t||e,"none"===ot.css(e,"display")||!ot.contains(e.ownerDocument,e)},Ot=ot.access=function(e,t,i,r,n,o,s){var a=0,l=e.length,u=null==i;if("object"===ot.type(i)){n=!0;for(a in i)ot.access(e,t,a,i[a],!0,o,s)}else if(void 0!==r&&(n=!0,ot.isFunction(r)||(s=!0),u&&(s?(t.call(e,r),t=null):(u=t,t=function(e,t,i){return u.call(ot(e),i)})),t))for(;l>a;a++)t(e[a],i,s?r:r.call(e[a],a,t(e[a],i)));return n?e:u?t.call(e):l?t(e[0],i):o},Pt=/^(?:checkbox|radio)$/i;!function(){var e=ft.createElement("input"),t=ft.createElement("div"),i=ft.createDocumentFragment();if(t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",rt.leadingWhitespace=3===t.firstChild.nodeType,rt.tbody=!t.getElementsByTagName("tbody").length,rt.htmlSerialize=!!t.getElementsByTagName("link").length,rt.html5Clone="<:nav></:nav>"!==ft.createElement("nav").cloneNode(!0).outerHTML,e.type="checkbox",e.checked=!0,i.appendChild(e),rt.appendChecked=e.checked,t.innerHTML="<textarea>x</textarea>",rt.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue,i.appendChild(t),t.innerHTML="<input type='radio' checked='checked' name='t'/>",rt.checkClone=t.cloneNode(!0).cloneNode(!0).lastChild.checked,rt.noCloneEvent=!0,t.attachEvent&&(t.attachEvent("onclick",function(){rt.noCloneEvent=!1}),t.cloneNode(!0).click()),null==rt.deleteExpando){rt.deleteExpando=!0;try{delete t.test}catch(r){rt.deleteExpando=!1}}}(),function(){var e,i,r=ft.createElement("div");for(e in{submit:!0,change:!0,focusin:!0})i="on"+e,(rt[e+"Bubbles"]=i in t)||(r.setAttribute(i,"t"),rt[e+"Bubbles"]=r.attributes[i].expando===!1);r=null}();var Dt=/^(?:input|select|textarea)$/i,_t=/^key/,Mt=/^(?:mouse|pointer|contextmenu)|click/,wt=/^(?:focusinfocus|focusoutblur)$/,Gt=/^([^.]*)(?:\.(.+)|)$/;ot.event={global:{},add:function(e,t,i,r,n){var o,s,a,l,u,p,c,d,E,h,f,m=ot._data(e);if(m){for(i.handler&&(l=i,i=l.handler,n=l.selector),i.guid||(i.guid=ot.guid++),(s=m.events)||(s=m.events={}),(p=m.handle)||(p=m.handle=function(e){return typeof ot===yt||e&&ot.event.triggered===e.type?void 0:ot.event.dispatch.apply(p.elem,arguments)},p.elem=e),t=(t||"").match(Nt)||[""],a=t.length;a--;)o=Gt.exec(t[a])||[],E=f=o[1],h=(o[2]||"").split(".").sort(),E&&(u=ot.event.special[E]||{},E=(n?u.delegateType:u.bindType)||E,u=ot.event.special[E]||{},c=ot.extend({type:E,origType:f,data:r,handler:i,guid:i.guid,selector:n,needsContext:n&&ot.expr.match.needsContext.test(n),namespace:h.join(".")},l),(d=s[E])||(d=s[E]=[],d.delegateCount=0,u.setup&&u.setup.call(e,r,h,p)!==!1||(e.addEventListener?e.addEventListener(E,p,!1):e.attachEvent&&e.attachEvent("on"+E,p))),u.add&&(u.add.call(e,c),c.handler.guid||(c.handler.guid=i.guid)),n?d.splice(d.delegateCount++,0,c):d.push(c),ot.event.global[E]=!0); e=null}},remove:function(e,t,i,r,n){var o,s,a,l,u,p,c,d,E,h,f,m=ot.hasData(e)&&ot._data(e);if(m&&(p=m.events)){for(t=(t||"").match(Nt)||[""],u=t.length;u--;)if(a=Gt.exec(t[u])||[],E=f=a[1],h=(a[2]||"").split(".").sort(),E){for(c=ot.event.special[E]||{},E=(r?c.delegateType:c.bindType)||E,d=p[E]||[],a=a[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=d.length;o--;)s=d[o],!n&&f!==s.origType||i&&i.guid!==s.guid||a&&!a.test(s.namespace)||r&&r!==s.selector&&("**"!==r||!s.selector)||(d.splice(o,1),s.selector&&d.delegateCount--,c.remove&&c.remove.call(e,s));l&&!d.length&&(c.teardown&&c.teardown.call(e,h,m.handle)!==!1||ot.removeEvent(e,E,m.handle),delete p[E])}else for(E in p)ot.event.remove(e,E+t[u],i,r,!0);ot.isEmptyObject(p)&&(delete m.handle,ot._removeData(e,"events"))}},trigger:function(e,i,r,n){var o,s,a,l,u,p,c,d=[r||ft],E=it.call(e,"type")?e.type:e,h=it.call(e,"namespace")?e.namespace.split("."):[];if(a=p=r=r||ft,3!==r.nodeType&&8!==r.nodeType&&!wt.test(E+ot.event.triggered)&&(E.indexOf(".")>=0&&(h=E.split("."),E=h.shift(),h.sort()),s=E.indexOf(":")<0&&"on"+E,e=e[ot.expando]?e:new ot.Event(E,"object"==typeof e&&e),e.isTrigger=n?2:3,e.namespace=h.join("."),e.namespace_re=e.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,e.result=void 0,e.target||(e.target=r),i=null==i?[e]:ot.makeArray(i,[e]),u=ot.event.special[E]||{},n||!u.trigger||u.trigger.apply(r,i)!==!1)){if(!n&&!u.noBubble&&!ot.isWindow(r)){for(l=u.delegateType||E,wt.test(l+E)||(a=a.parentNode);a;a=a.parentNode)d.push(a),p=a;p===(r.ownerDocument||ft)&&d.push(p.defaultView||p.parentWindow||t)}for(c=0;(a=d[c++])&&!e.isPropagationStopped();)e.type=c>1?l:u.bindType||E,o=(ot._data(a,"events")||{})[e.type]&&ot._data(a,"handle"),o&&o.apply(a,i),o=s&&a[s],o&&o.apply&&ot.acceptData(a)&&(e.result=o.apply(a,i),e.result===!1&&e.preventDefault());if(e.type=E,!n&&!e.isDefaultPrevented()&&(!u._default||u._default.apply(d.pop(),i)===!1)&&ot.acceptData(r)&&s&&r[E]&&!ot.isWindow(r)){p=r[s],p&&(r[s]=null),ot.event.triggered=E;try{r[E]()}catch(f){}ot.event.triggered=void 0,p&&(r[s]=p)}return e.result}},dispatch:function(e){e=ot.event.fix(e);var t,i,r,n,o,s=[],a=$.call(arguments),l=(ot._data(this,"events")||{})[e.type]||[],u=ot.event.special[e.type]||{};if(a[0]=e,e.delegateTarget=this,!u.preDispatch||u.preDispatch.call(this,e)!==!1){for(s=ot.event.handlers.call(this,e,l),t=0;(n=s[t++])&&!e.isPropagationStopped();)for(e.currentTarget=n.elem,o=0;(r=n.handlers[o++])&&!e.isImmediatePropagationStopped();)(!e.namespace_re||e.namespace_re.test(r.namespace))&&(e.handleObj=r,e.data=r.data,i=((ot.event.special[r.origType]||{}).handle||r.handler).apply(n.elem,a),void 0!==i&&(e.result=i)===!1&&(e.preventDefault(),e.stopPropagation()));return u.postDispatch&&u.postDispatch.call(this,e),e.result}},handlers:function(e,t){var i,r,n,o,s=[],a=t.delegateCount,l=e.target;if(a&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(n=[],o=0;a>o;o++)r=t[o],i=r.selector+" ",void 0===n[i]&&(n[i]=r.needsContext?ot(i,this).index(l)>=0:ot.find(i,this,null,[l]).length),n[i]&&n.push(r);n.length&&s.push({elem:l,handlers:n})}return a<t.length&&s.push({elem:this,handlers:t.slice(a)}),s},fix:function(e){if(e[ot.expando])return e;var t,i,r,n=e.type,o=e,s=this.fixHooks[n];for(s||(this.fixHooks[n]=s=Mt.test(n)?this.mouseHooks:_t.test(n)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new ot.Event(o),t=r.length;t--;)i=r[t],e[i]=o[i];return e.target||(e.target=o.srcElement||ft),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var i,r,n,o=t.button,s=t.fromElement;return null==e.pageX&&null!=t.clientX&&(r=e.target.ownerDocument||ft,n=r.documentElement,i=r.body,e.pageX=t.clientX+(n&&n.scrollLeft||i&&i.scrollLeft||0)-(n&&n.clientLeft||i&&i.clientLeft||0),e.pageY=t.clientY+(n&&n.scrollTop||i&&i.scrollTop||0)-(n&&n.clientTop||i&&i.clientTop||0)),!e.relatedTarget&&s&&(e.relatedTarget=s===e.target?t.toElement:s),e.which||void 0===o||(e.which=1&o?1:2&o?3:4&o?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==f()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===f()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return ot.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(e){return ot.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,i,r){var n=ot.extend(new ot.Event,i,{type:e,isSimulated:!0,originalEvent:{}});r?ot.event.trigger(n,null,t):ot.event.dispatch.call(t,n),n.isDefaultPrevented()&&i.preventDefault()}},ot.removeEvent=ft.removeEventListener?function(e,t,i){e.removeEventListener&&e.removeEventListener(t,i,!1)}:function(e,t,i){var r="on"+t;e.detachEvent&&(typeof e[r]===yt&&(e[r]=null),e.detachEvent(r,i))},ot.Event=function(e,t){return this instanceof ot.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&e.returnValue===!1?E:h):this.type=e,t&&ot.extend(this,t),this.timeStamp=e&&e.timeStamp||ot.now(),void(this[ot.expando]=!0)):new ot.Event(e,t)},ot.Event.prototype={isDefaultPrevented:h,isPropagationStopped:h,isImmediatePropagationStopped:h,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=E,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=E,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=E,e&&e.stopImmediatePropagation&&e.stopImmediatePropagation(),this.stopPropagation()}},ot.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){ot.event.special[e]={delegateType:t,bindType:t,handle:function(e){var i,r=this,n=e.relatedTarget,o=e.handleObj;return(!n||n!==r&&!ot.contains(r,n))&&(e.type=o.origType,i=o.handler.apply(this,arguments),e.type=t),i}}}),rt.submitBubbles||(ot.event.special.submit={setup:function(){return ot.nodeName(this,"form")?!1:void ot.event.add(this,"click._submit keypress._submit",function(e){var t=e.target,i=ot.nodeName(t,"input")||ot.nodeName(t,"button")?t.form:void 0;i&&!ot._data(i,"submitBubbles")&&(ot.event.add(i,"submit._submit",function(e){e._submit_bubble=!0}),ot._data(i,"submitBubbles",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&ot.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return ot.nodeName(this,"form")?!1:void ot.event.remove(this,"._submit")}}),rt.changeBubbles||(ot.event.special.change={setup:function(){return Dt.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(ot.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),ot.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),ot.event.simulate("change",this,e,!0)})),!1):void ot.event.add(this,"beforeactivate._change",function(e){var t=e.target;Dt.test(t.nodeName)&&!ot._data(t,"changeBubbles")&&(ot.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||ot.event.simulate("change",this.parentNode,e,!0)}),ot._data(t,"changeBubbles",!0))})},handle:function(e){var t=e.target;return this!==t||e.isSimulated||e.isTrigger||"radio"!==t.type&&"checkbox"!==t.type?e.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return ot.event.remove(this,"._change"),!Dt.test(this.nodeName)}}),rt.focusinBubbles||ot.each({focus:"focusin",blur:"focusout"},function(e,t){var i=function(e){ot.event.simulate(t,e.target,ot.event.fix(e),!0)};ot.event.special[t]={setup:function(){var r=this.ownerDocument||this,n=ot._data(r,t);n||r.addEventListener(e,i,!0),ot._data(r,t,(n||0)+1)},teardown:function(){var r=this.ownerDocument||this,n=ot._data(r,t)-1;n?ot._data(r,t,n):(r.removeEventListener(e,i,!0),ot._removeData(r,t))}}}),ot.fn.extend({on:function(e,t,i,r,n){var o,s;if("object"==typeof e){"string"!=typeof t&&(i=i||t,t=void 0);for(o in e)this.on(o,t,i,e[o],n);return this}if(null==i&&null==r?(r=t,i=t=void 0):null==r&&("string"==typeof t?(r=i,i=void 0):(r=i,i=t,t=void 0)),r===!1)r=h;else if(!r)return this;return 1===n&&(s=r,r=function(e){return ot().off(e),s.apply(this,arguments)},r.guid=s.guid||(s.guid=ot.guid++)),this.each(function(){ot.event.add(this,e,r,i,t)})},one:function(e,t,i,r){return this.on(e,t,i,r,1)},off:function(e,t,i){var r,n;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,ot(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(n in e)this.off(n,t,e[n]);return this}return(t===!1||"function"==typeof t)&&(i=t,t=void 0),i===!1&&(i=h),this.each(function(){ot.event.remove(this,e,i,t)})},trigger:function(e,t){return this.each(function(){ot.event.trigger(e,t,this)})},triggerHandler:function(e,t){var i=this[0];return i?ot.event.trigger(e,t,i,!0):void 0}});var kt="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Bt=/ jQuery\d+="(?:null|\d+)"/g,Ut=new RegExp("<(?:"+kt+")[\\s/>]","i"),Vt=/^\s+/,Ht=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Ft=/<([\w:]+)/,jt=/<tbody/i,Wt=/<|&#?\w+;/,qt=/<(?:script|style|link)/i,zt=/checked\s*(?:[^=]|=\s*.checked.)/i,Xt=/^$|\/(?:java|ecma)script/i,Yt=/^true\/(.*)/,Kt=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,$t={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:rt.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},Qt=m(ft),Zt=Qt.appendChild(ft.createElement("div"));$t.optgroup=$t.option,$t.tbody=$t.tfoot=$t.colgroup=$t.caption=$t.thead,$t.th=$t.td,ot.extend({clone:function(e,t,i){var r,n,o,s,a,l=ot.contains(e.ownerDocument,e);if(rt.html5Clone||ot.isXMLDoc(e)||!Ut.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Zt.innerHTML=e.outerHTML,Zt.removeChild(o=Zt.firstChild)),!(rt.noCloneEvent&&rt.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||ot.isXMLDoc(e)))for(r=g(o),a=g(e),s=0;null!=(n=a[s]);++s)r[s]&&y(n,r[s]);if(t)if(i)for(a=a||g(e),r=r||g(o),s=0;null!=(n=a[s]);s++)I(n,r[s]);else I(e,o);return r=g(o,"script"),r.length>0&&T(r,!l&&g(e,"script")),r=a=n=null,o},buildFragment:function(e,t,i,r){for(var n,o,s,a,l,u,p,c=e.length,d=m(t),E=[],h=0;c>h;h++)if(o=e[h],o||0===o)if("object"===ot.type(o))ot.merge(E,o.nodeType?[o]:o);else if(Wt.test(o)){for(a=a||d.appendChild(t.createElement("div")),l=(Ft.exec(o)||["",""])[1].toLowerCase(),p=$t[l]||$t._default,a.innerHTML=p[1]+o.replace(Ht,"<$1></$2>")+p[2],n=p[0];n--;)a=a.lastChild;if(!rt.leadingWhitespace&&Vt.test(o)&&E.push(t.createTextNode(Vt.exec(o)[0])),!rt.tbody)for(o="table"!==l||jt.test(o)?"<table>"!==p[1]||jt.test(o)?0:a:a.firstChild,n=o&&o.childNodes.length;n--;)ot.nodeName(u=o.childNodes[n],"tbody")&&!u.childNodes.length&&o.removeChild(u);for(ot.merge(E,a.childNodes),a.textContent="";a.firstChild;)a.removeChild(a.firstChild);a=d.lastChild}else E.push(t.createTextNode(o));for(a&&d.removeChild(a),rt.appendChecked||ot.grep(g(E,"input"),v),h=0;o=E[h++];)if((!r||-1===ot.inArray(o,r))&&(s=ot.contains(o.ownerDocument,o),a=g(d.appendChild(o),"script"),s&&T(a),i))for(n=0;o=a[n++];)Xt.test(o.type||"")&&i.push(o);return a=null,d},cleanData:function(e,t){for(var i,r,n,o,s=0,a=ot.expando,l=ot.cache,u=rt.deleteExpando,p=ot.event.special;null!=(i=e[s]);s++)if((t||ot.acceptData(i))&&(n=i[a],o=n&&l[n])){if(o.events)for(r in o.events)p[r]?ot.event.remove(i,r):ot.removeEvent(i,r,o.handle);l[n]&&(delete l[n],u?delete i[a]:typeof i.removeAttribute!==yt?i.removeAttribute(a):i[a]=null,K.push(n))}}}),ot.fn.extend({text:function(e){return Ot(this,function(e){return void 0===e?ot.text(this):this.empty().append((this[0]&&this[0].ownerDocument||ft).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=x(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=x(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){for(var i,r=e?ot.filter(e,this):this,n=0;null!=(i=r[n]);n++)t||1!==i.nodeType||ot.cleanData(g(i)),i.parentNode&&(t&&ot.contains(i.ownerDocument,i)&&T(g(i,"script")),i.parentNode.removeChild(i));return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){for(1===e.nodeType&&ot.cleanData(g(e,!1));e.firstChild;)e.removeChild(e.firstChild);e.options&&ot.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return ot.clone(this,e,t)})},html:function(e){return Ot(this,function(e){var t=this[0]||{},i=0,r=this.length;if(void 0===e)return 1===t.nodeType?t.innerHTML.replace(Bt,""):void 0;if(!("string"!=typeof e||qt.test(e)||!rt.htmlSerialize&&Ut.test(e)||!rt.leadingWhitespace&&Vt.test(e)||$t[(Ft.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(Ht,"<$1></$2>");try{for(;r>i;i++)t=this[i]||{},1===t.nodeType&&(ot.cleanData(g(t,!1)),t.innerHTML=e);t=0}catch(n){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=arguments[0];return this.domManip(arguments,function(t){e=this.parentNode,ot.cleanData(g(this)),e&&e.replaceChild(t,this)}),e&&(e.length||e.nodeType)?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t){e=Q.apply([],e);var i,r,n,o,s,a,l=0,u=this.length,p=this,c=u-1,d=e[0],E=ot.isFunction(d);if(E||u>1&&"string"==typeof d&&!rt.checkClone&&zt.test(d))return this.each(function(i){var r=p.eq(i);E&&(e[0]=d.call(this,i,r.html())),r.domManip(e,t)});if(u&&(a=ot.buildFragment(e,this[0].ownerDocument,!1,this),i=a.firstChild,1===a.childNodes.length&&(a=i),i)){for(o=ot.map(g(a,"script"),N),n=o.length;u>l;l++)r=a,l!==c&&(r=ot.clone(r,!0,!0),n&&ot.merge(o,g(r,"script"))),t.call(this[l],r,l);if(n)for(s=o[o.length-1].ownerDocument,ot.map(o,L),l=0;n>l;l++)r=o[l],Xt.test(r.type||"")&&!ot._data(r,"globalEval")&&ot.contains(s,r)&&(r.src?ot._evalUrl&&ot._evalUrl(r.src):ot.globalEval((r.text||r.textContent||r.innerHTML||"").replace(Kt,"")));a=i=null}return this}}),ot.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){ot.fn[e]=function(e){for(var i,r=0,n=[],o=ot(e),s=o.length-1;s>=r;r++)i=r===s?this:this.clone(!0),ot(o[r])[t](i),Z.apply(n,i.get());return this.pushStack(n)}});var Jt,ei={};!function(){var e;rt.shrinkWrapBlocks=function(){if(null!=e)return e;e=!1;var t,i,r;return i=ft.getElementsByTagName("body")[0],i&&i.style?(t=ft.createElement("div"),r=ft.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",i.appendChild(r).appendChild(t),typeof t.style.zoom!==yt&&(t.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",t.appendChild(ft.createElement("div")).style.width="5px",e=3!==t.offsetWidth),i.removeChild(r),e):void 0}}();var ti,ii,ri=/^margin/,ni=new RegExp("^("+Ct+")(?!px)[a-z%]+$","i"),oi=/^(top|right|bottom|left)$/;t.getComputedStyle?(ti=function(e){return e.ownerDocument.defaultView.getComputedStyle(e,null)},ii=function(e,t,i){var r,n,o,s,a=e.style;return i=i||ti(e),s=i?i.getPropertyValue(t)||i[t]:void 0,i&&(""!==s||ot.contains(e.ownerDocument,e)||(s=ot.style(e,t)),ni.test(s)&&ri.test(t)&&(r=a.width,n=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=s,s=i.width,a.width=r,a.minWidth=n,a.maxWidth=o)),void 0===s?s:s+""}):ft.documentElement.currentStyle&&(ti=function(e){return e.currentStyle},ii=function(e,t,i){var r,n,o,s,a=e.style;return i=i||ti(e),s=i?i[t]:void 0,null==s&&a&&a[t]&&(s=a[t]),ni.test(s)&&!oi.test(t)&&(r=a.left,n=e.runtimeStyle,o=n&&n.left,o&&(n.left=e.currentStyle.left),a.left="fontSize"===t?"1em":s,s=a.pixelLeft+"px",a.left=r,o&&(n.left=o)),void 0===s?s:s+""||"auto"}),function(){function e(){var e,i,r,n;i=ft.getElementsByTagName("body")[0],i&&i.style&&(e=ft.createElement("div"),r=ft.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",i.appendChild(r).appendChild(e),e.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",o=s=!1,l=!0,t.getComputedStyle&&(o="1%"!==(t.getComputedStyle(e,null)||{}).top,s="4px"===(t.getComputedStyle(e,null)||{width:"4px"}).width,n=e.appendChild(ft.createElement("div")),n.style.cssText=e.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",n.style.marginRight=n.style.width="0",e.style.width="1px",l=!parseFloat((t.getComputedStyle(n,null)||{}).marginRight)),e.innerHTML="<table><tr><td></td><td>t</td></tr></table>",n=e.getElementsByTagName("td"),n[0].style.cssText="margin:0;border:0;padding:0;display:none",a=0===n[0].offsetHeight,a&&(n[0].style.display="",n[1].style.display="none",a=0===n[0].offsetHeight),i.removeChild(r))}var i,r,n,o,s,a,l;i=ft.createElement("div"),i.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=i.getElementsByTagName("a")[0],r=n&&n.style,r&&(r.cssText="float:left;opacity:.5",rt.opacity="0.5"===r.opacity,rt.cssFloat=!!r.cssFloat,i.style.backgroundClip="content-box",i.cloneNode(!0).style.backgroundClip="",rt.clearCloneStyle="content-box"===i.style.backgroundClip,rt.boxSizing=""===r.boxSizing||""===r.MozBoxSizing||""===r.WebkitBoxSizing,ot.extend(rt,{reliableHiddenOffsets:function(){return null==a&&e(),a},boxSizingReliable:function(){return null==s&&e(),s},pixelPosition:function(){return null==o&&e(),o},reliableMarginRight:function(){return null==l&&e(),l}}))}(),ot.swap=function(e,t,i,r){var n,o,s={};for(o in t)s[o]=e.style[o],e.style[o]=t[o];n=i.apply(e,r||[]);for(o in t)e.style[o]=s[o];return n};var si=/alpha\([^)]*\)/i,ai=/opacity\s*=\s*([^)]*)/,li=/^(none|table(?!-c[ea]).+)/,ui=new RegExp("^("+Ct+")(.*)$","i"),pi=new RegExp("^([+-])=("+Ct+")","i"),ci={position:"absolute",visibility:"hidden",display:"block"},di={letterSpacing:"0",fontWeight:"400"},Ei=["Webkit","O","Moz","ms"];ot.extend({cssHooks:{opacity:{get:function(e,t){if(t){var i=ii(e,"opacity");return""===i?"1":i}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":rt.cssFloat?"cssFloat":"styleFloat"},style:function(e,t,i,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var n,o,s,a=ot.camelCase(t),l=e.style;if(t=ot.cssProps[a]||(ot.cssProps[a]=R(l,a)),s=ot.cssHooks[t]||ot.cssHooks[a],void 0===i)return s&&"get"in s&&void 0!==(n=s.get(e,!1,r))?n:l[t];if(o=typeof i,"string"===o&&(n=pi.exec(i))&&(i=(n[1]+1)*n[2]+parseFloat(ot.css(e,t)),o="number"),null!=i&&i===i&&("number"!==o||ot.cssNumber[a]||(i+="px"),rt.clearCloneStyle||""!==i||0!==t.indexOf("background")||(l[t]="inherit"),!(s&&"set"in s&&void 0===(i=s.set(e,i,r)))))try{l[t]=i}catch(u){}}},css:function(e,t,i,r){var n,o,s,a=ot.camelCase(t);return t=ot.cssProps[a]||(ot.cssProps[a]=R(e.style,a)),s=ot.cssHooks[t]||ot.cssHooks[a],s&&"get"in s&&(o=s.get(e,!0,i)),void 0===o&&(o=ii(e,t,r)),"normal"===o&&t in di&&(o=di[t]),""===i||i?(n=parseFloat(o),i===!0||ot.isNumeric(n)?n||0:o):o}}),ot.each(["height","width"],function(e,t){ot.cssHooks[t]={get:function(e,i,r){return i?li.test(ot.css(e,"display"))&&0===e.offsetWidth?ot.swap(e,ci,function(){return D(e,t,r)}):D(e,t,r):void 0},set:function(e,i,r){var n=r&&ti(e);return O(e,i,r?P(e,t,r,rt.boxSizing&&"border-box"===ot.css(e,"boxSizing",!1,n),n):0)}}}),rt.opacity||(ot.cssHooks.opacity={get:function(e,t){return ai.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var i=e.style,r=e.currentStyle,n=ot.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||i.filter||"";i.zoom=1,(t>=1||""===t)&&""===ot.trim(o.replace(si,""))&&i.removeAttribute&&(i.removeAttribute("filter"),""===t||r&&!r.filter)||(i.filter=si.test(o)?o.replace(si,n):o+" "+n)}}),ot.cssHooks.marginRight=C(rt.reliableMarginRight,function(e,t){return t?ot.swap(e,{display:"inline-block"},ii,[e,"marginRight"]):void 0}),ot.each({margin:"",padding:"",border:"Width"},function(e,t){ot.cssHooks[e+t]={expand:function(i){for(var r=0,n={},o="string"==typeof i?i.split(" "):[i];4>r;r++)n[e+Rt[r]+t]=o[r]||o[r-2]||o[0];return n}},ri.test(e)||(ot.cssHooks[e+t].set=O)}),ot.fn.extend({css:function(e,t){return Ot(this,function(e,t,i){var r,n,o={},s=0;if(ot.isArray(t)){for(r=ti(e),n=t.length;n>s;s++)o[t[s]]=ot.css(e,t[s],!1,r);return o}return void 0!==i?ot.style(e,t,i):ot.css(e,t)},e,t,arguments.length>1)},show:function(){return b(this,!0)},hide:function(){return b(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){bt(this)?ot(this).show():ot(this).hide()})}}),ot.Tween=_,_.prototype={constructor:_,init:function(e,t,i,r,n,o){this.elem=e,this.prop=i,this.easing=n||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(ot.cssNumber[i]?"":"px")},cur:function(){var e=_.propHooks[this.prop];return e&&e.get?e.get(this):_.propHooks._default.get(this)},run:function(e){var t,i=_.propHooks[this.prop];return this.pos=t=this.options.duration?ot.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),i&&i.set?i.set(this):_.propHooks._default.set(this),this}},_.prototype.init.prototype=_.prototype,_.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=ot.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){ot.fx.step[e.prop]?ot.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[ot.cssProps[e.prop]]||ot.cssHooks[e.prop])?ot.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},_.propHooks.scrollTop=_.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},ot.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},ot.fx=_.prototype.init,ot.fx.step={};var hi,fi,mi=/^(?:toggle|show|hide)$/,gi=new RegExp("^(?:([+-])=|)("+Ct+")([a-z%]*)$","i"),vi=/queueHooks$/,xi=[k],Ni={"*":[function(e,t){var i=this.createTween(e,t),r=i.cur(),n=gi.exec(t),o=n&&n[3]||(ot.cssNumber[e]?"":"px"),s=(ot.cssNumber[e]||"px"!==o&&+r)&&gi.exec(ot.css(i.elem,e)),a=1,l=20;if(s&&s[3]!==o){o=o||s[3],n=n||[],s=+r||1;do a=a||".5",s/=a,ot.style(i.elem,e,s+o);while(a!==(a=i.cur()/r)&&1!==a&&--l)}return n&&(s=i.start=+s||+r||0,i.unit=o,i.end=n[1]?s+(n[1]+1)*n[2]:+n[2]),i}]};ot.Animation=ot.extend(U,{tweener:function(e,t){ot.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");for(var i,r=0,n=e.length;n>r;r++)i=e[r],Ni[i]=Ni[i]||[],Ni[i].unshift(t)},prefilter:function(e,t){t?xi.unshift(e):xi.push(e)}}),ot.speed=function(e,t,i){var r=e&&"object"==typeof e?ot.extend({},e):{complete:i||!i&&t||ot.isFunction(e)&&e,duration:e,easing:i&&t||t&&!ot.isFunction(t)&&t};return r.duration=ot.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in ot.fx.speeds?ot.fx.speeds[r.duration]:ot.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){ot.isFunction(r.old)&&r.old.call(this),r.queue&&ot.dequeue(this,r.queue)},r},ot.fn.extend({fadeTo:function(e,t,i,r){return this.filter(bt).css("opacity",0).show().end().animate({opacity:t},e,i,r)},animate:function(e,t,i,r){var n=ot.isEmptyObject(e),o=ot.speed(t,i,r),s=function(){var t=U(this,ot.extend({},e),o);(n||ot._data(this,"finish"))&&t.stop(!0)};return s.finish=s,n||o.queue===!1?this.each(s):this.queue(o.queue,s)},stop:function(e,t,i){var r=function(e){var t=e.stop;delete e.stop,t(i)};return"string"!=typeof e&&(i=t,t=e,e=void 0),t&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=ot.timers,s=ot._data(this);if(n)s[n]&&s[n].stop&&r(s[n]);else for(n in s)s[n]&&s[n].stop&&vi.test(n)&&r(s[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(i),t=!1,o.splice(n,1));(t||!i)&&ot.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,i=ot._data(this),r=i[e+"queue"],n=i[e+"queueHooks"],o=ot.timers,s=r?r.length:0;for(i.finish=!0,ot.queue(this,e,[]),n&&n.stop&&n.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;s>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete i.finish})}}),ot.each(["toggle","show","hide"],function(e,t){var i=ot.fn[t];ot.fn[t]=function(e,r,n){return null==e||"boolean"==typeof e?i.apply(this,arguments):this.animate(w(t,!0),e,r,n)}}),ot.each({slideDown:w("show"),slideUp:w("hide"),slideToggle:w("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){ot.fn[e]=function(e,i,r){return this.animate(t,e,i,r)}}),ot.timers=[],ot.fx.tick=function(){var e,t=ot.timers,i=0;for(hi=ot.now();i<t.length;i++)e=t[i],e()||t[i]!==e||t.splice(i--,1);t.length||ot.fx.stop(),hi=void 0},ot.fx.timer=function(e){ot.timers.push(e),e()?ot.fx.start():ot.timers.pop()},ot.fx.interval=13,ot.fx.start=function(){fi||(fi=setInterval(ot.fx.tick,ot.fx.interval))},ot.fx.stop=function(){clearInterval(fi),fi=null},ot.fx.speeds={slow:600,fast:200,_default:400},ot.fn.delay=function(e,t){return e=ot.fx?ot.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,i){var r=setTimeout(t,e);i.stop=function(){clearTimeout(r)}})},function(){var e,t,i,r,n;t=ft.createElement("div"),t.setAttribute("className","t"),t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",r=t.getElementsByTagName("a")[0],i=ft.createElement("select"),n=i.appendChild(ft.createElement("option")),e=t.getElementsByTagName("input")[0],r.style.cssText="top:1px",rt.getSetAttribute="t"!==t.className,rt.style=/top/.test(r.getAttribute("style")),rt.hrefNormalized="/a"===r.getAttribute("href"),rt.checkOn=!!e.value,rt.optSelected=n.selected,rt.enctype=!!ft.createElement("form").enctype,i.disabled=!0,rt.optDisabled=!n.disabled,e=ft.createElement("input"),e.setAttribute("value",""),rt.input=""===e.getAttribute("value"),e.value="t",e.setAttribute("type","radio"),rt.radioValue="t"===e.value}();var Li=/\r/g;ot.fn.extend({val:function(e){var t,i,r,n=this[0];{if(arguments.length)return r=ot.isFunction(e),this.each(function(i){var n;1===this.nodeType&&(n=r?e.call(this,i,ot(this).val()):e,null==n?n="":"number"==typeof n?n+="":ot.isArray(n)&&(n=ot.map(n,function(e){return null==e?"":e+""})),t=ot.valHooks[this.type]||ot.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&void 0!==t.set(this,n,"value")||(this.value=n))});if(n)return t=ot.valHooks[n.type]||ot.valHooks[n.nodeName.toLowerCase()],t&&"get"in t&&void 0!==(i=t.get(n,"value"))?i:(i=n.value,"string"==typeof i?i.replace(Li,""):null==i?"":i)}}}),ot.extend({valHooks:{option:{get:function(e){var t=ot.find.attr(e,"value");return null!=t?t:ot.trim(ot.text(e))}},select:{get:function(e){for(var t,i,r=e.options,n=e.selectedIndex,o="select-one"===e.type||0>n,s=o?null:[],a=o?n+1:r.length,l=0>n?a:o?n:0;a>l;l++)if(i=r[l],!(!i.selected&&l!==n||(rt.optDisabled?i.disabled:null!==i.getAttribute("disabled"))||i.parentNode.disabled&&ot.nodeName(i.parentNode,"optgroup"))){if(t=ot(i).val(),o)return t;s.push(t)}return s},set:function(e,t){for(var i,r,n=e.options,o=ot.makeArray(t),s=n.length;s--;)if(r=n[s],ot.inArray(ot.valHooks.option.get(r),o)>=0)try{r.selected=i=!0}catch(a){r.scrollHeight}else r.selected=!1;return i||(e.selectedIndex=-1),n}}}}),ot.each(["radio","checkbox"],function(){ot.valHooks[this]={set:function(e,t){return ot.isArray(t)?e.checked=ot.inArray(ot(e).val(),t)>=0:void 0}},rt.checkOn||(ot.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Ti,Ii,yi=ot.expr.attrHandle,Ai=/^(?:checked|selected)$/i,Si=rt.getSetAttribute,Ci=rt.input;ot.fn.extend({attr:function(e,t){return Ot(this,ot.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){ot.removeAttr(this,e)})}}),ot.extend({attr:function(e,t,i){var r,n,o=e.nodeType;if(e&&3!==o&&8!==o&&2!==o)return typeof e.getAttribute===yt?ot.prop(e,t,i):(1===o&&ot.isXMLDoc(e)||(t=t.toLowerCase(),r=ot.attrHooks[t]||(ot.expr.match.bool.test(t)?Ii:Ti)),void 0===i?r&&"get"in r&&null!==(n=r.get(e,t))?n:(n=ot.find.attr(e,t),null==n?void 0:n):null!==i?r&&"set"in r&&void 0!==(n=r.set(e,i,t))?n:(e.setAttribute(t,i+""),i):void ot.removeAttr(e,t))},removeAttr:function(e,t){var i,r,n=0,o=t&&t.match(Nt);if(o&&1===e.nodeType)for(;i=o[n++];)r=ot.propFix[i]||i,ot.expr.match.bool.test(i)?Ci&&Si||!Ai.test(i)?e[r]=!1:e[ot.camelCase("default-"+i)]=e[r]=!1:ot.attr(e,i,""),e.removeAttribute(Si?i:r)},attrHooks:{type:{set:function(e,t){if(!rt.radioValue&&"radio"===t&&ot.nodeName(e,"input")){var i=e.value;return e.setAttribute("type",t),i&&(e.value=i),t}}}}}),Ii={set:function(e,t,i){return t===!1?ot.removeAttr(e,i):Ci&&Si||!Ai.test(i)?e.setAttribute(!Si&&ot.propFix[i]||i,i):e[ot.camelCase("default-"+i)]=e[i]=!0,i}},ot.each(ot.expr.match.bool.source.match(/\w+/g),function(e,t){var i=yi[t]||ot.find.attr;yi[t]=Ci&&Si||!Ai.test(t)?function(e,t,r){var n,o;return r||(o=yi[t],yi[t]=n,n=null!=i(e,t,r)?t.toLowerCase():null,yi[t]=o),n}:function(e,t,i){return i?void 0:e[ot.camelCase("default-"+t)]?t.toLowerCase():null}}),Ci&&Si||(ot.attrHooks.value={set:function(e,t,i){return ot.nodeName(e,"input")?void(e.defaultValue=t):Ti&&Ti.set(e,t,i)}}),Si||(Ti={set:function(e,t,i){var r=e.getAttributeNode(i);return r||e.setAttributeNode(r=e.ownerDocument.createAttribute(i)),r.value=t+="","value"===i||t===e.getAttribute(i)?t:void 0}},yi.id=yi.name=yi.coords=function(e,t,i){var r;return i?void 0:(r=e.getAttributeNode(t))&&""!==r.value?r.value:null},ot.valHooks.button={get:function(e,t){var i=e.getAttributeNode(t);return i&&i.specified?i.value:void 0},set:Ti.set},ot.attrHooks.contenteditable={set:function(e,t,i){Ti.set(e,""===t?!1:t,i)}},ot.each(["width","height"],function(e,t){ot.attrHooks[t]={set:function(e,i){return""===i?(e.setAttribute(t,"auto"),i):void 0}}})),rt.style||(ot.attrHooks.style={get:function(e){return e.style.cssText||void 0},set:function(e,t){return e.style.cssText=t+""}});var Ri=/^(?:input|select|textarea|button|object)$/i,bi=/^(?:a|area)$/i;ot.fn.extend({prop:function(e,t){return Ot(this,ot.prop,e,t,arguments.length>1)},removeProp:function(e){return e=ot.propFix[e]||e,this.each(function(){try{this[e]=void 0,delete this[e] }catch(t){}})}}),ot.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,i){var r,n,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return o=1!==s||!ot.isXMLDoc(e),o&&(t=ot.propFix[t]||t,n=ot.propHooks[t]),void 0!==i?n&&"set"in n&&void 0!==(r=n.set(e,i,t))?r:e[t]=i:n&&"get"in n&&null!==(r=n.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=ot.find.attr(e,"tabindex");return t?parseInt(t,10):Ri.test(e.nodeName)||bi.test(e.nodeName)&&e.href?0:-1}}}}),rt.hrefNormalized||ot.each(["href","src"],function(e,t){ot.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),rt.optSelected||(ot.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),ot.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){ot.propFix[this.toLowerCase()]=this}),rt.enctype||(ot.propFix.enctype="encoding");var Oi=/[\t\r\n\f]/g;ot.fn.extend({addClass:function(e){var t,i,r,n,o,s,a=0,l=this.length,u="string"==typeof e&&e;if(ot.isFunction(e))return this.each(function(t){ot(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(Nt)||[];l>a;a++)if(i=this[a],r=1===i.nodeType&&(i.className?(" "+i.className+" ").replace(Oi," "):" ")){for(o=0;n=t[o++];)r.indexOf(" "+n+" ")<0&&(r+=n+" ");s=ot.trim(r),i.className!==s&&(i.className=s)}return this},removeClass:function(e){var t,i,r,n,o,s,a=0,l=this.length,u=0===arguments.length||"string"==typeof e&&e;if(ot.isFunction(e))return this.each(function(t){ot(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(Nt)||[];l>a;a++)if(i=this[a],r=1===i.nodeType&&(i.className?(" "+i.className+" ").replace(Oi," "):"")){for(o=0;n=t[o++];)for(;r.indexOf(" "+n+" ")>=0;)r=r.replace(" "+n+" "," ");s=e?ot.trim(r):"",i.className!==s&&(i.className=s)}return this},toggleClass:function(e,t){var i=typeof e;return"boolean"==typeof t&&"string"===i?t?this.addClass(e):this.removeClass(e):this.each(ot.isFunction(e)?function(i){ot(this).toggleClass(e.call(this,i,this.className,t),t)}:function(){if("string"===i)for(var t,r=0,n=ot(this),o=e.match(Nt)||[];t=o[r++];)n.hasClass(t)?n.removeClass(t):n.addClass(t);else(i===yt||"boolean"===i)&&(this.className&&ot._data(this,"__className__",this.className),this.className=this.className||e===!1?"":ot._data(this,"__className__")||"")})},hasClass:function(e){for(var t=" "+e+" ",i=0,r=this.length;r>i;i++)if(1===this[i].nodeType&&(" "+this[i].className+" ").replace(Oi," ").indexOf(t)>=0)return!0;return!1}}),ot.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){ot.fn[t]=function(e,i){return arguments.length>0?this.on(t,null,e,i):this.trigger(t)}}),ot.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,i){return this.on(e,null,t,i)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,i,r){return this.on(t,e,i,r)},undelegate:function(e,t,i){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",i)}});var Pi=ot.now(),Di=/\?/,_i=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;ot.parseJSON=function(e){if(t.JSON&&t.JSON.parse)return t.JSON.parse(e+"");var i,r=null,n=ot.trim(e+"");return n&&!ot.trim(n.replace(_i,function(e,t,n,o){return i&&t&&(r=0),0===r?e:(i=n||t,r+=!o-!n,"")}))?Function("return "+n)():ot.error("Invalid JSON: "+e)},ot.parseXML=function(e){var i,r;if(!e||"string"!=typeof e)return null;try{t.DOMParser?(r=new DOMParser,i=r.parseFromString(e,"text/xml")):(i=new ActiveXObject("Microsoft.XMLDOM"),i.async="false",i.loadXML(e))}catch(n){i=void 0}return i&&i.documentElement&&!i.getElementsByTagName("parsererror").length||ot.error("Invalid XML: "+e),i};var Mi,wi,Gi=/#.*$/,ki=/([?&])_=[^&]*/,Bi=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ui=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Vi=/^(?:GET|HEAD)$/,Hi=/^\/\//,Fi=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,ji={},Wi={},qi="*/".concat("*");try{wi=location.href}catch(zi){wi=ft.createElement("a"),wi.href="",wi=wi.href}Mi=Fi.exec(wi.toLowerCase())||[],ot.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:wi,type:"GET",isLocal:Ui.test(Mi[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":qi,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":ot.parseJSON,"text xml":ot.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?F(F(e,ot.ajaxSettings),t):F(ot.ajaxSettings,e)},ajaxPrefilter:V(ji),ajaxTransport:V(Wi),ajax:function(e,t){function i(e,t,i,r){var n,p,g,v,N,T=t;2!==x&&(x=2,a&&clearTimeout(a),u=void 0,s=r||"",L.readyState=e>0?4:0,n=e>=200&&300>e||304===e,i&&(v=j(c,L,i)),v=W(c,v,L,n),n?(c.ifModified&&(N=L.getResponseHeader("Last-Modified"),N&&(ot.lastModified[o]=N),N=L.getResponseHeader("etag"),N&&(ot.etag[o]=N)),204===e||"HEAD"===c.type?T="nocontent":304===e?T="notmodified":(T=v.state,p=v.data,g=v.error,n=!g)):(g=T,(e||!T)&&(T="error",0>e&&(e=0))),L.status=e,L.statusText=(t||T)+"",n?h.resolveWith(d,[p,T,L]):h.rejectWith(d,[L,T,g]),L.statusCode(m),m=void 0,l&&E.trigger(n?"ajaxSuccess":"ajaxError",[L,c,n?p:g]),f.fireWith(d,[L,T]),l&&(E.trigger("ajaxComplete",[L,c]),--ot.active||ot.event.trigger("ajaxStop")))}"object"==typeof e&&(t=e,e=void 0),t=t||{};var r,n,o,s,a,l,u,p,c=ot.ajaxSetup({},t),d=c.context||c,E=c.context&&(d.nodeType||d.jquery)?ot(d):ot.event,h=ot.Deferred(),f=ot.Callbacks("once memory"),m=c.statusCode||{},g={},v={},x=0,N="canceled",L={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!p)for(p={};t=Bi.exec(s);)p[t[1].toLowerCase()]=t[2];t=p[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?s:null},setRequestHeader:function(e,t){var i=e.toLowerCase();return x||(e=v[i]=v[i]||e,g[e]=t),this},overrideMimeType:function(e){return x||(c.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else L.always(e[L.status]);return this},abort:function(e){var t=e||N;return u&&u.abort(t),i(0,t),this}};if(h.promise(L).complete=f.add,L.success=L.done,L.error=L.fail,c.url=((e||c.url||wi)+"").replace(Gi,"").replace(Hi,Mi[1]+"//"),c.type=t.method||t.type||c.method||c.type,c.dataTypes=ot.trim(c.dataType||"*").toLowerCase().match(Nt)||[""],null==c.crossDomain&&(r=Fi.exec(c.url.toLowerCase()),c.crossDomain=!(!r||r[1]===Mi[1]&&r[2]===Mi[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(Mi[3]||("http:"===Mi[1]?"80":"443")))),c.data&&c.processData&&"string"!=typeof c.data&&(c.data=ot.param(c.data,c.traditional)),H(ji,c,t,L),2===x)return L;l=c.global,l&&0===ot.active++&&ot.event.trigger("ajaxStart"),c.type=c.type.toUpperCase(),c.hasContent=!Vi.test(c.type),o=c.url,c.hasContent||(c.data&&(o=c.url+=(Di.test(o)?"&":"?")+c.data,delete c.data),c.cache===!1&&(c.url=ki.test(o)?o.replace(ki,"$1_="+Pi++):o+(Di.test(o)?"&":"?")+"_="+Pi++)),c.ifModified&&(ot.lastModified[o]&&L.setRequestHeader("If-Modified-Since",ot.lastModified[o]),ot.etag[o]&&L.setRequestHeader("If-None-Match",ot.etag[o])),(c.data&&c.hasContent&&c.contentType!==!1||t.contentType)&&L.setRequestHeader("Content-Type",c.contentType),L.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+("*"!==c.dataTypes[0]?", "+qi+"; q=0.01":""):c.accepts["*"]);for(n in c.headers)L.setRequestHeader(n,c.headers[n]);if(c.beforeSend&&(c.beforeSend.call(d,L,c)===!1||2===x))return L.abort();N="abort";for(n in{success:1,error:1,complete:1})L[n](c[n]);if(u=H(Wi,c,t,L)){L.readyState=1,l&&E.trigger("ajaxSend",[L,c]),c.async&&c.timeout>0&&(a=setTimeout(function(){L.abort("timeout")},c.timeout));try{x=1,u.send(g,i)}catch(T){if(!(2>x))throw T;i(-1,T)}}else i(-1,"No Transport");return L},getJSON:function(e,t,i){return ot.get(e,t,i,"json")},getScript:function(e,t){return ot.get(e,void 0,t,"script")}}),ot.each(["get","post"],function(e,t){ot[t]=function(e,i,r,n){return ot.isFunction(i)&&(n=n||r,r=i,i=void 0),ot.ajax({url:e,type:t,dataType:n,data:i,success:r})}}),ot.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ot.fn[t]=function(e){return this.on(t,e)}}),ot._evalUrl=function(e){return ot.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},ot.fn.extend({wrapAll:function(e){if(ot.isFunction(e))return this.each(function(t){ot(this).wrapAll(e.call(this,t))});if(this[0]){var t=ot(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return this.each(ot.isFunction(e)?function(t){ot(this).wrapInner(e.call(this,t))}:function(){var t=ot(this),i=t.contents();i.length?i.wrapAll(e):t.append(e)})},wrap:function(e){var t=ot.isFunction(e);return this.each(function(i){ot(this).wrapAll(t?e.call(this,i):e)})},unwrap:function(){return this.parent().each(function(){ot.nodeName(this,"body")||ot(this).replaceWith(this.childNodes)}).end()}}),ot.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0||!rt.reliableHiddenOffsets()&&"none"===(e.style&&e.style.display||ot.css(e,"display"))},ot.expr.filters.visible=function(e){return!ot.expr.filters.hidden(e)};var Xi=/%20/g,Yi=/\[\]$/,Ki=/\r?\n/g,$i=/^(?:submit|button|image|reset|file)$/i,Qi=/^(?:input|select|textarea|keygen)/i;ot.param=function(e,t){var i,r=[],n=function(e,t){t=ot.isFunction(t)?t():null==t?"":t,r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(void 0===t&&(t=ot.ajaxSettings&&ot.ajaxSettings.traditional),ot.isArray(e)||e.jquery&&!ot.isPlainObject(e))ot.each(e,function(){n(this.name,this.value)});else for(i in e)q(i,e[i],t,n);return r.join("&").replace(Xi,"+")},ot.fn.extend({serialize:function(){return ot.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=ot.prop(this,"elements");return e?ot.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!ot(this).is(":disabled")&&Qi.test(this.nodeName)&&!$i.test(e)&&(this.checked||!Pt.test(e))}).map(function(e,t){var i=ot(this).val();return null==i?null:ot.isArray(i)?ot.map(i,function(e){return{name:t.name,value:e.replace(Ki,"\r\n")}}):{name:t.name,value:i.replace(Ki,"\r\n")}}).get()}}),ot.ajaxSettings.xhr=void 0!==t.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&z()||X()}:z;var Zi=0,Ji={},er=ot.ajaxSettings.xhr();t.ActiveXObject&&ot(t).on("unload",function(){for(var e in Ji)Ji[e](void 0,!0)}),rt.cors=!!er&&"withCredentials"in er,er=rt.ajax=!!er,er&&ot.ajaxTransport(function(e){if(!e.crossDomain||rt.cors){var t;return{send:function(i,r){var n,o=e.xhr(),s=++Zi;if(o.open(e.type,e.url,e.async,e.username,e.password),e.xhrFields)for(n in e.xhrFields)o[n]=e.xhrFields[n];e.mimeType&&o.overrideMimeType&&o.overrideMimeType(e.mimeType),e.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");for(n in i)void 0!==i[n]&&o.setRequestHeader(n,i[n]+"");o.send(e.hasContent&&e.data||null),t=function(i,n){var a,l,u;if(t&&(n||4===o.readyState))if(delete Ji[s],t=void 0,o.onreadystatechange=ot.noop,n)4!==o.readyState&&o.abort();else{u={},a=o.status,"string"==typeof o.responseText&&(u.text=o.responseText);try{l=o.statusText}catch(p){l=""}a||!e.isLocal||e.crossDomain?1223===a&&(a=204):a=u.text?200:404}u&&r(a,l,u,o.getAllResponseHeaders())},e.async?4===o.readyState?setTimeout(t):o.onreadystatechange=Ji[s]=t:t()},abort:function(){t&&t(void 0,!0)}}}}),ot.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return ot.globalEval(e),e}}}),ot.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),ot.ajaxTransport("script",function(e){if(e.crossDomain){var t,i=ft.head||ot("head")[0]||ft.documentElement;return{send:function(r,n){t=ft.createElement("script"),t.async=!0,e.scriptCharset&&(t.charset=e.scriptCharset),t.src=e.url,t.onload=t.onreadystatechange=function(e,i){(i||!t.readyState||/loaded|complete/.test(t.readyState))&&(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),t=null,i||n(200,"success"))},i.insertBefore(t,i.firstChild)},abort:function(){t&&t.onload(void 0,!0)}}}});var tr=[],ir=/(=)\?(?=&|$)|\?\?/;ot.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=tr.pop()||ot.expando+"_"+Pi++;return this[e]=!0,e}}),ot.ajaxPrefilter("json jsonp",function(e,i,r){var n,o,s,a=e.jsonp!==!1&&(ir.test(e.url)?"url":"string"==typeof e.data&&!(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&ir.test(e.data)&&"data");return a||"jsonp"===e.dataTypes[0]?(n=e.jsonpCallback=ot.isFunction(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(ir,"$1"+n):e.jsonp!==!1&&(e.url+=(Di.test(e.url)?"&":"?")+e.jsonp+"="+n),e.converters["script json"]=function(){return s||ot.error(n+" was not called"),s[0]},e.dataTypes[0]="json",o=t[n],t[n]=function(){s=arguments},r.always(function(){t[n]=o,e[n]&&(e.jsonpCallback=i.jsonpCallback,tr.push(n)),s&&ot.isFunction(o)&&o(s[0]),s=o=void 0}),"script"):void 0}),ot.parseHTML=function(e,t,i){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(i=t,t=!1),t=t||ft;var r=dt.exec(e),n=!i&&[];return r?[t.createElement(r[1])]:(r=ot.buildFragment([e],t,n),n&&n.length&&ot(n).remove(),ot.merge([],r.childNodes))};var rr=ot.fn.load;ot.fn.load=function(e,t,i){if("string"!=typeof e&&rr)return rr.apply(this,arguments);var r,n,o,s=this,a=e.indexOf(" ");return a>=0&&(r=ot.trim(e.slice(a,e.length)),e=e.slice(0,a)),ot.isFunction(t)?(i=t,t=void 0):t&&"object"==typeof t&&(o="POST"),s.length>0&&ot.ajax({url:e,type:o,dataType:"html",data:t}).done(function(e){n=arguments,s.html(r?ot("<div>").append(ot.parseHTML(e)).find(r):e)}).complete(i&&function(e,t){s.each(i,n||[e.responseText,t,e])}),this},ot.expr.filters.animated=function(e){return ot.grep(ot.timers,function(t){return e===t.elem}).length};var nr=t.document.documentElement;ot.offset={setOffset:function(e,t,i){var r,n,o,s,a,l,u,p=ot.css(e,"position"),c=ot(e),d={};"static"===p&&(e.style.position="relative"),a=c.offset(),o=ot.css(e,"top"),l=ot.css(e,"left"),u=("absolute"===p||"fixed"===p)&&ot.inArray("auto",[o,l])>-1,u?(r=c.position(),s=r.top,n=r.left):(s=parseFloat(o)||0,n=parseFloat(l)||0),ot.isFunction(t)&&(t=t.call(e,i,a)),null!=t.top&&(d.top=t.top-a.top+s),null!=t.left&&(d.left=t.left-a.left+n),"using"in t?t.using.call(e,d):c.css(d)}},ot.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){ot.offset.setOffset(this,e,t)});var t,i,r={top:0,left:0},n=this[0],o=n&&n.ownerDocument;if(o)return t=o.documentElement,ot.contains(t,n)?(typeof n.getBoundingClientRect!==yt&&(r=n.getBoundingClientRect()),i=Y(o),{top:r.top+(i.pageYOffset||t.scrollTop)-(t.clientTop||0),left:r.left+(i.pageXOffset||t.scrollLeft)-(t.clientLeft||0)}):r},position:function(){if(this[0]){var e,t,i={top:0,left:0},r=this[0];return"fixed"===ot.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),ot.nodeName(e[0],"html")||(i=e.offset()),i.top+=ot.css(e[0],"borderTopWidth",!0),i.left+=ot.css(e[0],"borderLeftWidth",!0)),{top:t.top-i.top-ot.css(r,"marginTop",!0),left:t.left-i.left-ot.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||nr;e&&!ot.nodeName(e,"html")&&"static"===ot.css(e,"position");)e=e.offsetParent;return e||nr})}}),ot.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var i=/Y/.test(t);ot.fn[e]=function(r){return Ot(this,function(e,r,n){var o=Y(e);return void 0===n?o?t in o?o[t]:o.document.documentElement[r]:e[r]:void(o?o.scrollTo(i?ot(o).scrollLeft():n,i?n:ot(o).scrollTop()):e[r]=n)},e,r,arguments.length,null)}}),ot.each(["top","left"],function(e,t){ot.cssHooks[t]=C(rt.pixelPosition,function(e,i){return i?(i=ii(e,t),ni.test(i)?ot(e).position()[t]+"px":i):void 0})}),ot.each({Height:"height",Width:"width"},function(e,t){ot.each({padding:"inner"+e,content:t,"":"outer"+e},function(i,r){ot.fn[r]=function(r,n){var o=arguments.length&&(i||"boolean"!=typeof r),s=i||(r===!0||n===!0?"margin":"border");return Ot(this,function(t,i,r){var n;return ot.isWindow(t)?t.document.documentElement["client"+e]:9===t.nodeType?(n=t.documentElement,Math.max(t.body["scroll"+e],n["scroll"+e],t.body["offset"+e],n["offset"+e],n["client"+e])):void 0===r?ot.css(t,i,s):ot.style(t,i,r,s)},t,o?r:void 0,o,null)}})}),ot.fn.size=function(){return this.length},ot.fn.andSelf=ot.fn.addBack,"function"==typeof e&&e.amd&&e("jquery",[],function(){return ot});var or=t.jQuery,sr=t.$;return ot.noConflict=function(e){return t.$===ot&&(t.$=sr),e&&t.jQuery===ot&&(t.jQuery=or),ot},typeof i===yt&&(t.jQuery=t.$=ot),ot})},{}],10:[function(e,t){t.exports=e(9)},{}],11:[function(t,i){!function(t){function r(){try{return u in t&&t[u]}catch(e){return!1}}function n(e){return function(){var t=Array.prototype.slice.call(arguments,0);t.unshift(s),c.appendChild(s),s.addBehavior("#default#userData"),s.load(u);var i=e.apply(a,t);return c.removeChild(s),i}}function o(e){return e.replace(/^d/,"___$&").replace(h,"___")}var s,a={},l=t.document,u="localStorage",p="script";if(a.disabled=!1,a.set=function(){},a.get=function(){},a.remove=function(){},a.clear=function(){},a.transact=function(e,t,i){var r=a.get(e);null==i&&(i=t,t=null),"undefined"==typeof r&&(r=t||{}),i(r),a.set(e,r)},a.getAll=function(){},a.forEach=function(){},a.serialize=function(e){return JSON.stringify(e)},a.deserialize=function(e){if("string"!=typeof e)return void 0;try{return JSON.parse(e)}catch(t){return e||void 0}},r())s=t[u],a.set=function(e,t){return void 0===t?a.remove(e):(s.setItem(e,a.serialize(t)),t)},a.get=function(e){return a.deserialize(s.getItem(e))},a.remove=function(e){s.removeItem(e)},a.clear=function(){s.clear()},a.getAll=function(){var e={};return a.forEach(function(t,i){e[t]=i}),e},a.forEach=function(e){for(var t=0;t<s.length;t++){var i=s.key(t);e(i,a.get(i))}};else if(l.documentElement.addBehavior){var c,d;try{d=new ActiveXObject("htmlfile"),d.open(),d.write("<"+p+">document.w=window</"+p+'><iframe src="/favicon.ico"></iframe>'),d.close(),c=d.w.frames[0].document,s=c.createElement("div")}catch(E){s=l.createElement("div"),c=l.body}var h=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");a.set=n(function(e,t,i){return t=o(t),void 0===i?a.remove(t):(e.setAttribute(t,a.serialize(i)),e.save(u),i)}),a.get=n(function(e,t){return t=o(t),a.deserialize(e.getAttribute(t))}),a.remove=n(function(e,t){t=o(t),e.removeAttribute(t),e.save(u)}),a.clear=n(function(e){var t=e.XMLDocument.documentElement.attributes;e.load(u);for(var i,r=0;i=t[r];r++)e.removeAttribute(i.name);e.save(u)}),a.getAll=function(){var e={};return a.forEach(function(t,i){e[t]=i}),e},a.forEach=n(function(e,t){for(var i,r=e.XMLDocument.documentElement.attributes,n=0;i=r[n];++n)t(i.name,a.deserialize(e.getAttribute(i.name)))})}try{var f="__storejs__";a.set(f,f),a.get(f)!=f&&(a.disabled=!0),a.remove(f)}catch(E){a.disabled=!0}a.enabled=!a.disabled,"undefined"!=typeof i&&i.exports&&this.module!==i?i.exports=a:"function"==typeof e&&e.amd?e(a):t.store=a}(Function("return this")())},{}],12:[function(e,t){t.exports={name:"yasgui-utils",version:"1.1.3",description:"Utils for YASGUI libs",main:"src/main.js",repository:{type:"git",url:"git://github.com/YASGUI/Utils.git"},licenses:[{type:"MIT",url:"http://yasgui.github.io/license.txt"}],author:{name:"Laurens Rietveld"},maintainers:[{name:"Laurens Rietveld",email:"laurens.rietveld@gmail.com",url:"http://laurensrietveld.nl"}],bugs:{url:"https://github.com/YASGUI/Utils/issues"},homepage:"https://github.com/YASGUI/Utils",dependencies:{jquery:"~ 1.11.0",store:"^1.3.14"},readme:"A simple utils repo for the YASGUI tools\n",readmeFilename:"README.md",_id:"yasgui-utils@1.1.3",_from:"yasgui-utils@1.1.3"}},{}],13:[function(e,t){t.exports=function(t){return e("jquery")(t).closest("[id]").attr("id")}},{jquery:10}],14:[function(e,t){var i=e("jquery"),r=t.exports={cross:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><g> <path d="M83.288,88.13c-2.114,2.112-5.575,2.112-7.689,0L53.659,66.188c-2.114-2.112-5.573-2.112-7.687,0L24.251,87.907 c-2.113,2.114-5.571,2.114-7.686,0l-4.693-4.691c-2.114-2.114-2.114-5.573,0-7.688l21.719-21.721c2.113-2.114,2.113-5.573,0-7.686 L11.872,24.4c-2.114-2.113-2.114-5.571,0-7.686l4.842-4.842c2.113-2.114,5.571-2.114,7.686,0L46.12,33.591 c2.114,2.114,5.572,2.114,7.688,0l21.721-21.719c2.114-2.114,5.573-2.114,7.687,0l4.695,4.695c2.111,2.113,2.111,5.571-0.003,7.686 L66.188,45.973c-2.112,2.114-2.112,5.573,0,7.686L88.13,75.602c2.112,2.111,2.112,5.572,0,7.687L83.288,88.13z"/></g></svg>',check:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><path fill="#000000" d="M14.301,49.982l22.606,17.047L84.361,4.903c2.614-3.733,7.76-4.64,11.493-2.026l0.627,0.462 c3.732,2.614,4.64,7.758,2.025,11.492l-51.783,79.77c-1.955,2.791-3.896,3.762-7.301,3.988c-3.405,0.225-5.464-1.039-7.508-3.084 L2.447,61.814c-3.263-3.262-3.263-8.553,0-11.814l0.041-0.019C5.75,46.718,11.039,46.718,14.301,49.982z"/></svg>',unsorted:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,-0.70898699,-0.70898699,0.70522156,97.988199,55.081205)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path7-9" d="m 8.8748339,52.571766 16.9382111,-0.222584 4.050851,-0.06665 15.719154,-0.222166 0.27778,-0.04246 0.43276,0.0017 0.41632,-0.06121 0.37532,-0.0611 0.47132,-0.119342 0.27767,-0.08206 0.55244,-0.198047 0.19707,-0.08043 0.61095,-0.259721 0.0988,-0.05825 0.019,-0.01914 0.59303,-0.356548 0.11787,-0.0788 0.49125,-0.337892 0.17994,-0.139779 0.37317,-0.336871 0.21862,-0.219786 0.31311,-0.31479 0.21993,-0.259387 c 0.92402,-1.126057 1.55249,-2.512251 1.78961,-4.016904 l 0.0573,-0.25754 0.0195,-0.374113 0.0179,-0.454719 0.0175,-0.05874 -0.0169,-0.258049 -0.0225,-0.493503 -0.0398,-0.355569 -0.0619,-0.414201 -0.098,-0.414812 -0.083,-0.353334 L 53.23955,41.1484 53.14185,40.850967 52.93977,40.377742 52.84157,40.161628 34.38021,4.2507375 C 33.211567,1.9401875 31.035446,0.48226552 28.639484,0.11316952 l -0.01843,-0.01834 -0.671963,-0.07882 -0.236871,0.0042 L 27.335984,-4.7826577e-7 27.220736,0.00379952 l -0.398804,0.0025 -0.313848,0.04043 -0.594474,0.07724 -0.09611,0.02147 C 23.424549,0.60716252 21.216017,2.1142355 20.013025,4.4296865 L 0.93967491,40.894479 c -2.08310801,3.997178 -0.588125,8.835482 3.35080799,10.819749 1.165535,0.613495 2.43199,0.88731 3.675026,0.864202 l 0.49845,-0.02325 0.410875,0.01658 z M 9.1502369,43.934401 9.0136999,43.910011 27.164145,9.2564625 44.70942,43.42818 l -14.765289,0.214677 -4.031106,0.0468 -16.7627881,0.244744 z" /></svg>',sortDesc:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,-0.70898699,-0.70898699,0.70522156,97.988199,55.081205)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path9" d="m 27.813273,0.12823506 0.09753,0.02006 c 2.39093,0.458209 4.599455,1.96811104 5.80244,4.28639004 L 52.785897,40.894525 c 2.088044,4.002139 0.590949,8.836902 -3.348692,10.821875 -1.329078,0.688721 -2.766603,0.943695 -4.133174,0.841768 l -0.454018,0.02 L 27.910392,52.354171 23.855313,52.281851 8.14393,52.061827 7.862608,52.021477 7.429856,52.021738 7.014241,51.959818 6.638216,51.900838 6.164776,51.779369 5.889216,51.699439 5.338907,51.500691 5.139719,51.419551 4.545064,51.145023 4.430618,51.105123 4.410168,51.084563 3.817138,50.730843 3.693615,50.647783 3.207314,50.310611 3.028071,50.174369 2.652795,49.833957 2.433471,49.613462 2.140099,49.318523 1.901127,49.041407 C 0.97781,47.916059 0.347935,46.528448 0.11153,45.021676 L 0.05352,44.766255 0.05172,44.371683 0.01894,43.936017 0,43.877277 0.01836,43.62206 0.03666,43.122889 0.0765,42.765905 0.13912,42.352413 0.23568,41.940425 0.32288,41.588517 0.481021,41.151945 0.579391,40.853806 0.77369,40.381268 0.876097,40.162336 19.338869,4.2542801 c 1.172169,-2.308419 3.34759,-3.76846504 5.740829,-4.17716604 l 0.01975,0.01985 0.69605,-0.09573 0.218437,0.0225 0.490791,-0.02132 0.39809,0.0046 0.315972,0.03973 0.594462,0.08149 z" /></svg>',sortAsc:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,0.70898699,-0.70898699,-0.70522156,97.988199,58.704807)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path9" d="m 27.813273,113.65778 0.09753,-0.0201 c 2.39093,-0.45821 4.599455,-1.96811 5.80244,-4.28639 L 52.785897,72.891487 c 2.088044,-4.002139 0.590949,-8.836902 -3.348692,-10.821875 -1.329078,-0.688721 -2.766603,-0.943695 -4.133174,-0.841768 l -0.454018,-0.02 -16.939621,0.223997 -4.055079,0.07232 -15.711383,0.220024 -0.281322,0.04035 -0.432752,-2.61e-4 -0.415615,0.06192 -0.376025,0.05898 -0.47344,0.121469 -0.27556,0.07993 -0.550309,0.198748 -0.199188,0.08114 -0.594655,0.274528 -0.114446,0.0399 -0.02045,0.02056 -0.59303,0.35372 -0.123523,0.08306 -0.486301,0.337172 -0.179243,0.136242 -0.375276,0.340412 -0.219324,0.220495 -0.293372,0.294939 -0.238972,0.277116 C 0.97781,65.869953 0.347935,67.257564 0.11153,68.764336 L 0.05352,69.019757 0.05172,69.414329 0.01894,69.849995 0,69.908735 l 0.01836,0.255217 0.0183,0.499171 0.03984,0.356984 0.06262,0.413492 0.09656,0.411988 0.0872,0.351908 0.158141,0.436572 0.09837,0.298139 0.194299,0.472538 0.102407,0.218932 18.462772,35.908054 c 1.172169,2.30842 3.34759,3.76847 5.740829,4.17717 l 0.01975,-0.0199 0.69605,0.0957 0.218437,-0.0225 0.490791,0.0213 0.39809,-0.005 0.315972,-0.0397 0.594462,-0.0815 z" /></svg>',loader:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" fill="black"> <circle cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(45 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.125s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(90 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.25s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(135 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.375s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(180 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.5s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(225 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.625s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(270 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.75s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(315 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.875s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(180 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.5s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle></svg>',query:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 80 80" enable-background="new 0 0 80 80" xml:space="preserve"><g id="Layer_1"></g><g id="Layer_2"> <path d="M64.622,2.411H14.995c-6.627,0-12,5.373-12,12v49.897c0,6.627,5.373,12,12,12h49.627c6.627,0,12-5.373,12-12V14.411 C76.622,7.783,71.249,2.411,64.622,2.411z M24.125,63.906V15.093L61,39.168L24.125,63.906z"/></g></svg>',queryInvalid:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 73.627 73.897" enable-background="new 0 0 80 80" xml:space="preserve" ><g id="Layer_1" transform="translate(-2.995,-2.411)" /><g id="Layer_2" transform="translate(-2.995,-2.411)"><path d="M 64.622,2.411 H 14.995 c -6.627,0 -12,5.373 -12,12 v 49.897 c 0,6.627 5.373,12 12,12 h 49.627 c 6.627,0 12,-5.373 12,-12 V 14.411 c 0,-6.628 -5.373,-12 -12,-12 z M 24.125,63.906 V 15.093 L 61,39.168 24.125,63.906 z" id="path6" inkscape:connector-curvature="0" /></g><g transform="matrix(0.76805408,0,0,0.76805408,-0.90231954,-2.0060895)" id="g3"><path style="fill:#c02608;fill-opacity:1" inkscape:connector-curvature="0" d="m 88.184,81.468 c 1.167,1.167 1.167,3.075 0,4.242 l -2.475,2.475 c -1.167,1.167 -3.076,1.167 -4.242,0 l -69.65,-69.65 c -1.167,-1.167 -1.167,-3.076 0,-4.242 l 2.476,-2.476 c 1.167,-1.167 3.076,-1.167 4.242,0 l 69.649,69.651 z" id="path5" /></g><g transform="matrix(0.76805408,0,0,0.76805408,-0.90231954,-2.0060895)" id="g7"><path style="fill:#c02608;fill-opacity:1" inkscape:connector-curvature="0" d="m 18.532,88.184 c -1.167,1.166 -3.076,1.166 -4.242,0 l -2.475,-2.475 c -1.167,-1.166 -1.167,-3.076 0,-4.242 l 69.65,-69.651 c 1.167,-1.167 3.075,-1.167 4.242,0 l 2.476,2.476 c 1.166,1.167 1.166,3.076 0,4.242 l -69.651,69.65 z" id="path9" /></g></svg>',download:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="tiny" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" xml:space="preserve"><g id="Captions"></g><g id="Your_Icon"> <path fill-rule="evenodd" fill="#000000" d="M88,84v-2c0-2.961-0.859-4-4-4H16c-2.961,0-4,0.98-4,4v2c0,3.102,1.039,4,4,4h68 C87.02,88,88,87.039,88,84z M58,12H42c-5,0-6,0.941-6,6v22H16l34,34l34-34H64V18C64,12.941,62.939,12,58,12z"/></g></svg>',share:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Icons" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" style="enable-background:new 0 0 100 100;" xml:space="preserve"><path id="ShareThis" d="M36.764,50c0,0.308-0.07,0.598-0.088,0.905l32.247,16.119c2.76-2.338,6.293-3.797,10.195-3.797 C87.89,63.228,95,70.338,95,79.109C95,87.89,87.89,95,79.118,95c-8.78,0-15.882-7.11-15.882-15.891c0-0.316,0.07-0.598,0.088-0.905 L31.077,62.085c-2.769,2.329-6.293,3.788-10.195,3.788C12.11,65.873,5,58.771,5,50c0-8.78,7.11-15.891,15.882-15.891 c3.902,0,7.427,1.468,10.195,3.797l32.247-16.119c-0.018-0.308-0.088-0.598-0.088-0.914C63.236,12.11,70.338,5,79.118,5 C87.89,5,95,12.11,95,20.873c0,8.78-7.11,15.891-15.882,15.891c-3.911,0-7.436-1.468-10.195-3.806L36.676,49.086 C36.693,49.394,36.764,49.684,36.764,50z"/></svg>',draw:function(e,t){if(e){var n=r.getElement(t); n&&i(e).append(n)}},getElement:function(e){var t=e.id?r[e.id]:e.value;if(t&&0==t.indexOf("<svg")){var n=new DOMParser,o=n.parseFromString(t,"text/xml"),s=o.documentElement,a=i("<div></div>").css("display","inline-block");return e.width||(e.width="100%"),e.height||(e.height="100%"),a.width(e.width).height(e.height),a.append(s)}return!1}}},{jquery:10}],15:[function(e,t){window.console=window.console||{log:function(){}},t.exports={storage:e("./storage.js"),determineId:e("./determineId.js"),imgs:e("./imgs.js"),version:{"yasgui-utils":e("../package.json").version}}},{"../package.json":12,"./determineId.js":13,"./imgs.js":14,"./storage.js":16}],16:[function(e,t){{var i=e("store"),r={day:function(){return 864e5},month:function(){30*r.day()},year:function(){12*r.month()}};t.exports={set:function(e,t,n){"string"==typeof n&&(n=r[n]()),i.set(e,{val:t,exp:n,time:(new Date).getTime()})},get:function(e){var t=i.get(e);return t?t.exp&&(new Date).getTime()-t.time>t.exp?null:t.val:null}}}},{store:11}],17:[function(e,t){t.exports={name:"yasgui-yasqe",description:"Yet Another SPARQL Query Editor",version:"1.3.0",main:"src/main.js",licenses:[{type:"MIT",url:"http://yasgui.org/license.txt"}],devDependencies:{gulp:"~3.6.0","vinyl-source-stream":"~0.1.1",watchify:"^0.6.4","gulp-uglify":"^0.2.1","gulp-concat":"^2.2.0","gulp-minify-css":"^0.3.0","vinyl-buffer":"0.0.0",browserify:"^3.38.1","gulp-livereload":"^1.3.1","gulp-connect":"^2.0.5","gulp-notify":"^1.2.5","gulp-embedlr":"^0.5.2","gulp-yuidoc":"^0.1.2","gulp-jsvalidate":"^0.2.0"},bugs:"https://github.com/YASGUI/YASQE/issues/",keywords:["JavaScript","SPARQL","Editor","Semantic Web","Linked Data"],homepage:"http://yasqe.yasgui.org",maintainers:[{name:"Laurens Rietveld",email:"laurens.rietveld@gmail.com",web:"http://laurensrietveld.nl"}],repository:{type:"git",url:"https://github.com/YASGUI/YASQE.git"},dependencies:{jquery:"~ 1.11.0",codemirror:"~4.2.0",amplify:"0.0.11",store:"^1.3.14","twitter-bootstrap-3.0.0":"^3.0.0","yasgui-utils":"^1.0.0"}}},{}],18:[function(e,t){"use strict";function i(e,t,r){var n=e.getTokenAt({line:t,ch:r.start});return null!=n&&"ws"==n.type&&(n=i(e,t,n)),n}var r=e("jquery"),n=e("codemirror");e("codemirror/addon/hint/show-hint.js"),e("codemirror/addon/search/searchcursor.js"),e("codemirror/addon/edit/matchbrackets.js"),e("codemirror/addon/runmode/runmode.js"),window.console=window.console||{log:function(){}},e("../lib/flint.js");var o=e("../lib/trie.js"),s=t.exports=function(e,t){t=a(t);var i=l(n(e,t));return u(i),i},a=function(e){var t=r.extend(!0,{},s.defaults,e);return t},l=function(t){return t.query=function(e){s.executeQuery(t,e)},t.getPrefixesFromQuery=function(){return h(t)},t.storeBulkCompletions=function(i,r){p[i]=new o;for(var n=0;n<r.length;n++)p[i].insert(r[n]);var s=b(t,t.options.autocompletions[i].persistent);s&&e("yasgui-utils").storage.set(s,r,"month")},t.setCheckSyntaxErrors=function(e){t.options.syntaxErrorCheck=e,x(t)},t},u=function(t){var i=b(t,t.options.persistent);if(i){var r=e("yasgui-utils").storage.get(i);r&&t.setValue(r)}if(s.drawButtons(t),t.on("blur",function(e){s.storeQuery(e)}),t.on("change",function(e){x(e),s.appendPrefixIfNeeded(e),s.updateQueryButton(e),s.positionAbsoluteItems(e)}),t.on("cursorActivity",function(e){s.autoComplete(e,!0)}),t.prevQueryValid=!1,x(t),s.positionAbsoluteItems(t),t.options.autocompletions)for(var n in t.options.autocompletions)t.options.autocompletions[n].bulk&&E(t,n);t.options.consumeShareLink&&t.options.consumeShareLink(t)},p={},c={"string-2":"prefixed",atom:"var"},d=function(e,t){var i=!1;try{void 0!==e[t]&&(i=!0)}catch(r){}return i},E=function(t,i){var r=null;if(d(t.options.autocompletions[i],"get")&&(r=t.options.autocompletions[i].get),r instanceof Array)t.storeBulkCompletions(i,r);else{var n=null;if(b(t,t.options.autocompletions[i].persistent)&&(n=e("yasgui-utils").storage.get(b(t,t.options.autocompletions[i].persistent))),n&&n instanceof Array&&n.length>0)t.storeBulkCompletions(i,n);else if(r instanceof Function){var o=r(t);o&&o instanceof Array&&o.length>0&&t.storeBulkCompletions(i,o)}}},h=function(e){for(var t={},i=e.lineCount(),r=0;i>r;r++){var n=g(e,r);if(null!=n&&"PREFIX"==n.string.toUpperCase()){var o=g(e,r,n.end+1);if(o){var s=g(e,r,o.end+1);if(null!=o&&o.string.length>0&&null!=s&&s.string.length>0){var a=s.string;0==a.indexOf("<")&&(a=a.substring(1)),">"==a.slice(-1)&&(a=a.substring(0,a.length-1)),t[o.string]=a}}}}return t},f=function(e,t){for(var i=null,r=0,n=e.lineCount(),o=0;n>o;o++){var s=g(e,o);null==s||"PREFIX"!=s.string&&"BASE"!=s.string||(i=s,r=o)}if(null==i)e.replaceRange("PREFIX "+t+"\n",{line:0,ch:0});else{var a=m(e,r);e.replaceRange("\n"+a+"PREFIX "+t,{line:r})}},m=function(e,t,i){void 0==i&&(i=1);var r=e.getTokenAt({line:t,ch:i});return null==r||void 0==r||"ws"!=r.type?"":r.string+m(e,t,r.end+1)},g=function(e,t,i){void 0==i&&(i=1);var r=e.getTokenAt({line:t,ch:i});return null==r||void 0==r||r.end<i?null:"ws"==r.type?g(e,t,r.end+1):r},v=null,x=function(e,t){e.queryValid=!0,v&&(v(),v=null),e.clearGutter("gutterErrorBar");for(var i=null,n=0;n<e.lineCount();++n){var o=!1;if(e.prevQueryValid||(o=!0),i=e.getTokenAt({line:n,ch:e.getLine(n).length},o).state,0==i.OK){if(!e.options.syntaxErrorCheck)return void r(e.getWrapperElement).find(".sp-error").css("color","black");var s=document.createElement("span");s.innerHTML="&rarr;",s.className="gutterError",e.setGutterMarker(n,"gutterErrorBar",s),v=function(){e.markText({line:n,ch:i.errorStartPos},{line:n,ch:i.errorEndPos},"sp-error")},e.queryValid=!1;break}}if(e.prevQueryValid=e.queryValid,t&&null!=i&&void 0!=i.stack){var a=i.stack,l=i.stack.length;l>1?e.queryValid=!1:1==l&&"solutionModifier"!=a[0]&&"?limitOffsetClauses"!=a[0]&&"?offsetClause"!=a[0]&&(e.queryValid=!1)}};r.extend(s,n),s.positionAbsoluteItems=function(e){var t=r(e.getWrapperElement()).find(".CodeMirror-vscrollbar"),i=0;t.is(":visible")&&(i=t.outerWidth());var n=r(e.getWrapperElement()).find(".completionNotification");n.is(":visible")&&n.css("right",i);var o=r(e.getWrapperElement()).find(".yasqe_buttons");o.is(":visible")&&o.css("right",i)},s.createShareLink=function(e){return{query:e.getValue()}},s.consumeShareLink=function(t){e("../lib/deparam.js");var i=r.deparam(window.location.search.substring(1));i.query&&t.setValue(i.query)},s.drawButtons=function(t){var i=r("<div class='yasqe_buttons'></div>").appendTo(r(t.getWrapperElement()));if(t.options.createShareLink){var n=e("yasgui-utils").imgs.getElement({id:"share",width:"30px",height:"30px"});n.click(function(e){e.stopPropagation();var o=r("<div class='yasqe_sharePopup'></div>").appendTo(i);r("html").click(function(){o&&o.remove()}),o.click(function(e){e.stopPropagation()});var s=r("<textarea></textarea>").val(location.protocol+"//"+location.host+location.pathname+"?"+r.param(t.options.createShareLink(t)));s.focus(function(){var e=r(this);e.select(),e.mouseup(function(){return e.unbind("mouseup"),!1})}),o.empty().append(s);var a=n.position();o.css("top",a.top+n.outerHeight()+"px").css("left",a.left+n.outerWidth()-o.outerWidth()+"px")}).addClass("yasqe_share").attr("title","Share your query").appendTo(i)}if(t.options.sparql.showQueryButton){var o=40,a=40;r("<div class='yasqe_queryButton'></div>").click(function(){r(this).hasClass("query_busy")?(t.xhr&&t.xhr.abort(),s.updateQueryButton(t)):t.query()}).height(o).width(a).appendTo(i),s.updateQueryButton(t)}};var N={busy:"loader",valid:"query",error:"queryInvalid"};s.updateQueryButton=function(t,i){var n=r(t.getWrapperElement()).find(".yasqe_queryButton");0!=n.length&&(i||(i="valid",t.queryValid===!1&&(i="error")),i==t.queryStatus||"busy"!=i&&"valid"!=i&&"error"!=i||(n.empty().removeClass(function(e,t){return t.split(" ").filter(function(e){return 0==e.indexOf("query_")}).join(" ")}).addClass("query_"+i).append(e("yasgui-utils").imgs.getElement({id:N[i],width:"100%",height:"100%"})),t.queryStatus=i))},s.fromTextArea=function(e,t){t=a(t);var i=l(n.fromTextArea(e,t));return u(i),i},s.autocompleteVariables=function(e,t){if(0==t.trim().length)return[];var i={};r(e.getWrapperElement()).find(".cm-atom").each(function(){var e=this.innerHTML;if(0==e.indexOf("?")){var n=r(this).next(),o=n.attr("class");if(o&&n.attr("class").indexOf("cm-atom")>=0&&(e+=n.text()),e.length<=1)return;if(0!==e.indexOf(t))return;if(e==t)return;i[e]=!0}});var n=[];for(var o in i)n.push(o);return n.sort(),n},s.fetchFromPrefixCc=function(e){r.get("http://prefix.cc/popular/all.file.json",function(t){var i=[];for(var r in t)if("bif"!=r){var n=r+": <"+t[r]+">";i.push(n)}i.sort(),e.storeBulkCompletions("prefixes",i)})},s.determineId=function(e){return r(e.getWrapperElement()).closest("[id]").attr("id")},s.storeQuery=function(t){var i=b(t,t.options.persistent);i&&e("yasgui-utils").storage.set(i,t.getValue(),"month")},s.commentLines=function(e){for(var t=e.getCursor(!0).line,i=e.getCursor(!1).line,r=Math.min(t,i),n=Math.max(t,i),o=!0,s=r;n>=s;s++){var a=e.getLine(s);if(0==a.length||"#"!=a.substring(0,1)){o=!1;break}}for(var s=r;n>=s;s++)o?e.replaceRange("",{line:s,ch:0},{line:s,ch:1}):e.replaceRange("#",{line:s,ch:0})},s.copyLineUp=function(e){var t=e.getCursor(),i=e.lineCount();e.replaceRange("\n",{line:i-1,ch:e.getLine(i-1).length});for(var r=i;r>t.line;r--){var n=e.getLine(r-1);e.replaceRange(n,{line:r,ch:0},{line:r,ch:e.getLine(r).length})}},s.copyLineDown=function(e){s.copyLineUp(e);var t=e.getCursor();t.line++,e.setCursor(t)},s.doAutoFormat=function(e){if(e.somethingSelected()){var t={line:e.getCursor(!1).line,ch:e.getSelection().length};O(e,e.getCursor(!0),t)}else{var i=e.lineCount(),r=e.getTextArea().value.length;O(e,{line:0,ch:0},{line:i,ch:r})}},s.executeQuery=function(e,t){var i="function"==typeof t?t:null,n="object"==typeof t?t:{};if(e.options.sparql&&(n=r.extend({},e.options.sparql,n)),n.endpoint&&0!=n.endpoint.length){var o={url:n.endpoint,type:n.requestMethod,data:[{name:"query",value:e.getValue()}],headers:{Accept:n.acceptHeader}},a=!1;if(n.handlers)for(var l in n.handlers)n.handlers[l]&&(a=!0,o[l]=n.handlers[l]);if(a||i){if(i&&(o.complete=i),n.namedGraphs&&n.namedGraphs.length>0)for(var u=0;u<n.namedGraphs.length;u++)o.data.push({name:"named-graph-uri",value:n.namedGraphs[u]});if(n.defaultGraphs&&n.defaultGraphs.length>0)for(var u=0;u<n.defaultGraphs.length;u++)o.data.push({name:"default-graph-uri",value:n.defaultGraphs[u]});n.headers&&!r.isEmptyObject(n.headers)&&r.extend(o.headers,n.headers),n.args&&n.args.length>0&&r.merge(o.data,n.args),s.updateQueryButton(e,"busy");var p=function(){s.updateQueryButton(e)};if(o.complete){var c=o.complete;o.complete=function(e,t){c(e,t),p()}}else o.complete=p();e.xhr=r.ajax(o)}}};var L={};s.showCompletionNotification=function(e,t){e.options.autocompletions[t].autoshow||(L[t]||(L[t]=r("<div class='completionNotification'></div>")),L[t].show().text("Press "+(-1!=navigator.userAgent.indexOf("Mac OS X")?"CMD":"CTRL")+" - <spacebar> to autocomplete").appendTo(r(e.getWrapperElement())))},s.hideCompletionNotification=function(e,t){L[t]&&L[t].hide()},s.autoComplete=function(e,t){if(!e.somethingSelected()&&e.options.autocompletions){var i=function(i){if(t&&(!e.options.autocompletions[i].autoShow||e.options.autocompletions[i].async))return!1;var r={closeCharacters:/(?=a)b/,type:i,completeSingle:!1};e.options.autocompletions[i].async&&(r.async=!0);{var n=function(e,t){return R(e,i,t)};s.showHint(e,n,r)}return!0};for(var r in e.options.autocompletions)if(e.options.autocompletions[r].isValidCompletionPosition)if(e.options.autocompletions[r].isValidCompletionPosition(e)){if(!e.options.autocompletions[r].handlers||!e.options.autocompletions[r].handlers.validPosition||e.options.autocompletions[r].handlers.validPosition(e,r)!==!1){var n=i(r);if(n)break}}else e.options.autocompletions[r].handlers&&e.options.autocompletions[r].handlers.invalidPosition&&e.options.autocompletions[r].handlers.invalidPosition(e,r)}},s.appendPrefixIfNeeded=function(e){if(p.prefixes){var t=e.getCursor(),i=e.getTokenAt(t);if("prefixed"==c[i.type]){var r=i.string.indexOf(":");if(-1!==r){var n=g(e,t.line).string.toUpperCase(),o=e.getTokenAt({line:t.line,ch:i.start});if("PREFIX"!=n&&("ws"==o.type||null==o.type)){var s=i.string.substring(0,r+1),a=h(e);if(null==a[s]){var l=p.prefixes.autoComplete(s);l.length>0&&f(e,l[0])}}}}}},s.getCompleteToken=function(e,t,i){i||(i=e.getCursor()),t||(t=e.getTokenAt(i));var r=e.getTokenAt({line:i.line,ch:t.start});return null!=r.type&&"ws"!=r.type&&null!=t.type&&"ws"!=t.type?(t.start=r.start,t.string=r.string+t.string,s.getCompleteToken(e,t,{line:i.line,ch:r.start})):null!=t.type&&"ws"==t.type?(t.start=t.start+1,t.string=t.string.substring(1),t):t},s.fetchFromLov=function(t,i,n,o){if(!i||!i.string||0==i.string.trim().length)return L[n]&&L[n].empty().append("Nothing to autocomplete yet!"),!1;var s=50,a={q:i.uri,page:1};a.type="classes"==n?"class":"property";var l=[],u="",p=function(){u="http://lov.okfn.org/dataset/lov/api/v2/autocomplete/terms?"+r.param(a)};p();var c=function(){a.page++,p()},d=function(){r.get(u,function(e){for(var t=0;t<e.results.length;t++)l.push(e.results[t].uri);l.length<e.total_results&&l.length<s?(c(),d()):(L[n]&&(l.length>0?L[n].hide():L[n].text("0 matches found...")),o(l))}).fail(function(){L[n]&&L[n].empty().append("Failed fetching suggestions..")})};L[n]&&L[n].empty().append(r("<span>Fetchting autocompletions &nbsp;</span>")).append(e("yasgui-utils").imgs.getElement({id:"loader",width:"18px",height:"18px"}).css("vertical-align","middle")),d()};var T=function(e,t,i){i.text!=e.getTokenAt(e.getCursor()).string&&e.replaceRange(i.text,t.from,t.to)},I=function(e,t){var i=h(e);if(0==!t.string.indexOf("<")&&(t.tokenPrefix=t.string.substring(0,t.string.indexOf(":")+1),null!=i[t.tokenPrefix]&&(t.tokenPrefixUri=i[t.tokenPrefix])),t.uri=t.string.trim(),0==!t.string.indexOf("<")&&t.string.indexOf(":")>-1)for(var r in i)if(i.hasOwnProperty(r)&&0==t.string.indexOf(r)){t.uri=i[r],t.uri+=t.string.substring(r.length);break}return 0==t.uri.indexOf("<")&&(t.uri=t.uri.substring(1)),-1!==t.uri.indexOf(">",t.length-1)&&(t.uri=t.uri.substring(0,t.uri.length-1)),t},y=function(e,t,i){return t.tokenPrefix&&t.uri&&t.tokenPrefixUri?(i=i.substring(t.tokenPrefixUri.length),i=t.tokenPrefix+i):i="<"+i+">",i},A=function(e,t){var r=i(e,e.getCursor().line,t);return r&&r.string&&":"==r.string.slice(-1)&&(t={start:r.start,end:t.end,string:r.string+" "+t.string,state:t.state}),t},S=function(e,t,i){var r=[];if(p[t])r=p[t].autoComplete(i.string);else if("function"==typeof e.options.autocompletions[t].get&&0==e.options.autocompletions[t].async)r=e.options.autocompletions[t].get(e,i.string,t);else if("object"==typeof e.options.autocompletions[t].get)for(var n=i.string.length,o=0;o<e.options.autocompletions[t].get.length;o++){var s=e.options.autocompletions[t].get[o];s.slice(0,n)==i.string&&r.push(s)}return C(e,r,t,i)},C=function(e,t,i,r){for(var n=[],o=0;o<t.length;o++){var a=t[o];e.options.autocompletions[i].postProcessToken&&(a=e.options.autocompletions[i].postProcessToken(e,r,a)),n.push({text:a,displayText:a,hint:T,className:i+"Hint"})}var l=e.getCursor(),u={completionToken:r.string,list:n,from:{line:l.line,ch:r.start},to:{line:l.line,ch:r.end}};if(e.options.autocompletions[i].handlers)for(var p in e.options.autocompletions[i].handlers)e.options.autocompletions[i].handlers[p]&&s.on(u,p,e.options.autocompletions[i].handlers[p]);return u},R=function(e,t,i){var r=s.getCompleteToken(e);if(e.options.autocompletions[t].preProcessToken&&(r=e.options.autocompletions[t].preProcessToken(e,r,t)),r){if(!e.options.autocompletions[t].async)return S(e,t,r);var n=function(n){i(C(e,n,t,r))};e.options.autocompletions[t].get(e,r,t,n)}},b=function(e,t){var i=null;return t&&(i="string"==typeof t?t:t(e)),i},O=function(e,t,i){var r=e.indexFromPos(t),n=e.indexFromPos(i),o=P(e.getValue(),r,n);e.operation(function(){e.replaceRange(o,t,i);for(var n=e.posFromIndex(r).line,s=e.posFromIndex(r+o.length).line,a=n;s>=a;a++)e.indentLine(a,"smart")})},P=function(e,t,i){e=e.substring(t,i);var o=[["keyword","ws","prefixed","ws","uri"],["keyword","ws","uri"]],s=["{",".",";"],a=["}"],l=function(e){for(var t=0;t<o.length;t++)if(c.valueOf().toString()==o[t].valueOf().toString())return 1;for(var t=0;t<s.length;t++)if(e==s[t])return 1;for(var t=0;t<a.length;t++)if(""!=r.trim(p)&&e==a[t])return-1;return 0},u="",p="",c=[];return n.runMode(e,"sparql11",function(e,t){c.push(t);var i=l(e,t);0!=i?(1==i?(u+=e+"\n",p=""):(u+="\n"+e,p=e),c=[]):(p+=e,u+=e),1==c.length&&"sp-ws"==c[0]&&(c=[])}),r.trim(u.replace(/\n\s*\n/g,"\n"))};s.defaults=r.extend(s.defaults,{mode:"sparql11",value:"SELECT * WHERE {\n ?sub ?pred ?obj .\n} \nLIMIT 10",highlightSelectionMatches:{showToken:/\w/},tabMode:"indent",lineNumbers:!0,gutters:["gutterErrorBar","CodeMirror-linenumbers"],matchBrackets:!0,fixedGutter:!0,syntaxErrorCheck:!0,extraKeys:{"Ctrl-Space":s.autoComplete,"Cmd-Space":s.autoComplete,"Ctrl-D":s.deleteLine,"Ctrl-K":s.deleteLine,"Cmd-D":s.deleteLine,"Cmd-K":s.deleteLine,"Ctrl-/":s.commentLines,"Cmd-/":s.commentLines,"Ctrl-Alt-Down":s.copyLineDown,"Ctrl-Alt-Up":s.copyLineUp,"Cmd-Alt-Down":s.copyLineDown,"Cmd-Alt-Up":s.copyLineUp,"Shift-Ctrl-F":s.doAutoFormat,"Shift-Cmd-F":s.doAutoFormat,"Ctrl-]":s.indentMore,"Cmd-]":s.indentMore,"Ctrl-[":s.indentLess,"Cmd-[":s.indentLess,"Ctrl-S":s.storeQuery,"Cmd-S":s.storeQuery,"Ctrl-Enter":s.executeQuery,"Cmd-Enter":s.executeQuery},cursorHeight:.9,createShareLink:s.createShareLink,consumeShareLink:s.consumeShareLink,persistent:function(e){return"queryVal_"+s.determineId(e)},sparql:{showQueryButton:!1,endpoint:"http://dbpedia.org/sparql",requestMethod:"GET",acceptHeader:"application/sparql-results+json",namedGraphs:[],defaultGraphs:[],args:[],headers:{},handlers:{beforeSend:null,complete:null,error:null,success:null}},autocompletions:{prefixes:{isValidCompletionPosition:function(e){var t=e.getCursor(),i=e.getTokenAt(t);if(e.getLine(t.line).length>t.ch)return!1;if("ws"!=i.type&&(i=s.getCompleteToken(e)),0==!i.string.indexOf("a")&&-1==r.inArray("PNAME_NS",i.state.possibleCurrent))return!1;var n=g(e,t.line);return null==n||"PREFIX"!=n.string.toUpperCase()?!1:!0},get:s.fetchFromPrefixCc,preProcessToken:A,postProcessToken:null,async:!1,bulk:!0,autoShow:!0,autoAddDeclaration:!0,persistent:"prefixes",handlers:{validPosition:null,invalidPosition:null,shown:null,select:null,pick:null,close:null}},properties:{isValidCompletionPosition:function(e){var t=s.getCompleteToken(e);if(0==t.string.length)return!1;if(0==t.string.indexOf("?"))return!1;if(r.inArray("a",t.state.possibleCurrent)>=0)return!0;var n=e.getCursor(),o=i(e,n.line,t);return"rdfs:subPropertyOf"==o.string?!0:!1},get:s.fetchFromLov,preProcessToken:I,postProcessToken:y,async:!0,bulk:!1,autoShow:!1,persistent:"properties",handlers:{validPosition:s.showCompletionNotification,invalidPosition:s.hideCompletionNotification,shown:null,select:null,pick:null,close:null}},classes:{isValidCompletionPosition:function(e){var t=s.getCompleteToken(e);if(0==t.string.indexOf("?"))return!1;var r=e.getCursor(),n=i(e,r.line,t);return"a"==n.string?!0:"rdf:type"==n.string?!0:"rdfs:domain"==n.string?!0:"rdfs:range"==n.string?!0:!1},get:s.fetchFromLov,preProcessToken:I,postProcessToken:y,async:!0,bulk:!1,autoShow:!1,persistent:"classes",handlers:{validPosition:s.showCompletionNotification,invalidPosition:s.hideCompletionNotification,shown:null,select:null,pick:null,close:null}},variableNames:{isValidCompletionPosition:function(e){var t=e.getTokenAt(e.getCursor());return"ws"!=t.type&&(t=s.getCompleteToken(e,t),t&&0==t.string.indexOf("?"))?!0:!1},get:s.autocompleteVariables,preProcessToken:null,postProcessToken:null,async:!1,bulk:!1,autoShow:!0,persistent:null,handlers:{validPosition:null,invalidPosition:null,shown:null,select:null,pick:null,close:null}}}}),s.version={CodeMirror:n.version,YASQE:e("../package.json").version,jquery:r.fn.jquery,"yasgui-utils":e("yasgui-utils").version}},{"../lib/deparam.js":1,"../lib/flint.js":2,"../lib/trie.js":3,"../package.json":17,codemirror:8,"codemirror/addon/edit/matchbrackets.js":4,"codemirror/addon/hint/show-hint.js":5,"codemirror/addon/runmode/runmode.js":6,"codemirror/addon/search/searchcursor.js":7,jquery:9,"yasgui-utils":15}]},{},[18])(18)});
components/gpstracking/runlodingscreen.js
akashnautiyal013/ImpactRun01
'use strict'; import React, { Component } from 'react'; import{ StyleSheet, View, Image, ScrollView, Dimensions, TouchableOpacity, Text, WebView, } from 'react-native'; import TimerMixin from 'react-timer-mixin'; import Icon from 'react-native-vector-icons/Ionicons'; import { AnimatedCircularProgress } from 'react-native-circular-progress'; import styleConfig from '../../components/styleConfig'; var deviceWidth = Dimensions.get('window').width; var deviceHeight = Dimensions.get('window').height; class LodingRunScreen extends Component { mixins: [TimerMixin] constructor(props) { super(props); this.state = { seconds: 5 }; } componentDidMount() { this.timeout = setTimeout(() => { this.navigateToRunScreen(); },5000); this.refs.circularProgress.performLinearAnimation(100, 5000); this.interval = setInterval(this.tick.bind(this), 1000); } componentWillUnmount() { clearInterval(this.interval); } tick() { this.setState({ seconds: this.state.seconds - 1 }); } navigateToRunScreen(cause) { var cause = this.props.data; this.props.navigator.replace({ title: 'Gps', id:'runscreen', index: 0, passProps:{data:cause,user:this.props.user,getUserData:this.props.getUserData}, navigator: this.props.navigator, }); clearTimeout(this.timeout); } render() { var data = this.props.data; var second = this.state.seconds; var _this = this; return ( <View class={styles.container}> <TouchableOpacity style={styles.overlay} onPress={()=> this.navigateToRunScreen()}> <View style={styles.LoadingWrap}> <View style={styles.loadingFlex}> <Image style={styles.sponsorLogo} source={{uri:data.sponsors[0].sponsor_logo}}></Image> <View style={styles.sponsorText}> <Text style={{color:styleConfig.greyish_brown_two,fontSize:16,fontFamily:styleConfig.FontFamily,}}>is proud to sponsor your run.</Text> </View> </View> <View style={styles.loadingFlex}> <View style={styles.circleWrap}> <AnimatedCircularProgress ref='circularProgress' size={150} width={5} fill={100} prefill={0} tintColor={styleConfig.bright_blue} backgroundColor="#fafafa"> { (fill) => ( <View style={styles.secondWrap}> <Text style={styles.second}>{second}</Text> </View> ) } </AnimatedCircularProgress> </View> </View> <View style={styles.loadingFlex}> <Text style={styles.navigateToRunScreen} onPress={()=> this.navigateToRunScreen()}>TAP TO START NOW</Text> </View> </View> </TouchableOpacity> </View> ); } } var styles = StyleSheet.create({ container:{ flex:1, justifyContent: 'center', alignItems: 'center', }, LoadingWrap:{ flex:1, justifyContent: 'center', alignItems: 'center', }, sponsorLogo:{ resizeMode: 'contain', height:styleConfig.LogoHeight, width:styleConfig.LogoWidth, }, sponsorText:{ height:20, width:deviceWidth, alignItems: 'center', justifyContent: 'center', }, second:{ color:'#ccc', fontSize:70, }, secondWrap:{ position:'absolute', top:0, height:150, width:150, backgroundColor:'transparent', justifyContent: 'center', alignItems: 'center', }, CompnyWrap:{ bottom:70, }, circleWrap:{ height:150, width:150, justifyContent:'center', alignItems:'center', }, navigateToRunScreen:{ fontSize:20, }, shadow: { flex:1, backgroundColor: 'transparent', justifyContent: 'center', }, overlay:{ height:deviceHeight, width: deviceWidth, backgroundColor: 'transparent', justifyContent: 'center', }, shadow: { height:deviceHeight, width: deviceWidth, backgroundColor: 'white', justifyContent: 'center', }, loadingFlex:{ justifyContent: 'center', alignItems: 'center', flex:1, }, }) export default LodingRunScreen;
client/app/scripts/components/topology-options.js
kinvolk/scope
import React from 'react'; import { connect } from 'react-redux'; import { Set as makeSet, Map as makeMap } from 'immutable'; import includes from 'lodash/includes'; import { trackAnalyticsEvent } from '../utils/tracking-utils'; import { getCurrentTopologyOptions } from '../utils/topology-utils'; import { activeTopologyOptionsSelector } from '../selectors/topology'; import TopologyOptionAction from './topology-option-action'; import { changeTopologyOption } from '../actions/app-actions'; class TopologyOptions extends React.Component { constructor(props, context) { super(props, context); this.trackOptionClick = this.trackOptionClick.bind(this); this.handleOptionClick = this.handleOptionClick.bind(this); this.handleNoneClick = this.handleNoneClick.bind(this); } trackOptionClick(optionId, nextOptions) { trackAnalyticsEvent('scope.topology.option.click', { optionId, value: nextOptions, layout: this.props.topologyViewMode, topologyId: this.props.currentTopology.get('id'), parentTopologyId: this.props.currentTopology.get('parentId'), }); } handleOptionClick(optionId, value, topologyId) { let nextOptions = [value]; const { activeOptions, options } = this.props; const selectedOption = options.find(o => o.get('id') === optionId); if (selectedOption.get('selectType') === 'union') { // Multi-select topology options (such as k8s namespaces) are handled here. // Users can select one, many, or none of these options. // The component builds an array of the next selected values that are sent to the action. const opts = activeOptions.toJS(); const selected = selectedOption.get('id'); const selectedActiveOptions = opts[selected] || []; const isSelectedAlready = includes(selectedActiveOptions, value); if (isSelectedAlready) { // Remove the option if it is already selected nextOptions = selectedActiveOptions.filter(o => o !== value); } else { // Add it to the array if it's not selected nextOptions = selectedActiveOptions.concat(value); } // Since the user is clicking an option, remove the highlighting from the none option, // unless they are removing the last option. In that case, default to the none label. // Note that since the other ids are potentially user-controlled (eg. k8s namespaces), // the only string we can use for the none option is the empty string '', // since that can't collide. if (nextOptions.length === 0) { nextOptions = ['']; } else { nextOptions = nextOptions.filter(o => o !== ''); } } this.trackOptionClick(optionId, nextOptions); this.props.changeTopologyOption(optionId, nextOptions, topologyId); } handleNoneClick(optionId, value, topologyId) { const nextOptions = ['']; this.trackOptionClick(optionId, nextOptions); this.props.changeTopologyOption(optionId, nextOptions, topologyId); } renderOption(option) { const { activeOptions, currentTopologyId } = this.props; const optionId = option.get('id'); // Make the active value be the intersection of the available options // and the active selection and use the default value if there is no // overlap. It seems intuitive that active selection would always be a // subset of available option, but the exception can happen when going // back in time (making available options change, while not touching // the selection). // TODO: This logic should probably be made consistent with how topology // selection is handled when time travelling, especially when the name- // spaces are brought under category selection. // TODO: Consider extracting this into a global selector. let activeValue = option.get('defaultValue'); if (activeOptions && activeOptions.has(optionId)) { const activeSelection = makeSet(activeOptions.get(optionId)); const availableOptions = makeSet(option.get('options').map(o => o.get('value'))); const intersection = activeSelection.intersect(availableOptions); if (!intersection.isEmpty()) { activeValue = intersection.toJS(); } } const noneItem = makeMap({ value: '', label: option.get('noneLabel') }); return ( <div className="topology-option" key={optionId}> <div className="topology-option-wrapper"> {option.get('options').map(item => ( <TopologyOptionAction onClick={this.handleOptionClick} optionId={optionId} topologyId={currentTopologyId} key={item.get('value')} activeValue={activeValue} item={item} /> ))} {option.get('selectType') === 'union' && <TopologyOptionAction onClick={this.handleNoneClick} optionId={optionId} item={noneItem} topologyId={currentTopologyId} activeValue={activeValue} /> } </div> </div> ); } render() { const { options } = this.props; return ( <div className="topology-options"> {options && options.toIndexedSeq().map(option => this.renderOption(option))} </div> ); } } function mapStateToProps(state) { return { options: getCurrentTopologyOptions(state), topologyViewMode: state.get('topologyViewMode'), currentTopology: state.get('currentTopology'), currentTopologyId: state.get('currentTopologyId'), activeOptions: activeTopologyOptionsSelector(state) }; } export default connect( mapStateToProps, { changeTopologyOption } )(TopologyOptions);
ajax/libs/react-dom/18.0.0-rc.0-next-790b5246f-20220118/cjs/react-dom-server.browser.production.min.js
cdnjs/cdnjs
/** * @license React * react-dom-server.browser.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict';var k=require("object-assign"),aa=require("react");function l(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length;c++)b+="&args[]="+encodeURIComponent(arguments[c]);return"Minified React error #"+a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function n(a,b){a.enqueue(b);return 0<a.desiredSize}var ba=new TextEncoder;function p(a){return ba.encode(a)} function t(a){return ba.encode(a)}function ca(a,b){"function"===typeof a.error?a.error(b):a.close()}var u=Object.prototype.hasOwnProperty,da=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,ea={},fa={}; function ha(a){if(u.call(fa,a))return!0;if(u.call(ea,a))return!1;if(da.test(a))return fa[a]=!0;ea[a]=!0;return!1}function v(a,b,c,d,f,e,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=f;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=e;this.removeEmptyString=g}var w={}; "children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){w[a]=new v(a,0,!1,a,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];w[b]=new v(b,1,!1,a[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){w[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1)}); ["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){w[a]=new v(a,2,!1,a,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){w[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)}); ["checked","multiple","muted","selected"].forEach(function(a){w[a]=new v(a,3,!0,a,null,!1,!1)});["capture","download"].forEach(function(a){w[a]=new v(a,4,!1,a,null,!1,!1)});["cols","rows","size","span"].forEach(function(a){w[a]=new v(a,6,!1,a,null,!1,!1)});["rowSpan","start"].forEach(function(a){w[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ia=/[\-:]([a-z])/g;function ja(a){return a[1].toUpperCase()} "accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(ia, ja);w[b]=new v(b,1,!1,a,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(ia,ja);w[b]=new v(b,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(ia,ja);w[b]=new v(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(a){w[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1)}); w.xlinkHref=new v("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){w[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0)}); var x={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0, fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},ka=["Webkit","ms","Moz","O"];Object.keys(x).forEach(function(a){ka.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);x[b]=x[a]})});var la=/["'&<>]/; function y(a){if("boolean"===typeof a||"number"===typeof a)return""+a;a=""+a;var b=la.exec(a);if(b){var c="",d,f=0;for(d=b.index;d<a.length;d++){switch(a.charCodeAt(d)){case 34:b="&quot;";break;case 38:b="&amp;";break;case 39:b="&#x27;";break;case 60:b="&lt;";break;case 62:b="&gt;";break;default:continue}f!==d&&(c+=a.substring(f,d));f=d+1;c+=b}a=f!==d?c+a.substring(f,d):c}return a} var ma=/([A-Z])/g,na=/^ms-/,oa=Array.isArray,pa=t("<script>"),qa=t("\x3c/script>"),ra=t('<script src="'),sa=t('<script type="module" src="'),ta=t('" async="">\x3c/script>'); function ua(a,b,c,d,f){a=void 0===a?"":a;b=void 0===b?pa:t('<script nonce="'+y(b)+'">');var e=[];void 0!==c&&e.push(b,p(y(c)),qa);if(void 0!==d)for(c=0;c<d.length;c++)e.push(ra,p(y(d[c])),ta);if(void 0!==f)for(d=0;d<f.length;d++)e.push(sa,p(y(f[d])),ta);return{bootstrapChunks:e,startInlineScript:b,placeholderPrefix:t(a+"P:"),segmentPrefix:t(a+"S:"),boundaryPrefix:a+"B:",idPrefix:a+"R:",nextSuspenseID:0,sentCompleteSegmentFunction:!1,sentCompleteBoundaryFunction:!1,sentClientRenderFunction:!1}} function z(a,b){return{insertionMode:a,selectedValue:b}}function va(a){return z("http://www.w3.org/2000/svg"===a?2:"http://www.w3.org/1998/Math/MathML"===a?3:0,null)} function wa(a,b,c){switch(b){case "select":return z(1,null!=c.value?c.value:c.defaultValue);case "svg":return z(2,null);case "math":return z(3,null);case "foreignObject":return z(1,null);case "table":return z(4,null);case "thead":case "tbody":case "tfoot":return z(5,null);case "colgroup":return z(7,null);case "tr":return z(6,null)}return 4<=a.insertionMode||0===a.insertionMode?z(1,null):a}var xa=t("\x3c!-- --\x3e"),ya=new Map,za=t(' style="'),Aa=t(":"),Ba=t(";"); function Ca(a,b,c){if("object"!==typeof c)throw Error(l(62));b=!0;for(var d in c)if(u.call(c,d)){var f=c[d];if(null!=f&&"boolean"!==typeof f&&""!==f){if(0===d.indexOf("--")){var e=p(y(d));f=p(y((""+f).trim()))}else{e=d;var g=ya.get(e);void 0!==g?e=g:(g=t(y(e.replace(ma,"-$1").toLowerCase().replace(na,"-ms-"))),ya.set(e,g),e=g);f="number"===typeof f?0===f||u.call(x,d)?p(""+f):p(f+"px"):p(y((""+f).trim()))}b?(b=!1,a.push(za,e,Aa,f)):a.push(Ba,e,Aa,f)}}b||a.push(B)} var D=t(" "),E=t('="'),B=t('"'),Da=t('=""'); function G(a,b,c,d){switch(c){case "style":Ca(a,b,d);return;case "defaultValue":case "defaultChecked":case "innerHTML":case "suppressContentEditableWarning":case "suppressHydrationWarning":return}if(!(2<c.length)||"o"!==c[0]&&"O"!==c[0]||"n"!==c[1]&&"N"!==c[1])if(b=w.hasOwnProperty(c)?w[c]:null,null!==b){switch(typeof d){case "function":case "symbol":return;case "boolean":if(!b.acceptsBooleans)return}c=p(b.attributeName);switch(b.type){case 3:d&&a.push(D,c,Da);break;case 4:!0===d?a.push(D,c,Da):!1!== d&&a.push(D,c,E,p(y(d)),B);break;case 5:isNaN(d)||a.push(D,c,E,p(y(d)),B);break;case 6:!isNaN(d)&&1<=d&&a.push(D,c,E,p(y(d)),B);break;default:b.sanitizeURL&&(d=""+d),a.push(D,c,E,p(y(d)),B)}}else if(ha(c)){switch(typeof d){case "function":case "symbol":return;case "boolean":if(b=c.toLowerCase().slice(0,5),"data-"!==b&&"aria-"!==b)return}a.push(D,p(c),E,p(y(d)),B)}}var H=t(">"),Ea=t("/>"); function I(a,b,c){if(null!=b){if(null!=c)throw Error(l(60));if("object"!==typeof b||!("__html"in b))throw Error(l(61));b=b.__html;null!==b&&void 0!==b&&a.push(p(""+b))}}function Fa(a){var b="";aa.Children.forEach(a,function(a){null!=a&&(b+=a)});return b}var Ga=t(' selected=""'); function Ha(a,b,c,d){a.push(J(c));var f=c=null,e;for(e in b)if(u.call(b,e)){var g=b[e];if(null!=g)switch(e){case "children":c=g;break;case "dangerouslySetInnerHTML":f=g;break;default:G(a,d,e,g)}}a.push(H);I(a,f,c);return"string"===typeof c?(a.push(p(y(c))),null):c}var Ia=t("\n"),Ja=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,Ka=new Map;function J(a){var b=Ka.get(a);if(void 0===b){if(!Ja.test(a))throw Error(l(65,a));b=t("<"+a);Ka.set(a,b)}return b}var La=t("<!DOCTYPE html>"); function Ma(a,b,c,d,f){switch(b){case "select":a.push(J("select"));var e=null,g=null;for(q in c)if(u.call(c,q)){var h=c[q];if(null!=h)switch(q){case "children":e=h;break;case "dangerouslySetInnerHTML":g=h;break;case "defaultValue":case "value":break;default:G(a,d,q,h)}}a.push(H);I(a,g,e);return e;case "option":g=f.selectedValue;a.push(J("option"));var m=h=null,r=null;var q=null;for(e in c)if(u.call(c,e)&&(b=c[e],null!=b))switch(e){case "children":h=b;break;case "selected":r=b;break;case "dangerouslySetInnerHTML":q= b;break;case "value":m=b;default:G(a,d,e,b)}if(null!==g)if(c=null!==m?""+m:Fa(h),oa(g))for(d=0;d<g.length;d++){if(""+g[d]===c){a.push(Ga);break}}else g===c&&a.push(Ga);else r&&a.push(Ga);a.push(H);I(a,q,h);return h;case "textarea":a.push(J("textarea"));q=g=e=null;for(h in c)if(u.call(c,h)&&(m=c[h],null!=m))switch(h){case "children":q=m;break;case "value":e=m;break;case "defaultValue":g=m;break;case "dangerouslySetInnerHTML":throw Error(l(91));default:G(a,d,h,m)}null===e&&null!==g&&(e=g);a.push(H); if(null!=q){if(null!=e)throw Error(l(92));if(oa(q)&&1<q.length)throw Error(l(93));e=""+q}"string"===typeof e&&"\n"===e[0]&&a.push(Ia);return e;case "input":a.push(J("input"));m=q=h=e=null;for(g in c)if(u.call(c,g)&&(r=c[g],null!=r))switch(g){case "children":case "dangerouslySetInnerHTML":throw Error(l(399,"input"));case "defaultChecked":m=r;break;case "defaultValue":h=r;break;case "checked":q=r;break;case "value":e=r;break;default:G(a,d,g,r)}null!==q?G(a,d,"checked",q):null!==m&&G(a,d,"checked",m); null!==e?G(a,d,"value",e):null!==h&&G(a,d,"value",h);a.push(Ea);return null;case "menuitem":a.push(J("menuitem"));for(var C in c)if(u.call(c,C)&&(e=c[C],null!=e))switch(C){case "children":case "dangerouslySetInnerHTML":throw Error(l(400));default:G(a,d,C,e)}a.push(H);return null;case "listing":case "pre":a.push(J(b));g=e=null;for(m in c)if(u.call(c,m)&&(h=c[m],null!=h))switch(m){case "children":e=h;break;case "dangerouslySetInnerHTML":g=h;break;default:G(a,d,m,h)}a.push(H);if(null!=g){if(null!=e)throw Error(l(60)); if("object"!==typeof g||!("__html"in g))throw Error(l(61));c=g.__html;null!==c&&void 0!==c&&("string"===typeof c&&0<c.length&&"\n"===c[0]?a.push(Ia,p(c)):a.push(p(""+c)))}"string"===typeof e&&"\n"===e[0]&&a.push(Ia);return e;case "area":case "base":case "br":case "col":case "embed":case "hr":case "img":case "keygen":case "link":case "meta":case "param":case "source":case "track":case "wbr":a.push(J(b));for(var F in c)if(u.call(c,F)&&(e=c[F],null!=e))switch(F){case "children":case "dangerouslySetInnerHTML":throw Error(l(399, b));default:G(a,d,F,e)}a.push(Ea);return null;case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return Ha(a,c,b,d);case "html":return 0===f.insertionMode&&a.push(La),Ha(a,c,b,d);default:if(-1===b.indexOf("-")&&"string"!==typeof c.is)return Ha(a,c,b,d);a.push(J(b));g=e=null;for(r in c)if(u.call(c,r)&&(h=c[r],null!=h))switch(r){case "children":e=h;break;case "dangerouslySetInnerHTML":g= h;break;case "style":Ca(a,d,h);break;case "suppressContentEditableWarning":case "suppressHydrationWarning":break;default:ha(r)&&"function"!==typeof h&&"symbol"!==typeof h&&a.push(D,p(r),E,p(y(h)),B)}a.push(H);I(a,g,e);return e}}var Na=t("</"),Oa=t(">"),Pa=t('<template id="'),Qa=t('"></template>'),Ra=t("\x3c!--$--\x3e"),Sa=t('\x3c!--$?--\x3e<template id="'),Ta=t('"></template>'),Ua=t("\x3c!--$!--\x3e"),Va=t("\x3c!--/$--\x3e"); function Wa(a,b,c){n(a,Sa);if(null===c)throw Error(l(395));n(a,c);return n(a,Ta)} var Xa=t('<div hidden id="'),Ya=t('">'),Za=t("</div>"),$a=t('<svg aria-hidden="true" style="display:none" id="'),ab=t('">'),bb=t("</svg>"),cb=t('<math aria-hidden="true" style="display:none" id="'),db=t('">'),eb=t("</math>"),fb=t('<table hidden id="'),gb=t('">'),hb=t("</table>"),ib=t('<table hidden><tbody id="'),jb=t('">'),kb=t("</tbody></table>"),lb=t('<table hidden><tr id="'),mb=t('">'),nb=t("</tr></table>"),ob=t('<table hidden><colgroup id="'),pb=t('">'),qb=t("</colgroup></table>"); function rb(a,b,c,d){switch(c.insertionMode){case 0:case 1:return n(a,Xa),n(a,b.segmentPrefix),n(a,p(d.toString(16))),n(a,Ya);case 2:return n(a,$a),n(a,b.segmentPrefix),n(a,p(d.toString(16))),n(a,ab);case 3:return n(a,cb),n(a,b.segmentPrefix),n(a,p(d.toString(16))),n(a,db);case 4:return n(a,fb),n(a,b.segmentPrefix),n(a,p(d.toString(16))),n(a,gb);case 5:return n(a,ib),n(a,b.segmentPrefix),n(a,p(d.toString(16))),n(a,jb);case 6:return n(a,lb),n(a,b.segmentPrefix),n(a,p(d.toString(16))),n(a,mb);case 7:return n(a, ob),n(a,b.segmentPrefix),n(a,p(d.toString(16))),n(a,pb);default:throw Error(l(397));}}function sb(a,b){switch(b.insertionMode){case 0:case 1:return n(a,Za);case 2:return n(a,bb);case 3:return n(a,eb);case 4:return n(a,hb);case 5:return n(a,kb);case 6:return n(a,nb);case 7:return n(a,qb);default:throw Error(l(397));}} var tb=t('function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("'),ub=t('$RS("'),vb=t('","'),wb=t('")\x3c/script>'),xb=t('function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}};$RC("'), yb=t('$RC("'),zb=t('","'),Ab=t('")\x3c/script>'),Bb=t('function $RX(a){if(a=document.getElementById(a))a=a.previousSibling,a.data="$!",a._reactRetry&&a._reactRetry()};$RX("'),Cb=t('$RX("'),Db=t('")\x3c/script>'),Eb=60103,Fb=60106,Gb=60107,Hb=60108,Ib=60114,Jb=60109,Kb=60110,Lb=60112,Mb=60113,Nb=60120,Ob=60115,K=60116,Pb=60119,Qb=60129,Rb=60131,Sb=60132; if("function"===typeof Symbol&&Symbol.for){var L=Symbol.for;Eb=L("react.element");Fb=L("react.portal");Gb=L("react.fragment");Hb=L("react.strict_mode");Ib=L("react.profiler");Jb=L("react.provider");Kb=L("react.context");Lb=L("react.forward_ref");Mb=L("react.suspense");Nb=L("react.suspense_list");Ob=L("react.memo");K=L("react.lazy");Pb=L("react.scope");Qb=L("react.debug_trace_mode");Rb=L("react.legacy_hidden");Sb=L("react.cache")}var Tb="function"===typeof Symbol&&Symbol.iterator; function Ub(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case Gb:return"Fragment";case Fb:return"Portal";case Ib:return"Profiler";case Hb:return"StrictMode";case Mb:return"Suspense";case Nb:return"SuspenseList";case Sb:return"Cache"}if("object"===typeof a)switch(a.$$typeof){case Kb:return(a.displayName||"Context")+".Consumer";case Jb:return(a._context.displayName||"Context")+".Provider";case Lb:var b=a.render;a=a.displayName; a||(a=b.displayName||b.name||"",a=""!==a?"ForwardRef("+a+")":"ForwardRef");return a;case Ob:return b=a.displayName||null,null!==b?b:Ub(a.type)||"Memo";case K:b=a._payload;a=a._init;try{return Ub(a(b))}catch(c){}}return null}var Vb={};function Wb(a,b){a=a.contextTypes;if(!a)return Vb;var c={},d;for(d in a)c[d]=b[d];return c}var M=null; function N(a,b){if(a!==b){a.context._currentValue=a.parentValue;a=a.parent;var c=b.parent;if(null===a){if(null!==c)throw Error(l(401));}else{if(null===c)throw Error(l(401));N(a,c);b.context._currentValue=b.value}}}function Xb(a){a.context._currentValue=a.parentValue;a=a.parent;null!==a&&Xb(a)}function Yb(a){var b=a.parent;null!==b&&Yb(b);a.context._currentValue=a.value} function Zb(a,b){a.context._currentValue=a.parentValue;a=a.parent;if(null===a)throw Error(l(402));a.depth===b.depth?N(a,b):Zb(a,b)}function $b(a,b){var c=b.parent;if(null===c)throw Error(l(402));a.depth===c.depth?N(a,c):$b(a,c);b.context._currentValue=b.value}function O(a){var b=M;b!==a&&(null===b?Yb(a):null===a?Xb(b):b.depth===a.depth?N(b,a):b.depth>a.depth?Zb(b,a):$b(b,a),M=a)} var ac={isMounted:function(){return!1},enqueueSetState:function(a,b){a=a._reactInternals;null!==a.queue&&a.queue.push(b)},enqueueReplaceState:function(a,b){a=a._reactInternals;a.replace=!0;a.queue=[b]},enqueueForceUpdate:function(){}}; function bc(a,b,c,d){var f=void 0!==a.state?a.state:null;a.updater=ac;a.props=c;a.state=f;var e={queue:[],replace:!1};a._reactInternals=e;var g=b.contextType;a.context="object"===typeof g&&null!==g?g._currentValue:d;g=b.getDerivedStateFromProps;"function"===typeof g&&(g=g(c,f),f=null===g||void 0===g?f:k({},f,g),a.state=f);if("function"!==typeof b.getDerivedStateFromProps&&"function"!==typeof a.getSnapshotBeforeUpdate&&("function"===typeof a.UNSAFE_componentWillMount||"function"===typeof a.componentWillMount))if(b= a.state,"function"===typeof a.componentWillMount&&a.componentWillMount(),"function"===typeof a.UNSAFE_componentWillMount&&a.UNSAFE_componentWillMount(),b!==a.state&&ac.enqueueReplaceState(a,a.state,null),null!==e.queue&&0<e.queue.length)if(b=e.queue,g=e.replace,e.queue=null,e.replace=!1,g&&1===b.length)a.state=b[0];else{e=g?b[0]:a.state;f=!0;for(g=g?1:0;g<b.length;g++){var h=b[g];h="function"===typeof h?h.call(a,e,c,d):h;null!=h&&(f?(f=!1,e=k({},e,h)):k(e,h))}a.state=e}else e.queue=null} var cc={id:1,overflow:""};function dc(a,b,c){var d=a.id;a=a.overflow;var f=32-P(d)-1;d&=~(1<<f);c+=1;var e=32-P(b)+f;if(30<e){var g=f-f%5;e=(d&(1<<g)-1).toString(32);d>>=g;f-=g;return{id:1<<32-P(b)+f|c<<f|d,overflow:e+a}}return{id:1<<e|c<<f|d,overflow:a}}var P=Math.clz32?Math.clz32:ec,fc=Math.log,gc=Math.LN2;function ec(a){a>>>=0;return 0===a?32:31-(fc(a)/gc|0)|0}function hc(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b} var ic="function"===typeof Object.is?Object.is:hc,Q=null,jc=null,R=null,S=null,T=!1,U=!1,V=0,W=null,kc=0;function X(){if(null===Q)throw Error(l(321));return Q}function lc(){if(0<kc)throw Error(l(312));return{memoizedState:null,queue:null,next:null}}function mc(){null===S?null===R?(T=!1,R=S=lc()):(T=!0,S=R):null===S.next?(T=!1,S=S.next=lc()):(T=!0,S=S.next);return S}function nc(){jc=Q=null;U=!1;R=null;kc=0;S=W=null}function oc(a,b){return"function"===typeof b?b(a):b} function pc(a,b,c){Q=X();S=mc();if(T){var d=S.queue;b=d.dispatch;if(null!==W&&(c=W.get(d),void 0!==c)){W.delete(d);d=S.memoizedState;do d=a(d,c.action),c=c.next;while(null!==c);S.memoizedState=d;return[d,b]}return[S.memoizedState,b]}a=a===oc?"function"===typeof b?b():b:void 0!==c?c(b):b;S.memoizedState=a;a=S.queue={last:null,dispatch:null};a=a.dispatch=qc.bind(null,Q,a);return[S.memoizedState,a]} function rc(a,b){Q=X();S=mc();b=void 0===b?null:b;if(null!==S){var c=S.memoizedState;if(null!==c&&null!==b){var d=c[1];a:if(null===d)d=!1;else{for(var f=0;f<d.length&&f<b.length;f++)if(!ic(b[f],d[f])){d=!1;break a}d=!0}if(d)return c[0]}}a=a();S.memoizedState=[a,b];return a}function qc(a,b,c){if(25<=kc)throw Error(l(301));if(a===Q)if(U=!0,a={action:c,next:null},null===W&&(W=new Map),c=W.get(b),void 0===c)W.set(b,a);else{for(b=c;null!==b.next;)b=b.next;b.next=a}}function sc(){throw Error(l(394));} function tc(){} var vc={readContext:function(a){return a._currentValue},useContext:function(a){X();return a._currentValue},useMemo:rc,useReducer:pc,useRef:function(a){Q=X();S=mc();var b=S.memoizedState;return null===b?(a={current:a},S.memoizedState=a):b},useState:function(a){return pc(oc,a)},useInsertionEffect:tc,useLayoutEffect:function(){},useCallback:function(a,b){return rc(function(){return a},b)},useImperativeHandle:tc,useEffect:tc,useDebugValue:tc,useDeferredValue:function(a){X();return a},useTransition:function(){X();return[!1, sc]},useId:function(){var a=jc.treeContext;var b=a.overflow;a=a.id;a=(a&~(1<<32-P(a)-1)).toString(32)+b;var c=uc;if(null===c)throw Error(l(404));b=V++;a=c.idPrefix+a;0<b&&(a+=":"+b.toString(32));return a},useMutableSource:function(a,b){X();return b(a._source)},useSyncExternalStore:function(a,b,c){if(void 0===c)throw Error(l(407));return c()}},uc=null,wc=aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher;function xc(a){console.error(a)}function yc(){} function zc(a,b,c,d,f,e,g){var h=[],m=new Set;b={destination:null,responseState:b,progressiveChunkSize:void 0===d?12800:d,status:0,fatalError:null,nextSegmentId:0,allPendingTasks:0,pendingRootTasks:0,completedRootSegment:null,abortableTasks:m,pingedTasks:h,clientRenderedBoundaries:[],completedBoundaries:[],partialBoundaries:[],onError:void 0===f?xc:f,onCompleteAll:void 0===e?yc:e,onCompleteShell:void 0===g?yc:g};c=Ac(b,0,null,c);c.parentFlushed=!0;a=Bc(b,a,null,c,m,Vb,null,cc);h.push(a);return b} function Bc(a,b,c,d,f,e,g,h){a.allPendingTasks++;null===c?a.pendingRootTasks++:c.pendingTasks++;var m={node:b,ping:function(){var b=a.pingedTasks;b.push(m);1===b.length&&Cc(a)},blockedBoundary:c,blockedSegment:d,abortSet:f,legacyContext:e,context:g,treeContext:h};f.add(m);return m}function Ac(a,b,c,d){return{status:0,id:-1,index:b,parentFlushed:!1,chunks:[],children:[],formatContext:d,boundary:c}}function Y(a,b){a=a.onError;a(b)} function Dc(a,b){null!==a.destination?(a.status=2,ca(a.destination,b)):(a.status=1,a.fatalError=b)}function Ec(a,b,c,d,f){Q={};jc=b;V=0;for(a=c(d,f);U;)U=!1,V=0,kc+=1,S=null,a=c(d,f);nc();return a} function Fc(a,b,c,d){var f=c.render(),e=d.childContextTypes;if(null!==e&&void 0!==e){var g=b.legacyContext;if("function"!==typeof c.getChildContext)d=g;else{c=c.getChildContext();for(var h in c)if(!(h in e))throw Error(l(108,Ub(d)||"Unknown",h));d=k({},g,c)}b.legacyContext=d;Z(a,b,f);b.legacyContext=g}else Z(a,b,f)}function Gc(a,b){if(a&&a.defaultProps){b=k({},b);a=a.defaultProps;for(var c in a)void 0===b[c]&&(b[c]=a[c]);return b}return b} function Hc(a,b,c,d,f){if("function"===typeof c)if(c.prototype&&c.prototype.isReactComponent){f=Wb(c,b.legacyContext);var e=c.contextType;e=new c(d,"object"===typeof e&&null!==e?e._currentValue:f);bc(e,c,d,f);Fc(a,b,e,c)}else{e=Wb(c,b.legacyContext);f=Ec(a,b,c,d,e);var g=0!==V;if("object"===typeof f&&null!==f&&"function"===typeof f.render&&void 0===f.$$typeof)bc(f,c,d,e),Fc(a,b,f,c);else if(g){d=b.treeContext;b.treeContext=dc(d,1,0);try{Z(a,b,f)}finally{b.treeContext=d}}else Z(a,b,f)}else if("string"=== typeof c)switch(f=b.blockedSegment,e=Ma(f.chunks,c,d,a.responseState,f.formatContext),g=f.formatContext,f.formatContext=wa(g,c,d),Ic(a,b,e),f.formatContext=g,c){case "area":case "base":case "br":case "col":case "embed":case "hr":case "img":case "input":case "keygen":case "link":case "meta":case "param":case "source":case "track":case "wbr":break;default:f.chunks.push(Na,p(c),Oa)}else{switch(c){case Rb:case Qb:case Hb:case Ib:case Gb:Z(a,b,d.children);return;case Nb:Z(a,b,d.children);return;case Pb:throw Error(l(343)); case Mb:a:{c=b.blockedBoundary;f=b.blockedSegment;e=d.fallback;d=d.children;g=new Set;var h={id:null,rootSegmentID:-1,parentFlushed:!1,pendingTasks:0,forceClientRender:!1,completedSegments:[],byteSize:0,fallbackAbortableTasks:g},m=Ac(a,f.chunks.length,h,f.formatContext);f.children.push(m);var r=Ac(a,0,null,f.formatContext);r.parentFlushed=!0;b.blockedBoundary=h;b.blockedSegment=r;try{if(Ic(a,b,d),r.status=1,h.completedSegments.push(r),0===h.pendingTasks)break a}catch(q){r.status=4,Y(a,q),h.forceClientRender= !0}finally{b.blockedBoundary=c,b.blockedSegment=f}b=Bc(a,e,c,m,g,b.legacyContext,b.context,b.treeContext);a.pingedTasks.push(b)}return}if("object"===typeof c&&null!==c)switch(c.$$typeof){case Lb:d=Ec(a,b,c.render,d,f);if(0!==V){c=b.treeContext;b.treeContext=dc(c,1,0);try{Z(a,b,d)}finally{b.treeContext=c}}else Z(a,b,d);return;case Ob:c=c.type;d=Gc(c,d);Hc(a,b,c,d,f);return;case Jb:f=d.children;c=c._context;d=d.value;e=c._currentValue;c._currentValue=d;g=M;M=d={parent:g,depth:null===g?0:g.depth+1,context:c, parentValue:e,value:d};b.context=d;Z(a,b,f);a=M;if(null===a)throw Error(l(403));a.context._currentValue=a.parentValue;a=M=a.parent;b.context=a;return;case Kb:d=d.children;d=d(c._currentValue);Z(a,b,d);return;case K:f=c._init;c=f(c._payload);d=Gc(c,d);Hc(a,b,c,d,void 0);return}throw Error(l(130,null==c?c:typeof c,""));}} function Z(a,b,c){b.node=c;if("object"===typeof c&&null!==c){switch(c.$$typeof){case Eb:Hc(a,b,c.type,c.props,c.ref);return;case Fb:throw Error(l(257));case K:var d=c._init;c=d(c._payload);Z(a,b,c);return}if(oa(c)){Jc(a,b,c);return}null===c||"object"!==typeof c?d=null:(d=Tb&&c[Tb]||c["@@iterator"],d="function"===typeof d?d:null);if(d&&(d=d.call(c))){c=d.next();if(!c.done){var f=[];do f.push(c.value),c=d.next();while(!c.done);Jc(a,b,f)}return}b=Object.prototype.toString.call(c);throw Error(l(31,"[object Object]"=== b?"object with keys {"+Object.keys(c).join(", ")+"}":b));}"string"===typeof c?""!==c&&b.blockedSegment.chunks.push(p(y(c)),xa):"number"===typeof c&&(a=""+c,""!==a&&b.blockedSegment.chunks.push(p(y(a)),xa))}function Jc(a,b,c){for(var d=c.length,f=0;f<d;f++){var e=b.treeContext;b.treeContext=dc(e,d,f);try{Ic(a,b,c[f])}finally{b.treeContext=e}}} function Ic(a,b,c){var d=b.blockedSegment.formatContext,f=b.legacyContext,e=b.context;try{return Z(a,b,c)}catch(m){if(nc(),"object"===typeof m&&null!==m&&"function"===typeof m.then){c=m;var g=b.blockedSegment,h=Ac(a,g.chunks.length,null,g.formatContext);g.children.push(h);a=Bc(a,b.node,b.blockedBoundary,h,b.abortSet,b.legacyContext,b.context,b.treeContext).ping;c.then(a,a);b.blockedSegment.formatContext=d;b.legacyContext=f;b.context=e;O(e)}else throw b.blockedSegment.formatContext=d,b.legacyContext= f,b.context=e,O(e),m;}}function Kc(a){var b=a.blockedBoundary;a=a.blockedSegment;a.status=3;Lc(this,b,a)} function Mc(a){var b=a.blockedBoundary;a.blockedSegment.status=3;null===b?(this.allPendingTasks--,2!==this.status&&(this.status=2,null!==this.destination&&this.destination.close())):(b.pendingTasks--,b.forceClientRender||(b.forceClientRender=!0,b.parentFlushed&&this.clientRenderedBoundaries.push(b)),b.fallbackAbortableTasks.forEach(Mc,this),b.fallbackAbortableTasks.clear(),this.allPendingTasks--,0===this.allPendingTasks&&(a=this.onCompleteAll,a()))} function Lc(a,b,c){if(null===b){if(c.parentFlushed){if(null!==a.completedRootSegment)throw Error(l(389));a.completedRootSegment=c}a.pendingRootTasks--;0===a.pendingRootTasks&&(b=a.onCompleteShell,b())}else if(b.pendingTasks--,!b.forceClientRender)if(0===b.pendingTasks)c.parentFlushed&&1===c.status&&b.completedSegments.push(c),b.parentFlushed&&a.completedBoundaries.push(b),b.fallbackAbortableTasks.forEach(Kc,a),b.fallbackAbortableTasks.clear();else if(c.parentFlushed&&1===c.status){var d=b.completedSegments; d.push(c);1===d.length&&b.parentFlushed&&a.partialBoundaries.push(b)}a.allPendingTasks--;0===a.allPendingTasks&&(a=a.onCompleteAll,a())} function Cc(a){if(2!==a.status){var b=M,c=wc.current;wc.current=vc;var d=uc;uc=a.responseState;try{var f=a.pingedTasks,e;for(e=0;e<f.length;e++){var g=f[e];var h=a,m=g.blockedSegment;if(0===m.status){O(g.context);try{Z(h,g,g.node),g.abortSet.delete(g),m.status=1,Lc(h,g.blockedBoundary,m)}catch(A){if(nc(),"object"===typeof A&&null!==A&&"function"===typeof A.then){var r=g.ping;A.then(r,r)}else{g.abortSet.delete(g);m.status=4;var q=g.blockedBoundary,C=A;Y(h,C);null===q?Dc(h,C):(q.pendingTasks--,q.forceClientRender|| (q.forceClientRender=!0,q.parentFlushed&&h.clientRenderedBoundaries.push(q)));h.allPendingTasks--;if(0===h.allPendingTasks){var F=h.onCompleteAll;F()}}}finally{}}}f.splice(0,e);null!==a.destination&&Nc(a,a.destination)}catch(A){Y(a,A),Dc(a,A)}finally{uc=d,wc.current=c,c===vc&&O(b)}}} function Oc(a,b,c){c.parentFlushed=!0;switch(c.status){case 0:var d=c.id=a.nextSegmentId++;a=a.responseState;n(b,Pa);n(b,a.placeholderPrefix);a=p(d.toString(16));n(b,a);return n(b,Qa);case 1:c.status=2;var f=!0;d=c.chunks;var e=0;c=c.children;for(var g=0;g<c.length;g++){for(f=c[g];e<f.index;e++)n(b,d[e]);f=Pc(a,b,f)}for(;e<d.length;e++)f=n(b,d[e]);return f;default:throw Error(l(390));}} function Pc(a,b,c){var d=c.boundary;if(null===d)return Oc(a,b,c);d.parentFlushed=!0;if(d.forceClientRender)n(b,Ua),Oc(a,b,c);else if(0<d.pendingTasks){d.rootSegmentID=a.nextSegmentId++;0<d.completedSegments.length&&a.partialBoundaries.push(d);var f=a.responseState;var e=f.nextSuspenseID++;f=t(f.boundaryPrefix+e.toString(16));d=d.id=f;Wa(b,a.responseState,d);Oc(a,b,c)}else if(d.byteSize>a.progressiveChunkSize)d.rootSegmentID=a.nextSegmentId++,a.completedBoundaries.push(d),Wa(b,a.responseState,d.id), Oc(a,b,c);else{n(b,Ra);c=d.completedSegments;if(1!==c.length)throw Error(l(391));Pc(a,b,c[0])}return n(b,Va)}function Qc(a,b,c){rb(b,a.responseState,c.formatContext,c.id);Pc(a,b,c);return sb(b,c.formatContext)} function Rc(a,b,c){for(var d=c.completedSegments,f=0;f<d.length;f++)Sc(a,b,c,d[f]);d.length=0;a=a.responseState;d=c.id;c=c.rootSegmentID;n(b,a.startInlineScript);a.sentCompleteBoundaryFunction?n(b,yb):(a.sentCompleteBoundaryFunction=!0,n(b,xb));if(null===d)throw Error(l(395));c=p(c.toString(16));n(b,d);n(b,zb);n(b,a.segmentPrefix);n(b,c);return n(b,Ab)} function Sc(a,b,c,d){if(2===d.status)return!0;var f=d.id;if(-1===f){if(-1===(d.id=c.rootSegmentID))throw Error(l(392));return Qc(a,b,d)}Qc(a,b,d);a=a.responseState;n(b,a.startInlineScript);a.sentCompleteSegmentFunction?n(b,ub):(a.sentCompleteSegmentFunction=!0,n(b,tb));n(b,a.segmentPrefix);f=p(f.toString(16));n(b,f);n(b,vb);n(b,a.placeholderPrefix);n(b,f);return n(b,wb)} function Nc(a,b){try{var c=a.completedRootSegment;if(null!==c&&0===a.pendingRootTasks){Pc(a,b,c);a.completedRootSegment=null;var d=a.responseState.bootstrapChunks;for(c=0;c<d.length;c++)n(b,d[c])}var f=a.clientRenderedBoundaries,e;for(e=0;e<f.length;e++){d=b;var g=a.responseState,h=f[e].id;n(d,g.startInlineScript);g.sentClientRenderFunction?n(d,Cb):(g.sentClientRenderFunction=!0,n(d,Bb));if(null===h)throw Error(l(395));n(d,h);if(!n(d,Db)){a.destination=null;e++;f.splice(0,e);return}}f.splice(0,e); var m=a.completedBoundaries;for(e=0;e<m.length;e++)if(!Rc(a,b,m[e])){a.destination=null;e++;m.splice(0,e);return}m.splice(0,e);var r=a.partialBoundaries;for(e=0;e<r.length;e++){var q=r[e];a:{f=a;g=b;var C=q.completedSegments;for(h=0;h<C.length;h++)if(!Sc(f,g,q,C[h])){h++;C.splice(0,h);var F=!1;break a}C.splice(0,h);F=!0}if(!F){a.destination=null;e++;r.splice(0,e);return}}r.splice(0,e);var A=a.completedBoundaries;for(e=0;e<A.length;e++)if(!Rc(a,b,A[e])){a.destination=null;e++;A.splice(0,e);return}A.splice(0, e)}finally{0===a.allPendingTasks&&0===a.pingedTasks.length&&0===a.clientRenderedBoundaries.length&&0===a.completedBoundaries.length&&b.close()}} exports.renderToReadableStream=function(a,b){var c=zc(a,ua(b?b.identifierPrefix:void 0,b?b.nonce:void 0,b?b.bootstrapScriptContent:void 0,b?b.bootstrapScripts:void 0,b?b.bootstrapModules:void 0),va(b?b.namespaceURI:void 0),b?b.progressiveChunkSize:void 0,b?b.onError:void 0,b?b.onCompleteAll:void 0,b?b.onCompleteShell:void 0);if(b&&b.signal){var d=b.signal,f=function(){try{var a=c.abortableTasks;a.forEach(Mc,c);a.clear();null!==c.destination&&Nc(c,c.destination)}catch(h){Y(c,h),Dc(c,h)}d.removeEventListener("abort", f)};d.addEventListener("abort",f)}var e=new ReadableStream({start:function(){Cc(c)},pull:function(a){if(e.locked)if(1===c.status)c.status=2,ca(a,c.fatalError);else if(2!==c.status){c.destination=a;try{Nc(c,a)}catch(h){Y(c,h),Dc(c,h)}}},cancel:function(){}});return e};exports.version="18.0.0-rc.0-790b5246f-20220118";
src/Portal.js
IveWong/react-bootstrap
import React from 'react'; import CustomPropTypes from './utils/CustomPropTypes'; import domUtils from './utils/domUtils'; let Portal = React.createClass({ displayName: 'Portal', propTypes: { /** * The DOM Node that the Component will render it's children into */ container: CustomPropTypes.mountable }, componentDidMount() { this._renderOverlay(); }, componentDidUpdate() { this._renderOverlay(); }, componentWillUnmount() { this._unrenderOverlay(); this._unmountOverlayTarget(); }, _mountOverlayTarget() { if (!this._overlayTarget) { this._overlayTarget = document.createElement('div'); this.getContainerDOMNode() .appendChild(this._overlayTarget); } }, _unmountOverlayTarget() { if (this._overlayTarget) { this.getContainerDOMNode() .removeChild(this._overlayTarget); this._overlayTarget = null; } }, _renderOverlay() { let overlay = !this.props.children ? null : React.Children.only(this.props.children); // Save reference for future access. if (overlay !== null) { this._mountOverlayTarget(); this._overlayInstance = React.render(overlay, this._overlayTarget); } else { // Unrender if the component is null for transitions to null this._unrenderOverlay(); this._unmountOverlayTarget(); } }, _unrenderOverlay() { if (this._overlayTarget) { React.unmountComponentAtNode(this._overlayTarget); this._overlayInstance = null; } }, render() { return null; }, getOverlayDOMNode() { if (!this.isMounted()) { throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.'); } if (this._overlayInstance) { if (this._overlayInstance.getWrappedDOMNode) { return this._overlayInstance.getWrappedDOMNode(); } else { return React.findDOMNode(this._overlayInstance); } } return null; }, getContainerDOMNode() { return React.findDOMNode(this.props.container) || domUtils.ownerDocument(this).body; } }); export default Portal;
src/docs/reference/Architecture.js
grommet/grommet-docs
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Anchor from 'grommet/components/Anchor'; import DocsArticle from '../../components/DocsArticle'; export default class Architecture extends Component { render () { return ( <DocsArticle title='Architecture'> <section> <p> Grommet is based on <a href='http://reactjs.com' target='_blank'> ReactJS</a> which provides great features in JavaScript for building user interfaces. {"You'll"} also use a JavaScript syntax extension called <a href='https://facebook.github.io/react/docs/jsx-in-depth.html' target='_blank'>JSX</a>. </p> <p> We expect that you have at least a basic understanding on these technologies to be able to master Grommet, in addition to JavaScript of course. In terms of cascading style sheets (CSS), Grommet provides everything you need to quickly create applications based on the application <Anchor path="/docs/resources"> Style Guide</Anchor>. Under the hood, {"you'll"} find <a href='https://github.com/inuitcss' target='_blank'>InuitCSS</a> and <a href='http://sass-lang.com/' target='_blank'>Sass</a> to compile the style sheets. But, don&#39;t worry, you are not expected to write a lot of CSS when using Grommet. {"We've"} done that for you. But, if you would like to contribute, please do so! </p> </section> </DocsArticle> ); } };
src/views/GardenizeView/QuestionsListView.js
Vargentum/react-redux-apps
import React from 'react' import QuestionsList from '../../containers/gardenize/QuestionsList' import CommonView from '../CommonView' class QuestionsListView extends React.Component { render () { return ( <CommonView title="Test application for Gardenize" description="There is a simple QA platform as a skills-proof for junior javascript developer position." criteriaUrl="https://docs.google.com/document/d/1FUJ-dnKqeVGJBJ7YaeexeYK7HpusfxLR5K-Lr8ZPJac" sourceCodeUrl="https://github.com/Vargentum/react-redux-apps/tree/gardenize-test" Component={QuestionsList} /> ) } } export default QuestionsListView
ajax/libs/6to5/1.11.12/browser-polyfill.js
vfonic/cdnjs
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){if(typeof Symbol==="undefined"){require("es6-symbol/implement")}require("es6-shim");require("regenerator-6to5/runtime")},{"es6-shim":3,"es6-symbol/implement":4,"regenerator-6to5/runtime":27}],2:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canMutationObserver=typeof window!=="undefined"&&window.MutationObserver;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}var queue=[];if(canMutationObserver){var hiddenDiv=document.createElement("div");var observer=new MutationObserver(function(){var queueList=queue.slice();queue.length=0;queueList.forEach(function(fn){fn()})});observer.observe(hiddenDiv,{attributes:true});return function nextTick(fn){if(!queue.length){hiddenDiv.setAttribute("yes","no")}queue.push(fn)}}if(canPost){window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],3:[function(require,module,exports){(function(process){(function(root,factory){if(typeof define==="function"&&define.amd){define(factory)}else if(typeof exports==="object"){module.exports=factory()}else{root.returnExports=factory()}})(this,function(){"use strict";var isCallableWithoutNew=function(func){try{func()}catch(e){return false}return true};var supportsSubclassing=function(C,f){try{var Sub=function(){C.apply(this,arguments)};if(!Sub.__proto__){return false}Object.setPrototypeOf(Sub,C);Sub.prototype=Object.create(C.prototype,{constructor:{value:C}});return f(Sub)}catch(e){return false}};var arePropertyDescriptorsSupported=function(){try{Object.defineProperty({},"x",{});return true}catch(e){return false}};var startsWithRejectsRegex=function(){var rejectsRegex=false;if(String.prototype.startsWith){try{"/a/".startsWith(/a/)}catch(e){rejectsRegex=true}}return rejectsRegex};var getGlobal=new Function("return this;");var globals=getGlobal();var global_isFinite=globals.isFinite;var supportsDescriptors=!!Object.defineProperty&&arePropertyDescriptorsSupported();var startsWithIsCompliant=startsWithRejectsRegex();var _slice=Array.prototype.slice;var _indexOf=String.prototype.indexOf;var _toString=Object.prototype.toString;var _hasOwnProperty=Object.prototype.hasOwnProperty;var ArrayIterator;var defineProperty=function(object,name,value,force){if(!force&&name in object){return}if(supportsDescriptors){Object.defineProperty(object,name,{configurable:true,enumerable:false,writable:true,value:value})}else{object[name]=value}};var defineProperties=function(object,map){Object.keys(map).forEach(function(name){var method=map[name];defineProperty(object,name,method,false)})};var create=Object.create||function(prototype,properties){function Type(){}Type.prototype=prototype;var object=new Type;if(typeof properties!=="undefined"){defineProperties(object,properties)}return object};var $iterator$=typeof Symbol==="function"&&Symbol.iterator||"_es6shim_iterator_";if(globals.Set&&typeof(new globals.Set)["@@iterator"]==="function"){$iterator$="@@iterator"}var addIterator=function(prototype,impl){if(!impl){impl=function iterator(){return this}}var o={};o[$iterator$]=impl;defineProperties(prototype,o);if(!prototype[$iterator$]&&typeof $iterator$==="symbol"){prototype[$iterator$]=impl}};var isArguments=function isArguments(value){var str=_toString.call(value);var result=str==="[object Arguments]";if(!result){result=str!=="[object Array]"&&value!==null&&typeof value==="object"&&typeof value.length==="number"&&value.length>=0&&_toString.call(value.callee)==="[object Function]"}return result};var emulateES6construct=function(o){if(!ES.TypeIsObject(o)){throw new TypeError("bad object")}if(!o._es6construct){if(o.constructor&&ES.IsCallable(o.constructor["@@create"])){o=o.constructor["@@create"](o)}defineProperties(o,{_es6construct:true})}return o};var ES={CheckObjectCoercible:function(x,optMessage){if(x==null){throw new TypeError(optMessage||"Cannot call method on "+x)}return x},TypeIsObject:function(x){return x!=null&&Object(x)===x},ToObject:function(o,optMessage){return Object(ES.CheckObjectCoercible(o,optMessage))},IsCallable:function(x){return typeof x==="function"&&_toString.call(x)==="[object Function]"},ToInt32:function(x){return x>>0},ToUint32:function(x){return x>>>0},ToInteger:function(value){var number=+value;if(Number.isNaN(number)){return 0}if(number===0||!Number.isFinite(number)){return number}return(number>0?1:-1)*Math.floor(Math.abs(number))},ToLength:function(value){var len=ES.ToInteger(value);if(len<=0){return 0}if(len>Number.MAX_SAFE_INTEGER){return Number.MAX_SAFE_INTEGER}return len},SameValue:function(a,b){if(a===b){if(a===0){return 1/a===1/b}return true}return Number.isNaN(a)&&Number.isNaN(b)},SameValueZero:function(a,b){return a===b||Number.isNaN(a)&&Number.isNaN(b)},IsIterable:function(o){return ES.TypeIsObject(o)&&(typeof o[$iterator$]!=="undefined"||isArguments(o))},GetIterator:function(o){if(isArguments(o)){return new ArrayIterator(o,"value")}var it=o[$iterator$]();if(!ES.TypeIsObject(it)){throw new TypeError("bad iterator")}return it},IteratorNext:function(it){var result=arguments.length>1?it.next(arguments[1]):it.next();if(!ES.TypeIsObject(result)){throw new TypeError("bad iterator")}return result},Construct:function(C,args){var obj;if(ES.IsCallable(C["@@create"])){obj=C["@@create"]()}else{obj=create(C.prototype||null)}defineProperties(obj,{_es6construct:true});var result=C.apply(obj,args);return ES.TypeIsObject(result)?result:obj}};var numberConversion=function(){function roundToEven(n){var w=Math.floor(n),f=n-w;if(f<.5){return w}if(f>.5){return w+1}return w%2?w+1:w}function packIEEE754(v,ebits,fbits){var bias=(1<<ebits-1)-1,s,e,f,ln,i,bits,str,bytes;if(v!==v){e=(1<<ebits)-1;f=Math.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=Math.abs(v);if(v>=Math.pow(2,1-bias)){e=Math.min(Math.floor(Math.log(v)/Math.LN2),1023);f=roundToEven(v/Math.pow(2,e)*Math.pow(2,fbits));if(f/Math.pow(2,fbits)>=2){e=e+1;f=1}if(e>bias){e=(1<<ebits)-1;f=0}else{e=e+bias;f=f-Math.pow(2,fbits)}}else{e=0;f=roundToEven(v/Math.pow(2,1-bias-fbits))}}bits=[];for(i=fbits;i;i-=1){bits.push(f%2?1:0);f=Math.floor(f/2)}for(i=ebits;i;i-=1){bits.push(e%2?1:0);e=Math.floor(e/2)}bits.push(s?1:0);bits.reverse();str=bits.join("");bytes=[];while(str.length){bytes.push(parseInt(str.slice(0,8),2));str=str.slice(8)}return bytes}function unpackIEEE754(bytes,ebits,fbits){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("");bias=(1<<ebits-1)-1;s=parseInt(str.slice(0,1),2)?-1:1;e=parseInt(str.slice(1,1+ebits),2);f=parseInt(str.slice(1+ebits),2);if(e===(1<<ebits)-1){return f!==0?NaN:s*Infinity}else if(e>0){return s*Math.pow(2,e-bias)*(1+f/Math.pow(2,fbits))}else if(f!==0){return s*Math.pow(2,-(bias-1))*(f/Math.pow(2,fbits))}else{return s<0?-0:0}}function unpackFloat64(b){return unpackIEEE754(b,11,52)}function packFloat64(v){return packIEEE754(v,11,52)}function unpackFloat32(b){return unpackIEEE754(b,8,23)}function packFloat32(v){return packIEEE754(v,8,23)}var conversions={toFloat32:function(num){return unpackFloat32(packFloat32(num))}};if(typeof Float32Array!=="undefined"){var float32array=new Float32Array(1);conversions.toFloat32=function(num){float32array[0]=num;return float32array[0]}}return conversions}();defineProperties(String,{fromCodePoint:function(_){var points=_slice.call(arguments,0,arguments.length);var result=[];var next;for(var i=0,length=points.length;i<length;i++){next=Number(points[i]);if(!ES.SameValue(next,ES.ToInteger(next))||next<0||next>1114111){throw new RangeError("Invalid code point "+next)}if(next<65536){result.push(String.fromCharCode(next))}else{next-=65536;result.push(String.fromCharCode((next>>10)+55296));result.push(String.fromCharCode(next%1024+56320))}}return result.join("")},raw:function(callSite){var substitutions=_slice.call(arguments,1,arguments.length);var cooked=ES.ToObject(callSite,"bad callSite");var rawValue=cooked.raw;var raw=ES.ToObject(rawValue,"bad raw value");var len=Object.keys(raw).length;var literalsegments=ES.ToLength(len);if(literalsegments===0){return""}var stringElements=[];var nextIndex=0;var nextKey,next,nextSeg,nextSub;while(nextIndex<literalsegments){nextKey=String(nextIndex);next=raw[nextKey];nextSeg=String(next);stringElements.push(nextSeg);if(nextIndex+1>=literalsegments){break}next=substitutions[nextKey];if(typeof next==="undefined"){break}nextSub=String(next);stringElements.push(nextSub);nextIndex++}return stringElements.join("")}});if(String.fromCodePoint.length!==1){var originalFromCodePoint=String.fromCodePoint;defineProperty(String,"fromCodePoint",function(_){return originalFromCodePoint.apply(this,arguments)},true)}var StringShims={repeat:function(){var repeat=function(s,times){if(times<1){return""}if(times%2){return repeat(s,times-1)+s}var half=repeat(s,times/2);return half+half};return function(times){var thisStr=String(ES.CheckObjectCoercible(this));times=ES.ToInteger(times);if(times<0||times===Infinity){throw new RangeError("Invalid String#repeat value")}return repeat(thisStr,times)}}(),startsWith:function(searchStr){var thisStr=String(ES.CheckObjectCoercible(this));if(_toString.call(searchStr)==="[object RegExp]"){throw new TypeError('Cannot call method "startsWith" with a regex')}searchStr=String(searchStr);var startArg=arguments.length>1?arguments[1]:void 0;var start=Math.max(ES.ToInteger(startArg),0);return thisStr.slice(start,start+searchStr.length)===searchStr},endsWith:function(searchStr){var thisStr=String(ES.CheckObjectCoercible(this));if(_toString.call(searchStr)==="[object RegExp]"){throw new TypeError('Cannot call method "endsWith" with a regex')}searchStr=String(searchStr);var thisLen=thisStr.length;var posArg=arguments.length>1?arguments[1]:void 0;var pos=typeof posArg==="undefined"?thisLen:ES.ToInteger(posArg);var end=Math.min(Math.max(pos,0),thisLen);return thisStr.slice(end-searchStr.length,end)===searchStr},contains:function(searchString){var position=arguments.length>1?arguments[1]:void 0;return _indexOf.call(this,searchString,position)!==-1},codePointAt:function(pos){var thisStr=String(ES.CheckObjectCoercible(this));var position=ES.ToInteger(pos);var length=thisStr.length;if(position<0||position>=length){return}var first=thisStr.charCodeAt(position);var isEnd=position+1===length;if(first<55296||first>56319||isEnd){return first}var second=thisStr.charCodeAt(position+1);if(second<56320||second>57343){return first}return(first-55296)*1024+(second-56320)+65536}};defineProperties(String.prototype,StringShims);var hasStringTrimBug="…".trim().length!==1;if(hasStringTrimBug){var originalStringTrim=String.prototype.trim;delete String.prototype.trim;var ws=[" \n \f\r   ᠎    ","          \u2028","\u2029"].join("");var trimRegexp=new RegExp("(^["+ws+"]+)|(["+ws+"]+$)","g");defineProperties(String.prototype,{trim:function(){if(typeof this==="undefined"||this===null){throw new TypeError("can't convert "+this+" to object")}return String(this).replace(trimRegexp,"")}})}var StringIterator=function(s){this._s=String(ES.CheckObjectCoercible(s));this._i=0};StringIterator.prototype.next=function(){var s=this._s,i=this._i;if(typeof s==="undefined"||i>=s.length){this._s=void 0;return{value:void 0,done:true}}var first=s.charCodeAt(i),second,len;if(first<55296||first>56319||i+1==s.length){len=1}else{second=s.charCodeAt(i+1);len=second<56320||second>57343?1:2}this._i=i+len;return{value:s.substr(i,len),done:false}};addIterator(StringIterator.prototype);addIterator(String.prototype,function(){return new StringIterator(this)});if(!startsWithIsCompliant){String.prototype.startsWith=StringShims.startsWith;String.prototype.endsWith=StringShims.endsWith}var ArrayShims={from:function(iterable){var mapFn=arguments.length>1?arguments[1]:void 0;var list=ES.ToObject(iterable,"bad iterable");if(typeof mapFn!=="undefined"&&!ES.IsCallable(mapFn)){throw new TypeError("Array.from: when provided, the second argument must be a function")}var hasThisArg=arguments.length>2;var thisArg=hasThisArg?arguments[2]:void 0;var usingIterator=ES.IsIterable(list);var length;var result,i,value;if(usingIterator){i=0;result=ES.IsCallable(this)?Object(new this):[];var it=usingIterator?ES.GetIterator(list):null;var iterationValue;do{iterationValue=ES.IteratorNext(it);if(!iterationValue.done){value=iterationValue.value;if(mapFn){result[i]=hasThisArg?mapFn.call(thisArg,value,i):mapFn(value,i)}else{result[i]=value}i+=1}}while(!iterationValue.done);length=i}else{length=ES.ToLength(list.length);result=ES.IsCallable(this)?Object(new this(length)):new Array(length);for(i=0;i<length;++i){value=list[i];if(mapFn){result[i]=hasThisArg?mapFn.call(thisArg,value,i):mapFn(value,i)}else{result[i]=value}}}result.length=length;return result},of:function(){return Array.from(arguments)}};defineProperties(Array,ArrayShims);var arrayFromSwallowsNegativeLengths=function(){try{return Array.from({length:-1}).length===0}catch(e){return false}};if(!arrayFromSwallowsNegativeLengths()){defineProperty(Array,"from",ArrayShims.from,true)}ArrayIterator=function(array,kind){this.i=0;this.array=array;this.kind=kind};defineProperties(ArrayIterator.prototype,{next:function(){var i=this.i,array=this.array;if(!(this instanceof ArrayIterator)){throw new TypeError("Not an ArrayIterator")}if(typeof array!=="undefined"){var len=ES.ToLength(array.length);for(;i<len;i++){var kind=this.kind;var retval;if(kind==="key"){retval=i}else if(kind==="value"){retval=array[i]}else if(kind==="entry"){retval=[i,array[i]]}this.i=i+1;return{value:retval,done:false}}}this.array=void 0;return{value:void 0,done:true}}});addIterator(ArrayIterator.prototype);var ArrayPrototypeShims={copyWithin:function(target,start){var end=arguments[2];var o=ES.ToObject(this);var len=ES.ToLength(o.length);target=ES.ToInteger(target);start=ES.ToInteger(start);var to=target<0?Math.max(len+target,0):Math.min(target,len);var from=start<0?Math.max(len+start,0):Math.min(start,len);end=typeof end==="undefined"?len:ES.ToInteger(end);var fin=end<0?Math.max(len+end,0):Math.min(end,len);var count=Math.min(fin-from,len-to);var direction=1;if(from<to&&to<from+count){direction=-1;from+=count-1;to+=count-1}while(count>0){if(_hasOwnProperty.call(o,from)){o[to]=o[from]}else{delete o[from]}from+=direction;to+=direction;count-=1}return o},fill:function(value){var start=arguments.length>1?arguments[1]:void 0;var end=arguments.length>2?arguments[2]:void 0;var O=ES.ToObject(this);var len=ES.ToLength(O.length);start=ES.ToInteger(typeof start==="undefined"?0:start);end=ES.ToInteger(typeof end==="undefined"?len:end);var relativeStart=start<0?Math.max(len+start,0):Math.min(start,len);var relativeEnd=end<0?len+end:end;for(var i=relativeStart;i<len&&i<relativeEnd;++i){O[i]=value}return O},find:function find(predicate){var list=ES.ToObject(this);var length=ES.ToLength(list.length);if(!ES.IsCallable(predicate)){throw new TypeError("Array#find: predicate must be a function")}var thisArg=arguments[1];for(var i=0,value;i<length;i++){value=list[i];if(predicate.call(thisArg,value,i,list)){return value}}return},findIndex:function findIndex(predicate){var list=ES.ToObject(this);var length=ES.ToLength(list.length);if(!ES.IsCallable(predicate)){throw new TypeError("Array#findIndex: predicate must be a function")}var thisArg=arguments[1];for(var i=0;i<length;i++){if(predicate.call(thisArg,list[i],i,list)){return i}}return-1},keys:function(){return new ArrayIterator(this,"key")},values:function(){return new ArrayIterator(this,"value")},entries:function(){return new ArrayIterator(this,"entry")}};if(Array.prototype.keys&&!ES.IsCallable([1].keys().next)){delete Array.prototype.keys}if(Array.prototype.entries&&!ES.IsCallable([1].entries().next)){delete Array.prototype.entries}defineProperties(Array.prototype,ArrayPrototypeShims);addIterator(Array.prototype,function(){return this.values()});if(Object.getPrototypeOf){addIterator(Object.getPrototypeOf([].values()))}var maxSafeInteger=Math.pow(2,53)-1;defineProperties(Number,{MAX_SAFE_INTEGER:maxSafeInteger,MIN_SAFE_INTEGER:-maxSafeInteger,EPSILON:2.220446049250313e-16,parseInt:globals.parseInt,parseFloat:globals.parseFloat,isFinite:function(value){return typeof value==="number"&&global_isFinite(value)},isInteger:function(value){return Number.isFinite(value)&&ES.ToInteger(value)===value},isSafeInteger:function(value){return Number.isInteger(value)&&Math.abs(value)<=Number.MAX_SAFE_INTEGER},isNaN:function(value){return value!==value}});if(![,1].find(function(item,idx){return idx===0})){defineProperty(Array.prototype,"find",ArrayPrototypeShims.find,true)}if([,1].findIndex(function(item,idx){return idx===0})!==0){defineProperty(Array.prototype,"findIndex",ArrayPrototypeShims.findIndex,true)}if(supportsDescriptors){defineProperties(Object,{getPropertyDescriptor:function(subject,name){var pd=Object.getOwnPropertyDescriptor(subject,name);var proto=Object.getPrototypeOf(subject);while(typeof pd==="undefined"&&proto!==null){pd=Object.getOwnPropertyDescriptor(proto,name);proto=Object.getPrototypeOf(proto)}return pd},getPropertyNames:function(subject){var result=Object.getOwnPropertyNames(subject);var proto=Object.getPrototypeOf(subject);var addProperty=function(property){if(result.indexOf(property)===-1){result.push(property)}};while(proto!==null){Object.getOwnPropertyNames(proto).forEach(addProperty);proto=Object.getPrototypeOf(proto)}return result}});defineProperties(Object,{assign:function(target,source){if(!ES.TypeIsObject(target)){throw new TypeError("target must be an object")}return Array.prototype.reduce.call(arguments,function(target,source){return Object.keys(Object(source)).reduce(function(target,key){target[key]=source[key];return target},target)})},is:function(a,b){return ES.SameValue(a,b)},setPrototypeOf:function(Object,magic){var set;var checkArgs=function(O,proto){if(!ES.TypeIsObject(O)){throw new TypeError("cannot set prototype on a non-object")}if(!(proto===null||ES.TypeIsObject(proto))){throw new TypeError("can only set prototype to an object or null"+proto)}};var setPrototypeOf=function(O,proto){checkArgs(O,proto);set.call(O,proto);return O};try{set=Object.getOwnPropertyDescriptor(Object.prototype,magic).set;set.call({},null)}catch(e){if(Object.prototype!=={}[magic]){return}set=function(proto){this[magic]=proto};setPrototypeOf.polyfill=setPrototypeOf(setPrototypeOf({},null),Object.prototype)instanceof Object}return setPrototypeOf}(Object,"__proto__")})}if(Object.setPrototypeOf&&Object.getPrototypeOf&&Object.getPrototypeOf(Object.setPrototypeOf({},null))!==null&&Object.getPrototypeOf(Object.create(null))===null){(function(){var FAKENULL=Object.create(null);var gpo=Object.getPrototypeOf,spo=Object.setPrototypeOf;Object.getPrototypeOf=function(o){var result=gpo(o);return result===FAKENULL?null:result};Object.setPrototypeOf=function(o,p){if(p===null){p=FAKENULL}return spo(o,p)};Object.setPrototypeOf.polyfill=false})()}try{Object.keys("foo")}catch(e){var originalObjectKeys=Object.keys;Object.keys=function(obj){return originalObjectKeys(ES.ToObject(obj))}}var MathShims={acosh:function(value){value=Number(value);if(Number.isNaN(value)||value<1){return NaN}if(value===1){return 0}if(value===Infinity){return value}return Math.log(value+Math.sqrt(value*value-1))},asinh:function(value){value=Number(value);if(value===0||!global_isFinite(value)){return value}return value<0?-Math.asinh(-value):Math.log(value+Math.sqrt(value*value+1))},atanh:function(value){value=Number(value);if(Number.isNaN(value)||value<-1||value>1){return NaN}if(value===-1){return-Infinity}if(value===1){return Infinity}if(value===0){return value}return.5*Math.log((1+value)/(1-value))},cbrt:function(value){value=Number(value);if(value===0){return value}var negate=value<0,result;if(negate){value=-value}result=Math.pow(value,1/3);return negate?-result:result},clz32:function(value){value=Number(value);var number=ES.ToUint32(value);if(number===0){return 32}return 32-number.toString(2).length},cosh:function(value){value=Number(value);if(value===0){return 1}if(Number.isNaN(value)){return NaN}if(!global_isFinite(value)){return Infinity}if(value<0){value=-value}if(value>21){return Math.exp(value)/2}return(Math.exp(value)+Math.exp(-value))/2},expm1:function(value){value=Number(value);if(value===-Infinity){return-1}if(!global_isFinite(value)||value===0){return value}return Math.exp(value)-1},hypot:function(x,y){var anyNaN=false;var allZero=true;var anyInfinity=false;var numbers=[];Array.prototype.every.call(arguments,function(arg){var num=Number(arg);if(Number.isNaN(num)){anyNaN=true}else if(num===Infinity||num===-Infinity){anyInfinity=true}else if(num!==0){allZero=false}if(anyInfinity){return false}else if(!anyNaN){numbers.push(Math.abs(num))}return true});if(anyInfinity){return Infinity}if(anyNaN){return NaN}if(allZero){return 0}numbers.sort(function(a,b){return b-a});var largest=numbers[0];var divided=numbers.map(function(number){return number/largest});var sum=divided.reduce(function(sum,number){return sum+=number*number},0);return largest*Math.sqrt(sum)},log2:function(value){return Math.log(value)*Math.LOG2E},log10:function(value){return Math.log(value)*Math.LOG10E},log1p:function(value){value=Number(value);if(value<-1||Number.isNaN(value)){return NaN}if(value===0||value===Infinity){return value}if(value===-1){return-Infinity}var result=0;var n=50;if(value<0||value>1){return Math.log(1+value)}for(var i=1;i<n;i++){if(i%2===0){result-=Math.pow(value,i)/i}else{result+=Math.pow(value,i)/i}}return result},sign:function(value){var number=+value;if(number===0){return number}if(Number.isNaN(number)){return number}return number<0?-1:1},sinh:function(value){value=Number(value);if(!global_isFinite(value)||value===0){return value}return(Math.exp(value)-Math.exp(-value))/2},tanh:function(value){value=Number(value);if(Number.isNaN(value)||value===0){return value}if(value===Infinity){return 1}if(value===-Infinity){return-1}return(Math.exp(value)-Math.exp(-value))/(Math.exp(value)+Math.exp(-value))},trunc:function(value){var number=Number(value);return number<0?-Math.floor(-number):Math.floor(number)},imul:function(x,y){x=ES.ToUint32(x);y=ES.ToUint32(y);var ah=x>>>16&65535;var al=x&65535;var bh=y>>>16&65535;var bl=y&65535;return al*bl+(ah*bl+al*bh<<16>>>0)|0},fround:function(x){if(x===0||x===Infinity||x===-Infinity||Number.isNaN(x)){return x}var num=Number(x);return numberConversion.toFloat32(num)}};defineProperties(Math,MathShims);if(Math.imul(4294967295,5)!==-5){Math.imul=MathShims.imul}var PromiseShim=function(){var Promise,Promise$prototype;ES.IsPromise=function(promise){if(!ES.TypeIsObject(promise)){return false}if(!promise._promiseConstructor){return false}if(typeof promise._status==="undefined"){return false}return true};var PromiseCapability=function(C){if(!ES.IsCallable(C)){throw new TypeError("bad promise constructor")}var capability=this;var resolver=function(resolve,reject){capability.resolve=resolve;capability.reject=reject};capability.promise=ES.Construct(C,[resolver]);if(!capability.promise._es6construct){throw new TypeError("bad promise constructor")}if(!(ES.IsCallable(capability.resolve)&&ES.IsCallable(capability.reject))){throw new TypeError("bad promise constructor")}};var setTimeout=globals.setTimeout;var makeZeroTimeout;if(typeof window!=="undefined"&&ES.IsCallable(window.postMessage)){makeZeroTimeout=function(){var timeouts=[];var messageName="zero-timeout-message";var setZeroTimeout=function(fn){timeouts.push(fn);window.postMessage(messageName,"*")};var handleMessage=function(event){if(event.source==window&&event.data==messageName){event.stopPropagation();if(timeouts.length===0){return}var fn=timeouts.shift();fn()}};window.addEventListener("message",handleMessage,true);return setZeroTimeout}}var makePromiseAsap=function(){var P=globals.Promise;return P&&P.resolve&&function(task){return P.resolve().then(task)}};var enqueue=ES.IsCallable(globals.setImmediate)?globals.setImmediate.bind(globals):typeof process==="object"&&process.nextTick?process.nextTick:makePromiseAsap()||(ES.IsCallable(makeZeroTimeout)?makeZeroTimeout():function(task){setTimeout(task,0)});var triggerPromiseReactions=function(reactions,x){reactions.forEach(function(reaction){enqueue(function(){var handler=reaction.handler;var capability=reaction.capability;var resolve=capability.resolve;var reject=capability.reject;try{var result=handler(x);if(result===capability.promise){throw new TypeError("self resolution")}var updateResult=updatePromiseFromPotentialThenable(result,capability);if(!updateResult){resolve(result)}}catch(e){reject(e)}})})};var updatePromiseFromPotentialThenable=function(x,capability){if(!ES.TypeIsObject(x)){return false}var resolve=capability.resolve;var reject=capability.reject;try{var then=x.then;if(!ES.IsCallable(then)){return false}then.call(x,resolve,reject)}catch(e){reject(e)}return true};var promiseResolutionHandler=function(promise,onFulfilled,onRejected){return function(x){if(x===promise){return onRejected(new TypeError("self resolution"))}var C=promise._promiseConstructor;var capability=new PromiseCapability(C);var updateResult=updatePromiseFromPotentialThenable(x,capability);if(updateResult){return capability.promise.then(onFulfilled,onRejected)}else{return onFulfilled(x)}}};Promise=function(resolver){var promise=this;promise=emulateES6construct(promise);if(!promise._promiseConstructor){throw new TypeError("bad promise")}if(typeof promise._status!=="undefined"){throw new TypeError("promise already initialized")}if(!ES.IsCallable(resolver)){throw new TypeError("not a valid resolver")}promise._status="unresolved";promise._resolveReactions=[];promise._rejectReactions=[];var resolve=function(resolution){if(promise._status!=="unresolved"){return}var reactions=promise._resolveReactions;promise._result=resolution;promise._resolveReactions=void 0;promise._rejectReactions=void 0;promise._status="has-resolution";triggerPromiseReactions(reactions,resolution)};var reject=function(reason){if(promise._status!=="unresolved"){return}var reactions=promise._rejectReactions;promise._result=reason;promise._resolveReactions=void 0;promise._rejectReactions=void 0;promise._status="has-rejection";triggerPromiseReactions(reactions,reason)};try{resolver(resolve,reject)}catch(e){reject(e)}return promise};Promise$prototype=Promise.prototype;defineProperties(Promise,{"@@create":function(obj){var constructor=this;var prototype=constructor.prototype||Promise$prototype;obj=obj||create(prototype);defineProperties(obj,{_status:void 0,_result:void 0,_resolveReactions:void 0,_rejectReactions:void 0,_promiseConstructor:void 0});obj._promiseConstructor=constructor;return obj}});var _promiseAllResolver=function(index,values,capability,remaining){var done=false;return function(x){if(done){return}done=true;values[index]=x;if(--remaining.count===0){var resolve=capability.resolve;resolve(values)}}};Promise.all=function(iterable){var C=this;var capability=new PromiseCapability(C);var resolve=capability.resolve;var reject=capability.reject;try{if(!ES.IsIterable(iterable)){throw new TypeError("bad iterable")}var it=ES.GetIterator(iterable);var values=[],remaining={count:1};for(var index=0;;index++){var next=ES.IteratorNext(it);if(next.done){break}var nextPromise=C.resolve(next.value);var resolveElement=_promiseAllResolver(index,values,capability,remaining);remaining.count++;nextPromise.then(resolveElement,capability.reject)}if(--remaining.count===0){resolve(values)}}catch(e){reject(e)}return capability.promise};Promise.race=function(iterable){var C=this;var capability=new PromiseCapability(C);var resolve=capability.resolve;var reject=capability.reject;try{if(!ES.IsIterable(iterable)){throw new TypeError("bad iterable")}var it=ES.GetIterator(iterable);while(true){var next=ES.IteratorNext(it);if(next.done){break}var nextPromise=C.resolve(next.value);nextPromise.then(resolve,reject)}}catch(e){reject(e)}return capability.promise};Promise.reject=function(reason){var C=this;var capability=new PromiseCapability(C);var reject=capability.reject;reject(reason);return capability.promise};Promise.resolve=function(v){var C=this;if(ES.IsPromise(v)){var constructor=v._promiseConstructor;if(constructor===C){return v}}var capability=new PromiseCapability(C);var resolve=capability.resolve;resolve(v);return capability.promise};Promise.prototype["catch"]=function(onRejected){return this.then(void 0,onRejected)};Promise.prototype.then=function(onFulfilled,onRejected){var promise=this;if(!ES.IsPromise(promise)){throw new TypeError("not a promise")}var C=this.constructor;var capability=new PromiseCapability(C);if(!ES.IsCallable(onRejected)){onRejected=function(e){throw e}}if(!ES.IsCallable(onFulfilled)){onFulfilled=function(x){return x}}var resolutionHandler=promiseResolutionHandler(promise,onFulfilled,onRejected);var resolveReaction={capability:capability,handler:resolutionHandler};var rejectReaction={capability:capability,handler:onRejected};switch(promise._status){case"unresolved":promise._resolveReactions.push(resolveReaction);promise._rejectReactions.push(rejectReaction);break;case"has-resolution":triggerPromiseReactions([resolveReaction],promise._result);break;case"has-rejection":triggerPromiseReactions([rejectReaction],promise._result);break;default:throw new TypeError("unexpected")}return capability.promise};return Promise}();defineProperties(globals,{Promise:PromiseShim});var promiseSupportsSubclassing=supportsSubclassing(globals.Promise,function(S){return S.resolve(42)instanceof S});var promiseIgnoresNonFunctionThenCallbacks=function(){try{globals.Promise.reject(42).then(null,5).then(null,function(){});return true}catch(ex){return false}}();var promiseRequiresObjectContext=function(){try{Promise.call(3,function(){})}catch(e){return true}return false}();if(!promiseSupportsSubclassing||!promiseIgnoresNonFunctionThenCallbacks||!promiseRequiresObjectContext){globals.Promise=PromiseShim}var testOrder=function(a){var b=Object.keys(a.reduce(function(o,k){o[k]=true;return o},{}));return a.join(":")===b.join(":")};var preservesInsertionOrder=testOrder(["z","a","bb"]);var preservesNumericInsertionOrder=testOrder(["z",1,"a","3",2]);if(supportsDescriptors){var fastkey=function fastkey(key){if(!preservesInsertionOrder){return null}var type=typeof key;if(type==="string"){return"$"+key}else if(type==="number"){if(!preservesNumericInsertionOrder){return"n"+key}return key}return null};var emptyObject=function emptyObject(){return Object.create?Object.create(null):{}};var collectionShims={Map:function(){var empty={};function MapEntry(key,value){this.key=key;this.value=value;this.next=null;this.prev=null}MapEntry.prototype.isRemoved=function(){return this.key===empty };function MapIterator(map,kind){this.head=map._head;this.i=this.head;this.kind=kind}MapIterator.prototype={next:function(){var i=this.i,kind=this.kind,head=this.head,result;if(typeof this.i==="undefined"){return{value:void 0,done:true}}while(i.isRemoved()&&i!==head){i=i.prev}while(i.next!==head){i=i.next;if(!i.isRemoved()){if(kind==="key"){result=i.key}else if(kind==="value"){result=i.value}else{result=[i.key,i.value]}this.i=i;return{value:result,done:false}}}this.i=void 0;return{value:void 0,done:true}}};addIterator(MapIterator.prototype);function Map(iterable){var map=this;map=emulateES6construct(map);if(!map._es6map){throw new TypeError("bad map")}var head=new MapEntry(null,null);head.next=head.prev=head;defineProperties(map,{_head:head,_storage:emptyObject(),_size:0});if(typeof iterable!=="undefined"&&iterable!==null){var it=ES.GetIterator(iterable);var adder=map.set;if(!ES.IsCallable(adder)){throw new TypeError("bad map")}while(true){var next=ES.IteratorNext(it);if(next.done){break}var nextItem=next.value;if(!ES.TypeIsObject(nextItem)){throw new TypeError("expected iterable of pairs")}adder.call(map,nextItem[0],nextItem[1])}}return map}var Map$prototype=Map.prototype;defineProperties(Map,{"@@create":function(obj){var constructor=this;var prototype=constructor.prototype||Map$prototype;obj=obj||create(prototype);defineProperties(obj,{_es6map:true});return obj}});Object.defineProperty(Map.prototype,"size",{configurable:true,enumerable:false,get:function(){if(typeof this._size==="undefined"){throw new TypeError("size method called on incompatible Map")}return this._size}});defineProperties(Map.prototype,{get:function(key){var fkey=fastkey(key);if(fkey!==null){var entry=this._storage[fkey];if(entry){return entry.value}else{return}}var head=this._head,i=head;while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){return i.value}}return},has:function(key){var fkey=fastkey(key);if(fkey!==null){return typeof this._storage[fkey]!=="undefined"}var head=this._head,i=head;while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){return true}}return false},set:function(key,value){var head=this._head,i=head,entry;var fkey=fastkey(key);if(fkey!==null){if(typeof this._storage[fkey]!=="undefined"){this._storage[fkey].value=value;return}else{entry=this._storage[fkey]=new MapEntry(key,value);i=head.prev}}while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){i.value=value;return}}entry=entry||new MapEntry(key,value);if(ES.SameValue(-0,key)){entry.key=+0}entry.next=this._head;entry.prev=this._head.prev;entry.prev.next=entry;entry.next.prev=entry;this._size+=1;return this},"delete":function(key){var head=this._head,i=head;var fkey=fastkey(key);if(fkey!==null){if(typeof this._storage[fkey]==="undefined"){return false}i=this._storage[fkey].prev;delete this._storage[fkey]}while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){i.key=i.value=empty;i.prev.next=i.next;i.next.prev=i.prev;this._size-=1;return true}}return false},clear:function(){this._size=0;this._storage=emptyObject();var head=this._head,i=head,p=i.next;while((i=p)!==head){i.key=i.value=empty;p=i.next;i.next=i.prev=head}head.next=head.prev=head},keys:function(){return new MapIterator(this,"key")},values:function(){return new MapIterator(this,"value")},entries:function(){return new MapIterator(this,"key+value")},forEach:function(callback){var context=arguments.length>1?arguments[1]:null;var it=this.entries();for(var entry=it.next();!entry.done;entry=it.next()){callback.call(context,entry.value[1],entry.value[0],this)}}});addIterator(Map.prototype,function(){return this.entries()});return Map}(),Set:function(){var SetShim=function Set(iterable){var set=this;set=emulateES6construct(set);if(!set._es6set){throw new TypeError("bad set")}defineProperties(set,{"[[SetData]]":null,_storage:emptyObject()});if(typeof iterable!=="undefined"&&iterable!==null){var it=ES.GetIterator(iterable);var adder=set.add;if(!ES.IsCallable(adder)){throw new TypeError("bad set")}while(true){var next=ES.IteratorNext(it);if(next.done){break}var nextItem=next.value;adder.call(set,nextItem)}}return set};var Set$prototype=SetShim.prototype;defineProperties(SetShim,{"@@create":function(obj){var constructor=this;var prototype=constructor.prototype||Set$prototype;obj=obj||create(prototype);defineProperties(obj,{_es6set:true});return obj}});var ensureMap=function ensureMap(set){if(!set["[[SetData]]"]){var m=set["[[SetData]]"]=new collectionShims.Map;Object.keys(set._storage).forEach(function(k){if(k.charCodeAt(0)===36){k=k.slice(1)}else if(k.charAt(0)==="n"){k=+k.slice(1)}else{k=+k}m.set(k,k)});set._storage=null}};Object.defineProperty(SetShim.prototype,"size",{configurable:true,enumerable:false,get:function(){if(typeof this._storage==="undefined"){throw new TypeError("size method called on incompatible Set")}ensureMap(this);return this["[[SetData]]"].size}});defineProperties(SetShim.prototype,{has:function(key){var fkey;if(this._storage&&(fkey=fastkey(key))!==null){return!!this._storage[fkey]}ensureMap(this);return this["[[SetData]]"].has(key)},add:function(key){var fkey;if(this._storage&&(fkey=fastkey(key))!==null){this._storage[fkey]=true;return}ensureMap(this);this["[[SetData]]"].set(key,key);return this},"delete":function(key){var fkey;if(this._storage&&(fkey=fastkey(key))!==null){var hasFKey=_hasOwnProperty.call(this._storage,fkey);return delete this._storage[fkey]&&hasFKey}ensureMap(this);return this["[[SetData]]"]["delete"](key)},clear:function(){if(this._storage){this._storage=emptyObject();return}return this["[[SetData]]"].clear()},keys:function(){ensureMap(this);return this["[[SetData]]"].keys()},values:function(){ensureMap(this);return this["[[SetData]]"].values()},entries:function(){ensureMap(this);return this["[[SetData]]"].entries()},forEach:function(callback){var context=arguments.length>1?arguments[1]:null;var entireSet=this;ensureMap(this);this["[[SetData]]"].forEach(function(value,key){callback.call(context,key,key,entireSet)})}});addIterator(SetShim.prototype,function(){return this.values()});return SetShim}()};defineProperties(globals,collectionShims);if(globals.Map||globals.Set){if(typeof globals.Map.prototype.clear!=="function"||(new globals.Set).size!==0||(new globals.Map).size!==0||typeof globals.Map.prototype.keys!=="function"||typeof globals.Set.prototype.keys!=="function"||typeof globals.Map.prototype.forEach!=="function"||typeof globals.Set.prototype.forEach!=="function"||isCallableWithoutNew(globals.Map)||isCallableWithoutNew(globals.Set)||!supportsSubclassing(globals.Map,function(M){var m=new M([]);m.set(42,42);return m instanceof M})){globals.Map=collectionShims.Map;globals.Set=collectionShims.Set}}addIterator(Object.getPrototypeOf((new globals.Map).keys()));addIterator(Object.getPrototypeOf((new globals.Set).keys()))}return globals})}).call(this,require("_process"))},{_process:2}],4:[function(require,module,exports){"use strict";if(!require("./is-implemented")()){Object.defineProperty(require("es5-ext/global"),"Symbol",{value:require("./polyfill"),configurable:true,enumerable:false,writable:true})}},{"./is-implemented":5,"./polyfill":20,"es5-ext/global":7}],5:[function(require,module,exports){"use strict";module.exports=function(){var symbol;if(typeof Symbol!=="function")return false;symbol=Symbol("test symbol");try{String(symbol)}catch(e){return false}if(typeof Symbol.iterator==="symbol")return true;if(typeof Symbol.isConcatSpreadable!=="object")return false;if(typeof Symbol.isRegExp!=="object")return false;if(typeof Symbol.iterator!=="object")return false;if(typeof Symbol.toPrimitive!=="object")return false;if(typeof Symbol.toStringTag!=="object")return false;if(typeof Symbol.unscopables!=="object")return false;return true}},{}],6:[function(require,module,exports){"use strict";var assign=require("es5-ext/object/assign"),normalizeOpts=require("es5-ext/object/normalize-options"),isCallable=require("es5-ext/object/is-callable"),contains=require("es5-ext/string/#/contains"),d;d=module.exports=function(dscr,value){var c,e,w,options,desc;if(arguments.length<2||typeof dscr!=="string"){options=value;value=dscr;dscr=null}else{options=arguments[2]}if(dscr==null){c=w=true;e=false}else{c=contains.call(dscr,"c");e=contains.call(dscr,"e");w=contains.call(dscr,"w")}desc={value:value,configurable:c,enumerable:e,writable:w};return!options?desc:assign(normalizeOpts(options),desc)};d.gs=function(dscr,get,set){var c,e,options,desc;if(typeof dscr!=="string"){options=set;set=get;get=dscr;dscr=null}else{options=arguments[3]}if(get==null){get=undefined}else if(!isCallable(get)){options=get;get=set=undefined}else if(set==null){set=undefined}else if(!isCallable(set)){options=set;set=undefined}if(dscr==null){c=true;e=false}else{c=contains.call(dscr,"c");e=contains.call(dscr,"e")}desc={get:get,set:set,configurable:c,enumerable:e};return!options?desc:assign(normalizeOpts(options),desc)}},{"es5-ext/object/assign":8,"es5-ext/object/is-callable":11,"es5-ext/object/normalize-options":15,"es5-ext/string/#/contains":17}],7:[function(require,module,exports){"use strict";module.exports=new Function("return this")()},{}],8:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.assign:require("./shim")},{"./is-implemented":9,"./shim":10}],9:[function(require,module,exports){"use strict";module.exports=function(){var assign=Object.assign,obj;if(typeof assign!=="function")return false;obj={foo:"raz"};assign(obj,{bar:"dwa"},{trzy:"trzy"});return obj.foo+obj.bar+obj.trzy==="razdwatrzy"}},{}],10:[function(require,module,exports){"use strict";var keys=require("../keys"),value=require("../valid-value"),max=Math.max;module.exports=function(dest,src){var error,i,l=max(arguments.length,2),assign;dest=Object(value(dest));assign=function(key){try{dest[key]=src[key]}catch(e){if(!error)error=e}};for(i=1;i<l;++i){src=arguments[i];keys(src).forEach(assign)}if(error!==undefined)throw error;return dest}},{"../keys":12,"../valid-value":16}],11:[function(require,module,exports){"use strict";module.exports=function(obj){return typeof obj==="function"}},{}],12:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.keys:require("./shim")},{"./is-implemented":13,"./shim":14}],13:[function(require,module,exports){"use strict";module.exports=function(){try{Object.keys("primitive");return true}catch(e){return false}}},{}],14:[function(require,module,exports){"use strict";var keys=Object.keys;module.exports=function(object){return keys(object==null?object:Object(object))}},{}],15:[function(require,module,exports){"use strict";var assign=require("./assign"),forEach=Array.prototype.forEach,create=Object.create,getPrototypeOf=Object.getPrototypeOf,process;process=function(src,obj){var proto=getPrototypeOf(src);return assign(proto?process(proto,obj):obj,src)};module.exports=function(options){var result=create(null);forEach.call(arguments,function(options){if(options==null)return;process(Object(options),result)});return result}},{"./assign":8}],16:[function(require,module,exports){"use strict";module.exports=function(value){if(value==null)throw new TypeError("Cannot use null or undefined");return value}},{}],17:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?String.prototype.contains:require("./shim")},{"./is-implemented":18,"./shim":19}],18:[function(require,module,exports){"use strict";var str="razdwatrzy";module.exports=function(){if(typeof str.contains!=="function")return false;return str.contains("dwa")===true&&str.contains("foo")===false}},{}],19:[function(require,module,exports){"use strict";var indexOf=String.prototype.indexOf;module.exports=function(searchString){return indexOf.call(this,searchString,arguments[1])>-1}},{}],20:[function(require,module,exports){"use strict";var d=require("d"),create=Object.create,defineProperties=Object.defineProperties,generateName,Symbol;generateName=function(){var created=create(null);return function(desc){var postfix=0;while(created[desc+(postfix||"")])++postfix;desc+=postfix||"";created[desc]=true;return"@@"+desc}}();module.exports=Symbol=function(description){var symbol;if(this instanceof Symbol){throw new TypeError("TypeError: Symbol is not a constructor")}symbol=create(Symbol.prototype);description=description===undefined?"":String(description);return defineProperties(symbol,{__description__:d("",description),__name__:d("",generateName(description))})};Object.defineProperties(Symbol,{create:d("",Symbol("create")),hasInstance:d("",Symbol("hasInstance")),isConcatSpreadable:d("",Symbol("isConcatSpreadable")),isRegExp:d("",Symbol("isRegExp")),iterator:d("",Symbol("iterator")),toPrimitive:d("",Symbol("toPrimitive")),toStringTag:d("",Symbol("toStringTag")),unscopables:d("",Symbol("unscopables"))});defineProperties(Symbol.prototype,{properToString:d(function(){return"Symbol ("+this.__description__+")"}),toString:d("",function(){return this.__name__})});Object.defineProperty(Symbol.prototype,Symbol.toPrimitive,d("",function(hint){throw new TypeError("Conversion of symbol objects is not allowed")}));Object.defineProperty(Symbol.prototype,Symbol.toStringTag,d("c","Symbol"))},{d:6}],21:[function(require,module,exports){"use strict";module.exports=require("./lib/core.js");require("./lib/done.js");require("./lib/es6-extensions.js");require("./lib/node-extensions.js")},{"./lib/core.js":22,"./lib/done.js":23,"./lib/es6-extensions.js":24,"./lib/node-extensions.js":25}],22:[function(require,module,exports){"use strict";var asap=require("asap");module.exports=Promise;function Promise(fn){if(typeof this!=="object")throw new TypeError("Promises must be constructed via new");if(typeof fn!=="function")throw new TypeError("not a function");var state=null;var value=null;var deferreds=[];var self=this;this.then=function(onFulfilled,onRejected){return new self.constructor(function(resolve,reject){handle(new Handler(onFulfilled,onRejected,resolve,reject))})};function handle(deferred){if(state===null){deferreds.push(deferred);return}asap(function(){var cb=state?deferred.onFulfilled:deferred.onRejected;if(cb===null){(state?deferred.resolve:deferred.reject)(value);return}var ret;try{ret=cb(value)}catch(e){deferred.reject(e);return}deferred.resolve(ret)})}function resolve(newValue){try{if(newValue===self)throw new TypeError("A promise cannot be resolved with itself.");if(newValue&&(typeof newValue==="object"||typeof newValue==="function")){var then=newValue.then;if(typeof then==="function"){doResolve(then.bind(newValue),resolve,reject);return}}state=true;value=newValue;finale()}catch(e){reject(e)}}function reject(newValue){state=false;value=newValue;finale()}function finale(){for(var i=0,len=deferreds.length;i<len;i++)handle(deferreds[i]);deferreds=null}doResolve(fn,resolve,reject)}function Handler(onFulfilled,onRejected,resolve,reject){this.onFulfilled=typeof onFulfilled==="function"?onFulfilled:null;this.onRejected=typeof onRejected==="function"?onRejected:null;this.resolve=resolve;this.reject=reject}function doResolve(fn,onFulfilled,onRejected){var done=false;try{fn(function(value){if(done)return;done=true;onFulfilled(value)},function(reason){if(done)return;done=true;onRejected(reason)})}catch(ex){if(done)return;done=true;onRejected(ex)}}},{asap:26}],23:[function(require,module,exports){"use strict";var Promise=require("./core.js");var asap=require("asap");module.exports=Promise;Promise.prototype.done=function(onFulfilled,onRejected){var self=arguments.length?this.then.apply(this,arguments):this;self.then(null,function(err){asap(function(){throw err})})}},{"./core.js":22,asap:26}],24:[function(require,module,exports){"use strict";var Promise=require("./core.js");var asap=require("asap");module.exports=Promise;function ValuePromise(value){this.then=function(onFulfilled){if(typeof onFulfilled!=="function")return this;return new Promise(function(resolve,reject){asap(function(){try{resolve(onFulfilled(value))}catch(ex){reject(ex)}})})}}ValuePromise.prototype=Promise.prototype;var TRUE=new ValuePromise(true);var FALSE=new ValuePromise(false);var NULL=new ValuePromise(null);var UNDEFINED=new ValuePromise(undefined);var ZERO=new ValuePromise(0);var EMPTYSTRING=new ValuePromise("");Promise.resolve=function(value){if(value instanceof Promise)return value;if(value===null)return NULL;if(value===undefined)return UNDEFINED;if(value===true)return TRUE;if(value===false)return FALSE;if(value===0)return ZERO;if(value==="")return EMPTYSTRING;if(typeof value==="object"||typeof value==="function"){try{var then=value.then;if(typeof then==="function"){return new Promise(then.bind(value))}}catch(ex){return new Promise(function(resolve,reject){reject(ex)})}}return new ValuePromise(value)};Promise.all=function(arr){var args=Array.prototype.slice.call(arr);return new Promise(function(resolve,reject){if(args.length===0)return resolve([]);var remaining=args.length;function res(i,val){try{if(val&&(typeof val==="object"||typeof val==="function")){var then=val.then;if(typeof then==="function"){then.call(val,function(val){res(i,val)},reject);return}}args[i]=val;if(--remaining===0){resolve(args)}}catch(ex){reject(ex)}}for(var i=0;i<args.length;i++){res(i,args[i])}})};Promise.reject=function(value){return new Promise(function(resolve,reject){reject(value)})};Promise.race=function(values){return new Promise(function(resolve,reject){values.forEach(function(value){Promise.resolve(value).then(resolve,reject)})})};Promise.prototype["catch"]=function(onRejected){return this.then(null,onRejected)}},{"./core.js":22,asap:26}],25:[function(require,module,exports){"use strict";var Promise=require("./core.js");var asap=require("asap");module.exports=Promise;Promise.denodeify=function(fn,argumentCount){argumentCount=argumentCount||Infinity;return function(){var self=this;var args=Array.prototype.slice.call(arguments);return new Promise(function(resolve,reject){while(args.length&&args.length>argumentCount){args.pop()}args.push(function(err,res){if(err)reject(err);else resolve(res)});fn.apply(self,args)})}};Promise.nodeify=function(fn){return function(){var args=Array.prototype.slice.call(arguments);var callback=typeof args[args.length-1]==="function"?args.pop():null;var ctx=this;try{return fn.apply(this,arguments).nodeify(callback,ctx)}catch(ex){if(callback===null||typeof callback=="undefined"){return new Promise(function(resolve,reject){reject(ex)})}else{asap(function(){callback.call(ctx,ex)})}}}};Promise.prototype.nodeify=function(callback,ctx){if(typeof callback!="function")return this;this.then(function(value){asap(function(){callback.call(ctx,null,value)})},function(err){asap(function(){callback.call(ctx,err)})})}},{"./core.js":22,asap:26}],26:[function(require,module,exports){(function(process){var head={task:void 0,next:null};var tail=head;var flushing=false;var requestFlush=void 0;var isNodeJS=false;function flush(){while(head.next){head=head.next;var task=head.task;head.task=void 0;var domain=head.domain;if(domain){head.domain=void 0;domain.enter()}try{task()}catch(e){if(isNodeJS){if(domain){domain.exit()}setTimeout(flush,0);if(domain){domain.enter()}throw e}else{setTimeout(function(){throw e},0)}}if(domain){domain.exit()}}flushing=false}if(typeof process!=="undefined"&&process.nextTick){isNodeJS=true;requestFlush=function(){process.nextTick(flush)}}else if(typeof setImmediate==="function"){if(typeof window!=="undefined"){requestFlush=setImmediate.bind(window,flush)}else{requestFlush=function(){setImmediate(flush)}}}else if(typeof MessageChannel!=="undefined"){var channel=new MessageChannel;channel.port1.onmessage=flush;requestFlush=function(){channel.port2.postMessage(0)}}else{requestFlush=function(){setTimeout(flush,0)}}function asap(task){tail=tail.next={task:task,domain:isNodeJS&&process.domain,next:null};if(!flushing){flushing=true;requestFlush()}}module.exports=asap}).call(this,require("_process"))},{_process:2}],27:[function(require,module,exports){!function(){var hasOwn=Object.prototype.hasOwnProperty;var undefined;var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";if(typeof Promise==="undefined")try{Promise=require("promise")}catch(ignored){}if(typeof regeneratorRuntime==="object"){return}var runtime=regeneratorRuntime=typeof exports==="undefined"?{}:exports;function wrap(innerFn,outerFn,self,tryList){return new Generator(innerFn,outerFn,self||null,tryList||[])}runtime.wrap=wrap;var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};function GeneratorFunction(){}var Gp=Generator.prototype;var GFp=GeneratorFunction.prototype=Object.create(Function.prototype);GFp.constructor=GeneratorFunction;GFp.prototype=Gp;Gp.constructor=GFp;if(GeneratorFunction.name!=="GeneratorFunction"){GeneratorFunction.name="GeneratorFunction"}if(GeneratorFunction.name!=="GeneratorFunction"){throw new Error("GeneratorFunction renamed?")}runtime.isGeneratorFunction=function(genFun){var ctor=genFun&&genFun.constructor;return ctor?GeneratorFunction.name===ctor.name:false};runtime.mark=function(genFun){genFun.__proto__=GFp;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryList);var callNext=step.bind(generator.next);var callThrow=step.bind(generator.throw);function step(arg){try{var info=this(arg);var value=info.value}catch(error){return reject(error)}if(info.done){resolve(value)}else{Promise.resolve(value).then(callNext,callThrow)}}callNext()})};function Generator(innerFn,outerFn,self,tryList){var generator=outerFn?Object.create(outerFn.prototype):this;var context=new Context(tryList);var state=GenStateSuspendedStart;function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){throw new Error("Generator has already finished")}while(true){var delegate=context.delegate;if(delegate){try{var info=delegate.iterator[method](arg);method="next";arg=undefined}catch(uncaught){context.delegate=null;method="throw";arg=uncaught;continue}if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedStart&&typeof arg!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(arg)+" to newborn generator")}if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;try{var value=innerFn.call(self,context);state=context.done?GenStateCompleted:GenStateSuspendedYield;var info={value:value,done:context.done};if(value===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}catch(thrown){state=GenStateCompleted;if(method==="next"){context.dispatchException(thrown)}else{arg=thrown}}}}generator.next=invoke.bind(generator,"next");generator.throw=invoke.bind(generator,"throw");generator.return=invoke.bind(generator,"return");return generator}Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(triple){var entry={tryLoc:triple[0]};if(1 in triple){entry.catchLoc=triple[1]}if(2 in triple){entry.finallyLoc=triple[2]}this.tryEntries.push(entry)}function resetTryEntry(entry,i){var record=entry.completion||{};record.type=i===0?"normal":"return";delete record.arg;entry.completion=record}function Context(tryList){this.tryEntries=[{tryLoc:"root"}];tryList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){var iterator=iterable;if(iteratorSymbol in iterable){iterator=iterable[iteratorSymbol]()}else if(!isNaN(iterable.length)){var i=-1;iterator=function next(){while(++i<iterable.length){if(i in iterable){next.value=iterable[i];next.done=false;return next}}next.done=true;return next};iterator.next=iterator}return iterator}runtime.values=values;Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},_findFinallyEntry:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&(entry.finallyLoc===finallyLoc||this.prev<entry.finallyLoc)){return entry}}},abrupt:function(type,arg){var entry=this._findFinallyEntry();var record=entry?entry.completion:{};record.type=type;record.arg=arg;if(entry){this.next=entry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record){if(record.type==="throw"){throw record.arg}if(record.type==="break"||record.type==="continue"){this.next=record.arg}else if(record.type==="return"){this.rval=record.arg;this.next="end"}return ContinueSentinel},finish:function(finallyLoc){var entry=this._findFinallyEntry(finallyLoc);return this.complete(entry.completion)},"catch":function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if(record.type==="throw"){var thrown=record.arg;resetTryEntry(entry,i)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}()},{promise:21}]},{},[1]);
ajax/libs/extjs/4.2.1/src/AbstractComponent.js
boneskull/cdnjs
/* This file is part of Ext JS 4.2 Copyright (c) 2011-2013 Sencha Inc Contact: http://www.sencha.com/contact GNU General Public License Usage This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file. Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. Build date: 2013-05-16 14:36:50 (f9be68accb407158ba2b1be2c226a6ce1f649314) */ /** * An abstract base class which provides shared methods for Components across the Sencha product line. * * Please refer to sub class's documentation. * @private */ Ext.define('Ext.AbstractComponent', { /* Begin Definitions */ requires: [ 'Ext.ComponentQuery', 'Ext.ComponentManager', 'Ext.util.ProtoElement', 'Ext.dom.CompositeElement', 'Ext.PluginManager' ], mixins: { positionable: 'Ext.util.Positionable', observable: 'Ext.util.Observable', animate: 'Ext.util.Animate', elementCt: 'Ext.util.ElementContainer', renderable: 'Ext.util.Renderable', state: 'Ext.state.Stateful' }, // The "uses" property specifies class which are used in an instantiated AbstractComponent. // They do *not* have to be loaded before this class may be defined - that is what "requires" is for. uses: [ 'Ext.PluginManager', 'Ext.Element', 'Ext.DomHelper', 'Ext.XTemplate', 'Ext.ComponentLoader', 'Ext.EventManager', 'Ext.layout.Context', 'Ext.layout.Layout', 'Ext.layout.component.Auto', 'Ext.LoadMask', 'Ext.ZIndexManager' ], statics: { AUTO_ID: 1000, pendingLayouts: null, layoutSuspendCount: 0, /** * Cancels layout of a component. * @param {Ext.Component} comp */ cancelLayout: function(comp, isDestroying) { var context = this.runningLayoutContext || this.pendingLayouts; if (context) { context.cancelComponent(comp, false, isDestroying); } }, /** * Performs all pending layouts that were scheduled while * {@link Ext.AbstractComponent#suspendLayouts suspendLayouts} was in effect. * @static */ flushLayouts: function () { var me = this, context = me.pendingLayouts; if (context && context.invalidQueue.length) { me.pendingLayouts = null; me.runningLayoutContext = context; Ext.override(context, { runComplete: function () { // we need to release the layout queue before running any of the // finishedLayout calls because they call afterComponentLayout // which can re-enter by calling doLayout/doComponentLayout. me.runningLayoutContext = null; var result = this.callParent(); // not "me" here! if (Ext.globalEvents.hasListeners.afterlayout) { Ext.globalEvents.fireEvent('afterlayout'); } return result; } }); context.run(); } }, /** * Resumes layout activity in the whole framework. * * {@link Ext#suspendLayouts} is alias of {@link Ext.AbstractComponent#suspendLayouts}. * * @param {Boolean} [flush=false] `true` to perform all the pending layouts. This can also be * achieved by calling {@link Ext.AbstractComponent#flushLayouts flushLayouts} directly. * @static */ resumeLayouts: function (flush) { if (this.layoutSuspendCount && ! --this.layoutSuspendCount) { if (flush) { this.flushLayouts(); } if (Ext.globalEvents.hasListeners.resumelayouts) { Ext.globalEvents.fireEvent('resumelayouts'); } } }, /** * Stops layouts from happening in the whole framework. * * It's useful to suspend the layout activity while updating multiple components and * containers: * * Ext.suspendLayouts(); * // batch of updates... * Ext.resumeLayouts(true); * * {@link Ext#suspendLayouts} is alias of {@link Ext.AbstractComponent#suspendLayouts}. * * See also {@link Ext#batchLayouts} for more abstract way of doing this. * * @static */ suspendLayouts: function () { ++this.layoutSuspendCount; }, /** * Updates layout of a component. * * @param {Ext.Component} comp The component to update. * @param {Boolean} [defer=false] `true` to just queue the layout if this component. * @static */ updateLayout: function (comp, defer) { var me = this, running = me.runningLayoutContext, pending; if (running) { running.queueInvalidate(comp); } else { pending = me.pendingLayouts || (me.pendingLayouts = new Ext.layout.Context()); pending.queueInvalidate(comp); if (!defer && !me.layoutSuspendCount && !comp.isLayoutSuspended()) { me.flushLayouts(); } } } }, /* End Definitions */ /** * @property {Boolean} isComponent * `true` in this class to identify an object as an instantiated Component, or subclass thereof. */ isComponent: true, /** * @private */ getAutoId: function() { this.autoGenId = true; return ++Ext.AbstractComponent.AUTO_ID; }, deferLayouts: false, /** * @cfg {String} id * The **unique id of this component instance.** * * It should not be necessary to use this configuration except for singleton objects in your application. Components * created with an `id` may be accessed globally using {@link Ext#getCmp Ext.getCmp}. * * Instead of using assigned ids, use the {@link #itemId} config, and {@link Ext.ComponentQuery ComponentQuery} * which provides selector-based searching for Sencha Components analogous to DOM querying. The {@link * Ext.container.Container Container} class contains {@link Ext.container.Container#down shortcut methods} to query * its descendant Components by selector. * * Note that this `id` will also be used as the element id for the containing HTML element that is rendered to the * page for this component. This allows you to write id-based CSS rules to style the specific instance of this * component uniquely, and also to select sub-elements using this component's `id` as the parent. * * **Note:** To avoid complications imposed by a unique `id` also see `{@link #itemId}`. * * **Note:** To access the container of a Component see `{@link #ownerCt}`. * * Defaults to an {@link #getId auto-assigned id}. * * @since 1.1.0 */ /** * @property {Boolean} autoGenId * `true` indicates an `id` was auto-generated rather than provided by configuration. * @private */ autoGenId: false, /** * @cfg {String} itemId * An `itemId` can be used as an alternative way to get a reference to a component when no object reference is * available. Instead of using an `{@link #id}` with {@link Ext}.{@link Ext#getCmp getCmp}, use `itemId` with * {@link Ext.container.Container}.{@link Ext.container.Container#getComponent getComponent} which will retrieve * `itemId`'s or {@link #id}'s. Since `itemId`'s are an index to the container's internal MixedCollection, the * `itemId` is scoped locally to the container -- avoiding potential conflicts with {@link Ext.ComponentManager} * which requires a **unique** `{@link #id}`. * * var c = new Ext.panel.Panel({ // * {@link Ext.Component#height height}: 300, * {@link #renderTo}: document.body, * {@link Ext.container.Container#layout layout}: 'auto', * {@link Ext.container.Container#cfg-items items}: [ * { * itemId: 'p1', * {@link Ext.panel.Panel#title title}: 'Panel 1', * {@link Ext.Component#height height}: 150 * }, * { * itemId: 'p2', * {@link Ext.panel.Panel#title title}: 'Panel 2', * {@link Ext.Component#height height}: 150 * } * ] * }) * p1 = c.{@link Ext.container.Container#getComponent getComponent}('p1'); // not the same as {@link Ext#getCmp Ext.getCmp()} * p2 = p1.{@link #ownerCt}.{@link Ext.container.Container#getComponent getComponent}('p2'); // reference via a sibling * * Also see {@link #id}, `{@link Ext.container.Container#query}`, `{@link Ext.container.Container#down}` and * `{@link Ext.container.Container#child}`. * * **Note**: to access the container of an item see {@link #ownerCt}. * * @since 3.4.0 */ /** * @property {Ext.Container} ownerCt * This Component's owner {@link Ext.container.Container Container} (is set automatically * when this Component is added to a Container). * * *Important.* This is not a universal upwards navigation pointer. It indicates the Container which owns and manages * this Component if any. There are other similar relationships such as the {@link Ext.button.Button button} which activates a {@link Ext.button.Button#cfg-menu menu}, or the * {@link Ext.menu.Item menu item} which activated a {@link Ext.menu.Item#cfg-menu submenu}, or the * {@link Ext.grid.column.Column column header} which activated the column menu. * * These differences are abstracted away by the {@link #up} method. * * **Note**: to access items within the Container see {@link #itemId}. * @readonly * @since 2.3.0 */ /** * @cfg {String/Object} autoEl * A tag name or {@link Ext.DomHelper DomHelper} spec used to create the {@link #getEl Element} which will * encapsulate this Component. * * You do not normally need to specify this. For the base classes {@link Ext.Component} and * {@link Ext.container.Container}, this defaults to **'div'**. The more complex Sencha classes use a more * complex DOM structure specified by their own {@link #renderTpl}s. * * This is intended to allow the developer to create application-specific utility Components encapsulated by * different DOM elements. Example usage: * * { * xtype: 'component', * autoEl: { * tag: 'img', * src: 'http://www.example.com/example.jpg' * } * }, { * xtype: 'component', * autoEl: { * tag: 'blockquote', * html: 'autoEl is cool!' * } * }, { * xtype: 'container', * autoEl: 'ul', * cls: 'ux-unordered-list', * items: { * xtype: 'component', * autoEl: 'li', * html: 'First list item' * } * } * * @since 2.3.0 */ /** * @cfg {Ext.XTemplate/String/String[]} renderTpl * An {@link Ext.XTemplate XTemplate} used to create the internal structure inside this Component's encapsulating * {@link #getEl Element}. * * You do not normally need to specify this. For the base classes {@link Ext.Component} and * {@link Ext.container.Container}, this defaults to **`null`** which means that they will be initially rendered * with no internal structure; they render their {@link #getEl Element} empty. The more specialized Ext JS and Sencha Touch * classes which use a more complex DOM structure, provide their own template definitions. * * This is intended to allow the developer to create application-specific utility Components with customized * internal structure. * * Upon rendering, any created child elements may be automatically imported into object properties using the * {@link #renderSelectors} and {@link #cfg-childEls} options. * @protected */ renderTpl: '{%this.renderContent(out,values)%}', /** * @cfg {Object} renderData * * The data used by {@link #renderTpl} in addition to the following property values of the component: * * - id * - ui * - uiCls * - baseCls * - componentCls * - frame * * See {@link #renderSelectors} and {@link #cfg-childEls} for usage examples. */ /** * @cfg {Object} renderSelectors * An object containing properties specifying {@link Ext.DomQuery DomQuery} selectors which identify child elements * created by the render process. * * After the Component's internal structure is rendered according to the {@link #renderTpl}, this object is iterated through, * and the found Elements are added as properties to the Component using the `renderSelector` property name. * * For example, a Component which renders a title and description into its element: * * Ext.create('Ext.Component', { * renderTo: Ext.getBody(), * renderTpl: [ * '<h1 class="title">{title}</h1>', * '<p>{desc}</p>' * ], * renderData: { * title: "Error", * desc: "Something went wrong" * }, * renderSelectors: { * titleEl: 'h1.title', * descEl: 'p' * }, * listeners: { * afterrender: function(cmp){ * // After rendering the component will have a titleEl and descEl properties * cmp.titleEl.setStyle({color: "red"}); * } * } * }); * * For a faster, but less flexible, alternative that achieves the same end result (properties for child elements on the * Component after render), see {@link #cfg-childEls} and {@link #addChildEls}. */ /** * @cfg {Object[]} childEls * An array describing the child elements of the Component. Each member of the array * is an object with these properties: * * - `name` - The property name on the Component for the child element. * - `itemId` - The id to combine with the Component's id that is the id of the child element. * - `id` - The id of the child element. * * If the array member is a string, it is equivalent to `{ name: m, itemId: m }`. * * For example, a Component which renders a title and body text: * * @example * Ext.create('Ext.Component', { * renderTo: Ext.getBody(), * renderTpl: [ * '<h1 id="{id}-title">{title}</h1>', * '<p>{msg}</p>', * ], * renderData: { * title: "Error", * msg: "Something went wrong" * }, * childEls: ["title"], * listeners: { * afterrender: function(cmp){ * // After rendering the component will have a title property * cmp.title.setStyle({color: "red"}); * } * } * }); * * A more flexible, but somewhat slower, approach is {@link #renderSelectors}. */ /** * @cfg {String/HTMLElement/Ext.Element} renderTo * Specify the `id` of the element, a DOM element or an existing Element that this component will be rendered into. * * **Notes:** * * Do *not* use this option if the Component is to be a child item of a {@link Ext.container.Container Container}. * It is the responsibility of the {@link Ext.container.Container Container}'s * {@link Ext.container.Container#layout layout manager} to render and manage its child items. * * When using this config, a call to `render()` is not required. * * See also: {@link #method-render}. * * @since 2.3.0 */ /** * @cfg {Boolean} frame * Specify as `true` to have the Component inject framing elements within the Component at render time to provide a * graphical rounded frame around the Component content. * * This is only necessary when running on outdated, or non standard-compliant browsers such as Microsoft's Internet * Explorer prior to version 9 which do not support rounded corners natively. * * The extra space taken up by this framing is available from the read only property {@link #frameSize}. */ /** * @property {Object} frameSize * @readonly * Indicates the width of any framing elements which were added within the encapsulating * element to provide graphical, rounded borders. See the {@link #frame} config. This * property is `null` if the component is not framed. * * This is an object containing the frame width in pixels for all four sides of the * Component containing the following properties: * * @property {Number} [frameSize.top=0] The width of the top framing element in pixels. * @property {Number} [frameSize.right=0] The width of the right framing element in pixels. * @property {Number} [frameSize.bottom=0] The width of the bottom framing element in pixels. * @property {Number} [frameSize.left=0] The width of the left framing element in pixels. * @property {Number} [frameSize.width=0] The total width of the left and right framing elements in pixels. * @property {Number} [frameSize.height=0] The total height of the top and right bottom elements in pixels. */ frameSize: null, /** * @cfg {String/Object} componentLayout * The sizing and positioning of a Component's internal Elements is the responsibility of the Component's layout * manager which sizes a Component's internal structure in response to the Component being sized. * * Generally, developers will not use this configuration as all provided Components which need their internal * elements sizing (Such as {@link Ext.form.field.Base input fields}) come with their own componentLayout managers. * * The {@link Ext.layout.container.Auto default layout manager} will be used on instances of the base Ext.Component * class which simply sizes the Component's encapsulating element to the height and width specified in the * {@link #setSize} method. */ /** * @cfg {Ext.XTemplate/Ext.Template/String/String[]} tpl * An {@link Ext.Template}, {@link Ext.XTemplate} or an array of strings to form an Ext.XTemplate. Used in * conjunction with the `{@link #data}` and `{@link #tplWriteMode}` configurations. * * @since 3.4.0 */ /** * @cfg {Object} data * The initial set of data to apply to the `{@link #tpl}` to update the content area of the Component. * * @since 3.4.0 */ /** * @cfg {Ext.enums.Widget} xtype * This property provides a shorter alternative to creating objects than using a full * class name. Using `xtype` is the most common way to define component instances, * especially in a container. For example, the items in a form containing text fields * could be created explicitly like so: * * items: [ * Ext.create('Ext.form.field.Text', { * fieldLabel: 'Foo' * }), * Ext.create('Ext.form.field.Text', { * fieldLabel: 'Bar' * }), * Ext.create('Ext.form.field.Number', { * fieldLabel: 'Num' * }) * ] * * But by using `xtype`, the above becomes: * * items: [ * { * xtype: 'textfield', * fieldLabel: 'Foo' * }, * { * xtype: 'textfield', * fieldLabel: 'Bar' * }, * { * xtype: 'numberfield', * fieldLabel: 'Num' * } * ] * * When the `xtype` is common to many items, {@link Ext.container.AbstractContainer#defaultType} * is another way to specify the `xtype` for all items that don't have an explicit `xtype`: * * defaultType: 'textfield', * items: [ * { fieldLabel: 'Foo' }, * { fieldLabel: 'Bar' }, * { fieldLabel: 'Num', xtype: 'numberfield' } * ] * * Each member of the `items` array is now just a "configuration object". These objects * are used to create and configure component instances. A configuration object can be * manually used to instantiate a component using {@link Ext#widget}: * * var text1 = Ext.create('Ext.form.field.Text', { * fieldLabel: 'Foo' * }); * * // or alternatively: * * var text1 = Ext.widget({ * xtype: 'textfield', * fieldLabel: 'Foo' * }); * * This conversion of configuration objects into instantiated components is done when * a container is created as part of its {Ext.container.AbstractContainer#initComponent} * process. As part of the same process, the `items` array is converted from its raw * array form into a {@link Ext.util.MixedCollection} instance. * * You can define your own `xtype` on a custom {@link Ext.Component component} by specifying * the `xtype` property in {@link Ext#define}. For example: * * Ext.define('MyApp.PressMeButton', { * extend: 'Ext.button.Button', * xtype: 'pressmebutton', * text: 'Press Me' * }); * * Care should be taken when naming an `xtype` in a custom component because there is * a single, shared scope for all xtypes. Third part components should consider using * a prefix to avoid collisions. * * Ext.define('Foo.form.CoolButton', { * extend: 'Ext.button.Button', * xtype: 'ux-coolbutton', * text: 'Cool!' * }); * * See {@link Ext.enums.Widget} for list of all available xtypes. * * @since 2.3.0 */ /** * @cfg {String} tplWriteMode * The Ext.(X)Template method to use when updating the content area of the Component. * See `{@link Ext.XTemplate#overwrite}` for information on default mode. * * @since 3.4.0 */ tplWriteMode: 'overwrite', /** * @cfg {String} [baseCls='x-component'] * The base CSS class to apply to this component's element. This will also be prepended to elements within this * component like Panel's body will get a class `x-panel-body`. This means that if you create a subclass of Panel, and * you want it to get all the Panels styling for the element and the body, you leave the `baseCls` `x-panel` and use * `componentCls` to add specific styling for this component. */ baseCls: Ext.baseCSSPrefix + 'component', /** * @cfg {String} componentCls * CSS Class to be added to a components root level element to give distinction to it via styling. */ /** * @cfg {String} [cls=''] * An optional extra CSS class that will be added to this component's Element. This can be useful * for adding customized styles to the component or any of its children using standard CSS rules. * * @since 1.1.0 */ /** * @cfg {String} [overCls=''] * An optional extra CSS class that will be added to this component's Element when the mouse moves over the Element, * and removed when the mouse moves out. This can be useful for adding customized 'active' or 'hover' styles to the * component or any of its children using standard CSS rules. * * @since 2.3.0 */ /** * @cfg {String} [disabledCls='x-item-disabled'] * CSS class to add when the Component is disabled. */ disabledCls: Ext.baseCSSPrefix + 'item-disabled', /** * @cfg {String} ui * A UI style for a component. */ ui: 'default', /** * @cfg {String[]} uiCls * An array of of `classNames` which are currently applied to this component. * @private */ uiCls: [], /** * @cfg {String/Object} style * A custom style specification to be applied to this component's Element. Should be a valid argument to * {@link Ext.Element#applyStyles}. * * new Ext.panel.Panel({ * title: 'Some Title', * renderTo: Ext.getBody(), * width: 400, height: 300, * layout: 'form', * items: [{ * xtype: 'textarea', * style: { * width: '95%', * marginBottom: '10px' * } * }, * new Ext.button.Button({ * text: 'Send', * minWidth: '100', * style: { * marginBottom: '10px' * } * }) * ] * }); * * @since 1.1.0 */ /** * @cfg {Number} width * The width of this component in pixels. */ /** * @cfg {Number} height * The height of this component in pixels. */ /** * @cfg {Number/String/Boolean} border * Specifies the border size for this component. The border can be a single numeric value to apply to all sides or it can * be a CSS style specification for each style, for example: '10 5 3 10' (top, right, bottom, left). * * For components that have no border by default, setting this won't make the border appear by itself. * You also need to specify border color and style: * * border: 5, * style: { * borderColor: 'red', * borderStyle: 'solid' * } * * To turn off the border, use `border: false`. */ /** * @cfg {Number/String} padding * Specifies the padding for this component. The padding can be a single numeric value to apply to all sides or it * can be a CSS style specification for each style, for example: '10 5 3 10' (top, right, bottom, left). */ /** * @cfg {Number/String} margin * Specifies the margin for this component. The margin can be a single numeric value to apply to all sides or it can * be a CSS style specification for each style, for example: '10 5 3 10' (top, right, bottom, left). */ /** * @cfg {Boolean} hidden * `true` to hide the component. * @since 2.3.0 */ hidden: false, /** * @cfg {Boolean} disabled * `true` to disable the component. * @since 2.3.0 */ disabled: false, /** * @cfg {Boolean} [draggable=false] * Allows the component to be dragged. */ /** * @property {Boolean} draggable * Indicates whether or not the component can be dragged. * @readonly */ draggable: false, /** * @cfg {Boolean} floating * Create the Component as a floating and use absolute positioning. * * The z-index of floating Components is handled by a ZIndexManager. If you simply render a floating Component into the DOM, it will be managed * by the global {@link Ext.WindowManager WindowManager}. * * If you include a floating Component as a child item of a Container, then upon render, Ext JS will seek an ancestor floating Component to house a new * ZIndexManager instance to manage its descendant floaters. If no floating ancestor can be found, the global WindowManager will be used. * * When a floating Component which has a ZindexManager managing descendant floaters is destroyed, those descendant floaters will also be destroyed. */ floating: false, /** * @cfg {String} hideMode * A String which specifies how this Component's encapsulating DOM element will be hidden. Values may be: * * - `'display'` : The Component will be hidden using the `display: none` style. * - `'visibility'` : The Component will be hidden using the `visibility: hidden` style. * - `'offsets'` : The Component will be hidden by absolutely positioning it out of the visible area of the document. * This is useful when a hidden Component must maintain measurable dimensions. Hiding using `display` results in a * Component having zero dimensions. * * @since 1.1.0 */ hideMode: 'display', /** * @cfg {String} contentEl * Specify an existing HTML element, or the `id` of an existing HTML element to use as the content for this component. * * This config option is used to take an existing HTML element and place it in the layout element of a new component * (it simply moves the specified DOM element _after the Component is rendered_ to use as the content. * * **Notes:** * * The specified HTML element is appended to the layout element of the component _after any configured * {@link #html HTML} has been inserted_, and so the document will not contain this element at the time * the {@link #event-render} event is fired. * * The specified HTML element used will not participate in any **`{@link Ext.container.Container#layout layout}`** * scheme that the Component may use. It is just HTML. Layouts operate on child * **`{@link Ext.container.Container#cfg-items items}`**. * * Add either the `x-hidden` or the `x-hide-display` CSS class to prevent a brief flicker of the content before it * is rendered to the panel. * * @since 3.4.0 */ /** * @cfg {String/Object} [html=''] * An HTML fragment, or a {@link Ext.DomHelper DomHelper} specification to use as the layout element content. * The HTML content is added after the component is rendered, so the document will not contain this HTML at the time * the {@link #event-render} event is fired. This content is inserted into the body _before_ any configured {@link #contentEl} * is appended. * * @since 3.4.0 */ /** * @cfg {Number} minHeight * The minimum value in pixels which this Component will set its height to. * * **Warning:** This will override any size management applied by layout managers. */ /** * @cfg {Number} minWidth * The minimum value in pixels which this Component will set its width to. * * **Warning:** This will override any size management applied by layout managers. */ /** * @cfg {Number} maxHeight * The maximum value in pixels which this Component will set its height to. * * **Warning:** This will override any size management applied by layout managers. */ /** * @cfg {Number} maxWidth * The maximum value in pixels which this Component will set its width to. * * **Warning:** This will override any size management applied by layout managers. */ /** * @cfg {Ext.ComponentLoader/Object} loader * A configuration object or an instance of a {@link Ext.ComponentLoader} to load remote content * for this Component. * * Ext.create('Ext.Component', { * loader: { * url: 'content.html', * autoLoad: true * }, * renderTo: Ext.getBody() * }); */ /** * @cfg {Ext.ComponentLoader/Object/String/Boolean} autoLoad * An alias for {@link #loader} config which also allows to specify just a string which will be * used as the url that's automatically loaded: * * Ext.create('Ext.Component', { * autoLoad: 'content.html', * renderTo: Ext.getBody() * }); * * The above is the same as: * * Ext.create('Ext.Component', { * loader: { * url: 'content.html', * autoLoad: true * }, * renderTo: Ext.getBody() * }); * * Don't use it together with {@link #loader} config. * * @deprecated 4.1.1 Use {@link #loader} config instead. */ /** * @cfg {Boolean} autoShow * `true` to automatically show the component upon creation. This config option may only be used for * {@link #floating} components or components that use {@link #autoRender}. * * @since 2.3.0 */ autoShow: false, /** * @cfg {Boolean/String/HTMLElement/Ext.Element} autoRender * This config is intended mainly for non-{@link #cfg-floating} Components which may or may not be shown. Instead of using * {@link #renderTo} in the configuration, and rendering upon construction, this allows a Component to render itself * upon first _{@link Ext.Component#method-show show}_. If {@link #cfg-floating} is `true`, the value of this config is omitted as if it is `true`. * * Specify as `true` to have this Component render to the document body upon first show. * * Specify as an element, or the ID of an element to have this Component render to a specific element upon first * show. */ autoRender: false, // @private allowDomMove: true, /** * @cfg {Ext.AbstractPlugin[]/Ext.AbstractPlugin/Object[]/Object/Ext.enums.Plugin[]/Ext.enums.Plugin} plugins * An array of plugins to be added to this component. Can also be just a single plugin instead of array. * * Plugins provide custom functionality for a component. The only requirement for * a valid plugin is that it contain an `init` method that accepts a reference of type Ext.Component. When a component * is created, if any plugins are available, the component will call the init method on each plugin, passing a * reference to itself. Each plugin can then call methods or respond to events on the component as needed to provide * its functionality. * * Plugins can be added to component by either directly referencing the plugin instance: * * plugins: [Ext.create('Ext.grid.plugin.CellEditing', {clicksToEdit: 1})], * * By using config object with ptype: * * plugins: [{ptype: 'cellediting', clicksToEdit: 1}], * * Or with just a ptype: * * plugins: ['cellediting', 'gridviewdragdrop'], * * See {@link Ext.enums.Plugin} for list of all ptypes. * * @since 2.3.0 */ /** * @property {Boolean} rendered * Indicates whether or not the component has been rendered. * @readonly * @since 1.1.0 */ rendered: false, /** * @property {Number} componentLayoutCounter * @private * The number of component layout calls made on this object. */ componentLayoutCounter: 0, /** * @cfg {Boolean/Number} [shrinkWrap=2] * * If this property is a number, it is interpreted as follows: * * - 0: Neither width nor height depend on content. This is equivalent to `false`. * - 1: Width depends on content (shrink wraps), but height does not. * - 2: Height depends on content (shrink wraps), but width does not. The default. * - 3: Both width and height depend on content (shrink wrap). This is equivalent to `true`. * * In CSS terms, shrink-wrap width is analogous to an inline-block element as opposed * to a block-level element. Some container layouts always shrink-wrap their children, * effectively ignoring this property (e.g., {@link Ext.layout.container.HBox}, * {@link Ext.layout.container.VBox}, {@link Ext.layout.component.Dock}). */ shrinkWrap: 2, weight: 0, /** * @property {Boolean} maskOnDisable * This is an internal flag that you use when creating custom components. By default this is set to `true` which means * that every component gets a mask when it's disabled. Components like FieldContainer, FieldSet, Field, Button, Tab * override this property to `false` since they want to implement custom disable logic. */ maskOnDisable: true, /** * @property {Boolean} [_isLayoutRoot=false] * Setting this property to `true` causes the {@link #isLayoutRoot} method to return * `true` and stop the search for the top-most component for a layout. * @protected */ _isLayoutRoot: false, /** * @property {String} [contentPaddingProperty='padding'] * The name of the padding property that is used by the layout to manage * padding. See {@link Ext.layout.container.Auto#managePadding managePadding} */ contentPaddingProperty: 'padding', horizontalPosProp: 'left', // private borderBoxCls: Ext.baseCSSPrefix + 'border-box', /** * Creates new Component. * @param {Object} config (optional) Config object. */ constructor : function(config) { var me = this, i, len, xhooks; if (config) { Ext.apply(me, config); xhooks = me.xhooks; if (xhooks) { delete me.xhooks; Ext.override(me, xhooks); } } else { config = {}; } me.initialConfig = config; me.mixins.elementCt.constructor.call(me); me.addEvents( /** * @event beforeactivate * Fires before a Component has been visually activated. Returning `false` from an event listener can prevent * the activate from occurring. * @param {Ext.Component} this */ 'beforeactivate', /** * @event activate * Fires after a Component has been visually activated. * @param {Ext.Component} this */ 'activate', /** * @event beforedeactivate * Fires before a Component has been visually deactivated. Returning `false` from an event listener can * prevent the deactivate from occurring. * @param {Ext.Component} this */ 'beforedeactivate', /** * @event deactivate * Fires after a Component has been visually deactivated. * @param {Ext.Component} this */ 'deactivate', /** * @event added * Fires after a Component had been added to a Container. * @param {Ext.Component} this * @param {Ext.container.Container} container Parent Container * @param {Number} pos position of Component * @since 3.4.0 */ 'added', /** * @event disable * Fires after the component is disabled. * @param {Ext.Component} this * @since 1.1.0 */ 'disable', /** * @event enable * Fires after the component is enabled. * @param {Ext.Component} this * @since 1.1.0 */ 'enable', /** * @event beforeshow * Fires before the component is shown when calling the {@link Ext.Component#method-show show} method. Return `false` from an event * handler to stop the show. * @param {Ext.Component} this * @since 1.1.0 */ 'beforeshow', /** * @event show * Fires after the component is shown when calling the {@link Ext.Component#method-show show} method. * @param {Ext.Component} this * @since 1.1.0 */ 'show', /** * @event beforehide * Fires before the component is hidden when calling the {@link Ext.Component#method-hide hide} method. Return `false` from an event * handler to stop the hide. * @param {Ext.Component} this * @since 1.1.0 */ 'beforehide', /** * @event hide * Fires after the component is hidden. Fires after the component is hidden when calling the {@link Ext.Component#method-hide hide} * method. * @param {Ext.Component} this * @since 1.1.0 */ 'hide', /** * @event removed * Fires when a component is removed from an Ext.container.Container * @param {Ext.Component} this * @param {Ext.container.Container} ownerCt Container which holds the component * @since 3.4.0 */ 'removed', /** * @event beforerender * Fires before the component is {@link #rendered}. Return `false` from an event handler to stop the * {@link #method-render}. * @param {Ext.Component} this * @since 1.1.0 */ 'beforerender', /** * @event render * Fires after the component markup is {@link #rendered}. * @param {Ext.Component} this * @since 1.1.0 */ 'render', /** * @event afterrender * Fires after the component rendering is finished. * * The `afterrender` event is fired after this Component has been {@link #rendered}, been postprocessed by any * `afterRender` method defined for the Component. * @param {Ext.Component} this * @since 3.4.0 */ 'afterrender', /** * @event boxready * Fires *one time* - after the component has been laid out for the first time at its initial size. * @param {Ext.Component} this * @param {Number} width The initial width. * @param {Number} height The initial height. */ 'boxready', /** * @event beforedestroy * Fires before the component is {@link #method-destroy}ed. Return `false` from an event handler to stop the * {@link #method-destroy}. * @param {Ext.Component} this * @since 1.1.0 */ 'beforedestroy', /** * @event destroy * Fires after the component is {@link #method-destroy}ed. * @param {Ext.Component} this * @since 1.1.0 */ 'destroy', /** * @event resize * Fires after the component is resized. Note that this does *not* fire when the component is first laid out at its initial * size. To hook that point in the life cycle, use the {@link #boxready} event. * @param {Ext.Component} this * @param {Number} width The new width that was set. * @param {Number} height The new height that was set. * @param {Number} oldWidth The previous width. * @param {Number} oldHeight The previous height. */ 'resize', /** * @event move * Fires after the component is moved. * @param {Ext.Component} this * @param {Number} x The new x position. * @param {Number} y The new y position. */ 'move', /** * @event focus * Fires when this Component receives focus. * @param {Ext.Component} this * @param {Ext.EventObject} The focus event. */ 'focus', /** * @event blur * Fires when this Component loses focus. * @param {Ext.Component} this * @param {Ext.EventObject} The blur event. */ 'blur' ); me.getId(); me.setupProtoEl(); // initComponent, beforeRender, or event handlers may have set the style or `cls` property since the `protoEl` was set up // so we must apply styles and classes here too. if (me.cls) { me.initialCls = me.cls; me.protoEl.addCls(me.cls); } if (me.style) { me.initialStyle = me.style; me.protoEl.setStyle(me.style); } me.renderData = me.renderData || {}; me.renderSelectors = me.renderSelectors || {}; if (me.plugins) { me.plugins = me.constructPlugins(); } // we need this before we call initComponent if (!me.hasListeners) { me.hasListeners = new me.HasListeners(); } me.initComponent(); // ititComponent gets a chance to change the id property before registering Ext.ComponentManager.register(me); // Don't pass the config so that it is not applied to 'this' again me.mixins.observable.constructor.call(me); me.mixins.state.constructor.call(me, config); // Save state on resize. this.addStateEvents('resize'); // Move this into Observable? if (me.plugins) { for (i = 0, len = me.plugins.length; i < len; i++) { me.plugins[i] = me.initPlugin(me.plugins[i]); } } me.loader = me.getLoader(); if (me.renderTo) { me.render(me.renderTo); // EXTJSIV-1935 - should be a way to do afterShow or something, but that // won't work. Likewise, rendering hidden and then showing (w/autoShow) has // implications to afterRender so we cannot do that. } // Auto show only works unilaterally on *uncontained* Components. // If contained, then it is the Container's responsibility to do the showing at next layout time. if (me.autoShow && !me.isContained) { me.show(); } //<debug> if (Ext.isDefined(me.disabledClass)) { if (Ext.isDefined(Ext.global.console)) { Ext.global.console.warn('Ext.Component: disabledClass has been deprecated. Please use disabledCls.'); } me.disabledCls = me.disabledClass; delete me.disabledClass; } //</debug> }, initComponent: function () { // This is called again here to allow derived classes to add plugin configs to the // plugins array before calling down to this, the base initComponent. this.plugins = this.constructPlugins(); // this will properly (ignore or) constrain the configured width/height to their // min/max values for consistency. this.setSize(this.width, this.height); }, /** * The supplied default state gathering method for the AbstractComponent class. * * This method returns dimension settings such as `flex`, `anchor`, `width` and `height` along with `collapsed` * state. * * Subclasses which implement more complex state should call the superclass's implementation, and apply their state * to the result if this basic state is to be saved. * * Note that Component state will only be saved if the Component has a {@link #stateId} and there as a StateProvider * configured for the document. * * @return {Object} */ getState: function() { var me = this, state = null, sizeModel = me.getSizeModel(); if (sizeModel.width.configured) { state = me.addPropertyToState(state, 'width'); } if (sizeModel.height.configured) { state = me.addPropertyToState(state, 'height'); } return state; }, /** * Save a property to the given state object if it is not its default or configured * value. * * @param {Object} state The state object. * @param {String} propName The name of the property on this object to save. * @param {String} [value] The value of the state property (defaults to `this[propName]`). * @return {Boolean} The state object or a new object if state was `null` and the property * was saved. * @protected */ addPropertyToState: function (state, propName, value) { var me = this, len = arguments.length; // If the property is inherited, it is a default and we don't want to save it to // the state, however if we explicitly specify a value, always save it if (len == 3 || me.hasOwnProperty(propName)) { if (len < 3) { value = me[propName]; } // If the property has the same value as was initially configured, again, we // don't want to save it. if (value !== me.initialConfig[propName]) { (state || (state = {}))[propName] = value; } } return state; }, show: Ext.emptyFn, animate: function(animObj) { var me = this, hasToWidth, hasToHeight, toHeight, toWidth, to, clearWidth, clearHeight, curWidth, w, curHeight, h, isExpanding, wasConstrained, wasConstrainedHeader, passedCallback, oldOverflow; animObj = animObj || {}; to = animObj.to || {}; if (Ext.fx.Manager.hasFxBlock(me.id)) { return me; } hasToWidth = Ext.isDefined(to.width); if (hasToWidth) { toWidth = Ext.Number.constrain(to.width, me.minWidth, me.maxWidth); } hasToHeight = Ext.isDefined(to.height); if (hasToHeight) { toHeight = Ext.Number.constrain(to.height, me.minHeight, me.maxHeight); } // Special processing for animating Component dimensions. if (!animObj.dynamic && (hasToWidth || hasToHeight)) { curWidth = (animObj.from ? animObj.from.width : undefined) || me.getWidth(); w = curWidth; curHeight = (animObj.from ? animObj.from.height : undefined) || me.getHeight(); h = curHeight; isExpanding = false; if (hasToHeight && toHeight > curHeight) { h = toHeight; isExpanding = true; } if (hasToWidth && toWidth > curWidth) { w = toWidth; isExpanding = true; } // During animated sizing, overflow has to be hidden to clip expanded content if (hasToHeight || hasToWidth) { oldOverflow = me.el.getStyle('overtflow'); if (oldOverflow !== 'hidden') { me.el.setStyle('overflow', 'hidden'); } } // If any dimensions are being increased, we must resize the internal structure // of the Component, but then clip it by sizing its encapsulating element back to original dimensions. // The animation will then progressively reveal the larger content. if (isExpanding) { clearWidth = !Ext.isNumber(me.width); clearHeight = !Ext.isNumber(me.height); // Lay out this component at the new, larger size to get the internals correctly laid out. // Then size the encapsulating **Element** back down to size. // We will then just animate the element to reveal the correctly laid out content. me.setSize(w, h); me.el.setSize(curWidth, curHeight); if (clearWidth) { delete me.width; } if (clearHeight) { delete me.height; } } if (hasToWidth) { to.width = toWidth; } if (hasToHeight) { to.height = toHeight; } } // No constraining during the animate - the "to" size has already been calculated with respect to all settings. // Arrange to reinstate any constraining after the animation has completed wasConstrained = me.constrain; wasConstrainedHeader = me.constrainHeader; if (wasConstrained || wasConstrainedHeader) { me.constrain = me.constrainHeader = false; passedCallback = animObj.callback; animObj.callback = function() { me.constrain = wasConstrained; me.constrainHeader = wasConstrainedHeader; // Call the original callback if any if (passedCallback) { passedCallback.call(animObj.scope||me, arguments); } if (oldOverflow !== 'hidden') { me.el.setStyle('overflow', oldOverflow); } }; } return me.mixins.animate.animate.apply(me, arguments); }, setHiddenState: function(hidden){ var hierarchyState = this.getHierarchyState(); this.hidden = hidden; if (hidden) { hierarchyState.hidden = true; } else { delete hierarchyState.hidden; } }, onHide: function() { // Only lay out if there is an owning layout which might be affected by the hide if (this.ownerLayout) { this.updateLayout({ isRoot: false }); } }, onShow : function() { this.updateLayout({ isRoot: false }); }, /** * @private * @param {String/Object} ptype string or config object containing a ptype property. * * Constructs a plugin according to the passed config object/ptype string. * * Ensures that the constructed plugin always has a `cmp` reference back to this component. * The setting up of this is done in PluginManager. The PluginManager ensures that a reference to this * component is passed to the constructor. It also ensures that the plugin's `setCmp` method (if any) is called. */ constructPlugin: function(plugin) { var me = this; // ptype only, pass as the defultType if (typeof plugin == 'string') { plugin = Ext.PluginManager.create({}, plugin, me); } // Object (either config with ptype or an instantiated plugin) else { plugin = Ext.PluginManager.create(plugin, null, me); } return plugin; }, /** * @private * Returns an array of fully constructed plugin instances. This converts any configs into their * appropriate instances. * * It does not mutate the plugins array. It creates a new array. */ constructPlugins: function() { var me = this, plugins = me.plugins, result, i, len; if (plugins) { result = []; if (!Ext.isArray(plugins)) { plugins = [ plugins ]; } for (i = 0, len = plugins.length; i < len; i++) { // this just returns already-constructed plugin instances... result[i] = me.constructPlugin(plugins[i]); } } me.pluginsInitialized = true; return result; }, // @private initPlugin : function(plugin) { plugin.init(this); return plugin; }, // @private // Adds a plugin. May be called at any time in the component's lifecycle. addPlugin: function(plugin) { var me = this; plugin = me.constructPlugin(plugin); if (me.plugins) { me.plugins.push(plugin); } else { me.plugins = [ plugin ]; } if (me.pluginsInitialized) { me.initPlugin(plugin); } return plugin; }, removePlugin: function(plugin) { Ext.Array.remove(this.plugins, plugin); plugin.destroy(); }, /** * Retrieves plugin from this component's collection by its `ptype`. * @param {String} ptype The Plugin's ptype as specified by the class's `alias` configuration. * @return {Ext.AbstractPlugin} plugin instance. */ findPlugin: function(ptype) { var i, plugins = this.plugins, ln = plugins && plugins.length; for (i = 0; i < ln; i++) { if (plugins[i].ptype === ptype) { return plugins[i]; } } }, /** * Retrieves a plugin from this component's collection by its `pluginId`. * @param {String} pluginId * @return {Ext.AbstractPlugin} plugin instance. */ getPlugin: function(pluginId) { var i, plugins = this.plugins, ln = plugins && plugins.length; for (i = 0; i < ln; i++) { if (plugins[i].pluginId === pluginId) { return plugins[i]; } } }, /** * Occurs before componentLayout is run. In previous releases, this method could * return `false` to prevent its layout but that is not supported in Ext JS 4.1 or * higher. This method is simply a notification of the impending layout to give the * component a chance to adjust the DOM. Ideally, DOM reads should be avoided at this * time to reduce expensive document reflows. * * @template * @protected */ beforeLayout: Ext.emptyFn, /** * @private * Injected as an override by Ext.Aria.initialize */ updateAria: Ext.emptyFn, /** * Called by Component#doAutoRender * * Register a Container configured `floating: true` with this Component's {@link Ext.ZIndexManager ZIndexManager}. * * Components added in this way will not participate in any layout, but will be rendered * upon first show in the way that {@link Ext.window.Window Window}s are. */ registerFloatingItem: function(cmp) { var me = this; if (!me.floatingDescendants) { me.floatingDescendants = new Ext.ZIndexManager(me); } me.floatingDescendants.register(cmp); }, unregisterFloatingItem: function(cmp) { var me = this; if (me.floatingDescendants) { me.floatingDescendants.unregister(cmp); } }, layoutSuspendCount: 0, suspendLayouts: function () { var me = this; if (!me.rendered) { return; } if (++me.layoutSuspendCount == 1) { me.suspendLayout = true; } }, resumeLayouts: function (flushOptions) { var me = this; if (!me.rendered) { return; } if (! --me.layoutSuspendCount) { me.suspendLayout = false; if (flushOptions && !me.isLayoutSuspended()) { me.updateLayout(flushOptions); } } }, setupProtoEl: function() { var cls = this.initCls(); this.protoEl = new Ext.util.ProtoElement({ cls: cls.join(' ') // in case any of the parts have multiple classes }); }, initCls: function() { var me = this, cls = [ me.baseCls, me.getComponentLayout().targetCls ]; //<deprecated since=0.99> if (Ext.isDefined(me.cmpCls)) { if (Ext.isDefined(Ext.global.console)) { Ext.global.console.warn('Ext.Component: cmpCls has been deprecated. Please use componentCls.'); } me.componentCls = me.cmpCls; delete me.cmpCls; } //</deprecated> if (me.componentCls) { cls.push(me.componentCls); } else { me.componentCls = me.baseCls; } return cls; }, /** * Sets the UI for the component. This will remove any existing UIs on the component. It will also loop through any * `uiCls` set on the component and rename them so they include the new UI. * @param {String} ui The new UI for the component. */ setUI: function(ui) { var me = this, uiCls = me.uiCls, activeUI = me.activeUI, classes; if (ui === activeUI) { // The ui hasn't changed return; } // activeUI will only be set if setUI has been called before. If it hasn't there's no need to remove anything if (activeUI) { classes = me.removeClsWithUI(uiCls, true); if (classes.length) { me.removeCls(classes); } // Remove the UI from the element me.removeUIFromElement(); } else { // We need uiCls to be empty otherwise our call to addClsWithUI won't do anything me.uiCls = []; } // Set the UI me.ui = ui; // After the first call to setUI the values ui and activeUI should track each other but initially we need some // way to tell whether the ui has really been set. me.activeUI = ui; // Add the new UI to the element me.addUIToElement(); classes = me.addClsWithUI(uiCls, true); if (classes.length) { me.addCls(classes); } // Changing the ui can lead to significant changes to a component's appearance, so the layout needs to be // updated. Internally most calls to setUI are pre-render. Buttons are a notable exception as setScale changes // the ui and often requires the layout to be updated. if (me.rendered) { me.updateLayout(); } }, /** * Adds a `cls` to the `uiCls` array, which will also call {@link #addUIClsToElement} and adds to all elements of this * component. * @param {String/String[]} classes A string or an array of strings to add to the `uiCls`. * @param {Object} skip (Boolean) skip `true` to skip adding it to the class and do it later (via the return). */ addClsWithUI: function(classes, skip) { var me = this, clsArray = [], i = 0, uiCls = me.uiCls = Ext.Array.clone(me.uiCls), activeUI = me.activeUI, length, cls; if (typeof classes === "string") { classes = (classes.indexOf(' ') < 0) ? [classes] : Ext.String.splitWords(classes); } length = classes.length; for (; i < length; i++) { cls = classes[i]; if (cls && !me.hasUICls(cls)) { uiCls.push(cls); // We can skip this bit if there isn't an activeUI because we'll be called again from setUI if (activeUI) { clsArray = clsArray.concat(me.addUIClsToElement(cls)); } } } if (skip !== true && activeUI) { me.addCls(clsArray); } return clsArray; }, /** * Removes a `cls` to the `uiCls` array, which will also call {@link #removeUIClsFromElement} and removes it from all * elements of this component. * @param {String/String[]} cls A string or an array of strings to remove to the `uiCls`. */ removeClsWithUI: function(classes, skip) { var me = this, clsArray = [], i = 0, extArray = Ext.Array, remove = extArray.remove, uiCls = me.uiCls = extArray.clone(me.uiCls), activeUI = me.activeUI, length, cls; if (typeof classes === "string") { classes = (classes.indexOf(' ') < 0) ? [classes] : Ext.String.splitWords(classes); } length = classes.length; for (i = 0; i < length; i++) { cls = classes[i]; if (cls && me.hasUICls(cls)) { remove(uiCls, cls); //If there's no activeUI then there's nothing to remove if (activeUI) { clsArray = clsArray.concat(me.removeUIClsFromElement(cls)); } } } if (skip !== true && activeUI) { me.removeCls(clsArray); } return clsArray; }, /** * Checks if there is currently a specified `uiCls`. * @param {String} cls The `cls` to check. */ hasUICls: function(cls) { var me = this, uiCls = me.uiCls || []; return Ext.Array.contains(uiCls, cls); }, frameElementsArray: ['tl', 'tc', 'tr', 'ml', 'mc', 'mr', 'bl', 'bc', 'br'], /** * Method which adds a specified UI + `uiCls` to the components element. Can be overridden to remove the UI from more * than just the components element. * @param {String} ui The UI to remove from the element. */ addUIClsToElement: function(cls) { var me = this, baseClsUi = me.baseCls + '-' + me.ui + '-' + cls, result = [Ext.baseCSSPrefix + cls, me.baseCls + '-' + cls, baseClsUi], frameElementsArray, frameElementsLength, i, el, frameElement; if (me.rendered && me.frame && !Ext.supports.CSS3BorderRadius) { // define each element of the frame frameElementsArray = me.frameElementsArray; frameElementsLength = frameElementsArray.length; // loop through each of them, and if they are defined add the ui for (i = 0; i < frameElementsLength; i++) { frameElement = frameElementsArray[i]; el = me['frame' + frameElement.toUpperCase()]; if (el) { el.addCls(baseClsUi + '-' + frameElement); } } } return result; }, /** * Method which removes a specified UI + `uiCls` from the components element. The `cls` which is added to the element * will be: `this.baseCls + '-' + ui`. * @param {String} ui The UI to add to the element. */ removeUIClsFromElement: function(cls) { var me = this, baseClsUi = me.baseCls + '-' + me.ui + '-' + cls, result = [Ext.baseCSSPrefix + cls, me.baseCls + '-' + cls, baseClsUi], frameElementsArray, frameElementsLength, i, el, frameElement; if (me.rendered && me.frame && !Ext.supports.CSS3BorderRadius) { // define each element of the frame frameElementsArray = me.frameElementsArray; frameElementsLength = frameElementsArray.length; // loop through each of them, and if they are defined add the ui for (i = 0; i < frameElementsLength; i++) { frameElement = frameElementsArray[i]; el = me['frame' + frameElement.toUpperCase()]; if (el) { el.removeCls(baseClsUi + '-' + frameElement); } } } return result; }, /** * Method which adds a specified UI to the components element. * @private */ addUIToElement: function() { var me = this, baseClsUI = me.baseCls + '-' + me.ui, frameElementsArray, frameElementsLength, i, el, frameElement; me.addCls(baseClsUI); if (me.rendered && me.frame && !Ext.supports.CSS3BorderRadius) { // define each element of the frame frameElementsArray = me.frameElementsArray; frameElementsLength = frameElementsArray.length; // loop through each of them, and if they are defined add the ui for (i = 0; i < frameElementsLength; i++) { frameElement = frameElementsArray[i]; el = me['frame' + frameElement.toUpperCase()]; if (el) { el.addCls(baseClsUI + '-' + frameElement); } } } }, /** * Method which removes a specified UI from the components element. * @private */ removeUIFromElement: function() { var me = this, baseClsUI = me.baseCls + '-' + me.ui, frameElementsArray, frameElementsLength, i, el, frameElement; me.removeCls(baseClsUI); if (me.rendered && me.frame && !Ext.supports.CSS3BorderRadius) { // define each element of the frame frameElementsArray = me.frameElementsArray; frameElementsLength = frameElementsArray.length; for (i = 0; i < frameElementsLength; i++) { frameElement = frameElementsArray[i]; el = me['frame' + frameElement.toUpperCase()]; if (el) { el.removeCls(baseClsUI + '-' + frameElement); } } } }, /** * @private */ getTpl: function(name) { return Ext.XTemplate.getTpl(this, name); }, /** * Applies padding, margin, border, top, left, height, and width configs to the * appropriate elements. * @private */ initStyles: function(targetEl) { var me = this, Element = Ext.Element, margin = me.margin, border = me.border, cls = me.cls, style = me.style, x = me.x, y = me.y, width, height; me.initPadding(targetEl); if (margin != null) { targetEl.setStyle('margin', this.unitizeBox((margin === true) ? 5 : margin)); } if (border != null) { me.setBorder(border, targetEl); } // initComponent, beforeRender, or event handlers may have set the style or cls property since the protoEl was set up // so we must apply styles and classes here too. if (cls && cls != me.initialCls) { targetEl.addCls(cls); me.cls = me.initialCls = null; } if (style && style != me.initialStyle) { targetEl.setStyle(style); me.style = me.initialStyle = null; } if (x != null) { targetEl.setStyle(me.horizontalPosProp, (typeof x == 'number') ? (x + 'px') : x); } if (y != null) { targetEl.setStyle('top', (typeof y == 'number') ? (y + 'px') : y); } if (Ext.isBorderBox && (!me.ownerCt || me.floating)) { targetEl.addCls(me.borderBoxCls); } // Framed components need their width/height to apply to the frame, which is // best handled in layout at present. if (!me.getFrameInfo()) { width = me.width; height = me.height; // If we're using the content box model, we also cannot assign numeric initial sizes since we do not know the border widths to subtract if (width != null) { if (typeof width === 'number') { if (Ext.isBorderBox) { targetEl.setStyle('width', width + 'px'); } } else { targetEl.setStyle('width', width); } } if (height != null) { if (typeof height === 'number') { if (Ext.isBorderBox) { targetEl.setStyle('height', height + 'px'); } } else { targetEl.setStyle('height', height); } } } }, /** * Initializes padding by applying it to the target element, or if the layout manages * padding ensures that the padding on the target element is "0". * @private */ initPadding: function(targetEl) { var me = this, padding = me.padding; if (padding != null) { if (me.layout && me.layout.managePadding && me.contentPaddingProperty === 'padding') { // If the container layout manages padding, the layout will apply the // padding to an inner element rather than the target element. The // assumed intent is for the configured padding to override any padding // that is applied to the target element via stylesheet rules. It is // therefore necessary to set the target element's padding to "0". targetEl.setStyle('padding', 0); } else { // Convert the padding, margin and border properties from a space seperated string // into a proper style string targetEl.setStyle('padding', this.unitizeBox((padding === true) ? 5 : padding)); } } }, parseBox: function(box) { return Ext.dom.Element.parseBox(box); }, unitizeBox: function(box) { return Ext.dom.Element.unitizeBox(box); }, /** * Sets the margin on the target element. * @param {Number/String} margin The margin to set. See the {@link #margin} config. */ setMargin: function(margin, /* private */ preventLayout) { var me = this; if (me.rendered) { if (!margin && margin !== 0) { margin = ''; } else { if (margin === true) { margin = 5; } margin = this.unitizeBox(margin); } me.getTargetEl().setStyle('margin', margin); if (!preventLayout) { me.updateLayout(); } } else { me.margin = margin; } }, /** * Initialize any events on this component * @protected */ initEvents : function() { var me = this, afterRenderEvents = me.afterRenderEvents, afterRenderEvent, el, property, index, len; if (afterRenderEvents) { for (property in afterRenderEvents) { el = me[property]; if (el && el.on) { afterRenderEvent = afterRenderEvents[property]; for (index = 0, len = afterRenderEvent.length ; index < len ; ++index) { me.mon(el, afterRenderEvent[index]); } } } } // This will add focus/blur listeners to the getFocusEl() element if that is naturally focusable. // If *not* naturally focusable, then the FocusManager must be enabled to get it to listen for focus so that // the FocusManager can track and highlight focus. me.addFocusListener(); }, /** * @private * Sets up the focus listener on this Component's {@link #getFocusEl focusEl} if it has one. * * Form Components which must implicitly participate in tabbing order usually have a naturally focusable * element as their {@link #getFocusEl focusEl}, and it is the DOM event of that receiving focus which drives * the Component's `onFocus` handling, and the DOM event of it being blurred which drives the `onBlur` handling. * * If the {@link #getFocusEl focusEl} is **not** naturally focusable, then the listeners are only added * if the {@link Ext.FocusManager FocusManager} is enabled. */ addFocusListener: function() { var me = this, focusEl = me.getFocusEl(), needsTabIndex; // All Containers may be focusable, not only "form" type elements, but also // Panels, Toolbars, Windows etc. // Usually, the <DIV> element they will return as their focusEl will not be able to receive focus // However, if the FocusManager is invoked, its non-default navigation handlers (invoked when // tabbing/arrowing off of certain Components) may explicitly focus a Panel or Container or FieldSet etc. // Add listeners to the focus and blur events on the focus element // If this Component returns a focusEl, we might need to add a focus listener to it. if (focusEl) { // getFocusEl might return a Component if a Container wishes to delegate focus to a descendant. // Window can do this via its defaultFocus configuration which can reference a Button. if (focusEl.isComponent) { return focusEl.addFocusListener(); } // If the focusEl is naturally focusable, then we always need a focus listener to drive the Component's // onFocus handling. // If *not* naturally focusable, then we only need the focus listener if the FocusManager is enabled. needsTabIndex = focusEl.needsTabIndex(); if (!me.focusListenerAdded && (!needsTabIndex || Ext.FocusManager.enabled)) { if (needsTabIndex) { focusEl.dom.tabIndex = -1; } focusEl.on({ focus: me.onFocus, blur: me.onBlur, scope: me }); me.focusListenerAdded = true; } } }, /** * @private * Returns the focus holder element associated with this Component. At the Component base class level, this function returns `undefined`. * * Subclasses which use embedded focusable elements (such as Window, Field and Button) should override this * for use by the {@link Ext.Component#method-focus focus} method. * * Containers which need to participate in the {@link Ext.FocusManager FocusManager}'s navigation and Container focusing scheme also * need to return a `focusEl`, although focus is only listened for in this case if the {@link Ext.FocusManager FocusManager} is {@link Ext.FocusManager#method-enable enable}d. * * @returns {undefined} `undefined` because raw Components cannot by default hold focus. */ getFocusEl: Ext.emptyFn, isFocusable: function() { var me = this, focusEl; if ((me.focusable !== false) && (focusEl = me.getFocusEl()) && me.rendered && !me.destroying && !me.isDestroyed && !me.disabled && me.isVisible(true)) { // getFocusEl might return a Component if a Container wishes to delegate focus to a descendant. // Window can do this via its defaultFocus configuration which can reference a Button. // Both Component and Element implement isFocusable, so always ask that. return focusEl.isFocusable(true); } }, /** * Template method to do any pre-focus processing. * @protected * @param {Ext.EventObject} e The event object */ beforeFocus: Ext.emptyFn, // private onFocus: function(e) { var me = this, focusCls = me.focusCls, focusEl = me.getFocusEl(); if (!me.disabled) { me.beforeFocus(e); if (focusCls && focusEl) { focusEl.addCls(me.addClsWithUI(focusCls, true)); } if (!me.hasFocus) { me.hasFocus = true; me.fireEvent('focus', me, e); } } }, /** * Template method to do any pre-blur processing. * @protected * @param {Ext.EventObject} e The event object */ beforeBlur : Ext.emptyFn, // private onBlur : function(e) { var me = this, focusCls = me.focusCls, focusEl = me.getFocusEl(); if (me.destroying) { return; } me.beforeBlur(e); if (focusCls && focusEl) { focusEl.removeCls(me.removeClsWithUI(focusCls, true)); } if (me.validateOnBlur) { me.validate(); } me.hasFocus = false; me.fireEvent('blur', me, e); me.postBlur(e); }, /** * Template method to do any post-blur processing. * @protected * @param {Ext.EventObject} e The event object */ postBlur : Ext.emptyFn, /** * Tests whether this Component matches the selector string. * @param {String} selector The selector string to test against. * @return {Boolean} `true` if this Component matches the selector. */ is: function(selector) { return Ext.ComponentQuery.is(this, selector); }, /** * Navigates up the ownership hierarchy searching for an ancestor Container which matches any passed simple selector or component. * * *Important.* There is not a universal upwards navigation pointer. There are several upwards relationships * such as the {@link Ext.button.Button button} which activates a {@link Ext.button.Button#cfg-menu menu}, or the * {@link Ext.menu.Item menu item} which activated a {@link Ext.menu.Item#cfg-menu submenu}, or the * {@link Ext.grid.column.Column column header} which activated the column menu. * * These differences are abstracted away by this method. * * Example: * * var owningTabPanel = grid.up('tabpanel'); * * @param {String/Ext.Component} [selector] The simple selector component or actual component to test. If not passed the immediate owner/activater is returned. * @param {String/Number/Ext.Component} [limit] This may be a selector upon which to stop the upward scan, or a limit of teh number of steps, or Component reference to stop on. * @return {Ext.container.Container} The matching ancestor Container (or `undefined` if no match was found). */ up: function (selector, limit) { var result = this.getRefOwner(), limitSelector = typeof limit === 'string', limitCount = typeof limit === 'number', limitComponent = limit && limit.isComponent, steps = 0; if (selector) { for (; result; result = result.getRefOwner()) { steps++; if (selector.isComponent) { if (result === selector) { return result; } } else { if (Ext.ComponentQuery.is(result, selector)) { return result; } } // Stop when we hit the limit selector if (limitSelector && result.is(limit)) { return; } if (limitCount && steps === limit) { return; } if (limitComponent && result === limit) { return; } } } return result; }, /** * Returns the next sibling of this Component. * * Optionally selects the next sibling which matches the passed {@link Ext.ComponentQuery ComponentQuery} selector. * * May also be referred to as **`next()`** * * Note that this is limited to siblings, and if no siblings of the item match, `null` is returned. Contrast with * {@link #nextNode} * @param {String} [selector] A {@link Ext.ComponentQuery ComponentQuery} selector to filter the following items. * @return {Ext.Component} The next sibling (or the next sibling which matches the selector). * Returns `null` if there is no matching sibling. */ nextSibling: function(selector) { var o = this.ownerCt, it, last, idx, c; if (o) { it = o.items; idx = it.indexOf(this) + 1; if (idx) { if (selector) { for (last = it.getCount(); idx < last; idx++) { if ((c = it.getAt(idx)).is(selector)) { return c; } } } else { if (idx < it.getCount()) { return it.getAt(idx); } } } } return null; }, /** * Returns the previous sibling of this Component. * * Optionally selects the previous sibling which matches the passed {@link Ext.ComponentQuery ComponentQuery} * selector. * * May also be referred to as **`prev()`** * * Note that this is limited to siblings, and if no siblings of the item match, `null` is returned. Contrast with * {@link #previousNode} * @param {String} [selector] A {@link Ext.ComponentQuery ComponentQuery} selector to filter the preceding items. * @return {Ext.Component} The previous sibling (or the previous sibling which matches the selector). * Returns `null` if there is no matching sibling. */ previousSibling: function(selector) { var o = this.ownerCt, it, idx, c; if (o) { it = o.items; idx = it.indexOf(this); if (idx != -1) { if (selector) { for (--idx; idx >= 0; idx--) { if ((c = it.getAt(idx)).is(selector)) { return c; } } } else { if (idx) { return it.getAt(--idx); } } } } return null; }, /** * Returns the previous node in the Component tree in tree traversal order. * * Note that this is not limited to siblings, and if invoked upon a node with no matching siblings, will walk the * tree in reverse order to attempt to find a match. Contrast with {@link #previousSibling}. * @param {String} [selector] A {@link Ext.ComponentQuery ComponentQuery} selector to filter the preceding nodes. * @return {Ext.Component} The previous node (or the previous node which matches the selector). * Returns `null` if there is no matching node. */ previousNode: function(selector, /* private */ includeSelf) { var node = this, ownerCt = node.ownerCt, result, it, i, sib; // If asked to include self, test me if (includeSelf && node.is(selector)) { return node; } if (ownerCt) { for (it = ownerCt.items.items, i = Ext.Array.indexOf(it, node) - 1; i > -1; i--) { sib = it[i]; if (sib.query) { result = sib.query(selector); result = result[result.length - 1]; if (result) { return result; } } if (sib.is(selector)) { return sib; } } return ownerCt.previousNode(selector, true); } return null; }, /** * Returns the next node in the Component tree in tree traversal order. * * Note that this is not limited to siblings, and if invoked upon a node with no matching siblings, will walk the * tree to attempt to find a match. Contrast with {@link #nextSibling}. * @param {String} [selector] A {@link Ext.ComponentQuery ComponentQuery} selector to filter the following nodes. * @return {Ext.Component} The next node (or the next node which matches the selector). * Returns `null` if there is no matching node. */ nextNode: function(selector, /* private */ includeSelf) { var node = this, ownerCt = node.ownerCt, result, it, len, i, sib; // If asked to include self, test me if (includeSelf && node.is(selector)) { return node; } if (ownerCt) { for (it = ownerCt.items.items, i = Ext.Array.indexOf(it, node) + 1, len = it.length; i < len; i++) { sib = it[i]; if (sib.is(selector)) { return sib; } if (sib.down) { result = sib.down(selector); if (result) { return result; } } } return ownerCt.nextNode(selector); } return null; }, /** * Retrieves the `id` of this component. Will auto-generate an `id` if one has not already been set. * @return {String} */ getId : function() { return this.id || (this.id = 'ext-comp-' + (this.getAutoId())); }, /** * Returns the value of {@link #itemId} assigned to this component, or when that * is not set, returns the value of {@link #id}. * @return {String} */ getItemId : function() { return this.itemId || this.id; }, /** * Retrieves the top level element representing this component. * @return {Ext.dom.Element} * @since 1.1.0 */ getEl : function() { return this.el; }, /** * This is used to determine where to insert the 'html', 'contentEl' and 'items' in this component. * @private */ getTargetEl: function() { return this.frameBody || this.el; }, /** * Get an el for overflowing, defaults to the target el * @private */ getOverflowEl: function(){ return this.getTargetEl(); }, /** * @private * Returns the CSS style object which will set the Component's scroll styles. This must be applied * to the {@link #getTargetEl target element}. */ getOverflowStyle: function() { var me = this, result = null, ox, oy, overflowStyle; // Note to maintainer. To save on waves of testing, setting and defaulting, the code below // rolls assignent statements into conditional test value expressiona and property object initializers. // This avoids sprawling code. Maintain with care. if (typeof me.autoScroll === 'boolean') { result = { overflow: overflowStyle = me.autoScroll ? 'auto' : '' }; me.scrollFlags = { overflowX: overflowStyle, overflowY: overflowStyle, x: true, y: true, both: true }; } else { ox = me.overflowX; oy = me.overflowY; if (ox !== undefined || oy !== undefined) { result = { 'overflowX': ox = ox || '', 'overflowY': oy = oy || '' }; /** * @member Ext.Component * @property {Object} scrollFlags * An object property which provides unified information as to which dimensions are scrollable based upon * the {@link #autoScroll}, {@link #overflowX} and {@link #overflowY} settings (And for *views* of trees and grids, the owning panel's {@link Ext.panel.Table#scroll scroll} setting). * * Note that if you set overflow styles using the {@link #style} config or {@link Ext.panel.Panel#bodyStyle bodyStyle} config, this object does not include that information; * it is best to use {@link #autoScroll}, {@link #overflowX} and {@link #overflowY} if you need to access these flags. * * This object has the following properties: * @property {Boolean} scrollFlags.x `true` if this Component is scrollable horizontally - style setting may be `'auto'` or `'scroll'`. * @property {Boolean} scrollFlags.y `true` if this Component is scrollable vertically - style setting may be `'auto'` or `'scroll'`. * @property {Boolean} scrollFlags.both `true` if this Component is scrollable both horizontally and vertically. * @property {String} scrollFlags.overflowX The `overflow-x` style setting, `'auto'` or `'scroll'` or `''`. * @property {String} scrollFlags.overflowY The `overflow-y` style setting, `'auto'` or `'scroll'` or `''`. * @readonly */ me.scrollFlags = { overflowX: ox, overflowY: oy, x: ox = (ox === 'auto' || ox === 'scroll'), y: oy = (oy === 'auto' || oy === 'scroll'), both: ox && oy }; } else { me.scrollFlags = { overflowX: '', overflowY: '', x: false, y: false, both: false }; } } // The scrollable container element must be non-statically positioned or IE6/7 will make // positioned children stay in place rather than scrolling with the rest of the content if (result && Ext.isIE7m) { result.position = 'relative'; } return result; }, /** * Tests whether or not this Component is of a specific xtype. This can test whether this Component is descended * from the xtype (default) or whether it is directly of the xtype specified (`shallow = true`). * * **If using your own subclasses, be aware that a Component must register its own xtype to participate in * determination of inherited xtypes.** * * For a list of all available xtypes, see the {@link Ext.Component} header. * * Example usage: * * @example * var t = new Ext.form.field.Text(); * var isText = t.isXType('textfield'); // true * var isBoxSubclass = t.isXType('field'); // true, descended from Ext.form.field.Base * var isBoxInstance = t.isXType('field', true); // false, not a direct Ext.form.field.Base instance * * @param {String} xtype The xtype to check for this Component * @param {Boolean} [shallow=false] `true` to check whether this Component is directly of the specified xtype, `false` to * check whether this Component is descended from the xtype. * @return {Boolean} `true` if this component descends from the specified xtype, `false` otherwise. * * @since 2.3.0 */ isXType: function(xtype, shallow) { if (shallow) { return this.xtype === xtype; } else { return this.xtypesMap[xtype]; } }, /** * Returns this Component's xtype hierarchy as a slash-delimited string. For a list of all available xtypes, see the * {@link Ext.Component} header. * * **If using your own subclasses, be aware that a Component must register its own xtype to participate in * determination of inherited xtypes.** * * Example usage: * * @example * var t = new Ext.form.field.Text(); * alert(t.getXTypes()); // alerts 'component/field/textfield' * * @return {String} The xtype hierarchy string * * @since 2.3.0 */ getXTypes: function() { var self = this.self, xtypes, parentPrototype, parentXtypes; if (!self.xtypes) { xtypes = []; parentPrototype = this; while (parentPrototype) { parentXtypes = parentPrototype.xtypes; if (parentXtypes !== undefined) { xtypes.unshift.apply(xtypes, parentXtypes); } parentPrototype = parentPrototype.superclass; } self.xtypeChain = xtypes; self.xtypes = xtypes.join('/'); } return self.xtypes; }, /** * Update the content area of a component. * @param {String/Object} htmlOrData If this component has been configured with a template via the tpl config then * it will use this argument as data to populate the template. If this component was not configured with a template, * the components content area will be updated via Ext.Element update. * @param {Boolean} [loadScripts=false] Only legitimate when using the `html` configuration. * @param {Function} [callback] Only legitimate when using the `html` configuration. Callback to execute when * scripts have finished loading. * * @since 3.4.0 */ update : function(htmlOrData, loadScripts, cb) { var me = this, isData = (me.tpl && !Ext.isString(htmlOrData)), el; if (isData) { me.data = htmlOrData; } else { me.html = Ext.isObject(htmlOrData) ? Ext.DomHelper.markup(htmlOrData) : htmlOrData; } if (me.rendered) { el = me.isContainer ? me.layout.getRenderTarget() : me.getTargetEl(); if (isData) { me.tpl[me.tplWriteMode](el, htmlOrData || {}); } else { el.update(me.html, loadScripts, cb); } me.updateLayout(); } }, /** * Convenience function to hide or show this component by Boolean. * @param {Boolean} visible `true` to show, `false` to hide. * @return {Ext.Component} this * @since 1.1.0 */ setVisible : function(visible) { return this[visible ? 'show': 'hide'](); }, /** * Returns `true` if this component is visible. * * @param {Boolean} [deep=false] Pass `true` to interrogate the visibility status of all parent Containers to * determine whether this Component is truly visible to the user. * * Generally, to determine whether a Component is hidden, the no argument form is needed. For example when creating * dynamically laid out UIs in a hidden Container before showing them. * * @return {Boolean} `true` if this component is visible, `false` otherwise. * * @since 1.1.0 */ isVisible: function(deep) { var me = this, hidden; if (me.hidden || !me.rendered || me.isDestroyed) { hidden = true; } else if (deep) { hidden = me.isHierarchicallyHidden(); } return !hidden; }, isHierarchicallyHidden: function() { var child = this, hidden = false, parent, parentHierarchyState; // It is possible for some components to be immune to collapse meaning the immune // component remains visible when its direct parent is collapsed, e.g. panel header. // Because of this, we must walk up the component hierarchy to determine the true // visible state of the component. for (; (parent = child.ownerCt || child.floatParent); child = parent) { parentHierarchyState = parent.getHierarchyState(); if (parentHierarchyState.hidden) { hidden = true; break; } if (child.getHierarchyState().collapseImmune) { // The child or one of its ancestors is immune to collapse. if (parent.collapsed && !child.collapseImmune) { // If the child's direct parent is collapsed, and the child // itself does not have collapse immunity we know that // the child is not visible. hidden = true; break; } } else { // We have ascended the tree to a point where collapse immunity // is not in play. This means if any anscestor above this point // is collapsed, then the component is not visible. hidden = !!parentHierarchyState.collapsed; break; } } return hidden; }, onBoxReady: function(width, height) { var me = this; if (me.disableOnBoxReady) { me.onDisable(); } else if (me.enableOnBoxReady) { me.onEnable(); } if (me.resizable) { me.initResizable(me.resizable); } // Draggability must be initialized after resizability // Because if we have to be wrapped, the resizer wrapper must be dragged as a pseudo-Component if (me.draggable) { me.initDraggable(); } if (me.hasListeners.boxready) { me.fireEvent('boxready', me, width, height); } }, /** * Enable the component * @param {Boolean} [silent=false] Passing `true` will suppress the `enable` event from being fired. * @since 1.1.0 */ enable: function(silent) { var me = this; delete me.disableOnBoxReady; me.removeCls(me.disabledCls); if (me.rendered) { me.onEnable(); } else { me.enableOnBoxReady = true; } me.disabled = false; delete me.resetDisable; if (silent !== true) { me.fireEvent('enable', me); } return me; }, /** * Disable the component. * @param {Boolean} [silent=false] Passing `true` will suppress the `disable` event from being fired. * @since 1.1.0 */ disable: function(silent) { var me = this; delete me.enableOnBoxReady; me.addCls(me.disabledCls); if (me.rendered) { me.onDisable(); } else { me.disableOnBoxReady = true; } me.disabled = true; if (silent !== true) { delete me.resetDisable; me.fireEvent('disable', me); } return me; }, /** * Allows addition of behavior to the enable operation. * After calling the superclass's `onEnable`, the Component will be enabled. * * @template * @protected */ onEnable: function() { if (this.maskOnDisable) { this.el.dom.disabled = false; this.unmask(); } }, /** * Allows addition of behavior to the disable operation. * After calling the superclass's `onDisable`, the Component will be disabled. * * @template * @protected */ onDisable : function() { var me = this, focusCls = me.focusCls, focusEl = me.getFocusEl(); if (focusCls && focusEl) { focusEl.removeCls(me.removeClsWithUI(focusCls, true)); } if (me.maskOnDisable) { me.el.dom.disabled = true; me.mask(); } }, mask: function() { var box = this.lastBox, target = this.getMaskTarget(), args = []; // Pass it the height of our element if we know it. if (box) { args[2] = box.height; } target.mask.apply(target, args); }, unmask: function() { this.getMaskTarget().unmask(); }, getMaskTarget: function(){ return this.el; }, /** * Method to determine whether this Component is currently disabled. * @return {Boolean} the disabled state of this Component. */ isDisabled : function() { return this.disabled; }, /** * Enable or disable the component. * @param {Boolean} disabled `true` to disable. */ setDisabled : function(disabled) { return this[disabled ? 'disable': 'enable'](); }, /** * Method to determine whether this Component is currently set to hidden. * @return {Boolean} the hidden state of this Component. */ isHidden : function() { return this.hidden; }, /** * Adds a CSS class to the top level element representing this component. * @param {String/String[]} cls The CSS class name to add. * @return {Ext.Component} Returns the Component to allow method chaining. */ addCls : function(cls) { var me = this, el = me.rendered ? me.el : me.protoEl; el.addCls.apply(el, arguments); return me; }, /** * @inheritdoc Ext.AbstractComponent#addCls * @deprecated 4.1 Use {@link #addCls} instead. * @since 2.3.0 */ addClass : function() { return this.addCls.apply(this, arguments); }, /** * Checks if the specified CSS class exists on this element's DOM node. * @param {String} className The CSS class to check for. * @return {Boolean} `true` if the class exists, else `false`. * @method */ hasCls: function (cls) { var me = this, el = me.rendered ? me.el : me.protoEl; return el.hasCls.apply(el, arguments); }, /** * Removes a CSS class from the top level element representing this component. * @param {String/String[]} cls The CSS class name to remove. * @returns {Ext.Component} Returns the Component to allow method chaining. */ removeCls : function(cls) { var me = this, el = me.rendered ? me.el : me.protoEl; el.removeCls.apply(el, arguments); return me; }, //<debug> // @since 2.3.0 removeClass : function() { if (Ext.isDefined(Ext.global.console)) { Ext.global.console.warn('Ext.Component: removeClass has been deprecated. Please use removeCls.'); } return this.removeCls.apply(this, arguments); }, //</debug> addOverCls: function() { var me = this; if (!me.disabled) { me.el.addCls(me.overCls); } }, removeOverCls: function() { this.el.removeCls(this.overCls); }, addListener : function(element, listeners, scope, options) { var me = this, fn, option; if (Ext.isString(element) && (Ext.isObject(listeners) || options && options.element)) { if (options.element) { fn = listeners; listeners = {}; listeners[element] = fn; element = options.element; if (scope) { listeners.scope = scope; } for (option in options) { if (options.hasOwnProperty(option)) { if (me.eventOptionsRe.test(option)) { listeners[option] = options[option]; } } } } // At this point we have a variable called element, // and a listeners object that can be passed to on if (me[element] && me[element].on) { me.mon(me[element], listeners); } else { me.afterRenderEvents = me.afterRenderEvents || {}; if (!me.afterRenderEvents[element]) { me.afterRenderEvents[element] = []; } me.afterRenderEvents[element].push(listeners); } return; } return me.mixins.observable.addListener.apply(me, arguments); }, // inherit docs removeManagedListenerItem: function(isClear, managedListener, item, ename, fn, scope){ var me = this, element = managedListener.options ? managedListener.options.element : null; if (element) { element = me[element]; if (element && element.un) { if (isClear || (managedListener.item === item && managedListener.ename === ename && (!fn || managedListener.fn === fn) && (!scope || managedListener.scope === scope))) { element.un(managedListener.ename, managedListener.fn, managedListener.scope); if (!isClear) { Ext.Array.remove(me.managedListeners, managedListener); } } } } else { return me.mixins.observable.removeManagedListenerItem.apply(me, arguments); } }, /** * Provides the link for Observable's `fireEvent` method to bubble up the ownership hierarchy. * @return {Ext.container.Container} the Container which owns this Component. * @since 3.4.0 */ getBubbleTarget : function() { return this.ownerCt; }, /** * Method to determine whether this Component is floating. * @return {Boolean} the floating state of this component. */ isFloating : function() { return this.floating; }, /** * Method to determine whether this Component is draggable. * @return {Boolean} the draggable state of this component. */ isDraggable : function() { return !!this.draggable; }, /** * Method to determine whether this Component is droppable. * @return {Boolean} the droppable state of this component. */ isDroppable : function() { return !!this.droppable; }, /** * Method to manage awareness of when components are added to their * respective Container, firing an #added event. References are * established at add time rather than at render time. * * Allows addition of behavior when a Component is added to a * Container. At this stage, the Component is in the parent * Container's collection of child items. After calling the * superclass's `onAdded`, the `ownerCt` reference will be present, * and if configured with a ref, the `refOwner` will be set. * * @param {Ext.container.Container} container Container which holds the component. * @param {Number} pos Position at which the component was added. * * @template * @protected * @since 3.4.0 */ onAdded : function(container, pos) { var me = this; me.ownerCt = container; if (me.hierarchyState) { // if component has a hierarchyState at this point we set an invalid flag in the // hierarchy state so that descendants of this component know to re-initialize // their hierarchyState the next time it is requested (see getHierarchyState()) me.hierarchyState.invalid = true; // We can now delete the old hierarchyState since it is invalid. IMPORTANT: // the descendants are still linked to the old hierarchy state via the // prototype chain, and their heirarchyState property will be synced up // the next time their getHierarchyState() method is called. For this reason // hierarchyState should always be accessed using getHierarchyState() delete me.hierarchyState; } if (me.hasListeners.added) { me.fireEvent('added', me, container, pos); } }, /** * Method to manage awareness of when components are removed from their * respective Container, firing a #removed event. References are properly * cleaned up after removing a component from its owning container. * * Allows addition of behavior when a Component is removed from * its parent Container. At this stage, the Component has been * removed from its parent Container's collection of child items, * but has not been destroyed (It will be destroyed if the parent * Container's `autoDestroy` is `true`, or if the remove call was * passed a truthy second parameter). After calling the * superclass's `onRemoved`, the `ownerCt` and the `refOwner` will not * be present. * @param {Boolean} destroying Will be passed as `true` if the Container performing the remove operation will delete this * Component upon remove. * * @template * @protected * @since 3.4.0 */ onRemoved : function(destroying) { var me = this; if (me.hasListeners.removed) { me.fireEvent('removed', me, me.ownerCt); } delete me.ownerCt; delete me.ownerLayout; }, /** * Invoked before the Component is destroyed. * * @method * @template * @protected */ beforeDestroy : Ext.emptyFn, /** * Allows addition of behavior to the resize operation. * * Called when Ext.resizer.Resizer#drag event is fired. * * @method * @template * @protected */ onResize: function(width, height, oldWidth, oldHeight) { var me = this; // constrain is a config on Floating if (me.floating && me.constrain) { me.doConstrain(); } if (me.hasListeners.resize) { me.fireEvent('resize', me, width, height, oldWidth, oldHeight); } }, /** * Sets the width and height of this Component. This method fires the {@link #resize} event. This method can accept * either width and height as separate arguments, or you can pass a size object like `{width:10, height:20}`. * * @param {Number/String/Object} width The new width to set. This may be one of: * * - A Number specifying the new width in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels). * - A String used to set the CSS width style. * - A size object in the format `{width: widthValue, height: heightValue}`. * - `undefined` to leave the width unchanged. * * @param {Number/String} height The new height to set (not required if a size object is passed as the first arg). * This may be one of: * * - A Number specifying the new height in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels). * - A String used to set the CSS height style. Animation may **not** be used. * - `undefined` to leave the height unchanged. * * @return {Ext.Component} this */ setSize : function(width, height) { var me = this; // support for standard size objects if (width && typeof width == 'object') { height = width.height; width = width.width; } // Constrain within configured maxima if (typeof width == 'number') { me.width = Ext.Number.constrain(width, me.minWidth, me.maxWidth); } else if (width === null) { delete me.width; } if (typeof height == 'number') { me.height = Ext.Number.constrain(height, me.minHeight, me.maxHeight); } else if (height === null) { delete me.height; } // If not rendered, all we need to is set the properties. // The initial layout will set the size if (me.rendered && me.isVisible()) { // If we are changing size, then we are not the root. me.updateLayout({ isRoot: false }); } return me; }, /** * Determines whether this Component is the root of a layout. This returns `true` if * this component can run its layout without assistance from or impact on its owner. * If this component cannot run its layout given these restrictions, `false` is returned * and its owner will be considered as the next candidate for the layout root. * * Setting the {@link #_isLayoutRoot} property to `true` causes this method to always * return `true`. This may be useful when updating a layout of a Container which shrink * wraps content, and you know that it will not change size, and so can safely be the * topmost participant in the layout run. * @protected */ isLayoutRoot: function() { var me = this, ownerLayout = me.ownerLayout; // Return true if we have been explicitly flagged as the layout root, or if we are floating. // Sometimes floating Components get an ownerCt ref injected into them which is *not* a true ownerCt, merely // an upward link for reference purposes. For example a grid column menu is linked to the // owning header via an ownerCt reference. if (!ownerLayout || me._isLayoutRoot || me.floating) { return true; } return ownerLayout.isItemLayoutRoot(me); }, /** * Returns `true` if layout is suspended for this component. This can come from direct * suspension of this component's layout activity ({@link Ext.Container#suspendLayout}) or if one * of this component's containers is suspended. * * @return {Boolean} `true` layout of this component is suspended. */ isLayoutSuspended: function () { var comp = this, ownerLayout; while (comp) { if (comp.layoutSuspendCount || comp.suspendLayout) { return true; } ownerLayout = comp.ownerLayout; if (!ownerLayout) { break; } // TODO - what about suspending a Layout instance? // this works better than ownerCt since ownerLayout means "is managed by" in // the proper sense... some floating components have ownerCt but won't have an // ownerLayout comp = ownerLayout.owner; } return false; }, /** * Updates this component's layout. If this update affects this components {@link #ownerCt}, * that component's `updateLayout` method will be called to perform the layout instead. * Otherwise, just this component (and its child items) will layout. * * @param {Object} [options] An object with layout options. * @param {Boolean} options.defer `true` if this layout should be deferred. * @param {Boolean} options.isRoot `true` if this layout should be the root of the layout. */ updateLayout: function (options) { var me = this, defer, lastBox = me.lastBox, isRoot = options && options.isRoot; if (lastBox) { // remember that this component's last layout result is invalid and must be // recalculated lastBox.invalid = true; } if (!me.rendered || me.layoutSuspendCount || me.suspendLayout) { return; } if (me.hidden) { Ext.AbstractComponent.cancelLayout(me); } else if (typeof isRoot != 'boolean') { isRoot = me.isLayoutRoot(); } // if we aren't the root, see if our ownerLayout will handle it... if (isRoot || !me.ownerLayout || !me.ownerLayout.onContentChange(me)) { // either we are the root or our ownerLayout doesn't care if (!me.isLayoutSuspended()) { // we aren't suspended (knew that), but neither is any of our ownerCt's... defer = (options && options.hasOwnProperty('defer')) ? options.defer : me.deferLayouts; Ext.AbstractComponent.updateLayout(me, defer); } } }, /** * Returns an object that describes how this component's width and height are managed. * All of these objects are shared and should not be modified. * * @return {Object} The size model for this component. * @return {Ext.layout.SizeModel} return.width The {@link Ext.layout.SizeModel size model} * for the width. * @return {Ext.layout.SizeModel} return.height The {@link Ext.layout.SizeModel size model} * for the height. */ getSizeModel: function (ownerCtSizeModel) { var me = this, models = Ext.layout.SizeModel, ownerContext = me.componentLayout.ownerContext, width = me.width, height = me.height, typeofWidth, typeofHeight, hasPixelWidth, hasPixelHeight, heightModel, ownerLayout, policy, shrinkWrap, topLevel, widthModel; if (ownerContext) { // If we are in the middle of a running layout, always report the current, // dynamic size model rather than recompute it. This is not (only) a time // saving thing, but a correctness thing since we cannot get the right answer // otherwise. widthModel = ownerContext.widthModel; heightModel = ownerContext.heightModel; } if (!widthModel || !heightModel) { hasPixelWidth = ((typeofWidth = typeof width) == 'number'); hasPixelHeight = ((typeofHeight = typeof height) == 'number'); topLevel = me.floating || !(ownerLayout = me.ownerLayout); // Floating or no owner layout, e.g. rendered using renderTo if (topLevel) { policy = Ext.layout.Layout.prototype.autoSizePolicy; shrinkWrap = me.floating ? 3 : me.shrinkWrap; if (hasPixelWidth) { widthModel = models.configured; } if (hasPixelHeight) { heightModel = models.configured; } } else { policy = ownerLayout.getItemSizePolicy(me, ownerCtSizeModel); shrinkWrap = ownerLayout.isItemShrinkWrap(me); } if (ownerContext) { ownerContext.ownerSizePolicy = policy; } shrinkWrap = (shrinkWrap === true) ? 3 : (shrinkWrap || 0); // false->0, true->3 // Now that we have shrinkWrap as a 0-3 value, we need to turn off shrinkWrap // bits for any dimension that has a configured size not in pixels. These must // be read from the DOM. // if (topLevel && shrinkWrap) { if (width && typeofWidth == 'string') { shrinkWrap &= 2; // percentage, "30em" or whatever - not width shrinkWrap } if (height && typeofHeight == 'string') { shrinkWrap &= 1; // percentage, "30em" or whatever - not height shrinkWrap } } if (shrinkWrap !== 3) { if (!ownerCtSizeModel) { ownerCtSizeModel = me.ownerCt && me.ownerCt.getSizeModel(); } if (ownerCtSizeModel) { shrinkWrap |= (ownerCtSizeModel.width.shrinkWrap ? 1 : 0) | (ownerCtSizeModel.height.shrinkWrap ? 2 : 0); } } if (!widthModel) { if (!policy.setsWidth) { if (hasPixelWidth) { widthModel = models.configured; } else { widthModel = (shrinkWrap & 1) ? models.shrinkWrap : models.natural; } } else if (policy.readsWidth) { if (hasPixelWidth) { widthModel = models.calculatedFromConfigured; } else { widthModel = (shrinkWrap & 1) ? models.calculatedFromShrinkWrap : models.calculatedFromNatural; } } else { widthModel = models.calculated; } } if (!heightModel) { if (!policy.setsHeight) { if (hasPixelHeight) { heightModel = models.configured; } else { heightModel = (shrinkWrap & 2) ? models.shrinkWrap : models.natural; } } else if (policy.readsHeight) { if (hasPixelHeight) { heightModel = models.calculatedFromConfigured; } else { heightModel = (shrinkWrap & 2) ? models.calculatedFromShrinkWrap : models.calculatedFromNatural; } } else { heightModel = models.calculated; } } } // We return one of the cached objects with the proper "width" and "height" as the // sizeModels we have determined. return widthModel.pairsByHeightOrdinal[heightModel.ordinal]; }, isDescendant: function(ancestor) { if (ancestor.isContainer) { for (var c = this.ownerCt; c; c = c.ownerCt) { if (c === ancestor) { return true; } } } return false; }, /** * This method needs to be called whenever you change something on this component that requires the Component's * layout to be recalculated. * @return {Ext.container.Container} this */ doComponentLayout : function() { this.updateLayout(); return this; }, /** * Forces this component to redo its componentLayout. * @deprecated 4.1.0 Use {@link #updateLayout} instead. */ forceComponentLayout: function () { this.updateLayout(); }, // @private setComponentLayout : function(layout) { var currentLayout = this.componentLayout; if (currentLayout && currentLayout.isLayout && currentLayout != layout) { currentLayout.setOwner(null); } this.componentLayout = layout; layout.setOwner(this); }, getComponentLayout : function() { var me = this; if (!me.componentLayout || !me.componentLayout.isLayout) { me.setComponentLayout(Ext.layout.Layout.create(me.componentLayout, 'autocomponent')); } return me.componentLayout; }, /** * Called by the layout system after the Component has been laid out. * * @param {Number} width The width that was set * @param {Number} height The height that was set * @param {Number/undefined} oldWidth The old width, or `undefined` if this was the initial layout. * @param {Number/undefined} oldHeight The old height, or `undefined` if this was the initial layout. * * @template * @protected */ afterComponentLayout: function(width, height, oldWidth, oldHeight) { var me = this; if (++me.componentLayoutCounter === 1) { me.afterFirstLayout(width, height); } if (width !== oldWidth || height !== oldHeight) { me.onResize(width, height, oldWidth, oldHeight); } }, /** * Occurs before `componentLayout` is run. Returning `false` from this method will prevent the `componentLayout` from * being executed. * * @param {Number} adjWidth The box-adjusted width that was set. * @param {Number} adjHeight The box-adjusted height that was set. * * @template * @protected */ beforeComponentLayout: function(width, height) { return true; }, /** * @member Ext.Component * Sets the left and top of the component. To set the page XY position instead, use {@link Ext.Component#setPagePosition setPagePosition}. This * method fires the {@link #event-move} event. * @param {Number/Number[]/Object} x The new left, an array of `[x,y]`, or animation config object containing `x` and `y` properties. * @param {Number} [y] The new top. * @param {Boolean/Object} [animate] If `true`, the Component is _animated_ into its new position. You may also pass an * animation configuration. * @return {Ext.Component} this */ setPosition: function(x, y, animate) { var me = this, pos = me.beforeSetPosition.apply(me, arguments); if (pos && me.rendered) { x = pos.x; y = pos.y; if (animate) { // Proceed only if the new position is different from the current // one. We only do these DOM reads in the animate case as we don't // want to incur the penalty of read/write on every call to setPosition if (x !== me.getLocalX() || y !== me.getLocalY()) { me.stopAnimation(); me.animate(Ext.apply({ duration: 1000, listeners: { afteranimate: Ext.Function.bind(me.afterSetPosition, me, [x, y]) }, to: { x: x, y: y } }, animate)); } } else { me.setLocalXY(x, y); me.afterSetPosition(x, y); } } return me; }, /** * @private Template method called before a Component is positioned. * * Ensures that the position is adjusted so that the Component is constrained if so configured. */ beforeSetPosition: function (x, y, animate) { var pos, x0; // Decode members of x if x is an array or an object. // If it is numeric (including zero), we need do nothing. if (x) { // Position in first argument as an array of [x, y] if (Ext.isNumber(x0 = x[0])) { animate = y; y = x[1]; x = x0; } // Position in first argument as object w/ x & y properties else if ((x0 = x.x) !== undefined) { animate = y; y = x.y; x = x0; } } if (this.constrain || this.constrainHeader) { pos = this.calculateConstrainedPosition(null, [x, y], true); if (pos) { x = pos[0]; y = pos[1]; } } // Set up the return info and store the position in this object pos = { x : this.x = x, y : this.y = y, anim: animate, hasX: x !== undefined, hasY: y !== undefined }; return (pos.hasX || pos.hasY) ? pos : null; }, /** * Template method called after a Component has been positioned. * * @param {Number} x * @param {Number} y * * @template * @protected */ afterSetPosition: function(x, y) { var me = this; me.onPosition(x, y); if (me.hasListeners.move) { me.fireEvent('move', me, x, y); } }, /** * Called after the component is moved, this method is empty by default but can be implemented by any * subclass that needs to perform custom logic after a move occurs. * * @param {Number} x The new x position. * @param {Number} y The new y position. * * @template * @protected */ onPosition: Ext.emptyFn, /** * Sets the width of the component. This method fires the {@link #resize} event. * * @param {Number} width The new width to setThis may be one of: * * - A Number specifying the new width in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels). * - A String used to set the CSS width style. * * @return {Ext.Component} this */ setWidth : function(width) { return this.setSize(width); }, /** * Sets the height of the component. This method fires the {@link #resize} event. * * @param {Number} height The new height to set. This may be one of: * * - A Number specifying the new height in the {@link #getEl Element}'s {@link Ext.Element#defaultUnit}s (by default, pixels). * - A String used to set the CSS height style. * - _undefined_ to leave the height unchanged. * * @return {Ext.Component} this */ setHeight : function(height) { return this.setSize(undefined, height); }, /** * Gets the current size of the component's underlying element. * @return {Object} An object containing the element's size `{width: (element width), height: (element height)}` */ getSize : function() { return this.el.getSize(); }, /** * Gets the current width of the component's underlying element. * @return {Number} */ getWidth : function() { return this.el.getWidth(); }, /** * Gets the current height of the component's underlying element. * @return {Number} */ getHeight : function() { return this.el.getHeight(); }, /** * Gets the {@link Ext.ComponentLoader} for this Component. * @return {Ext.ComponentLoader} The loader instance, null if it doesn't exist. */ getLoader: function(){ var me = this, autoLoad = me.autoLoad ? (Ext.isObject(me.autoLoad) ? me.autoLoad : {url: me.autoLoad}) : null, loader = me.loader || autoLoad; if (loader) { if (!loader.isLoader) { me.loader = new Ext.ComponentLoader(Ext.apply({ target: me, autoLoad: autoLoad }, loader)); } else { loader.setTarget(me); } return me.loader; } return null; }, /** * Sets the dock position of this component in its parent panel. Note that this only has effect if this item is part * of the `dockedItems` collection of a parent that has a DockLayout (note that any Panel has a DockLayout by default) * @param {Object} dock The dock position. * @param {Boolean} [layoutParent=false] `true` to re-layout parent. * @return {Ext.Component} this */ setDocked : function(dock, layoutParent) { var me = this; me.dock = dock; if (layoutParent && me.ownerCt && me.rendered) { me.ownerCt.updateLayout(); } return me; }, /** * * @param {String/Number} border The border, see {@link #border}. If a falsey value is passed * the border will be removed. */ setBorder: function(border, /* private */ targetEl) { var me = this, initial = !!targetEl; if (me.rendered || initial) { if (!initial) { targetEl = me.el; } if (!border) { border = 0; } else if (border === true) { border = '1px'; } else { border = this.unitizeBox(border); } targetEl.setStyle('border-width', border); if (!initial) { me.updateLayout(); } } me.border = border; }, onDestroy : function() { var me = this; if (me.monitorResize && Ext.EventManager.resizeEvent) { Ext.EventManager.resizeEvent.removeListener(me.setSize, me); } // Destroying the floatingItems ZIndexManager will also destroy descendant floating Components Ext.destroy( me.componentLayout, me.loadMask, me.floatingDescendants ); }, /** * Destroys the Component. * @since 1.1.0 */ destroy : function() { var me = this, selectors = me.renderSelectors, selector, el; if (!me.isDestroyed) { if (!me.hasListeners.beforedestroy || me.fireEvent('beforedestroy', me) !== false) { me.destroying = true; me.beforeDestroy(); if (me.floating) { delete me.floatParent; // A zIndexManager is stamped into a *floating* Component when it is added to a Container. // If it has no zIndexManager at render time, it is assigned to the global Ext.WindowManager instance. if (me.zIndexManager) { me.zIndexManager.unregister(me); } } else if (me.ownerCt && me.ownerCt.remove) { me.ownerCt.remove(me, false); } me.stopAnimation(); me.onDestroy(); // Attempt to destroy all plugins Ext.destroy(me.plugins); if (me.hasListeners.destroy) { me.fireEvent('destroy', me); } Ext.ComponentManager.unregister(me); me.mixins.state.destroy.call(me); me.clearListeners(); // make sure we clean up the element references after removing all events if (me.rendered) { if (!me.preserveElOnDestroy) { me.el.remove(); } me.mixins.elementCt.destroy.call(me); // removes childEls if (selectors) { for (selector in selectors) { if (selectors.hasOwnProperty(selector)) { el = me[selector]; if (el) { // in case any other code may have already removed it delete me[selector]; el.remove(); } } } } delete me.el; delete me.frameBody; delete me.rendered; } me.destroying = false; me.isDestroyed = true; } } }, /** * Determines whether this component is the descendant of a particular container. * @param {Ext.Container} container * @return {Boolean} `true` if the component is the descendant of a particular container, otherwise `false`. */ isDescendantOf: function(container) { return !!this.findParentBy(function(p){ return p === container; }); }, /** * A component's hierarchyState is used to keep track of aspects of a component's * state that affect its descendants hierarchically like "collapsed" and "hidden". * For example, if this.hierarchyState.hidden == true, it means that either this * component, or one of its ancestors is hidden. * * Hierarchical state management is implemented by chaining each component's * hierarchyState property to its parent container's hierarchyState property via the * prototype. The result is such that if a component's hierarchyState does not have * it's own property, it inherits the property from the nearest ancestor that does. * * To set a hierarchical "hidden" value: * * this.getHierarchyState().hidden = true; * * It is important to remember when unsetting hierarchyState properties to delete * them instead of just setting them to a falsy value. This ensures that the * hierarchyState returns to a state of inheriting the value instead of overriding it * To unset the hierarchical "hidden" value: * * delete this.getHierarchyState().hidden; * * IMPORTANT! ALWAYS access hierarchyState using this method, not by accessing * this.hierarchyState directly. The hierarchyState property does not exist until * the first time getHierarchyState() is called. At that point getHierarchyState() * walks up the component tree to establish the hierarchyState prototype chain. * Additionally the hierarchyState property should NOT be relied upon even after * the initial call to getHierarchyState() because it is possible for the * hierarchyState to be invalidated. Invalidation typically happens when a component * is moved to a new container. In such a case the hierarchy state remains invalid * until the next time getHierarchyState() is called on the component or one of its * descendants. * * @private */ getHierarchyState: function (inner) { var me = this, hierarchyState = (inner && me.hierarchyStateInner) || me.hierarchyState, ownerCt = me.ownerCt, parent, layout, hierarchyStateInner, getInner; if (!hierarchyState || hierarchyState.invalid) { // Use upward navigational link, not ownerCt. // 99% of the time, this will use ownerCt/floatParent. // Certain floating components do not have an ownerCt, but they are still linked // into a navigational hierarchy. The getRefOwner method normalizes these differences. parent = me.getRefOwner(); if (ownerCt) { // This will only be true if the item is a "child" of its owning container // For example, a docked item will not get the inner hierarchy state getInner = me.ownerLayout === ownerCt.layout; } me.hierarchyState = hierarchyState = // chain this component's hierarchyState to that of its parent. If it // doesn't have a parent, then chain to the rootHierarchyState. This is // done so that when there is a viewport, all component's will inherit // from its hierarchyState, even components that are not descendants of // the viewport. Ext.Object.chain(parent ? parent.getHierarchyState(getInner) : Ext.rootHierarchyState); me.initHierarchyState(hierarchyState); if ((layout = me.componentLayout).initHierarchyState) { layout.initHierarchyState(hierarchyState); } if (me.isContainer) { me.hierarchyStateInner = hierarchyStateInner = Ext.Object.chain(hierarchyState); layout = me.layout; if (layout && layout.initHierarchyState) { layout.initHierarchyState(hierarchyStateInner, hierarchyState); } if (inner) { hierarchyState = hierarchyStateInner; } } } return hierarchyState; }, /** * Called by {@link #getHierarchyState} to initialize the hierarchyState the first * time it is requested. * @private */ initHierarchyState: function(hierarchyState) { var me = this; if (me.collapsed) { hierarchyState.collapsed = true; } if (me.hidden) { hierarchyState.hidden = true; } if (me.collapseImmune) { hierarchyState.collapseImmune = true; } }, // ********************************************************************************** // Begin Positionable methods // ********************************************************************************** getAnchorToXY: function(el, anchor, local, mySize) { return el.getAnchorXY(anchor, local, mySize); }, getBorderPadding: function() { return this.el.getBorderPadding(); }, getLocalX: function() { return this.el.getLocalX(); }, getLocalXY: function() { return this.el.getLocalXY(); }, getLocalY: function() { return this.el.getLocalY(); }, getX: function() { return this.el.getX(); }, getXY: function() { return this.el.getXY(); }, getY: function() { return this.el.getY(); }, setLocalX: function(x) { this.el.setLocalX(x); }, setLocalXY: function(x, y) { this.el.setLocalXY(x, y); }, setLocalY: function(y) { this.el.setLocalY(y); }, setX: function(x, animate) { this.el.setX(x, animate); }, setXY: function(xy, animate) { this.el.setXY(xy, animate); }, setY: function(y, animate) { this.el.setY(y, animate); } // ********************************************************************************** // End Positionable methods // ********************************************************************************** }, function() { var AbstractComponent = this; AbstractComponent.createAlias({ on: 'addListener', prev: 'previousSibling', next: 'nextSibling' }); /** * @inheritdoc Ext.AbstractComponent#resumeLayouts * @member Ext */ Ext.resumeLayouts = function (flush) { AbstractComponent.resumeLayouts(flush); }; /** * @inheritdoc Ext.AbstractComponent#suspendLayouts * @member Ext */ Ext.suspendLayouts = function () { AbstractComponent.suspendLayouts(); }; /** * Utility wrapper that suspends layouts of all components for the duration of a given function. * @param {Function} fn The function to execute. * @param {Object} [scope] The scope (`this` reference) in which the specified function is executed. * @member Ext */ Ext.batchLayouts = function(fn, scope) { AbstractComponent.suspendLayouts(); // Invoke the function fn.call(scope); AbstractComponent.resumeLayouts(true); }; });
server/sonar-web/src/main/js/apps/permissions/shared/components/UserHolder.js
lbndev/sonarqube
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React from 'react'; import shallowCompare from 'react-addons-shallow-compare'; import Avatar from '../../../../components/ui/Avatar'; import { translate } from '../../../../helpers/l10n'; export default class UserHolder extends React.Component { static propTypes = { user: React.PropTypes.object.isRequired, permissions: React.PropTypes.array.isRequired, selectedPermission: React.PropTypes.string, permissionsOrder: React.PropTypes.array.isRequired, onToggle: React.PropTypes.func.isRequired }; shouldComponentUpdate(nextProps, nextState) { return shallowCompare(this, nextProps, nextState); } handleClick(permission, e) { e.preventDefault(); e.target.blur(); this.props.onToggle(this.props.user, permission); } render() { const { selectedPermission } = this.props; const permissionCells = this.props.permissionsOrder.map(p => ( <td key={p.key} className="text-center text-middle" style={{ backgroundColor: p.key === selectedPermission ? '#d9edf7' : 'transparent' }}> <button className="button-clean" onClick={this.handleClick.bind(this, p.key)}> {this.props.permissions.includes(p.key) ? <i className="icon-checkbox icon-checkbox-checked" /> : <i className="icon-checkbox" />} </button> </td> )); const { user } = this.props; const isCreator = user.login === '<creator>'; return ( <tr> <td className="nowrap"> {!isCreator && <Avatar email={user.email} size={36} className="text-middle big-spacer-right" />} <div className="display-inline-block text-middle"> <div> <strong>{user.name}</strong> {!isCreator && <span className="note spacer-left">{user.login}</span>} </div> {!isCreator && <div className="little-spacer-top">{user.email}</div>} {isCreator && <div className="little-spacer-top" style={{ whiteSpace: 'normal' }}> {translate('permission_templates.project_creators.explanation')} </div>} </div> </td> {permissionCells} </tr> ); } }
docs/src/components/browser.js
adamrneary/nuclear-js
import React from 'react' export default React.createClass({ render() { var className = 'browser-component'; if (this.props.size) { className += " browser-component__" + this.props.size } var contentClassName = "browser-component--content" return <div className={className}> <div className="browser-component--top"> <div className="browser-component--top-left"></div> <div className="browser-component--top-middle"></div> <div className="browser-component--top-right"></div> </div> <div className={contentClassName}> {this.props.children} </div> </div> } })
src/svg-icons/av/art-track.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvArtTrack = (props) => ( <SvgIcon {...props}> <path d="M22 13h-8v-2h8v2zm0-6h-8v2h8V7zm-8 10h8v-2h-8v2zm-2-8v6c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V9c0-1.1.9-2 2-2h6c1.1 0 2 .9 2 2zm-1.5 6l-2.25-3-1.75 2.26-1.25-1.51L3.5 15h7z"/> </SvgIcon> ); AvArtTrack = pure(AvArtTrack); AvArtTrack.displayName = 'AvArtTrack'; AvArtTrack.muiName = 'SvgIcon'; export default AvArtTrack;
src/components/TimeAndSalary/SearchScreen/SearchScreen.js
goodjoblife/GoodJobShare
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { compose, setStatic } from 'recompose'; import qs from 'qs'; import Loading from 'common/Loader'; import { P } from 'common/base'; import FanPageBlock from 'common/FanPageBlock'; import { querySelector, pathSelector } from 'common/routing/selectors'; import Pagination from 'common/Pagination'; import { queryKeyword, keywordMinLength, } from '../../../actions/timeAndSalarySearch'; import { isFetching, isFetched } from '../../../constants/status'; import { searchCriteriaSelector, searchKeywordSelector, pageSelector, } from '../common/selectors'; import { pageType } from '../../../constants/companyJobTitle'; import { validatePage, validateSearchKeyword } from '../common/validators'; import WorkingHourBlock from './WorkingHourBlock'; import Helmet from './Helmet'; import styles from './SearchScreen.module.css'; function getTitle(keyword) { if (keyword) { if (keyword.length < keywordMinLength) { return '請輸入更長的搜尋關鍵字'; } else { return `查詢「${keyword}」的結果`; } } else { return '請輸入搜尋條件!'; } } class SearchScreen extends Component { static propTypes = { data: ImmutablePropTypes.list, status: PropTypes.string, // eslint-disable-next-line react/no-unused-prop-types match: PropTypes.shape({ path: PropTypes.string.isRequired, params: PropTypes.object.isRequired, }), queryKeyword: PropTypes.func, history: PropTypes.shape({ push: PropTypes.func.isRequired, }).isRequired, }; componentDidMount() { const keyword = validateSearchKeyword(searchKeywordSelector(this.props)); this.props .queryKeyword({ keyword }) .then(() => this.redirectOnSingleResult()); } componentDidUpdate(prevProps) { if ( pathSelector(prevProps) !== pathSelector(this.props) || searchCriteriaSelector(prevProps) !== searchCriteriaSelector(this.props) || searchKeywordSelector(prevProps) !== searchKeywordSelector(this.props) ) { const keyword = validateSearchKeyword(searchKeywordSelector(this.props)); this.props .queryKeyword({ keyword }) .then(() => this.redirectOnSingleResult()); } } redirectOnSingleResult() { if (this.props.data.size === 1) { const firstData = this.props.data.get(0).toJS(); this.props.history.replace(this.getLinkForData(firstData)); } } getLinkForData(data) { if (data.pageType === pageType.COMPANY) { return `/companies/${encodeURIComponent( data.name, )}/overview${qs.stringify( { ...querySelector(this.props), p: 1 }, { addQueryPrefix: true }, )}`; } else if (data.pageType === pageType.JOB_TITLE) { return `/job-titles/${encodeURIComponent( data.name, )}/overview${qs.stringify( { ...querySelector(this.props), p: 1 }, { addQueryPrefix: true }, )}`; } return ''; } render() { const { status } = this.props; const page = validatePage(pageSelector(this.props)); const pageSize = 10; const totalNum = this.props.data.size; const keyword = validateSearchKeyword(searchKeywordSelector(this.props)); const title = getTitle(keyword); const queryParams = querySelector(this.props); const raw = this.props.data .slice((page - 1) * pageSize, page * pageSize) .toJS(); return ( <section className={styles.searchResult}> <Helmet keyword={keyword} page={page} /> <h2 className={styles.heading}>{title}</h2> {isFetching(status) && <Loading size="s" />} {isFetched(status) && raw.length === 0 && ( <P size="l" bold className={styles.searchNoResult}> 尚未有 「{keyword} 」的資料 </P> )} {raw.map((o, i) => ( <WorkingHourBlock key={i} pageType={o.pageType} name={o.name} to={this.getLinkForData(o)} dataCount={o.salary_work_time_statistics.count} /> ))} <Pagination totalCount={totalNum} unit={pageSize} currentPage={page} createPageLinkTo={toPage => qs.stringify( { ...queryParams, p: toPage }, { addQueryPrefix: true }, ) } /> <FanPageBlock className={styles.fanPageBlock} /> </section> ); } } const ssr = setStatic('fetchData', ({ store: { dispatch }, ...props }) => { const keyword = validateSearchKeyword(searchKeywordSelector(props)); return dispatch(queryKeyword({ keyword })); }); const hoc = compose(ssr); export default hoc(SearchScreen);
src/ui/GroupFooter.js
touchstonejs/touchstonejs
import blacklist from 'blacklist'; import classnames from 'classnames'; import React from 'react'; module.exports = React.createClass({ displayName: 'GroupFooter', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string }, render () { var className = classnames('Group__footer', this.props.className); var props = blacklist(this.props, 'className'); return ( <div className={className} {...props} /> ); } });
geonode/monitoring/frontend/src/components/molecules/total-requests/index.js
mcldev/geonode
import React from 'react'; import PropTypes from 'prop-types'; import CircularProgress from 'material-ui/CircularProgress'; import HoverPaper from '../../atoms/hover-paper'; import styles from './styles'; class TotalRequests extends React.Component { static propTypes = { requests: PropTypes.number, } static contextTypes = { muiTheme: PropTypes.object.isRequired, } render() { let requests = this.props.requests; if (requests === undefined) { requests = 'N/A'; } else if (typeof requests === 'number') { if (requests === 0) { requests = <CircularProgress size={this.context.muiTheme.spinner.size} />; } } return ( <HoverPaper style={styles.content}> <h5>Total Requests</h5> <div style={styles.stat}> <h3>{requests}</h3> </div> </HoverPaper> ); } } export default TotalRequests;
fields/types/select/SelectFilter.js
tony2cssc/keystone
import React from 'react'; import { Checkbox, FormField, SegmentedControl } from 'elemental'; import PopoutList from '../../../admin/client/components/Popout/PopoutList'; const INVERTED_OPTIONS = [ { label: 'Matches', value: false }, { label: 'Does NOT Match', value: true }, ]; function getDefaultValue () { return { inverted: INVERTED_OPTIONS[0].value, value: [], }; } var SelectFilter = React.createClass({ propTypes: { field: React.PropTypes.object, filter: React.PropTypes.shape({ inverted: React.PropTypes.boolean, value: React.PropTypes.array, }), }, statics: { getDefaultValue: getDefaultValue, }, getDefaultProps () { return { filter: getDefaultValue(), }; }, toggleInverted (inverted) { this.updateFilter({ inverted }); }, toggleAllOptions () { const { field, filter } = this.props; if (filter.value.length < field.ops.length) { this.updateFilter({ value: field.ops.map(i => i.value) }); } else { this.updateFilter({ value: [] }); } }, selectOption (option) { const value = this.props.filter.value.concat(option.value); this.updateFilter({ value }); }, removeOption (option) { const value = this.props.filter.value.filter(i => i !== option.value); this.updateFilter({ value }); }, updateFilter (value) { this.props.onChange({ ...this.props.filter, ...value }); }, renderOptions () { return this.props.field.ops.map((option, i) => { const selected = this.props.filter.value.indexOf(option.value) > -1; return ( <PopoutList.Item key={`item-${i}-${option.value}`} icon={selected ? 'check' : 'dash'} isSelected={selected} label={option.label} onClick={() => { if (selected) this.removeOption(option); else this.selectOption(option); }} /> ); }); }, render () { const { field, filter } = this.props; const allSelected = filter.value.length; const indeterminate = filter.value.lenght === field.ops.length; return ( <div> <FormField> <SegmentedControl equalWidthSegments options={INVERTED_OPTIONS} value={filter.inverted} onChange={this.toggleInverted} /> </FormField> <FormField style={{ borderBottom: '1px dashed rgba(0,0,0,0.1)', paddingBottom: '1em' }}> <Checkbox autofocus onChange={this.toggleAllOptions} label="Select all options" checked={allSelected} indeterminate={indeterminate} /> </FormField> {this.renderOptions()} </div> ); }, }); module.exports = SelectFilter;
src/js/components/Pokemon.js
ilken/PokePower
import React from 'react'; import * as PokemonActions from '../actions/PokemonActions'; export default class Pokemon extends React.Component { evaluateSelection (selection) { PokemonActions.selectPokemon(selection); } render () { const { Name, MaxCP } = this.props; const imgSrc = 'http://assets.pokemon.com/assets/cms2/img/pokedex/detail/' + this.props.Number + '.png'; return ( <div className="col-md-6 col-sm-6 col-xs-12"> <div className="row" onClick={this.evaluateSelection.bind(this, { Name })}> <div className="col-md-12 col-sm-12 col-xs-12"> <p className="text-center">{Name}</p> </div> <div className="col-md-12 col-sm-12 col-xs-12"> <p className="text-center">{MaxCP}</p> </div> <div className="col-md-12 col-sm-12 col-xs-12"> <img className="img-responsive center-block" alt={Name} src={imgSrc} /> </div> </div> </div> ); } }
mobile_app/src/components/views/settings/Settings.js
youennPennarun/agorask
/* @flow */ import React from 'react'; import { View, Text, StyleSheet, Dimensions, Switch } from 'react-native'; import { connect } from 'react-redux'; import type { SettingsStateType } from '../../../redux/reducers/settings'; import { setNotifications } from '../../../redux/actions/settings'; const { width } = Dimensions.get('window'); function Header(): React.Element<View> { return ( <View style={styles.header}> <Text style={styles.title}>Settings</Text> </View> ); } type SettingsPropsType = SettingsStateType & DispatchToPropsType; function Settings(props: SettingsPropsType): React.Element<View> { return ( <View style={styles.container}> <Header /> <View style={styles.row}> <Text style={styles.label}>Notifications: </Text> <Switch onValueChange={(enabled: Boolean) => { props.setNotifications(enabled); }} value={props.notifications} /> </View> <View style={styles.separator} /> </View> ); } const styles = StyleSheet.create({ container: { backgroundColor: 'white', flex: 1, }, header: { paddingLeft: 20, justifyContent: 'center', width, height: 50, backgroundColor: 'white', elevation: 2, marginBottom: 10, }, title: { fontSize: 30, }, label: { fontSize: 20, alignSelf: 'center', }, row: { marginHorizontal: 10, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', height: 40, }, spearator: { backgroundColor: '#e9e9e9', width, height: 10, }, }); const mapStateToProps = (state): SettingsStateType => { return { ...state.settings, }; }; type DispatchToPropsType = { setNotifications: Function, }; const mapDispatchToProps = (dispatch): DispatchToPropsType => { return { setNotifications: (enabled: Boolean) => { dispatch(setNotifications(enabled)); }, }; }; export default connect(mapStateToProps, mapDispatchToProps)(Settings);
ajax/libs/jquery-confirm/1.5.1/jquery-confirm.min.js
viskin/cdnjs
"use strict"; /*! * jquery-confirm v1.5.1 (http://craftpip.github.io/jquery-confirm/) * Author: Boniface Pereira * Website: www.craftpip.com * Contact: hey@craftpip.com * * Copyright 2013-2015 jquery-confirm * Licensed under MIT (https://github.com/craftpip/jquery-confirm/blob/master/LICENSE) */ if(typeof jQuery==="undefined"){throw new Error("jquery-confirm requires jQuery")}var jconfirm,Jconfirm;(function(b){b.confirm=function(c){return jconfirm(c)};b.alert=function(c){c.cancelButton=false;return jconfirm(c)};b.dialog=function(c){c.cancelButton=false;c.confirmButton=false;return jconfirm(c)};jconfirm=function(c){if(jconfirm.defaults){b.extend(jconfirm.pluginDefaults,jconfirm.defaults)}var c=b.extend({},jconfirm.pluginDefaults,c);return new Jconfirm(c)};Jconfirm=function(c){b.extend(this,c);this._init()};Jconfirm.prototype={_init:function(){var c=this;this._rand=Math.round(Math.random()*99999);this._buildHTML();this._bindEvents();setTimeout(function(){c.open()},0)},animations:["anim-scale","anim-top","anim-bottom","anim-left","anim-right","anim-zoom","anim-opacity","anim-none","anim-rotate","anim-rotatex","anim-rotatey","anim-scalex","anim-scaley"],_buildHTML:function(){var e=this;this.animation="anim-"+this.animation.toLowerCase();if(this.animation==="none"){this.animationSpeed=0}this.$el=b(this.template).appendTo(this.container).addClass(this.theme);this.$b=this.$el.find(".jconfirm-box").css({"-webkit-transition-duration":this.animationSpeed/1000+"s","transition-duration":this.animationSpeed/1000+"s"});this.$b=this.$el.find(".jconfirm-box");this.$b.addClass(this.animation);this.$el.find("div.title").html('<i class="'+this.icon+'"></i> '+this.title);var d=this.$el.find("div.content");var f=this.$el.find(".buttons");if(this.confirmButton&&this.confirmButton.trim()!==""){this.$confirmButton=b('<button class="btn">'+this.confirmButton+"</button>").appendTo(f);this.$confirmButton.addClass(this.confirmButtonClass)}if(this.cancelButton&&this.cancelButton.trim()!==""){this.$cancelButton=b('<button class="btn">'+this.cancelButton+"</button>").appendTo(f);this.$cancelButton.addClass(this.cancelButtonClass)}if(!this.confirmButton&&!this.cancelButton){f.remove();if(this.closeIcon){this.$closeButton=this.$b.find(".closeIcon").show()}}if(this.content.substr(0,4).toLowerCase()==="url:"){d.html("");f.find("button").attr("disabled","disabled");var c=this.content.substring(4,this.content.length);setTimeout(function(){b.get(c,function(g){d.html(g);f.find("button").removeAttr("disabled");e.setDialogCenter()})},1)}else{d.html(this.content)}if(this.autoClose){this._startCountDown()}},_startCountDown:function(){var c=this.autoClose.split("|");if(/cancel/.test(c[0])&&this.type==="alert"){return false}if(/confirm|cancel/.test(c[0])){this.$cd=b(' <span class="countdown"></span>').appendTo(this["$"+c[0]+"Button"]);var d=this;d.$cd.parent().click();var e=c[1]/1000;this.interval=setInterval(function(){d.$cd.html(" ["+(e-=1)+"]");if(e===0){d.$cd.parent().trigger("click");clearInterval(d.interval)}},1000)}},_bindEvents:function(){var c=this;this.$el.find(".jconfirm-bg").click(function(d){if(c.backgroundDismiss){c.cancel();c.close()}else{c.$b.addClass("hilight");setTimeout(function(){c.$b.removeClass("hilight")},400)}});if(this.$confirmButton){this.$confirmButton.click(function(f){f.preventDefault();var d=c.confirm(c.$b);if(typeof d==="undefined"||d){c.close()}})}if(this.$cancelButton){this.$cancelButton.click(function(f){f.preventDefault();var d=c.cancel(c.$b);if(typeof d==="undefined"||d){c.close()}})}if(this.$closeButton){this.$closeButton.click(function(d){d.preventDefault();c.cancel();c.close()})}if(this.keyboardEnabled){setTimeout(function(){b(window).on("keyup."+this._rand,function(d){c.reactOnKey(d)})},500)}b(window).on("resize."+this._rand,function(){c.setDialogCenter()});this.setDialogCenter()},reactOnKey:function a(f){var c=b(".jconfirm");if(c.eq(c.length-1)[0]!==this.$el[0]){return false}var d=f.which;console.log(f);if(d===27){if(!this.backgroundDismiss){this.$el.find(".jconfirm-bg").click();return false}if(this.$cancelButton){this.$cancelButton.click()}else{this.close()}}if(d===13){if(this.$confirmButton){this.$confirmButton.click()}else{}}},setDialogCenter:function(){var d=b(window).height(),c=this.$b.height(),e=(d-c)/2;this.$b.find(".content").css({"max-height":d-200+"px"});this.$b.css({"margin-top":e})},close:function(){var c=this;b(window).unbind("resize."+this._rand);if(this.keyboardEnabled){b(window).unbind("keyup."+this._rand)}this.$b.addClass(this.animation);b("body").removeClass("jconfirm-noscroll");setTimeout(function(){c.$el.remove()},this.animationSpeed)},open:function(){var c=this;b("body").addClass("jconfirm-noscroll");this.$b.removeClass(this.animations.join(" "));b("body :focus").trigger("blur")}};jconfirm.pluginDefaults={template:'<div class="jconfirm"><div class="jconfirm-bg"></div><div class="container"><div class="row"><div class="col-md-6 col-md-offset-3 span6 offset3"><div class="jconfirm-box"><div class="closeIcon"><span class="glyphicon glyphicon-remove"></span></div><div class="title"></div><div class="content"></div><div class="buttons pull-right"></div><div class="jquery-clear"></div></div></div></div></div></div>',title:"Hello",content:"Are you sure to continue?",icon:"",confirmButton:"Okay",cancelButton:"Cancel",confirmButtonClass:"btn-default",cancelButtonClass:"btn-default",theme:"white",animation:"scale",animationSpeed:400,keyboardEnabled:false,container:"body",confirm:function(){},cancel:function(){},backgroundDismiss:true,autoClose:false,closeIcon:true,}})(jQuery);
ajax/libs/es6-shim/0.26.0/es6-shim.js
steadiest/cdnjs
/*! * https://github.com/paulmillr/es6-shim * @license es6-shim Copyright 2013-2015 by Paul Miller (http://paulmillr.com) * and contributors, MIT License * es6-shim: v0.26.0 * see https://github.com/paulmillr/es6-shim/blob/0.26.0/LICENSE * Details and documentation: * https://github.com/paulmillr/es6-shim/ */ // UMD (Universal Module Definition) // see https://github.com/umdjs/umd/blob/master/returnExports.js (function (root, factory) { /*global define, module, exports */ if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(factory); } else if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like enviroments that support module.exports, // like Node. module.exports = factory(); } else { // Browser globals (root is window) root.returnExports = factory(); } }(this, function () { 'use strict'; var isCallableWithoutNew = function (func) { try { func(); } catch (e) { return false; } return true; }; var supportsSubclassing = function (C, f) { /* jshint proto:true */ try { var Sub = function () { C.apply(this, arguments); }; if (!Sub.__proto__) { return false; /* skip test on IE < 11 */ } Object.setPrototypeOf(Sub, C); Sub.prototype = Object.create(C.prototype, { constructor: { value: C } }); return f(Sub); } catch (e) { return false; } }; var arePropertyDescriptorsSupported = function () { try { Object.defineProperty({}, 'x', {}); return true; } catch (e) { /* this is IE 8. */ return false; } }; var startsWithRejectsRegex = function () { var rejectsRegex = false; if (String.prototype.startsWith) { try { '/a/'.startsWith(/a/); } catch (e) { /* this is spec compliant */ rejectsRegex = true; } } return rejectsRegex; }; /*jshint evil: true */ var getGlobal = new Function('return this;'); /*jshint evil: false */ var globals = getGlobal(); var global_isFinite = globals.isFinite; var supportsDescriptors = !!Object.defineProperty && arePropertyDescriptorsSupported(); var startsWithIsCompliant = startsWithRejectsRegex(); var _indexOf = Function.call.bind(String.prototype.indexOf); var _toString = Function.call.bind(Object.prototype.toString); var _hasOwnProperty = Function.call.bind(Object.prototype.hasOwnProperty); var ArrayIterator; // make our implementation private var noop = function () {}; var Symbol = globals.Symbol || {}; var symbolSpecies = Symbol.species || '@@species'; var Type = { object: function (x) { return x !== null && typeof x === 'object'; }, string: function (x) { return _toString(x) === '[object String]'; }, regex: function (x) { return _toString(x) === '[object RegExp]'; }, symbol: function (x) { /*jshint notypeof: true */ return typeof globals.Symbol === 'function' && typeof x === 'symbol'; /*jshint notypeof: false */ } }; var defineProperty = function (object, name, value, force) { if (!force && name in object) { return; } if (supportsDescriptors) { Object.defineProperty(object, name, { configurable: true, enumerable: false, writable: true, value: value }); } else { object[name] = value; } }; var Value = { getter: function (object, name, getter) { if (!supportsDescriptors) { throw new TypeError('getters require true ES5 support'); } Object.defineProperty(object, name, { configurable: true, enumerable: false, get: getter }); }, proxy: function (originalObject, key, targetObject) { if (!supportsDescriptors) { throw new TypeError('getters require true ES5 support'); } var originalDescriptor = Object.getOwnPropertyDescriptor(originalObject, key); Object.defineProperty(targetObject, key, { configurable: originalDescriptor.configurable, enumerable: originalDescriptor.enumerable, get: function getKey() { return originalObject[key]; }, set: function setKey(value) { originalObject[key] = value; } }); }, redefine: function (object, property, newValue) { if (supportsDescriptors) { var descriptor = Object.getOwnPropertyDescriptor(object, property); descriptor.value = newValue; Object.defineProperty(object, property, descriptor); } else { object[property] = newValue; } }, preserveToString: function (target, source) { defineProperty(target, 'toString', source.toString.bind(source), true); } }; // Define configurable, writable and non-enumerable props // if they don’t exist. var defineProperties = function (object, map) { Object.keys(map).forEach(function (name) { var method = map[name]; defineProperty(object, name, method, false); }); }; // Simple shim for Object.create on ES3 browsers // (unlike real shim, no attempt to support `prototype === null`) var create = Object.create || function (prototype, properties) { function Prototype() {} Prototype.prototype = prototype; var object = new Prototype(); if (typeof properties !== 'undefined') { defineProperties(object, properties); } return object; }; // This is a private name in the es6 spec, equal to '[Symbol.iterator]' // we're going to use an arbitrary _-prefixed name to make our shims // work properly with each other, even though we don't have full Iterator // support. That is, `Array.from(map.keys())` will work, but we don't // pretend to export a "real" Iterator interface. var $iterator$ = Type.symbol(Symbol.iterator) ? Symbol.iterator : '_es6-shim iterator_'; // Firefox ships a partial implementation using the name @@iterator. // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 // So use that name if we detect it. if (globals.Set && typeof new globals.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var addIterator = function (prototype, impl) { if (!impl) { impl = function iterator() { return this; }; } var o = {}; o[$iterator$] = impl; defineProperties(prototype, o); if (!prototype[$iterator$] && Type.symbol($iterator$)) { // implementations are buggy when $iterator$ is a Symbol prototype[$iterator$] = impl; } }; // taken directly from https://github.com/ljharb/is-arguments/blob/master/index.js // can be replaced with require('is-arguments') if we ever use a build process instead var isArguments = function isArguments(value) { var str = _toString(value); var result = str === '[object Arguments]'; if (!result) { result = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && _toString(value.callee) === '[object Function]'; } return result; }; var safeApply = Function.call.bind(Function.apply); var ES = { // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-call-f-v-args Call: function Call(F, V) { var args = arguments.length > 2 ? arguments[2] : []; if (!ES.IsCallable(F)) { throw new TypeError(F + ' is not a function'); } return safeApply(F, V, args); }, RequireObjectCoercible: function (x, optMessage) { /* jshint eqnull:true */ if (x == null) { throw new TypeError(optMessage || 'Cannot call method on ' + x); } }, TypeIsObject: function (x) { /* jshint eqnull:true */ // this is expensive when it returns false; use this function // when you expect it to return true in the common case. return x != null && Object(x) === x; }, ToObject: function (o, optMessage) { ES.RequireObjectCoercible(o, optMessage); return Object(o); }, IsCallable: function (x) { // some versions of IE say that typeof /abc/ === 'function' return typeof x === 'function' && _toString(x) === '[object Function]'; }, ToInt32: function (x) { return ES.ToNumber(x) >> 0; }, ToUint32: function (x) { return ES.ToNumber(x) >>> 0; }, ToNumber: function (value) { if (_toString(value) === '[object Symbol]') { throw new TypeError('Cannot convert a Symbol value to a number'); } return +value; }, ToInteger: function (value) { var number = ES.ToNumber(value); if (Number.isNaN(number)) { return 0; } if (number === 0 || !Number.isFinite(number)) { return number; } return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number)); }, ToLength: function (value) { var len = ES.ToInteger(value); if (len <= 0) { return 0; } // includes converting -0 to +0 if (len > Number.MAX_SAFE_INTEGER) { return Number.MAX_SAFE_INTEGER; } return len; }, SameValue: function (a, b) { if (a === b) { // 0 === -0, but they are not identical. if (a === 0) { return 1 / a === 1 / b; } return true; } return Number.isNaN(a) && Number.isNaN(b); }, SameValueZero: function (a, b) { // same as SameValue except for SameValueZero(+0, -0) == true return (a === b) || (Number.isNaN(a) && Number.isNaN(b)); }, IsIterable: function (o) { return ES.TypeIsObject(o) && (typeof o[$iterator$] !== 'undefined' || isArguments(o)); }, GetIterator: function (o) { if (isArguments(o)) { // special case support for `arguments` return new ArrayIterator(o, 'value'); } var itFn = o[$iterator$]; if (!ES.IsCallable(itFn)) { throw new TypeError('value is not an iterable'); } var it = itFn.call(o); if (!ES.TypeIsObject(it)) { throw new TypeError('bad iterator'); } return it; }, IteratorNext: function (it) { var result = arguments.length > 1 ? it.next(arguments[1]) : it.next(); if (!ES.TypeIsObject(result)) { throw new TypeError('bad iterator'); } return result; }, Construct: function (C, args) { // CreateFromConstructor var obj; if (ES.IsCallable(C[symbolSpecies])) { obj = C[symbolSpecies](); } else { // OrdinaryCreateFromConstructor obj = create(C.prototype || null); } // Mark that we've used the es6 construct path // (see emulateES6construct) defineProperties(obj, { _es6construct: true }); // Call the constructor. var result = ES.Call(C, obj, args); return ES.TypeIsObject(result) ? result : obj; }, CreateHTML: function (string, tag, attribute, value) { var S = String(string); var p1 = '<' + tag; if (attribute !== '') { var V = String(value); var escapedV = V.replace(/"/g, '&quot;'); p1 += ' ' + attribute + '="' + escapedV + '"'; } var p2 = p1 + '>'; var p3 = p2 + S; return p3 + '</' + tag + '>'; } }; var emulateES6construct = function (o) { if (!ES.TypeIsObject(o)) { throw new TypeError('bad object'); } // es5 approximation to es6 subclass semantics: in es6, 'new Foo' // would invoke Foo.@@species to allocation/initialize the new object. // In es5 we just get the plain object. So if we detect an // uninitialized object, invoke o.constructor.@@species if (!o._es6construct) { if (o.constructor && ES.IsCallable(o.constructor[symbolSpecies])) { o = o.constructor[symbolSpecies](o); } defineProperties(o, { _es6construct: true }); } return o; }; var numberConversion = (function () { // from https://github.com/inexorabletash/polyfill/blob/master/typedarray.js#L176-L266 // with permission and license, per https://twitter.com/inexorabletash/status/372206509540659200 function roundToEven(n) { var w = Math.floor(n), f = n - w; if (f < 0.5) { return w; } if (f > 0.5) { return w + 1; } return w % 2 ? w + 1 : w; } function packIEEE754(v, ebits, fbits) { var bias = (1 << (ebits - 1)) - 1, s, e, f, i, bits, str, bytes; // Compute sign, exponent, fraction if (v !== v) { // NaN // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping e = (1 << ebits) - 1; f = Math.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 = Math.abs(v); if (v >= Math.pow(2, 1 - bias)) { e = Math.min(Math.floor(Math.log(v) / Math.LN2), 1023); f = roundToEven(v / Math.pow(2, e) * Math.pow(2, fbits)); if (f / Math.pow(2, fbits) >= 2) { e = e + 1; f = 1; } if (e > bias) { // Overflow e = (1 << ebits) - 1; f = 0; } else { // Normal e = e + bias; f = f - Math.pow(2, fbits); } } else { // Subnormal e = 0; f = roundToEven(v / Math.pow(2, 1 - bias - fbits)); } } // Pack sign, exponent, fraction bits = []; for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = Math.floor(f / 2); } for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = Math.floor(e / 2); } bits.push(s ? 1 : 0); bits.reverse(); str = bits.join(''); // Bits to bytes bytes = []; while (str.length) { bytes.push(parseInt(str.slice(0, 8), 2)); str = str.slice(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.slice(0, 1), 2) ? -1 : 1; e = parseInt(str.slice(1, 1 + ebits), 2); f = parseInt(str.slice(1 + ebits), 2); // Produce number if (e === (1 << ebits) - 1) { return f !== 0 ? NaN : s * Infinity; } else if (e > 0) { // Normalized return s * Math.pow(2, e - bias) * (1 + f / Math.pow(2, fbits)); } else if (f !== 0) { // Denormalized return s * Math.pow(2, -(bias - 1)) * (f / Math.pow(2, fbits)); } else { return s < 0 ? -0 : 0; } } function unpackFloat64(b) { return unpackIEEE754(b, 11, 52); } function packFloat64(v) { return packIEEE754(v, 11, 52); } function unpackFloat32(b) { return unpackIEEE754(b, 8, 23); } function packFloat32(v) { return packIEEE754(v, 8, 23); } var conversions = { toFloat32: function (num) { return unpackFloat32(packFloat32(num)); } }; if (typeof Float32Array !== 'undefined') { var float32array = new Float32Array(1); conversions.toFloat32 = function (num) { float32array[0] = num; return float32array[0]; }; } return conversions; }()); defineProperties(String, { fromCodePoint: function fromCodePoint(codePoints) { var result = []; var next; for (var i = 0, length = arguments.length; i < length; i++) { next = Number(arguments[i]); if (!ES.SameValue(next, ES.ToInteger(next)) || next < 0 || next > 0x10FFFF) { throw new RangeError('Invalid code point ' + next); } if (next < 0x10000) { result.push(String.fromCharCode(next)); } else { next -= 0x10000; result.push(String.fromCharCode((next >> 10) + 0xD800)); result.push(String.fromCharCode((next % 0x400) + 0xDC00)); } } return result.join(''); }, raw: function raw(callSite) { var cooked = ES.ToObject(callSite, 'bad callSite'); var rawValue = cooked.raw; var rawString = ES.ToObject(rawValue, 'bad raw value'); var len = rawString.length; var literalsegments = ES.ToLength(len); if (literalsegments <= 0) { return ''; } var stringElements = []; var nextIndex = 0; var nextKey, next, nextSeg, nextSub; while (nextIndex < literalsegments) { nextKey = String(nextIndex); next = rawString[nextKey]; nextSeg = String(next); stringElements.push(nextSeg); if (nextIndex + 1 >= literalsegments) { break; } next = nextIndex + 1 < arguments.length ? arguments[nextIndex + 1] : ''; nextSub = String(next); stringElements.push(nextSub); nextIndex++; } return stringElements.join(''); } }); // Firefox 31 reports this function's length as 0 // https://bugzilla.mozilla.org/show_bug.cgi?id=1062484 if (String.fromCodePoint.length !== 1) { var originalFromCodePoint = Function.apply.bind(String.fromCodePoint); defineProperty(String, 'fromCodePoint', function fromCodePoint(codePoints) { return originalFromCodePoint(this, arguments); }, true); } // Fast repeat, uses the `Exponentiation by squaring` algorithm. // Perf: http://jsperf.com/string-repeat2/2 var stringRepeat = function repeat(s, times) { if (times < 1) { return ''; } if (times % 2) { return repeat(s, times - 1) + s; } var half = repeat(s, times / 2); return half + half; }; var stringMaxLength = Infinity; var StringShims = { repeat: function repeat(times) { ES.RequireObjectCoercible(this); var thisStr = String(this); times = ES.ToInteger(times); if (times < 0 || times >= stringMaxLength) { throw new RangeError('repeat count must be less than infinity and not overflow maximum string size'); } return stringRepeat(thisStr, times); }, startsWith: function (searchStr) { ES.RequireObjectCoercible(this); var thisStr = String(this); if (Type.regex(searchStr)) { throw new TypeError('Cannot call method "startsWith" with a regex'); } searchStr = String(searchStr); var startArg = arguments.length > 1 ? arguments[1] : void 0; var start = Math.max(ES.ToInteger(startArg), 0); return thisStr.slice(start, start + searchStr.length) === searchStr; }, endsWith: function (searchStr) { ES.RequireObjectCoercible(this); var thisStr = String(this); if (Type.regex(searchStr)) { throw new TypeError('Cannot call method "endsWith" with a regex'); } searchStr = String(searchStr); var thisLen = thisStr.length; var posArg = arguments.length > 1 ? arguments[1] : void 0; var pos = typeof posArg === 'undefined' ? thisLen : ES.ToInteger(posArg); var end = Math.min(Math.max(pos, 0), thisLen); return thisStr.slice(end - searchStr.length, end) === searchStr; }, includes: function includes(searchString) { var position = arguments.length > 1 ? arguments[1] : void 0; // Somehow this trick makes method 100% compat with the spec. return _indexOf(this, searchString, position) !== -1; }, codePointAt: function (pos) { ES.RequireObjectCoercible(this); var thisStr = String(this); var position = ES.ToInteger(pos); var length = thisStr.length; if (position >= 0 && position < length) { var first = thisStr.charCodeAt(position); var isEnd = (position + 1 === length); if (first < 0xD800 || first > 0xDBFF || isEnd) { return first; } var second = thisStr.charCodeAt(position + 1); if (second < 0xDC00 || second > 0xDFFF) { return first; } return ((first - 0xD800) * 1024) + (second - 0xDC00) + 0x10000; } } }; defineProperties(String.prototype, StringShims); var hasStringTrimBug = '\u0085'.trim().length !== 1; if (hasStringTrimBug) { delete String.prototype.trim; // whitespace from: http://es5.github.io/#x15.5.4.20 // implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324 var ws = [ '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003', '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028', '\u2029\uFEFF' ].join(''); var trimRegexp = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g'); defineProperties(String.prototype, { trim: function () { if (typeof this === 'undefined' || this === null) { throw new TypeError("can't convert " + this + ' to object'); } return String(this).replace(trimRegexp, ''); } }); } // see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype-@@iterator var StringIterator = function (s) { ES.RequireObjectCoercible(s); this._s = String(s); this._i = 0; }; StringIterator.prototype.next = function () { var s = this._s, i = this._i; if (typeof s === 'undefined' || i >= s.length) { this._s = void 0; return { value: void 0, done: true }; } var first = s.charCodeAt(i), second, len; if (first < 0xD800 || first > 0xDBFF || (i + 1) === s.length) { len = 1; } else { second = s.charCodeAt(i + 1); len = (second < 0xDC00 || second > 0xDFFF) ? 1 : 2; } this._i = i + len; return { value: s.substr(i, len), done: false }; }; addIterator(StringIterator.prototype); addIterator(String.prototype, function () { return new StringIterator(this); }); if (!startsWithIsCompliant) { // Firefox has a noncompliant startsWith implementation defineProperty(String.prototype, 'startsWith', StringShims.startsWith, true); defineProperty(String.prototype, 'endsWith', StringShims.endsWith, true); } var ArrayShims = { from: function (iterable) { var mapFn = arguments.length > 1 ? arguments[1] : void 0; var list = ES.ToObject(iterable, 'bad iterable'); if (typeof mapFn !== 'undefined' && !ES.IsCallable(mapFn)) { throw new TypeError('Array.from: when provided, the second argument must be a function'); } var hasThisArg = arguments.length > 2; var thisArg = hasThisArg ? arguments[2] : void 0; var usingIterator = ES.IsIterable(list); // does the spec really mean that Arrays should use ArrayIterator? // https://bugs.ecmascript.org/show_bug.cgi?id=2416 //if (Array.isArray(list)) { usingIterator=false; } var length; var result, i, value; if (usingIterator) { i = 0; result = ES.IsCallable(this) ? Object(new this()) : []; var it = usingIterator ? ES.GetIterator(list) : null; var iterationValue; do { iterationValue = ES.IteratorNext(it); if (!iterationValue.done) { value = iterationValue.value; if (mapFn) { result[i] = hasThisArg ? mapFn.call(thisArg, value, i) : mapFn(value, i); } else { result[i] = value; } i += 1; } } while (!iterationValue.done); length = i; } else { length = ES.ToLength(list.length); result = ES.IsCallable(this) ? Object(new this(length)) : new Array(length); for (i = 0; i < length; ++i) { value = list[i]; if (mapFn) { result[i] = hasThisArg ? mapFn.call(thisArg, value, i) : mapFn(value, i); } else { result[i] = value; } } } result.length = length; return result; }, of: function () { return Array.from(arguments); } }; defineProperties(Array, ArrayShims); var arrayFromSwallowsNegativeLengths = function () { try { return Array.from({ length: -1 }).length === 0; } catch (e) { return false; } }; // Fixes a Firefox bug in v32 // https://bugzilla.mozilla.org/show_bug.cgi?id=1063993 if (!arrayFromSwallowsNegativeLengths()) { defineProperty(Array, 'from', ArrayShims.from, true); } // Given an argument x, it will return an IteratorResult object, // with value set to x and done to false. // Given no arguments, it will return an iterator completion object. var iterator_result = function (x) { return { value: x, done: arguments.length === 0 }; }; // Our ArrayIterator is private; see // https://github.com/paulmillr/es6-shim/issues/252 ArrayIterator = function (array, kind) { this.i = 0; this.array = array; this.kind = kind; }; defineProperties(ArrayIterator.prototype, { next: function () { var i = this.i, array = this.array; if (!(this instanceof ArrayIterator)) { throw new TypeError('Not an ArrayIterator'); } if (typeof array !== 'undefined') { var len = ES.ToLength(array.length); for (; i < len; i++) { var kind = this.kind; var retval; if (kind === 'key') { retval = i; } else if (kind === 'value') { retval = array[i]; } else if (kind === 'entry') { retval = [i, array[i]]; } this.i = i + 1; return { value: retval, done: false }; } } this.array = void 0; return { value: void 0, done: true }; } }); addIterator(ArrayIterator.prototype); var ObjectIterator = function (object, kind) { this.object = object; // Don't generate keys yet. this.array = null; this.kind = kind; }; function getAllKeys(object) { var keys = []; for (var key in object) { keys.push(key); } return keys; } defineProperties(ObjectIterator.prototype, { next: function () { var key, array = this.array; if (!(this instanceof ObjectIterator)) { throw new TypeError('Not an ObjectIterator'); } // Keys not generated if (array === null) { array = this.array = getAllKeys(this.object); } // Find next key in the object while (ES.ToLength(array.length) > 0) { key = array.shift(); // The candidate key isn't defined on object. // Must have been deleted, or object[[Prototype]] // has been modified. if (!(key in this.object)) { continue; } if (this.kind === 'key') { return iterator_result(key); } else if (this.kind === 'value') { return iterator_result(this.object[key]); } else { return iterator_result([key, this.object[key]]); } } return iterator_result(); } }); addIterator(ObjectIterator.prototype); var ArrayPrototypeShims = { copyWithin: function (target, start) { var end = arguments[2]; // copyWithin.length must be 2 var o = ES.ToObject(this); var len = ES.ToLength(o.length); target = ES.ToInteger(target); start = ES.ToInteger(start); var to = target < 0 ? Math.max(len + target, 0) : Math.min(target, len); var from = start < 0 ? Math.max(len + start, 0) : Math.min(start, len); end = typeof end === 'undefined' ? len : ES.ToInteger(end); var fin = end < 0 ? Math.max(len + end, 0) : Math.min(end, len); var count = Math.min(fin - from, len - to); var direction = 1; if (from < to && to < (from + count)) { direction = -1; from += count - 1; to += count - 1; } while (count > 0) { if (_hasOwnProperty(o, from)) { o[to] = o[from]; } else { delete o[from]; } from += direction; to += direction; count -= 1; } return o; }, fill: function (value) { var start = arguments.length > 1 ? arguments[1] : void 0; var end = arguments.length > 2 ? arguments[2] : void 0; var O = ES.ToObject(this); var len = ES.ToLength(O.length); start = ES.ToInteger(typeof start === 'undefined' ? 0 : start); end = ES.ToInteger(typeof end === 'undefined' ? len : end); var relativeStart = start < 0 ? Math.max(len + start, 0) : Math.min(start, len); var relativeEnd = end < 0 ? len + end : end; for (var i = relativeStart; i < len && i < relativeEnd; ++i) { O[i] = value; } return O; }, find: function find(predicate) { var list = ES.ToObject(this); var length = ES.ToLength(list.length); if (!ES.IsCallable(predicate)) { throw new TypeError('Array#find: predicate must be a function'); } var thisArg = arguments.length > 1 ? arguments[1] : null; for (var i = 0, value; i < length; i++) { value = list[i]; if (thisArg) { if (predicate.call(thisArg, value, i, list)) { return value; } } else if (predicate(value, i, list)) { return value; } } }, findIndex: function findIndex(predicate) { var list = ES.ToObject(this); var length = ES.ToLength(list.length); if (!ES.IsCallable(predicate)) { throw new TypeError('Array#findIndex: predicate must be a function'); } var thisArg = arguments.length > 1 ? arguments[1] : null; for (var i = 0; i < length; i++) { if (thisArg) { if (predicate.call(thisArg, list[i], i, list)) { return i; } } else if (predicate(list[i], i, list)) { return i; } } return -1; }, keys: function () { return new ArrayIterator(this, 'key'); }, values: function () { return new ArrayIterator(this, 'value'); }, entries: function () { return new ArrayIterator(this, 'entry'); } }; // Safari 7.1 defines Array#keys and Array#entries natively, // but the resulting ArrayIterator objects don't have a "next" method. if (Array.prototype.keys && !ES.IsCallable([1].keys().next)) { delete Array.prototype.keys; } if (Array.prototype.entries && !ES.IsCallable([1].entries().next)) { delete Array.prototype.entries; } // Chrome 38 defines Array#keys and Array#entries, and Array#@@iterator, but not Array#values if (Array.prototype.keys && Array.prototype.entries && !Array.prototype.values && Array.prototype[$iterator$]) { defineProperties(Array.prototype, { values: Array.prototype[$iterator$] }); if (Type.symbol(Symbol.unscopables)) { Array.prototype[Symbol.unscopables].values = true; } } defineProperties(Array.prototype, ArrayPrototypeShims); addIterator(Array.prototype, function () { return this.values(); }); // Chrome defines keys/values/entries on Array, but doesn't give us // any way to identify its iterator. So add our own shimmed field. if (Object.getPrototypeOf) { addIterator(Object.getPrototypeOf([].values())); } var maxSafeInteger = Math.pow(2, 53) - 1; defineProperties(Number, { MAX_SAFE_INTEGER: maxSafeInteger, MIN_SAFE_INTEGER: -maxSafeInteger, EPSILON: 2.220446049250313e-16, parseInt: globals.parseInt, parseFloat: globals.parseFloat, isFinite: function (value) { return typeof value === 'number' && global_isFinite(value); }, isInteger: function (value) { return Number.isFinite(value) && ES.ToInteger(value) === value; }, isSafeInteger: function (value) { return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER; }, isNaN: function (value) { // NaN !== NaN, but they are identical. // NaNs are the only non-reflexive value, i.e., if x !== x, // then x is NaN. // isNaN is broken: it converts its argument to number, so // isNaN('foo') => true return value !== value; } }); // Work around bugs in Array#find and Array#findIndex -- early // implementations skipped holes in sparse arrays. (Note that the // implementations of find/findIndex indirectly use shimmed // methods of Number, so this test has to happen down here.) /*jshint elision: true */ if (![, 1].find(function (item, idx) { return idx === 0; })) { defineProperty(Array.prototype, 'find', ArrayPrototypeShims.find, true); } if ([, 1].findIndex(function (item, idx) { return idx === 0; }) !== 0) { defineProperty(Array.prototype, 'findIndex', ArrayPrototypeShims.findIndex, true); } /*jshint elision: false */ if (supportsDescriptors) { defineProperties(Object, { // 19.1.3.1 assign: function (target, source) { if (!ES.TypeIsObject(target)) { throw new TypeError('target must be an object'); } return Array.prototype.reduce.call(arguments, function (target, source) { return Object.keys(Object(source)).reduce(function (target, key) { target[key] = source[key]; return target; }, target); }); }, is: function (a, b) { return ES.SameValue(a, b); }, // 19.1.3.9 // shim from https://gist.github.com/WebReflection/5593554 setPrototypeOf: (function (Object, magic) { var set; var checkArgs = function (O, proto) { if (!ES.TypeIsObject(O)) { throw new TypeError('cannot set prototype on a non-object'); } if (!(proto === null || ES.TypeIsObject(proto))) { throw new TypeError('can only set prototype to an object or null' + proto); } }; var setPrototypeOf = function (O, proto) { checkArgs(O, proto); set.call(O, proto); return O; }; try { // this works already in Firefox and Safari set = Object.getOwnPropertyDescriptor(Object.prototype, magic).set; set.call({}, null); } catch (e) { if (Object.prototype !== {}[magic]) { // IE < 11 cannot be shimmed return; } // probably Chrome or some old Mobile stock browser set = function (proto) { this[magic] = proto; }; // please note that this will **not** work // in those browsers that do not inherit // __proto__ by mistake from Object.prototype // in these cases we should probably throw an error // or at least be informed about the issue setPrototypeOf.polyfill = setPrototypeOf( setPrototypeOf({}, null), Object.prototype ) instanceof Object; // setPrototypeOf.polyfill === true means it works as meant // setPrototypeOf.polyfill === false means it's not 100% reliable // setPrototypeOf.polyfill === undefined // or // setPrototypeOf.polyfill == null means it's not a polyfill // which means it works as expected // we can even delete Object.prototype.__proto__; } return setPrototypeOf; }(Object, '__proto__')) }); } // Workaround bug in Opera 12 where setPrototypeOf(x, null) doesn't work, // but Object.create(null) does. if (Object.setPrototypeOf && Object.getPrototypeOf && Object.getPrototypeOf(Object.setPrototypeOf({}, null)) !== null && Object.getPrototypeOf(Object.create(null)) === null) { (function () { var FAKENULL = Object.create(null); var gpo = Object.getPrototypeOf, spo = Object.setPrototypeOf; Object.getPrototypeOf = function (o) { var result = gpo(o); return result === FAKENULL ? null : result; }; Object.setPrototypeOf = function (o, p) { if (p === null) { p = FAKENULL; } return spo(o, p); }; Object.setPrototypeOf.polyfill = false; }()); } var objectKeysAcceptsPrimitives = (function () { try { Object.keys('foo'); return true; } catch (e) { return false; } }()); if (!objectKeysAcceptsPrimitives) { var originalObjectKeys = Object.keys; defineProperty(Object, 'keys', function keys(value) { return originalObjectKeys(ES.ToObject(value)); }, true); Value.preserveToString(Object.keys, originalObjectKeys); } if (Object.getOwnPropertyNames) { var objectGOPNAcceptsPrimitives = (function () { try { Object.getOwnPropertyNames('foo'); return true; } catch (e) { return false; } }()); if (!objectGOPNAcceptsPrimitives) { var originalObjectGetOwnPropertyNames = Object.getOwnPropertyNames; defineProperty(Object, 'getOwnPropertyNames', function getOwnPropertyNames(value) { return originalObjectGetOwnPropertyNames(ES.ToObject(value)); }, true); Value.preserveToString(Object.getOwnPropertyNames, originalObjectGetOwnPropertyNames); } } if (Object.getOwnPropertyDescriptor) { var objectGOPDAcceptsPrimitives = (function () { try { Object.getOwnPropertyDescriptor('foo', 'bar'); return true; } catch (e) { return false; } }()); if (!objectGOPDAcceptsPrimitives) { var originalObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; defineProperty(Object, 'getOwnPropertyDescriptor', function getOwnPropertyDescriptor(value, property) { return originalObjectGetOwnPropertyDescriptor(ES.ToObject(value), property); }, true); Value.preserveToString(Object.getOwnPropertyDescriptor, originalObjectGetOwnPropertyDescriptor); } } if (Object.seal) { var objectSealAcceptsPrimitives = (function () { try { Object.seal('foo'); return true; } catch (e) { return false; } }()); if (!objectSealAcceptsPrimitives) { var originalObjectSeal = Object.seal; defineProperty(Object, 'seal', function seal(value) { if (!Type.object(value)) { return value; } return originalObjectSeal(value); }, true); Value.preserveToString(Object.seal, originalObjectSeal); } } if (Object.isSealed) { var objectIsSealedAcceptsPrimitives = (function () { try { Object.isSealed('foo'); return true; } catch (e) { return false; } }()); if (!objectIsSealedAcceptsPrimitives) { var originalObjectIsSealed = Object.isSealed; defineProperty(Object, 'isSealed', function isSealed(value) { if (!Type.object(value)) { return true; } return originalObjectIsSealed(value); }, true); Value.preserveToString(Object.isSealed, originalObjectIsSealed); } } if (Object.freeze) { var objectFreezeAcceptsPrimitives = (function () { try { Object.freeze('foo'); return true; } catch (e) { return false; } }()); if (!objectFreezeAcceptsPrimitives) { var originalObjectFreeze = Object.freeze; defineProperty(Object, 'freeze', function freeze(value) { if (!Type.object(value)) { return value; } return originalObjectFreeze(value); }, true); Value.preserveToString(Object.freeze, originalObjectFreeze); } } if (Object.isFrozen) { var objectIsFrozenAcceptsPrimitives = (function () { try { Object.isFrozen('foo'); return true; } catch (e) { return false; } }()); if (!objectIsFrozenAcceptsPrimitives) { var originalObjectIsFrozen = Object.isFrozen; defineProperty(Object, 'isFrozen', function isFrozen(value) { if (!Type.object(value)) { return true; } return originalObjectIsFrozen(value); }, true); Value.preserveToString(Object.isFrozen, originalObjectIsFrozen); } } if (Object.preventExtensions) { var objectPreventExtensionsAcceptsPrimitives = (function () { try { Object.preventExtensions('foo'); return true; } catch (e) { return false; } }()); if (!objectPreventExtensionsAcceptsPrimitives) { var originalObjectPreventExtensions = Object.preventExtensions; defineProperty(Object, 'preventExtensions', function preventExtensions(value) { if (!Type.object(value)) { return value; } return originalObjectPreventExtensions(value); }, true); Value.preserveToString(Object.preventExtensions, originalObjectPreventExtensions); } } if (Object.isExtensible) { var objectIsExtensibleAcceptsPrimitives = (function () { try { Object.isExtensible('foo'); return true; } catch (e) { return false; } }()); if (!objectIsExtensibleAcceptsPrimitives) { var originalObjectIsExtensible = Object.isExtensible; defineProperty(Object, 'isExtensible', function isExtensible(value) { if (!Type.object(value)) { return false; } return originalObjectIsExtensible(value); }, true); Value.preserveToString(Object.isExtensible, originalObjectIsExtensible); } } if (Object.getPrototypeOf) { var objectGetProtoAcceptsPrimitives = (function () { try { Object.getPrototypeOf('foo'); return true; } catch (e) { return false; } }()); if (!objectGetProtoAcceptsPrimitives) { var originalGetProto = Object.getPrototypeOf; defineProperty(Object, 'getPrototypeOf', function getPrototypeOf(value) { return originalGetProto(ES.ToObject(value)); }, true); Value.preserveToString(Object.getPrototypeOf, originalGetProto); } } if (!RegExp.prototype.flags && supportsDescriptors) { var regExpFlagsGetter = function flags() { if (!ES.TypeIsObject(this)) { throw new TypeError('Method called on incompatible type: must be an object.'); } var result = ''; if (this.global) { result += 'g'; } if (this.ignoreCase) { result += 'i'; } if (this.multiline) { result += 'm'; } if (this.unicode) { result += 'u'; } if (this.sticky) { result += 'y'; } return result; }; Value.getter(RegExp.prototype, 'flags', regExpFlagsGetter); } var regExpSupportsFlagsWithRegex = (function () { try { return String(new RegExp(/a/g, 'i')) === '/a/i'; } catch (e) { return false; } }()); if (!regExpSupportsFlagsWithRegex && supportsDescriptors) { var OrigRegExp = RegExp; var RegExpShim = function RegExp(pattern, flags) { if (Type.regex(pattern) && Type.string(flags)) { return new RegExp(pattern.source, flags); } return new OrigRegExp(pattern, flags); }; Value.preserveToString(RegExpShim, OrigRegExp); if (Object.setPrototypeOf) { // sets up proper prototype chain where possible Object.setPrototypeOf(OrigRegExp, RegExpShim); } Object.getOwnPropertyNames(OrigRegExp).forEach(function (key) { if (key === '$input') { return; } // Chrome < v39 & Opera < 26 have a nonstandard "$input" property if (key in noop) { return; } Value.proxy(OrigRegExp, key, RegExpShim); }); RegExpShim.prototype = OrigRegExp.prototype; Value.redefine(OrigRegExp.prototype, 'constructor', RegExpShim); /*globals RegExp: true */ RegExp = RegExpShim; Value.redefine(globals, 'RegExp', RegExpShim); /*globals RegExp: false */ } var MathShims = { acosh: function (value) { var x = Number(value); if (Number.isNaN(x) || value < 1) { return NaN; } if (x === 1) { return 0; } if (x === Infinity) { return x; } return Math.log(x / Math.E + Math.sqrt(x + 1) * Math.sqrt(x - 1) / Math.E) + 1; }, asinh: function (value) { value = Number(value); if (value === 0 || !global_isFinite(value)) { return value; } return value < 0 ? -Math.asinh(-value) : Math.log(value + Math.sqrt(value * value + 1)); }, atanh: function (value) { value = Number(value); if (Number.isNaN(value) || value < -1 || value > 1) { return NaN; } if (value === -1) { return -Infinity; } if (value === 1) { return Infinity; } if (value === 0) { return value; } return 0.5 * Math.log((1 + value) / (1 - value)); }, cbrt: function (value) { value = Number(value); if (value === 0) { return value; } var negate = value < 0, result; if (negate) { value = -value; } result = Math.pow(value, 1 / 3); return negate ? -result : result; }, clz32: function (value) { // See https://bugs.ecmascript.org/show_bug.cgi?id=2465 value = Number(value); var number = ES.ToUint32(value); if (number === 0) { return 32; } return 32 - (number).toString(2).length; }, cosh: function (value) { value = Number(value); if (value === 0) { return 1; } // +0 or -0 if (Number.isNaN(value)) { return NaN; } if (!global_isFinite(value)) { return Infinity; } if (value < 0) { value = -value; } if (value > 21) { return Math.exp(value) / 2; } return (Math.exp(value) + Math.exp(-value)) / 2; }, expm1: function (value) { var x = Number(value); if (x === -Infinity) { return -1; } if (!global_isFinite(x) || value === 0) { return x; } if (Math.abs(x) > 0.5) { return Math.exp(x) - 1; } // A more precise approximation using Taylor series expansion // from https://github.com/paulmillr/es6-shim/issues/314#issuecomment-70293986 var t = x; var sum = 0; var n = 1; while (sum + t !== sum) { sum += t; n += 1; t *= x / n; } return sum; }, hypot: function (x, y) { var anyNaN = false; var allZero = true; var anyInfinity = false; var numbers = []; Array.prototype.every.call(arguments, function (arg) { var num = Number(arg); if (Number.isNaN(num)) { anyNaN = true; } else if (num === Infinity || num === -Infinity) { anyInfinity = true; } else if (num !== 0) { allZero = false; } if (anyInfinity) { return false; } else if (!anyNaN) { numbers.push(Math.abs(num)); } return true; }); if (anyInfinity) { return Infinity; } if (anyNaN) { return NaN; } if (allZero) { return 0; } numbers.sort(function (a, b) { return b - a; }); var largest = numbers[0]; var divided = numbers.map(function (number) { return number / largest; }); var sum = divided.reduce(function (sum, number) { return sum + (number * number); }, 0); return largest * Math.sqrt(sum); }, log2: function (value) { return Math.log(value) * Math.LOG2E; }, log10: function (value) { return Math.log(value) * Math.LOG10E; }, log1p: function (value) { var x = Number(value); if (x < -1 || Number.isNaN(x)) { return NaN; } if (x === 0 || x === Infinity) { return x; } if (x === -1) { return -Infinity; } return (1 + x) - 1 === 0 ? x : x * (Math.log(1 + x) / ((1 + x) - 1)); }, sign: function (value) { var number = +value; if (number === 0) { return number; } if (Number.isNaN(number)) { return number; } return number < 0 ? -1 : 1; }, sinh: function (value) { var x = Number(value); if (!global_isFinite(value) || value === 0) { return value; } if (Math.abs(x) < 1) { return (Math.expm1(x) - Math.expm1(-x)) / 2; } return (Math.exp(x - 1) - Math.exp(-x - 1)) * Math.E / 2; }, tanh: function (value) { var x = Number(value); if (Number.isNaN(value) || x === 0) { return x; } if (x === Infinity) { return 1; } if (x === -Infinity) { return -1; } var a = Math.expm1(x); var b = Math.expm1(-x); if (a === Infinity) { return 1; } if (b === Infinity) { return -1; } return (a - b) / (Math.exp(x) + Math.exp(-x)); }, trunc: function (value) { var number = Number(value); return number < 0 ? -Math.floor(-number) : Math.floor(number); }, imul: function (x, y) { // taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul x = ES.ToUint32(x); y = ES.ToUint32(y); var ah = (x >>> 16) & 0xffff; var al = x & 0xffff; var bh = (y >>> 16) & 0xffff; var bl = y & 0xffff; // the shift by 0 fixes the sign on the high part // the final |0 converts the unsigned value into a signed value return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0); }, fround: function (x) { if (x === 0 || x === Infinity || x === -Infinity || Number.isNaN(x)) { return x; } var num = Number(x); return numberConversion.toFloat32(num); } }; defineProperties(Math, MathShims); // Chrome 40 has an imprecise Math.tanh with very small numbers defineProperty(Math, 'tanh', MathShims.tanh, Math.tanh(-2e-17) !== -2e-17); // Chrome 40 loses Math.acosh precision with high numbers defineProperty(Math, 'acosh', MathShims.acosh, Math.acosh(Number.MAX_VALUE) === Infinity); // node 0.11 has an imprecise Math.sinh with very small numbers defineProperty(Math, 'sinh', MathShims.sinh, Math.sinh(-2e-17) !== -2e-17); // FF 35 on Linux reports 22025.465794806725 for Math.expm1(10) var expm1OfTen = Math.expm1(10); defineProperty(Math, 'expm1', MathShims.expm1, expm1OfTen > 22025.465794806719 || expm1OfTen < 22025.4657948067165168); var roundHandlesBoundaryConditions = Math.round(0.5 - Number.EPSILON / 4) === 0 && Math.round(-0.5 + Number.EPSILON / 3.99) === 1; var origMathRound = Math.round; defineProperty(Math, 'round', function round(x) { if (-0.5 <= x && x < 0.5 && x !== 0) { return Math.sign(x * 0); } return origMathRound(x); }, !roundHandlesBoundaryConditions); if (Math.imul(0xffffffff, 5) !== -5) { // Safari 6.1, at least, reports "0" for this value Math.imul = MathShims.imul; } // Promises // Simplest possible implementation; use a 3rd-party library if you // want the best possible speed and/or long stack traces. var PromiseShim = (function () { var Promise, Promise$prototype; ES.IsPromise = function (promise) { if (!ES.TypeIsObject(promise)) { return false; } if (!promise._promiseConstructor) { // _promiseConstructor is a bit more unique than _status, so we'll // check that instead of the [[PromiseStatus]] internal field. return false; } if (typeof promise._status === 'undefined') { return false; // uninitialized } return true; }; // "PromiseCapability" in the spec is what most promise implementations // call a "deferred". var PromiseCapability = function (C) { if (!ES.IsCallable(C)) { throw new TypeError('bad promise constructor'); } var capability = this; var resolver = function (resolve, reject) { capability.resolve = resolve; capability.reject = reject; }; capability.promise = ES.Construct(C, [resolver]); // see https://bugs.ecmascript.org/show_bug.cgi?id=2478 if (!capability.promise._es6construct) { throw new TypeError('bad promise constructor'); } if (!(ES.IsCallable(capability.resolve) && ES.IsCallable(capability.reject))) { throw new TypeError('bad promise constructor'); } }; // find an appropriate setImmediate-alike var setTimeout = globals.setTimeout; var makeZeroTimeout; /*global window */ if (typeof window !== 'undefined' && ES.IsCallable(window.postMessage)) { makeZeroTimeout = function () { // from http://dbaron.org/log/20100309-faster-timeouts var timeouts = []; var messageName = 'zero-timeout-message'; var setZeroTimeout = function (fn) { timeouts.push(fn); window.postMessage(messageName, '*'); }; var handleMessage = function (event) { if (event.source === window && event.data === messageName) { event.stopPropagation(); if (timeouts.length === 0) { return; } var fn = timeouts.shift(); fn(); } }; window.addEventListener('message', handleMessage, true); return setZeroTimeout; }; } var makePromiseAsap = function () { // An efficient task-scheduler based on a pre-existing Promise // implementation, which we can use even if we override the // global Promise below (in order to workaround bugs) // https://github.com/Raynos/observ-hash/issues/2#issuecomment-35857671 var P = globals.Promise; return P && P.resolve && function (task) { return P.resolve().then(task); }; }; /*global process */ var enqueue = ES.IsCallable(globals.setImmediate) ? globals.setImmediate.bind(globals) : typeof process === 'object' && process.nextTick ? process.nextTick : makePromiseAsap() || (ES.IsCallable(makeZeroTimeout) ? makeZeroTimeout() : function (task) { setTimeout(task, 0); }); // fallback var updatePromiseFromPotentialThenable = function (x, capability) { if (!ES.TypeIsObject(x)) { return false; } var resolve = capability.resolve; var reject = capability.reject; try { var then = x.then; // only one invocation of accessor if (!ES.IsCallable(then)) { return false; } then.call(x, resolve, reject); } catch (e) { reject(e); } return true; }; var triggerPromiseReactions = function (reactions, x) { reactions.forEach(function (reaction) { enqueue(function () { // PromiseReactionTask var handler = reaction.handler; var capability = reaction.capability; var resolve = capability.resolve; var reject = capability.reject; try { var result = handler(x); if (result === capability.promise) { throw new TypeError('self resolution'); } var updateResult = updatePromiseFromPotentialThenable(result, capability); if (!updateResult) { resolve(result); } } catch (e) { reject(e); } }); }); }; var promiseResolutionHandler = function (promise, onFulfilled, onRejected) { return function (x) { if (x === promise) { return onRejected(new TypeError('self resolution')); } var C = promise._promiseConstructor; var capability = new PromiseCapability(C); var updateResult = updatePromiseFromPotentialThenable(x, capability); if (updateResult) { return capability.promise.then(onFulfilled, onRejected); } else { return onFulfilled(x); } }; }; Promise = function (resolver) { var promise = this; promise = emulateES6construct(promise); if (!promise._promiseConstructor) { // we use _promiseConstructor as a stand-in for the internal // [[PromiseStatus]] field; it's a little more unique. throw new TypeError('bad promise'); } if (typeof promise._status !== 'undefined') { throw new TypeError('promise already initialized'); } // see https://bugs.ecmascript.org/show_bug.cgi?id=2482 if (!ES.IsCallable(resolver)) { throw new TypeError('not a valid resolver'); } promise._status = 'unresolved'; promise._resolveReactions = []; promise._rejectReactions = []; var resolve = function (resolution) { if (promise._status !== 'unresolved') { return; } var reactions = promise._resolveReactions; promise._result = resolution; promise._resolveReactions = void 0; promise._rejectReactions = void 0; promise._status = 'has-resolution'; triggerPromiseReactions(reactions, resolution); }; var reject = function (reason) { if (promise._status !== 'unresolved') { return; } var reactions = promise._rejectReactions; promise._result = reason; promise._resolveReactions = void 0; promise._rejectReactions = void 0; promise._status = 'has-rejection'; triggerPromiseReactions(reactions, reason); }; try { resolver(resolve, reject); } catch (e) { reject(e); } return promise; }; Promise$prototype = Promise.prototype; var _promiseAllResolver = function (index, values, capability, remaining) { var done = false; return function (x) { if (done) { return; } // protect against being called multiple times done = true; values[index] = x; if ((--remaining.count) === 0) { var resolve = capability.resolve; resolve(values); // call w/ this===undefined } }; }; defineProperty(Promise, symbolSpecies, function (obj) { var constructor = this; // AllocatePromise // The `obj` parameter is a hack we use for es5 // compatibility. var prototype = constructor.prototype || Promise$prototype; obj = obj || create(prototype); defineProperties(obj, { _status: void 0, _result: void 0, _resolveReactions: void 0, _rejectReactions: void 0, _promiseConstructor: void 0 }); obj._promiseConstructor = constructor; return obj; }); defineProperties(Promise, { all: function all(iterable) { var C = this; var capability = new PromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; try { if (!ES.IsIterable(iterable)) { throw new TypeError('bad iterable'); } var it = ES.GetIterator(iterable); var values = [], remaining = { count: 1 }; for (var index = 0; ; index++) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextPromise = C.resolve(next.value); var resolveElement = _promiseAllResolver( index, values, capability, remaining ); remaining.count++; nextPromise.then(resolveElement, capability.reject); } if ((--remaining.count) === 0) { resolve(values); // call w/ this===undefined } } catch (e) { reject(e); } return capability.promise; }, race: function race(iterable) { var C = this; var capability = new PromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; try { if (!ES.IsIterable(iterable)) { throw new TypeError('bad iterable'); } var it = ES.GetIterator(iterable); while (true) { var next = ES.IteratorNext(it); if (next.done) { // If iterable has no items, resulting promise will never // resolve; see: // https://github.com/domenic/promises-unwrapping/issues/75 // https://bugs.ecmascript.org/show_bug.cgi?id=2515 break; } var nextPromise = C.resolve(next.value); nextPromise.then(resolve, reject); } } catch (e) { reject(e); } return capability.promise; }, reject: function reject(reason) { var C = this; var capability = new PromiseCapability(C); var rejectPromise = capability.reject; rejectPromise(reason); // call with this===undefined return capability.promise; }, resolve: function resolve(v) { var C = this; if (ES.IsPromise(v)) { var constructor = v._promiseConstructor; if (constructor === C) { return v; } } var capability = new PromiseCapability(C); var resolvePromise = capability.resolve; resolvePromise(v); // call with this===undefined return capability.promise; } }); defineProperties(Promise$prototype, { 'catch': function (onRejected) { return this.then(void 0, onRejected); }, then: function then(onFulfilled, onRejected) { var promise = this; if (!ES.IsPromise(promise)) { throw new TypeError('not a promise'); } // this.constructor not this._promiseConstructor; see // https://bugs.ecmascript.org/show_bug.cgi?id=2513 var C = this.constructor; var capability = new PromiseCapability(C); if (!ES.IsCallable(onRejected)) { onRejected = function (e) { throw e; }; } if (!ES.IsCallable(onFulfilled)) { onFulfilled = function (x) { return x; }; } var resolutionHandler = promiseResolutionHandler(promise, onFulfilled, onRejected); var resolveReaction = { capability: capability, handler: resolutionHandler }; var rejectReaction = { capability: capability, handler: onRejected }; switch (promise._status) { case 'unresolved': promise._resolveReactions.push(resolveReaction); promise._rejectReactions.push(rejectReaction); break; case 'has-resolution': triggerPromiseReactions([resolveReaction], promise._result); break; case 'has-rejection': triggerPromiseReactions([rejectReaction], promise._result); break; default: throw new TypeError('unexpected'); } return capability.promise; } }); return Promise; }()); // Chrome's native Promise has extra methods that it shouldn't have. Let's remove them. if (globals.Promise) { delete globals.Promise.accept; delete globals.Promise.defer; delete globals.Promise.prototype.chain; } // export the Promise constructor. defineProperties(globals, { Promise: PromiseShim }); // In Chrome 33 (and thereabouts) Promise is defined, but the // implementation is buggy in a number of ways. Let's check subclassing // support to see if we have a buggy implementation. var promiseSupportsSubclassing = supportsSubclassing(globals.Promise, function (S) { return S.resolve(42) instanceof S; }); var promiseIgnoresNonFunctionThenCallbacks = (function () { try { globals.Promise.reject(42).then(null, 5).then(null, noop); return true; } catch (ex) { return false; } }()); var promiseRequiresObjectContext = (function () { /*global Promise */ try { Promise.call(3, noop); } catch (e) { return true; } return false; }()); if (!promiseSupportsSubclassing || !promiseIgnoresNonFunctionThenCallbacks || !promiseRequiresObjectContext) { /*globals Promise: true */ Promise = PromiseShim; /*globals Promise: false */ defineProperty(globals, 'Promise', PromiseShim, true); } // Map and Set require a true ES5 environment // Their fast path also requires that the environment preserve // property insertion order, which is not guaranteed by the spec. var testOrder = function (a) { var b = Object.keys(a.reduce(function (o, k) { o[k] = true; return o; }, {})); return a.join(':') === b.join(':'); }; var preservesInsertionOrder = testOrder(['z', 'a', 'bb']); // some engines (eg, Chrome) only preserve insertion order for string keys var preservesNumericInsertionOrder = testOrder(['z', 1, 'a', '3', 2]); if (supportsDescriptors) { var fastkey = function fastkey(key) { if (!preservesInsertionOrder) { return null; } var type = typeof key; if (type === 'string') { return '$' + key; } else if (type === 'number') { // note that -0 will get coerced to "0" when used as a property key if (!preservesNumericInsertionOrder) { return 'n' + key; } return key; } return null; }; var emptyObject = function emptyObject() { // accomodate some older not-quite-ES5 browsers return Object.create ? Object.create(null) : {}; }; var collectionShims = { Map: (function () { var empty = {}; function MapEntry(key, value) { this.key = key; this.value = value; this.next = null; this.prev = null; } MapEntry.prototype.isRemoved = function () { return this.key === empty; }; function MapIterator(map, kind) { this.head = map._head; this.i = this.head; this.kind = kind; } MapIterator.prototype = { next: function () { var i = this.i, kind = this.kind, head = this.head, result; if (typeof this.i === 'undefined') { return { value: void 0, done: true }; } while (i.isRemoved() && i !== head) { // back up off of removed entries i = i.prev; } // advance to next unreturned element. while (i.next !== head) { i = i.next; if (!i.isRemoved()) { if (kind === 'key') { result = i.key; } else if (kind === 'value') { result = i.value; } else { result = [i.key, i.value]; } this.i = i; return { value: result, done: false }; } } // once the iterator is done, it is done forever. this.i = void 0; return { value: void 0, done: true }; } }; addIterator(MapIterator.prototype); function Map(iterable) { var map = this; if (!ES.TypeIsObject(map)) { throw new TypeError('Map does not accept arguments when called as a function'); } map = emulateES6construct(map); if (!map._es6map) { throw new TypeError('bad map'); } var head = new MapEntry(null, null); // circular doubly-linked list. head.next = head.prev = head; defineProperties(map, { _head: head, _storage: emptyObject(), _size: 0 }); // Optionally initialize map from iterable if (typeof iterable !== 'undefined' && iterable !== null) { var it = ES.GetIterator(iterable); var adder = map.set; if (!ES.IsCallable(adder)) { throw new TypeError('bad map'); } while (true) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextItem = next.value; if (!ES.TypeIsObject(nextItem)) { throw new TypeError('expected iterable of pairs'); } adder.call(map, nextItem[0], nextItem[1]); } } return map; } var Map$prototype = Map.prototype; defineProperty(Map, symbolSpecies, function (obj) { var constructor = this; var prototype = constructor.prototype || Map$prototype; obj = obj || create(prototype); defineProperties(obj, { _es6map: true }); return obj; }); Value.getter(Map.prototype, 'size', function () { if (typeof this._size === 'undefined') { throw new TypeError('size method called on incompatible Map'); } return this._size; }); defineProperties(Map.prototype, { get: function (key) { var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path var entry = this._storage[fkey]; if (entry) { return entry.value; } else { return; } } var head = this._head, i = head; while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { return i.value; } } }, has: function (key) { var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path return typeof this._storage[fkey] !== 'undefined'; } var head = this._head, i = head; while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { return true; } } return false; }, set: function (key, value) { var head = this._head, i = head, entry; var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path if (typeof this._storage[fkey] !== 'undefined') { this._storage[fkey].value = value; return this; } else { entry = this._storage[fkey] = new MapEntry(key, value); i = head.prev; // fall through } } while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { i.value = value; return this; } } entry = entry || new MapEntry(key, value); if (ES.SameValue(-0, key)) { entry.key = +0; // coerce -0 to +0 in entry } entry.next = this._head; entry.prev = this._head.prev; entry.prev.next = entry; entry.next.prev = entry; this._size += 1; return this; }, 'delete': function (key) { var head = this._head, i = head; var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path if (typeof this._storage[fkey] === 'undefined') { return false; } i = this._storage[fkey].prev; delete this._storage[fkey]; // fall through } while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { i.key = i.value = empty; i.prev.next = i.next; i.next.prev = i.prev; this._size -= 1; return true; } } return false; }, clear: function () { this._size = 0; this._storage = emptyObject(); var head = this._head, i = head, p = i.next; while ((i = p) !== head) { i.key = i.value = empty; p = i.next; i.next = i.prev = head; } head.next = head.prev = head; }, keys: function () { return new MapIterator(this, 'key'); }, values: function () { return new MapIterator(this, 'value'); }, entries: function () { return new MapIterator(this, 'key+value'); }, forEach: function (callback) { var context = arguments.length > 1 ? arguments[1] : null; var it = this.entries(); for (var entry = it.next(); !entry.done; entry = it.next()) { if (context) { callback.call(context, entry.value[1], entry.value[0], this); } else { callback(entry.value[1], entry.value[0], this); } } } }); addIterator(Map.prototype, function () { return this.entries(); }); return Map; }()), Set: (function () { // Creating a Map is expensive. To speed up the common case of // Sets containing only string or numeric keys, we use an object // as backing storage and lazily create a full Map only when // required. var SetShim = function Set(iterable) { var set = this; if (!ES.TypeIsObject(set)) { throw new TypeError('Set does not accept arguments when called as a function'); } set = emulateES6construct(set); if (!set._es6set) { throw new TypeError('bad set'); } defineProperties(set, { '[[SetData]]': null, _storage: emptyObject() }); // Optionally initialize map from iterable if (typeof iterable !== 'undefined' && iterable !== null) { var it = ES.GetIterator(iterable); var adder = set.add; if (!ES.IsCallable(adder)) { throw new TypeError('bad set'); } while (true) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextItem = next.value; adder.call(set, nextItem); } } return set; }; var Set$prototype = SetShim.prototype; defineProperty(SetShim, symbolSpecies, function (obj) { var constructor = this; var prototype = constructor.prototype || Set$prototype; obj = obj || create(prototype); defineProperties(obj, { _es6set: true }); return obj; }); // Switch from the object backing storage to a full Map. var ensureMap = function ensureMap(set) { if (!set['[[SetData]]']) { var m = set['[[SetData]]'] = new collectionShims.Map(); Object.keys(set._storage).forEach(function (k) { // fast check for leading '$' if (k.charCodeAt(0) === 36) { k = k.slice(1); } else if (k.charAt(0) === 'n') { k = +k.slice(1); } else { k = +k; } m.set(k, k); }); set._storage = null; // free old backing storage } }; Value.getter(SetShim.prototype, 'size', function () { if (typeof this._storage === 'undefined') { // https://github.com/paulmillr/es6-shim/issues/176 throw new TypeError('size method called on incompatible Set'); } ensureMap(this); return this['[[SetData]]'].size; }); defineProperties(SetShim.prototype, { has: function (key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { return !!this._storage[fkey]; } ensureMap(this); return this['[[SetData]]'].has(key); }, add: function (key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { this._storage[fkey] = true; return this; } ensureMap(this); this['[[SetData]]'].set(key, key); return this; }, 'delete': function (key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { var hasFKey = _hasOwnProperty(this._storage, fkey); return (delete this._storage[fkey]) && hasFKey; } ensureMap(this); return this['[[SetData]]']['delete'](key); }, clear: function () { if (this._storage) { this._storage = emptyObject(); } else { this['[[SetData]]'].clear(); } }, values: function () { ensureMap(this); return this['[[SetData]]'].values(); }, entries: function () { ensureMap(this); return this['[[SetData]]'].entries(); }, forEach: function (callback) { var context = arguments.length > 1 ? arguments[1] : null; var entireSet = this; ensureMap(entireSet); this['[[SetData]]'].forEach(function (value, key) { if (context) { callback.call(context, key, key, entireSet); } else { callback(key, key, entireSet); } }); } }); defineProperty(SetShim, 'keys', SetShim.values, true); addIterator(SetShim.prototype, function () { return this.values(); }); return SetShim; }()) }; defineProperties(globals, collectionShims); if (globals.Map || globals.Set) { /* - In Firefox < 23, Map#size is a function. - In all current Firefox, Set#entries/keys/values & Map#clear do not exist - https://bugzilla.mozilla.org/show_bug.cgi?id=869996 - In Firefox 24, Map and Set do not implement forEach - In Firefox 25 at least, Map and Set are callable without "new" */ if ( typeof globals.Map.prototype.clear !== 'function' || new globals.Set().size !== 0 || new globals.Map().size !== 0 || typeof globals.Map.prototype.keys !== 'function' || typeof globals.Set.prototype.keys !== 'function' || typeof globals.Map.prototype.forEach !== 'function' || typeof globals.Set.prototype.forEach !== 'function' || isCallableWithoutNew(globals.Map) || isCallableWithoutNew(globals.Set) || !supportsSubclassing(globals.Map, function (M) { var m = new M([]); // Firefox 32 is ok with the instantiating the subclass but will // throw when the map is used. m.set(42, 42); return m instanceof M; }) ) { globals.Map = collectionShims.Map; globals.Set = collectionShims.Set; } } if (globals.Set.prototype.keys !== globals.Set.prototype.values) { defineProperty(globals.Set.prototype, 'keys', globals.Set.prototype.values, true); } // Shim incomplete iterator implementations. addIterator(Object.getPrototypeOf((new globals.Map()).keys())); addIterator(Object.getPrototypeOf((new globals.Set()).keys())); } // Reflect if (!globals.Reflect) { defineProperty(globals, 'Reflect', {}); } var Reflect = globals.Reflect; var throwUnlessTargetIsObject = function throwUnlessTargetIsObject(target) { if (!ES.TypeIsObject(target)) { throw new TypeError('target must be an object'); } }; // Some Reflect methods are basically the same as // those on the Object global, except that a TypeError is thrown if // target isn't an object. As well as returning a boolean indicating // the success of the operation. defineProperties(globals.Reflect, { // Apply method in a functional form. apply: function apply() { return ES.Call.apply(null, arguments); }, // New operator in a functional form. construct: function construct(constructor, args) { if (!ES.IsCallable(constructor)) { throw new TypeError('First argument must be callable.'); } return ES.Construct(constructor, args); }, // When deleting a non-existent or configurable property, // true is returned. // When attempting to delete a non-configurable property, // it will return false. deleteProperty: function deleteProperty(target, key) { throwUnlessTargetIsObject(target); if (supportsDescriptors) { var desc = Object.getOwnPropertyDescriptor(target, key); if (desc && !desc.configurable) { return false; } } // Will return true. return delete target[key]; }, enumerate: function enumerate(target) { throwUnlessTargetIsObject(target); return new ObjectIterator(target, 'key'); }, has: function has(target, key) { throwUnlessTargetIsObject(target); return key in target; } }); if (Object.getOwnPropertyNames) { defineProperties(globals.Reflect, { // Basically the result of calling the internal [[OwnPropertyKeys]]. // Concatenating propertyNames and propertySymbols should do the trick. // This should continue to work together with a Symbol shim // which overrides Object.getOwnPropertyNames and implements // Object.getOwnPropertySymbols. ownKeys: function ownKeys(target) { throwUnlessTargetIsObject(target); var keys = Object.getOwnPropertyNames(target); if (ES.IsCallable(Object.getOwnPropertySymbols)) { keys.push.apply(keys, Object.getOwnPropertySymbols(target)); } return keys; } }); } if (Object.preventExtensions) { defineProperties(globals.Reflect, { isExtensible: function isExtensible(target) { throwUnlessTargetIsObject(target); return Object.isExtensible(target); }, preventExtensions: function preventExtensions(target) { throwUnlessTargetIsObject(target); return callAndCatchException(function () { Object.preventExtensions(target); }); } }); } if (supportsDescriptors) { var internal_get = function get(target, key, receiver) { var desc = Object.getOwnPropertyDescriptor(target, key); if (!desc) { var parent = Object.getPrototypeOf(target); if (parent === null) { return undefined; } return internal_get(parent, key, receiver); } if ('value' in desc) { return desc.value; } if (desc.get) { return desc.get.call(receiver); } return undefined; }; var internal_set = function set(target, key, value, receiver) { var desc = Object.getOwnPropertyDescriptor(target, key); if (!desc) { var parent = Object.getPrototypeOf(target); if (parent !== null) { return internal_set(parent, key, value, receiver); } desc = { value: void 0, writable: true, enumerable: true, configurable: true }; } if ('value' in desc) { if (!desc.writable) { return false; } if (!ES.TypeIsObject(receiver)) { return false; } var existingDesc = Object.getOwnPropertyDescriptor(receiver, key); if (existingDesc) { return Reflect.defineProperty(receiver, key, { value: value }); } else { return Reflect.defineProperty(receiver, key, { value: value, writable: true, enumerable: true, configurable: true }); } } if (desc.set) { desc.set.call(receiver, value); return true; } return false; }; var callAndCatchException = function ConvertExceptionToBoolean(func) { try { func(); } catch (_) { return false; } return true; }; defineProperties(globals.Reflect, { defineProperty: function defineProperty(target, propertyKey, attributes) { throwUnlessTargetIsObject(target); return callAndCatchException(function () { Object.defineProperty(target, propertyKey, attributes); }); }, getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey) { throwUnlessTargetIsObject(target); return Object.getOwnPropertyDescriptor(target, propertyKey); }, // Syntax in a functional form. get: function get(target, key) { throwUnlessTargetIsObject(target); var receiver = arguments.length > 2 ? arguments[2] : target; return internal_get(target, key, receiver); }, set: function set(target, key, value) { throwUnlessTargetIsObject(target); var receiver = arguments.length > 3 ? arguments[3] : target; return internal_set(target, key, value, receiver); } }); } if (Object.getPrototypeOf) { var objectDotGetPrototypeOf = Object.getPrototypeOf; defineProperties(globals.Reflect, { getPrototypeOf: function getPrototypeOf(target) { throwUnlessTargetIsObject(target); return objectDotGetPrototypeOf(target); } }); } if (Object.setPrototypeOf) { var willCreateCircularPrototype = function (object, proto) { while (proto) { if (object === proto) { return true; } proto = Reflect.getPrototypeOf(proto); } return false; }; defineProperties(globals.Reflect, { // Sets the prototype of the given object. // Returns true on success, otherwise false. setPrototypeOf: function setPrototypeOf(object, proto) { throwUnlessTargetIsObject(object); if (proto !== null && !ES.TypeIsObject(proto)) { throw new TypeError('proto must be an object or null'); } // If they already are the same, we're done. if (proto === Reflect.getPrototypeOf(object)) { return true; } // Cannot alter prototype if object not extensible. if (Reflect.isExtensible && !Reflect.isExtensible(object)) { return false; } // Ensure that we do not create a circular prototype chain. if (willCreateCircularPrototype(object, proto)) { return false; } Object.setPrototypeOf(object, proto); return true; } }); } if (String(new Date(NaN)) !== 'Invalid Date') { var dateToString = Date.prototype.toString; var shimmedDateToString = function toString() { var valueOf = +this; if (valueOf !== valueOf) { return 'Invalid Date'; } return dateToString.call(this); }; defineProperty(shimmedDateToString, 'toString', dateToString.toString, true); defineProperty(Date.prototype, 'toString', shimmedDateToString, true); } // Annex B HTML methods // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-additional-properties-of-the-string.prototype-object var stringHTMLshims = { anchor: function anchor(name) { return ES.CreateHTML(this, 'a', 'name', name); }, big: function big() { return ES.CreateHTML(this, 'big', '', ''); }, blink: function blink() { return ES.CreateHTML(this, 'blink', '', ''); }, bold: function bold() { return ES.CreateHTML(this, 'b', '', ''); }, fixed: function fixed() { return ES.CreateHTML(this, 'tt', '', ''); }, fontcolor: function fontcolor(color) { return ES.CreateHTML(this, 'font', 'color', color); }, fontsize: function fontsize(size) { return ES.CreateHTML(this, 'font', 'size', size); }, italics: function italics() { return ES.CreateHTML(this, 'i', '', ''); }, link: function link(url) { return ES.CreateHTML(this, 'a', 'href', url); }, small: function small() { return ES.CreateHTML(this, 'small', '', ''); }, strike: function strike() { return ES.CreateHTML(this, 'strike', '', ''); }, sub: function sub() { return ES.CreateHTML(this, 'sub', '', ''); }, sup: function sub() { return ES.CreateHTML(this, 'sup', '', ''); } }; defineProperties(String.prototype, stringHTMLshims); Object.keys(stringHTMLshims).forEach(function (key) { var method = String.prototype[key]; var shouldOverwrite = false; if (ES.IsCallable(method)) { var output = method.call('', ' " '); var quotesCount = [].concat(output.match(/"/g)).length; shouldOverwrite = output !== output.toLowerCase() || quotesCount > 2; } else { shouldOverwrite = true; } if (shouldOverwrite) { defineProperty(String.prototype, key, stringHTMLshims[key], true); } }); return globals; }));
web/src/server/components/chart-layout.js
opendaylight/spectrometer
/** # @License EPL-1.0 <http://spdx.org/licenses/EPL-1.0> ############################################################################## # Copyright (c) 2016 The Linux Foundation and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at # http://www.eclipse.org/legal/epl-v10.html ############################################################################## */ /** * React component to display Charts in a layout * Uses Paper material-ui component * * @author: Vasu Srinivasan * @since: 0.0.1 */ import _ from 'lodash' import React, { Component } from 'react'; import Paper from 'material-ui/Paper'; export default class ChartLayout extends Component { handleButtonActions(type, option) { this.props.handleButtonActions(type, option) } render() { const { id, className, style, zDepth, ...props } = this.props; return ( <Paper id={id} zDepth={zDepth} className={`animated flipX chart ${className}`} style={style}> <div className={`chart--header ${props.headerClassName}`} > <span className={`chart--title ${props.titleClassName}`}>{props.title}</span> {_.map(props.buttonActions, (button) => { let buttonClassName = 'card-button material-icons' buttonClassName += props.currentView[button.type] === button.option ? ' selected' : '' buttonClassName += button.group ? ' group' : '' return ( <span key={`${props.id}-${button.type}-${button.option}`} className={buttonClassName} title={button.tooltip} onClick={this.handleButtonActions.bind(this, button.type, button.option)}>{button.icon} </span>) })} </div> {this.props.children} </Paper> ) } } ChartLayout.defaultProps = { title: 'Chart', currentView: {}, buttonActions: [], zDepth: 2, className: '', headerClassName: '', titleClassName: '', style: {} } ChartLayout.propTyes = { id: React.PropTypes.string.isRequired, zDepth: React.PropTypes.number, title: React.PropTypes.string.isRequired, className: React.PropTypes.string, headerClassName: React.PropTypes.string, titleClassName: React.PropTypes.string, style: React.PropTypes.object, buttonActions: React.PropTypes.array, handleButtonActions: React.PropTypes.func, currentView: React.PropTypes.object }
app/components/specificComponents/CommentaryForm/select.js
romainquellec/cuistot
import React from 'react'; import Formsy from 'formsy-react'; import SelectStyled from './selectStyled'; const Select = React.createClass({ mixins: [Formsy.Mixin], changeValue(event) { this.setValue(event.currentTarget.value); }, render() { const className = `form-group${this.props.className || ' '}${this.showRequired() ? 'required' : this.showError() ? 'error' : ''}`; const errorMessage = this.getErrorMessage(); const options = this.props.options.map((option, i) => <option key={option.title + option.value} value={option.value}> {option.title} </option> ); return ( <div className={className}> <label htmlFor={this.props.name}> {this.props.title} </label> <SelectStyled name={this.props.name} onChange={this.changeValue} value={this.getValue()} > {options} </SelectStyled> <span className="validation-error"> {errorMessage} </span> </div> ); }, }); export default Select;
server/dashboard/js/components/BenchReports.react.js
timofey-barmin/mzbench
import React from 'react'; import ReactDOM from 'react-dom'; import Modal from './Modal.react'; import PropTypes from 'prop-types'; class BenchReports extends React.Component { constructor(props) { super(props); } renderDownloadReportPanel() { return ( <div className="panel panel-default panel-report"> <div className="panel-heading"> <h3 className="panel-title">Download report</h3> </div> <div className="panel-body btn-toolbar"> <a href={`/data?id=${this.props.bench.id}`} target="_blank" className="btn btn-primary" type="submit">Metrics</a> <a href={`/log?id=${this.props.bench.id}`} target="_blank" className="btn btn-primary" type="submit">System logs</a> <a href={`/userlog?id=${this.props.bench.id}`} target="_blank" className="btn btn-primary" type="submit">User logs</a> </div> </div> ); } render() { return ( <div> {this.renderDownloadReportPanel()} </div> ); } }; BenchReports.propTypes = { bench: PropTypes.object.isRequired }; export default BenchReports;
src/client/pages/tocheckitem.react.js
terakilobyte/socketreact
import Component from '../components/component.react'; import React from 'react'; import {FormattedHTMLMessage} from 'react-intl'; class ToCheckItem extends Component { render() { return ( <li> <FormattedHTMLMessage message={this.props.item.get('txt')} /> </li> ); } } ToCheckItem.propTypes = { item: React.PropTypes.object.isRequired }; export default ToCheckItem;
packages/material-ui-icons/src/LabelRounded.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M17.63 5.84C17.27 5.33 16.67 5 16 5L5 5.01C3.9 5.01 3 5.9 3 7v10c0 1.1.9 1.99 2 1.99L16 19c.67 0 1.27-.33 1.63-.84l3.96-5.58c.25-.35.25-.81 0-1.16l-3.96-5.58z" /></React.Fragment> , 'LabelRounded');
src/utils/domUtils.js
nickuraltsev/react-bootstrap
import React from 'react'; import canUseDom from 'dom-helpers/util/inDOM'; import getOwnerDocument from 'dom-helpers/ownerDocument'; import getOwnerWindow from 'dom-helpers/ownerWindow'; import contains from 'dom-helpers/query/contains'; import activeElement from 'dom-helpers/activeElement'; import getOffset from 'dom-helpers/query/offset'; import offsetParent from 'dom-helpers/query/offsetParent'; import getPosition from 'dom-helpers/query/position'; import css from 'dom-helpers/style'; function ownerDocument(componentOrElement) { let elem = React.findDOMNode(componentOrElement); return getOwnerDocument((elem && elem.ownerDocument) || document); } function ownerWindow(componentOrElement) { let doc = ownerDocument(componentOrElement); return getOwnerWindow(doc); } // TODO remove in 0.26 function getComputedStyles(elem) { return ownerDocument(elem).defaultView.getComputedStyle(elem, null); } /** * Get the height of the document * * @returns {documentHeight: number} */ function getDocumentHeight() { return Math.max(document.documentElement.offsetHeight, document.height, document.body.scrollHeight, document.body.offsetHeight); } /** * Get an element's size * * @param {HTMLElement} elem * @returns {{width: number, height: number}} */ function getSize(elem) { let rect = { width: elem.offsetWidth || 0, height: elem.offsetHeight || 0 }; if (typeof elem.getBoundingClientRect !== 'undefined') { let {width, height} = elem.getBoundingClientRect(); rect.width = width || rect.width; rect.height = height || rect.height; } return rect; } export default { canUseDom, css, getComputedStyles, contains, ownerWindow, ownerDocument, getOffset, getDocumentHeight, getPosition, getSize, activeElement, offsetParent };
ajax/libs/qooxdoo/2.1/q.js
rcyrus/cdnjs
/** qooxdoo v.2.1 | (c) 2012 1&1 Internet AG 1und1.de | qooxdoo.org/license */ (function(){ if (!window.qx) window.qx = {}; var qx = window.qx; if (!qx.$$environment) qx.$$environment = {}; var envinfo = {"json":true,"qx.application":"library.Application","qx.debug":false,"qx.debug.databinding":false,"qx.debug.dispose":false,"qx.debug.ui.queue":false,"qx.optimization.variants":true,"qx.revision":"","qx.theme":"qx.theme.Modern","qx.version":"2.1"}; for (var k in envinfo) qx.$$environment[k] = envinfo[k]; qx.$$packageData = {}; /** qooxdoo v.2.1 | (c) 2012 1&1 Internet AG 1und1.de | qooxdoo.org/license */ qx.$$packageData['0']={"locales":{},"resources":{},"translations":{"C":{},"en":{}}}; /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Martin Wittemann (martinwittemann) ************************************************************************ */ /* ************************************************************************ #ignore(qx.data) #ignore(qx.data.IListData) #ignore(qx.util.OOUtil) ************************************************************************ */ /** * Create namespace */ if(!window.qx){ window.qx = { }; }; /** * Bootstrap qx.Bootstrap to create myself later * This is needed for the API browser etc. to let them detect me */ qx.Bootstrap = { genericToString : function(){ return "[Class " + this.classname + "]"; }, createNamespace : function(name, object){ var splits = name.split("."); var parent = window; var part = splits[0]; for(var i = 0,len = splits.length - 1;i < len;i++,part = splits[i]){ if(!parent[part]){ parent = parent[part] = { }; } else { parent = parent[part]; }; }; // store object parent[part] = object; // return last part name (e.g. classname) return part; }, setDisplayName : function(fcn, classname, name){ fcn.displayName = classname + "." + name + "()"; }, setDisplayNames : function(functionMap, classname){ for(var name in functionMap){ var value = functionMap[name]; if(value instanceof Function){ value.displayName = classname + "." + name + "()"; }; }; }, define : function(name, config){ if(!config){ var config = { statics : { } }; }; var clazz; var proto = null; qx.Bootstrap.setDisplayNames(config.statics, name); if(config.members || config.extend){ qx.Bootstrap.setDisplayNames(config.members, name + ".prototype"); clazz = config.construct || new Function; if(config.extend){ this.extendClass(clazz, clazz, config.extend, name, basename); }; var statics = config.statics || { }; // use keys to include the shadowed in IE for(var i = 0,keys = qx.Bootstrap.keys(statics),l = keys.length;i < l;i++){ var key = keys[i]; clazz[key] = statics[key]; }; proto = clazz.prototype; var members = config.members || { }; // use keys to include the shadowed in IE for(var i = 0,keys = qx.Bootstrap.keys(members),l = keys.length;i < l;i++){ var key = keys[i]; proto[key] = members[key]; }; } else { clazz = config.statics || { }; }; // Create namespace var basename = name ? this.createNamespace(name, clazz) : ""; // Store names in constructor/object clazz.name = clazz.classname = name; clazz.basename = basename; // Store type info clazz.$$type = "Class"; // Attach toString if(!clazz.hasOwnProperty("toString")){ clazz.toString = this.genericToString; }; // Execute defer section if(config.defer){ config.defer(clazz, proto); }; // Store class reference in global class registry qx.Bootstrap.$$registry[name] = clazz; return clazz; } }; /** * Internal class that is responsible for bootstrapping the qooxdoo * framework at load time. * * Does support: * * * Construct * * Statics * * Members * * Extend * * Defer * * Does not support: * * * Super class calls * * Mixins, Interfaces, Properties, ... */ qx.Bootstrap.define("qx.Bootstrap", { statics : { /** Timestamp of qooxdoo based application startup */ LOADSTART : qx.$$start || new Date(), /** * Mapping for early use of the qx.debug environment setting. */ DEBUG : (function(){ // make sure to reflect all changes here to the environment class! var debug = true; if(qx.$$environment && qx.$$environment["qx.debug"] === false){ debug = false; }; return debug; })(), /** * Minimal accessor API for the environment settings given from the * generator. * * WARNING: This method only should be used if the * {@link qx.core.Environment} class is not loaded! * * @param key {String} The key to get the value from. * @return {var} The value of the setting or <code>undefined</code>. */ getEnvironmentSetting : function(key){ if(qx.$$environment){ return qx.$$environment[key]; }; }, /** * Minimal mutator for the environment settings given from the generator. * It checks for the existance of the environment settings and sets the * key if its not given from the generator. If a setting is available from * the generator, the setting will be ignored. * * WARNING: This method only should be used if the * {@link qx.core.Environment} class is not loaded! * * @param key {String} The key of the setting. * @param value {var} The value for the setting. */ setEnvironmentSetting : function(key, value){ if(!qx.$$environment){ qx.$$environment = { }; }; if(qx.$$environment[key] === undefined){ qx.$$environment[key] = value; }; }, /** * Creates a namespace and assigns the given object to it. * * @internal * @param name {String} The complete namespace to create. Typically, the last part is the class name itself * @param object {Object} The object to attach to the namespace * @return {Object} last part of the namespace (typically the class name) * @throws {Error} when the given object already exists. */ createNamespace : qx.Bootstrap.createNamespace, /** * Define a new class using the qooxdoo class system. * Lightweight version of {@link qx.Class#define} only used during bootstrap phase. * * @internal * @signature function(name, config) * @param name {String?} Name of the class. If null, the class will not be * attached to a namespace. * @param config {Map ? null} Class definition structure. * @return {Class} The defined class */ define : qx.Bootstrap.define, /** * Sets the display name of the given function * * @signature function(fcn, classname, name) * @param fcn {Function} the function to set the display name for * @param classname {String} the name of the class the function is defined in * @param name {String} the function name */ setDisplayName : qx.Bootstrap.setDisplayName, /** * Set the names of all functions defined in the given map * * @signature function(functionMap, classname) * @param functionMap {Object} a map with functions as values * @param classname {String} the name of the class, the functions are * defined in */ setDisplayNames : qx.Bootstrap.setDisplayNames, /** * This method will be attached to all classes to return * a nice identifier for them. * * @internal * @signature function() * @return {String} The class identifier */ genericToString : qx.Bootstrap.genericToString, /** * Inherit a clazz from a super class. * * This function differentiates between class and constructor because the * constructor written by the user might be wrapped and the <code>base</code> * property has to be attached to the constructor, while the <code>superclass</code> * property has to be attached to the wrapped constructor. * * @param clazz {Function} The class's wrapped constructor * @param construct {Function} The unwrapped constructor * @param superClass {Function} The super class * @param name {Function} fully qualified class name * @param basename {Function} the base name */ extendClass : function(clazz, construct, superClass, name, basename){ var superproto = superClass.prototype; // Use helper function/class to save the unnecessary constructor call while // setting up inheritance. var helper = new Function(); helper.prototype = superproto; var proto = new helper(); // Apply prototype to new helper instance clazz.prototype = proto; // Store names in prototype proto.name = proto.classname = name; proto.basename = basename; /* - Store base constructor to constructor- - Store reference to extend class */ construct.base = superClass; clazz.superclass = superClass; /* - Store statics/constructor onto constructor/prototype - Store correct constructor - Store statics onto prototype */ construct.self = clazz.constructor = proto.constructor = clazz; }, /** * Find a class by its name * * @param name {String} class name to resolve * @return {Class} the class */ getByName : function(name){ return qx.Bootstrap.$$registry[name]; }, /** {Map} Stores all defined classes */ $$registry : { }, /* --------------------------------------------------------------------------- OBJECT UTILITY FUNCTIONS --------------------------------------------------------------------------- */ /** * Get the number of own properties in the object. * * @param map {Object} the map * @return {Integer} number of objects in the map * @lint ignoreUnused(key) */ objectGetLength : function(map){ return qx.Bootstrap.keys(map).length; }, /** * Inserts all keys of the source object into the * target objects. Attention: The target map gets modified. * * @param target {Object} target object * @param source {Object} object to be merged * @param overwrite {Boolean ? true} If enabled existing keys will be overwritten * @return {Object} Target with merged values from the source object */ objectMergeWith : function(target, source, overwrite){ if(overwrite === undefined){ overwrite = true; }; for(var key in source){ if(overwrite || target[key] === undefined){ target[key] = source[key]; }; }; return target; }, /** * IE does not return "shadowed" keys even if they are defined directly * in the object. * * @internal */ __shadowedKeys : ["isPrototypeOf", "hasOwnProperty", "toLocaleString", "toString", "valueOf", "propertyIsEnumerable", "constructor"], /** * Get the keys of a map as array as returned by a "for ... in" statement. * * @deprecated {2.1.} Please use Object.keys instead. * @param map {Object} the map * @return {Array} array of the keys of the map */ getKeys : function(map){ if(qx.Bootstrap.DEBUG){ qx.Bootstrap.warn("'qx.Bootstrap.getKeys' is deprecated. " + "Please use the native 'Object.keys()' instead."); }; return qx.Bootstrap.keys(map); }, /** * Get the keys of a map as array as returned by a "for ... in" statement. * * @signature function(map) * @internal * @param map {Object} the map * @return {Array} array of the keys of the map */ keys : ({ "ES5" : Object.keys, "BROKEN_IE" : function(map){ if(map === null || (typeof map != "object" && typeof map != "function")){ throw new TypeError("Object.keys requires an object as argument."); }; var arr = []; var hasOwnProperty = Object.prototype.hasOwnProperty; for(var key in map){ if(hasOwnProperty.call(map, key)){ arr.push(key); }; }; // IE does not return "shadowed" keys even if they are defined directly // in the object. This is incompatible with the ECMA standard!! // This is why this checks are needed. var shadowedKeys = qx.Bootstrap.__shadowedKeys; for(var i = 0,a = shadowedKeys,l = a.length;i < l;i++){ if(hasOwnProperty.call(map, a[i])){ arr.push(a[i]); }; }; return arr; }, "default" : function(map){ if(map === null || (typeof map != "object" && typeof map != "function")){ throw new TypeError("Object.keys requires an object as argument."); }; var arr = []; var hasOwnProperty = Object.prototype.hasOwnProperty; for(var key in map){ if(hasOwnProperty.call(map, key)){ arr.push(key); }; }; return arr; } })[typeof (Object.keys) == "function" ? "ES5" : (function(){ for(var key in { toString : 1 }){ return key; }; })() !== "toString" ? "BROKEN_IE" : "default"], /** * Get the keys of a map as string * * @param map {Object} the map * @deprecated {2.1} Object.keys(map).join('\", "'). * @return {String} String of the keys of the map * The keys are separated by ", " */ getKeysAsString : function(map){ { }; var keys = qx.Bootstrap.keys(map); if(keys.length == 0){ return ""; }; return '"' + keys.join('\", "') + '"'; }, /** * Mapping from JavaScript string representation of objects to names * @internal */ __classToTypeMap : { "[object String]" : "String", "[object Array]" : "Array", "[object Object]" : "Object", "[object RegExp]" : "RegExp", "[object Number]" : "Number", "[object Boolean]" : "Boolean", "[object Date]" : "Date", "[object Function]" : "Function", "[object Error]" : "Error" }, /* --------------------------------------------------------------------------- FUNCTION UTILITY FUNCTIONS --------------------------------------------------------------------------- */ /** * Returns a function whose "this" is altered. * * *Syntax* * * <pre class='javascript'>qx.Bootstrap.bind(myFunction, [self, [varargs...]]);</pre> * * *Example* * * <pre class='javascript'> * function myFunction() * { * this.setStyle('color', 'red'); * // note that 'this' here refers to myFunction, not an element * // we'll need to bind this function to the element we want to alter * }; * * var myBoundFunction = qx.Bootstrap.bind(myFunction, myElement); * myBoundFunction(); // this will make the element myElement red. * </pre> * * @param func {Function} Original function to wrap * @param self {Object ? null} The object that the "this" of the function will refer to. * @param varargs {arguments ? null} The arguments to pass to the function. * @return {Function} The bound function. */ bind : function(func, self, varargs){ var fixedArgs = Array.prototype.slice.call(arguments, 2, arguments.length); return function(){ var args = Array.prototype.slice.call(arguments, 0, arguments.length); return func.apply(self, fixedArgs.concat(args)); }; }, /* --------------------------------------------------------------------------- STRING UTILITY FUNCTIONS --------------------------------------------------------------------------- */ /** * Convert the first character of the string to upper case. * * @param str {String} the string * @return {String} the string with an upper case first character */ firstUp : function(str){ return str.charAt(0).toUpperCase() + str.substr(1); }, /** * Convert the first character of the string to lower case. * * @param str {String} the string * @return {String} the string with a lower case first character */ firstLow : function(str){ return str.charAt(0).toLowerCase() + str.substr(1); }, /* --------------------------------------------------------------------------- TYPE UTILITY FUNCTIONS --------------------------------------------------------------------------- */ /** * Get the internal class of the value. See * http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ * for details. * * @param value {var} value to get the class for * @return {String} the internal class of the value */ getClass : function(value){ var classString = Object.prototype.toString.call(value); return (qx.Bootstrap.__classToTypeMap[classString] || classString.slice(8, -1)); }, /** * Whether the value is a string. * * @param value {var} Value to check. * @return {Boolean} Whether the value is a string. */ isString : function(value){ // Added "value !== null" because IE throws an exception "Object expected" // by executing "value instanceof String" if value is a DOM element that // doesn't exist. It seems that there is an internal different between a // JavaScript null and a null returned from calling DOM. // e.q. by document.getElementById("ReturnedNull"). return (value !== null && (typeof value === "string" || qx.Bootstrap.getClass(value) == "String" || value instanceof String || (!!value && !!value.$$isString))); }, /** * Whether the value is an array. * * @param value {var} Value to check. * @return {Boolean} Whether the value is an array. */ isArray : function(value){ // Added "value !== null" because IE throws an exception "Object expected" // by executing "value instanceof Array" if value is a DOM element that // doesn't exist. It seems that there is an internal different between a // JavaScript null and a null returned from calling DOM. // e.q. by document.getElementById("ReturnedNull"). return (value !== null && (value instanceof Array || (value && qx.data && qx.data.IListData && qx.util.OOUtil.hasInterface(value.constructor, qx.data.IListData)) || qx.Bootstrap.getClass(value) == "Array" || (!!value && !!value.$$isArray))); }, /** * Whether the value is an object. Note that built-in types like Window are * not reported to be objects. * * @param value {var} Value to check. * @return {Boolean} Whether the value is an object. */ isObject : function(value){ return (value !== undefined && value !== null && qx.Bootstrap.getClass(value) == "Object"); }, /** * Whether the value is a function. * * @param value {var} Value to check. * @return {Boolean} Whether the value is a function. */ isFunction : function(value){ return qx.Bootstrap.getClass(value) == "Function"; }, /* --------------------------------------------------------------------------- LOGGING UTILITY FUNCTIONS --------------------------------------------------------------------------- */ $$logs : [], /** * Sending a message at level "debug" to the logger. * * @param object {Object} Contextual object (either instance or static class) * @param message {var} Any number of arguments supported. An argument may * have any JavaScript data type. All data is serialized immediately and * does not keep references to other objects. */ debug : function(object, message){ qx.Bootstrap.$$logs.push(["debug", arguments]); }, /** * Sending a message at level "info" to the logger. * * @param object {Object} Contextual object (either instance or static class) * @param message {var} Any number of arguments supported. An argument may * have any JavaScript data type. All data is serialized immediately and * does not keep references to other objects. */ info : function(object, message){ qx.Bootstrap.$$logs.push(["info", arguments]); }, /** * Sending a message at level "warn" to the logger. * * @param object {Object} Contextual object (either instance or static class) * @param message {var} Any number of arguments supported. An argument may * have any JavaScript data type. All data is serialized immediately and * does not keep references to other objects. */ warn : function(object, message){ qx.Bootstrap.$$logs.push(["warn", arguments]); }, /** * Sending a message at level "error" to the logger. * * @param object {Object} Contextual object (either instance or static class) * @param message {var} Any number of arguments supported. An argument may * have any JavaScript data type. All data is serialized immediately and * does not keep references to other objects. */ error : function(object, message){ qx.Bootstrap.$$logs.push(["error", arguments]); }, /** * Prints the current stack trace at level "info" * * @param object {Object} Contextual object (either instance or static class) */ trace : function(object){ } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2005-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * This class is the single point to access all settings that may be different * in different environments. This contains e.g. the browser name, engine * version but also qooxdoo or application specific settings. * * Its public API can be found in its four main methods. One pair of methods * is used to check the synchronous values of the environment. The other pair * of methods is used for asynchronous checks. * * The most often used method should be {@link #get}, which returns the * current value for a given environment check. * * All qooxdoo settings can be changed via the generator's config. See the manual * for more details about the environment key in the config. As you can see * from the methods API, there is no way to override an existing key. So if you * need to change a qooxdoo setting, you have to use the generator to do so. * * The following table shows the available checks. If you are * interested in more details, check the reference to the implementation of * each check. Please do not use those check implementations directly, as the * Environment class comes with a smart caching feature. * * <table border="0" cellspacing="10"> * <tbody> * <tr> * <td colspan="4"><h2>Synchronous checks</h2> * </td> * </tr> * <tr> * <th><h3>Key</h3></th> * <th><h3>Type</h3></th> * <th><h3>Example</h3></th> * <th><h3>Details</h3></th> * </tr> * <tr> * <td colspan="4"><b>browser</b></td> * </tr> * <tr> * <td>browser.documentmode</td><td><i>Integer</i></td><td><code>0</code></td> * <td>{@link qx.bom.client.Browser#getDocumentMode}</td> * </tr> * <tr> * <td>browser.name</td><td><i>String</i></td><td><code> chrome </code></td> * <td>{@link qx.bom.client.Browser#getName}</td> * </tr> * <tr> * <td>browser.quirksmode</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Browser#getQuirksMode}</td> * </tr> * <tr> * <td>browser.version</td><td><i>String</i></td><td><code>11.0</code></td> * <td>{@link qx.bom.client.Browser#getVersion}</td> * </tr> * <tr> * <td colspan="4"><b>runtime</b></td> * </tr> * <tr> * <td>runtime.name</td><td><i> String </i></td><td><code> node.js </code></td> * <td>{@link qx.bom.client.Runtime#getName}</td> * </tr> * <tr> * <td colspan="4"><b>css</b></td> * </tr> * <tr> * <td>css.borderradius</td><td><i>String</i> or <i>null</i></td><td><code>borderRadius</code></td> * <td>{@link qx.bom.client.Css#getBorderRadius}</td> * </tr> * <tr> * <td>css.borderimage</td><td><i>String</i> or <i>null</i></td><td><code>WebkitBorderImage</code></td> * <td>{@link qx.bom.client.Css#getBorderImage}</td> * </tr> * <tr> * <td>css.borderimage.standardsyntax</td><td><i>Boolean</i> or <i>null</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getBorderImageSyntax}</td> * </tr> * <tr> * <td>css.boxmodel</td><td><i>String</i></td><td><code>content</code></td> * <td>{@link qx.bom.client.Css#getBoxModel}</td> * </tr> * <tr> * <td>css.boxshadow</td><td><i>String</i> or <i>null</i></td><td><code>boxShadow</code></td> * <td>{@link qx.bom.client.Css#getBoxShadow}</td> * </tr> * <tr> * <td>css.gradient.linear</td><td><i>String</i> or <i>null</i></td><td><code>-moz-linear-gradient</code></td> * <td>{@link qx.bom.client.Css#getLinearGradient}</td> * </tr> * <tr> * <td>css.gradient.filter</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getFilterGradient}</td> * </tr> * <tr> * <td>css.gradient.radial</td><td><i>String</i> or <i>null</i></td><td><code>-moz-radial-gradient</code></td> * <td>{@link qx.bom.client.Css#getRadialGradient}</td> * </tr> * <tr> * <td>css.gradient.legacywebkit</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Css#getLegacyWebkitGradient}</td> * </tr> * <tr> * <td>css.placeholder</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getPlaceholder}</td> * </tr> * <tr> * <td>css.textoverflow</td><td><i>String</i> or <i>null</i></td><td><code>textOverflow</code></td> * <td>{@link qx.bom.client.Css#getTextOverflow}</td> * </tr> * <tr> * <td>css.rgba</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getRgba}</td> * </tr> * <tr> * <td>css.usermodify</td><td><i>String</i> or <i>null</i></td><td><code>WebkitUserModify</code></td> * <td>{@link qx.bom.client.Css#getUserModify}</td> * </tr> * <tr> * <td>css.appearance</td><td><i>String</i> or <i>null</i></td><td><code>WebkitAppearance</code></td> * <td>{@link qx.bom.client.Css#getAppearance}</td> * </tr> * <tr> * <td>css.float</td><td><i>String</i> or <i>null</i></td><td><code>cssFloat</code></td> * <td>{@link qx.bom.client.Css#getFloat}</td> * </tr> * <tr> * <td>css.userselect</td><td><i>String</i> or <i>null</i></td><td><code>WebkitUserSelect</code></td> * <td>{@link qx.bom.client.Css#getUserSelect}</td> * </tr> * <tr> * <td>css.userselect.none</td><td><i>String</i> or <i>null</i></td><td><code>-moz-none</code></td> * <td>{@link qx.bom.client.Css#getUserSelectNone}</td> * </tr> * <tr> * <td>css.boxsizing</td><td><i>String</i> or <i>null</i></td><td><code>boxSizing</code></td> * <td>{@link qx.bom.client.Css#getBoxSizing}</td> * </tr> * <tr> * <td>css.animation</td><td><i>Object</i> or <i>null</i></td><td><code>{end-event: "webkitAnimationEnd", keyframes: "@-webkit-keyframes", play-state: null, name: "WebkitAnimation"}</code></td> * <td>{@link qx.bom.client.CssAnimation#getSupport}</td> * </tr> * <tr> * <td>css.animation.requestframe</td><td><i>String</i> or <i>null</i></td><td><code>mozRequestAnimationFrame</code></td> * <td>{@link qx.bom.client.CssAnimation#getRequestAnimationFrame}</td> * </tr> * <tr> * <td>css.transform</td><td><i>Object</i> or <i>null</i></td><td><code>{3d: true, origin: "WebkitTransformOrigin", name: "WebkitTransform", style: "WebkitTransformStyle", perspective: "WebkitPerspective", perspective-origin: "WebkitPerspectiveOrigin", backface-visibility: "WebkitBackfaceVisibility"}</code></td> * <td>{@link qx.bom.client.CssTransform#getSupport}</td> * </tr> * <tr> * <td>css.transform.3d</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.CssTransform#get3D}</td> * </tr> * <tr> * <td>css.inlineblock</td><td><i>String</i> or <i>null</i></td><td><code>inline-block</code></td> * <td>{@link qx.bom.client.Css#getInlineBlock}</td> * </tr> * <tr> * <td>css.opacity</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getOpacity}</td> * </tr> * <tr> * <td>deprecated since 2.1: css.overflowxy</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getOverflowXY}</td> * </tr> * <tr> * <td>css.textShadow</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getTextShadow}</td> * </tr> * <tr> * <td>css.textShadow.filter</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Css#getFilterTextShadow}</td> * </tr> * <tr> * <td colspan="4"><b>device</b></td> * </tr> * <tr> * <td>device.name</td><td><i>String</i></td><td><code>pc</code></td> * <td>{@link qx.bom.client.Device#getName}</td> * </tr> * <tr> * <td>device.type</td><td><i>String</i></td><td><code>mobile</code></td> * <td>{@link qx.bom.client.Device#getType}</td> * </tr> * <tr> * <td colspan="4"><b>ecmascript</b></td> * </tr> * <tr> * <td>ecmascript.error.stacktrace</td><td><i>String</i> or <i>null</i></td><td><code>stack</code></td> * <td>{@link qx.bom.client.EcmaScript#getStackTrace}</td> * </tr> * <tr> * <td>ecmascript.array.indexof<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayIndexOf}</td> * </tr> * <tr> * <td>ecmascript.array.lastindexof<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayLastIndexOf}</td> * </tr> * <tr> * <td>ecmascript.array.foreach<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayForEach}</td> * </tr> * <tr> * <td>ecmascript.array.filter<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayFilter}</td> * </tr> * <tr> * <td>ecmascript.array.map<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayMap}</td> * </tr> * <tr> * <td>ecmascript.array.some<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArraySome}</td> * </tr> * <tr> * <td>ecmascript.array.every<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayEvery}</td> * </tr> * <tr> * <td>ecmascript.array.reduce<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayReduce}</td> * </tr> * <tr> * <td>ecmascript.array.reduceright<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getArrayReduceRight}</td> * </tr> * <tr> * <td>ecmascript.function.bind<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getFunctionBind}</td> * </tr> * <tr> * <td>ecmascript.object.keys<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getObjectKeys}</td> * </tr> * <tr> * <td>ecmascript.date.now<td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getDateNow}</td> * </tr> * <tr> * <td>ecmascript.error.toString</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getErrorToString}</td> * </tr> * <tr> * <td>ecmascript.string.trim</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.EcmaScript#getStringTrim}</td> * </tr> * <tr> * <td colspan="4"><b>engine</b></td> * </tr> * <tr> * <td>engine.name</td><td><i>String</i></td><td><code>webkit</code></td> * <td>{@link qx.bom.client.Engine#getName}</td> * </tr> * <tr> * <td>engine.version</td><td><i>String</i></td><td><code>534.24</code></td> * <td>{@link qx.bom.client.Engine#getVersion}</td> * </tr> * <tr> * <td colspan="4"><b>event</b></td> * </tr> * <tr> * <td>event.pointer</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Event#getPointer}</td> * </tr> * <tr> * <td>event.mspointer</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Event#getMsPointer}</td> * </tr> * <tr> * <td>event.touch</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Event#getTouch}</td> * </tr> * <tr> * <td>event.help</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Event#getHelp}</td> * </tr> * <tr> * <td>event.hashchange</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Event#getHashChange}</td> * </tr> * <tr> * <td colspan="4"><b>html</b></td> * </tr> * <tr> * <td>html.audio</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getAudio}</td> * </tr> * <tr> * <td>html.audio.mp3</td><td><i>String</i></td><td><code>""</code></td> * <td>{@link qx.bom.client.Html#getAudioMp3}</td> * </tr> * <tr> * <td>html.audio.ogg</td><td><i>String</i></td><td><code>"maybe"</code></td> * <td>{@link qx.bom.client.Html#getAudioOgg}</td> * </tr> * <tr> * <td>html.audio.wav</td><td><i>String</i></td><td><code>"probably"</code></td> * <td>{@link qx.bom.client.Html#getAudioWav}</td> * </tr> * <tr> * <td>html.audio.au</td><td><i>String</i></td><td><code>"maybe"</code></td> * <td>{@link qx.bom.client.Html#getAudioAu}</td> * </tr> * <tr> * <td>html.audio.aif</td><td><i>String</i></td><td><code>"probably"</code></td> * <td>{@link qx.bom.client.Html#getAudioAif}</td> * </tr> * <tr> * <td>html.canvas</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getCanvas}</td> * </tr> * <tr> * <td>html.classlist</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getClassList}</td> * </tr> * <tr> * <td>html.geolocation</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getGeoLocation}</td> * </tr> * <tr> * <td>html.storage.local</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getLocalStorage}</td> * </tr> * <tr> * <td>html.storage.session</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getSessionStorage}</td> * </tr> * <tr> * <td>html.storage.userdata</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getUserDataStorage}</td> * </tr> * <tr> * <td>html.svg</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getSvg}</td> * </tr> * <tr> * <td>html.video</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getVideo}</td> * </tr> * <tr> * <td>html.video.h264</td><td><i>String</i></td><td><code>"probably"</code></td> * <td>{@link qx.bom.client.Html#getVideoH264}</td> * </tr> * <tr> * <td>html.video.ogg</td><td><i>String</i></td><td><code>""</code></td> * <td>{@link qx.bom.client.Html#getVideoOgg}</td> * </tr> * <tr> * <td>html.video.webm</td><td><i>String</i></td><td><code>"maybe"</code></td> * <td>{@link qx.bom.client.Html#getVideoWebm}</td> * </tr> * <tr> * <td>html.vml</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Html#getVml}</td> * </tr> * <tr> * <td>html.webworker</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getWebWorker}</td> * <tr> * <td>html.filereader</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getFileReader}</td> * </tr> * <tr> * <td>html.xpath</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getXPath}</td> * </tr> * <tr> * <td>html.xul</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getXul}</td> * </tr> * <tr> * <td>html.console</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getConsole}</td> * </tr> * <tr> * <td>html.element.contains</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getContains}</td> * </tr> * <tr> * <td>html.element.compareDocumentPosition</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getCompareDocumentPosition}</td> * </tr> * <tr> * <td>html.element.textContent</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getTextContent}</td> * </tr> * <tr> * <td>html.image.naturaldimensions</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getNaturalDimensions}</td> * </tr> * <tr> * <td>html.history.state</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getHistoryState}</td> * </tr> * <tr> * <td colspan="4"><b>XML</b></td> * </tr> * <tr> * <td>xml.implementation</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Xml#getImplementation}</td> * </tr> * <tr> * <td>xml.domparser</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Xml#getDomParser}</td> * </tr> * <tr> * <td>xml.selectsinglenode</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Xml#getSelectSingleNode}</td> * </tr> * <tr> * <td>xml.selectnodes</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Xml#getSelectNodes}</td> * </tr> * <tr> * <td>xml.getelementsbytagnamens</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Xml#getElementsByTagNameNS}</td> * </tr> * <tr> * <td>xml.domproperties</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Xml#getDomProperties}</td> * </tr> * <tr> * <td>xml.attributens</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Xml#getAttributeNS}</td> * </tr> * <tr> * <td>xml.createelementns</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Xml#getCreateElementNS}</td> * </tr> * <tr> * <td>xml.createnode</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Xml#getCreateNode}</td> * </tr> * <tr> * <td>xml.getqualifieditem</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Xml#getQualifiedItem}</td> * </tr> * <tr> * <td colspan="4"><b>Stylesheets</b></td> * </tr> * <tr> * <td>html.stylesheet.createstylesheet</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Stylesheet#getCreateStyleSheet}</td> * </tr> * <tr> * <td>html.stylesheet.insertrule</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Stylesheet#getInsertRule}</td> * </tr> * <tr> * <td>html.stylesheet.deleterule</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Stylesheet#getDeleteRule}</td> * </tr> * <tr> * <td>html.stylesheet.addimport</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Stylesheet#getAddImport}</td> * </tr> * <tr> * <td>html.stylesheet.removeimport</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Stylesheet#getRemoveImport}</td> * </tr> * <tr> * <td colspan="4"><b>io</b></td> * </tr> * <tr> * <td>io.maxrequests</td><td><i>Integer</i></td><td><code>4</code></td> * <td>{@link qx.bom.client.Transport#getMaxConcurrentRequestCount}</td> * </tr> * <tr> * <td>io.ssl</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Transport#getSsl}</td> * </tr> * <tr> * <td>io.xhr</td><td><i>String</i></td><td><code>xhr</code></td> * <td>{@link qx.bom.client.Transport#getXmlHttpRequest}</td> * </tr> * <tr> * <td colspan="4"><b>locale</b></td> * </tr> * <tr> * <td>locale</td><td><i>String</i></td><td><code>de</code></td> * <td>{@link qx.bom.client.Locale#getLocale}</td> * </tr> * <tr> * <td>locale.variant</td><td><i>String</i></td><td><code>de</code></td> * <td>{@link qx.bom.client.Locale#getVariant}</td> * </tr> * <tr> * <td colspan="4"><b>os</b></td> * </tr> * <tr> * <td>os.name</td><td><i>String</i></td><td><code>osx</code></td> * <td>{@link qx.bom.client.OperatingSystem#getName}</td> * </tr> * <tr> * <td>os.version</td><td><i>String</i></td><td><code>10.6</code></td> * <td>{@link qx.bom.client.OperatingSystem#getVersion}</td> * </tr> * <tr> * <td>os.scrollBarOverlayed</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Scroll#scrollBarOverlayed}</td> * </tr> * <tr> * <td colspan="4"><b>phonegap</b></td> * </tr> * <tr> * <td>phonegap</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.PhoneGap#getPhoneGap}</td> * </tr> * <tr> * <td>phonegap.notification</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.PhoneGap#getNotification}</td> * </tr> * <tr> * <td colspan="4"><b>plugin</b></td> * </tr> * <tr> * <td>plugin.divx</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Plugin#getDivX}</td> * </tr> * <tr> * <td>plugin.divx.version</td><td><i>String</i></td><td></td> * <td>{@link qx.bom.client.Plugin#getDivXVersion}</td> * </tr> * <tr> * <td>plugin.flash</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Flash#isAvailable}</td> * </tr> * <tr> * <td>plugin.flash.express</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Flash#getExpressInstall}</td> * </tr> * <tr> * <td>plugin.flash.strictsecurity</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Flash#getStrictSecurityModel}</td> * </tr> * <tr> * <td>plugin.flash.version</td><td><i>String</i></td><td><code>10.2.154</code></td> * <td>{@link qx.bom.client.Flash#getVersion}</td> * </tr> * <tr> * <td>plugin.gears</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Plugin#getGears}</td> * </tr> * <tr> * <td>plugin.activex</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Plugin#getActiveX}</td> * </tr> * <tr> * <td>plugin.skype</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Plugin#getSkype}</td> * </tr> * <tr> * <td>plugin.pdf</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Plugin#getPdf}</td> * </tr> * <tr> * <td>plugin.pdf.version</td><td><i>String</i></td><td></td> * <td>{@link qx.bom.client.Plugin#getPdfVersion}</td> * </tr> * <tr> * <td>plugin.quicktime</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Plugin#getQuicktime}</td> * </tr> * <tr> * <td>plugin.quicktime.version</td><td><i>String</i></td><td><code>7.6</code></td> * <td>{@link qx.bom.client.Plugin#getQuicktimeVersion}</td> * </tr> * <tr> * <td>plugin.silverlight</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Plugin#getSilverlight}</td> * </tr> * <tr> * <td>plugin.silverlight.version</td><td><i>String</i></td><td></td> * <td>{@link qx.bom.client.Plugin#getSilverlightVersion}</td> * </tr> * <tr> * <td>plugin.windowsmedia</td><td><i>Boolean</i></td><td><code>false</code></td> * <td>{@link qx.bom.client.Plugin#getWindowsMedia}</td> * </tr> * <tr> * <td>plugin.windowsmedia.version</td><td><i>String</i></td><td></td> * <td>{@link qx.bom.client.Plugin#getWindowsMediaVersion}</td> * </tr> * <tr> * <td colspan="4"><b>qx</b></td> * </tr> * <tr> * <td>qx.allowUrlSettings</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.allowUrlVariants</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.application</td><td><i>String</i></td><td><code>name.space</code></td> * <td><i>default:</i> <code>&lt;&lt;application name&gt;&gt;</code></td> * </tr> * <tr> * <td>qx.aspects</td><td><i>Boolean</i></td><td><code>false</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.debug</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>qx.debug.databinding</td><td><i>Boolean</i></td><td><code>false</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.debug.dispose</td><td><i>Boolean</i></td><td><code>false</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.debug.dispose.level</td><td><i>Integer</i></td><td><code>0</code></td> * <td><i>default:</i> <code>0</code></td> * </tr> * <tr> * <td>qx.debug.io</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <tr> * <td>qx.debug.io.remote</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <tr> * <td>qx.debug.io.remote.data</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.debug.property.level</td><td><i>Integer</i></td><td><code>0</code></td> * <td><i>default:</i> <code>0</code></td> * </tr> * <tr> * <td>qx.debug.ui.queue</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>qx.dynamicmousewheel</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>qx.dynlocale</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>qx.globalErrorHandling</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>qx.mobile.emulatetouch</td><td><i>Boolean</i></td><td><code>false</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.mobile.nativescroll</td><td><i>Boolean</i></td><td><code>false</code></td> * <td><i>default:</i> <code>false</code></td> * </tr> * <tr> * <td>qx.optimization.basecalls</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>true if the corresp. <i>optimize</i> key is set in the config</td> * </tr> * <tr> * <td>qx.optimization.comments</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>true if the corresp. <i>optimize</i> key is set in the config</td> * </tr> * <tr> * <td>qx.optimization.privates</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>true if the corresp. <i>optimize</i> key is set in the config</td> * </tr> * <tr> * <td>qx.optimization.strings</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>true if the corresp. <i>optimize</i> key is set in the config</td> * </tr> * <tr> * <td>qx.optimization.variables</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>true if the corresp. <i>optimize</i> key is set in the config</td> * </tr> * <tr> * <td>qx.optimization.variants</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>true if the corresp. <i>optimize</i> key is set in the config</td> * </tr> * <tr> * <td>qx.revision</td><td><i>String</i></td><td><code>27348</code></td> * </tr> * <tr> * <td>qx.theme</td><td><i>String</i></td><td><code>qx.theme.Modern</code></td> * <td><i>default:</i> <code>&lt;&lt;initial theme name&gt;&gt;</code></td> * </tr> * <tr> * <td>qx.version</td><td><i>String</i></td><td><code>${qxversion}</code></td> * </tr> * <tr> * <td>qx.blankpage</td><td><i>String</i></td><td><code>URI to blank.html page</code></td> * </tr> * <tr> * <td colspan="4"><b>module</b></td> * </tr> * <tr> * <td>module.databinding</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>module.logger</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>module.property</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td>module.events</td><td><i>Boolean</i></td><td><code>true</code></td> * <td><i>default:</i> <code>true</code></td> * </tr> * <tr> * <td colspan="4"><h3>Asynchronous checks</h3> * </td> * </tr> * <tr> * <td>html.dataurl</td><td><i>Boolean</i></td><td><code>true</code></td> * <td>{@link qx.bom.client.Html#getDataUrl}</td> * </tr> * </tbody> * </table> * */ qx.Bootstrap.define("qx.core.Environment", { statics : { /** Map containing the synchronous check functions. */ _checks : { }, /** Map containing the asynchronous check functions. */ _asyncChecks : { }, /** Internal cache for all checks. */ __cache : { }, /** Internal map for environment keys to check methods. */ _checksMap : { "engine.version" : "qx.bom.client.Engine.getVersion", "engine.name" : "qx.bom.client.Engine.getName", "browser.name" : "qx.bom.client.Browser.getName", "browser.version" : "qx.bom.client.Browser.getVersion", "browser.documentmode" : "qx.bom.client.Browser.getDocumentMode", "browser.quirksmode" : "qx.bom.client.Browser.getQuirksMode", "runtime.name" : "qx.bom.client.Runtime.getName", "device.name" : "qx.bom.client.Device.getName", "device.type" : "qx.bom.client.Device.getType", "locale" : "qx.bom.client.Locale.getLocale", "locale.variant" : "qx.bom.client.Locale.getVariant", "os.name" : "qx.bom.client.OperatingSystem.getName", "os.version" : "qx.bom.client.OperatingSystem.getVersion", "os.scrollBarOverlayed" : "qx.bom.client.Scroll.scrollBarOverlayed", "plugin.gears" : "qx.bom.client.Plugin.getGears", "plugin.activex" : "qx.bom.client.Plugin.getActiveX", "plugin.skype" : "qx.bom.client.Plugin.getSkype", "plugin.quicktime" : "qx.bom.client.Plugin.getQuicktime", "plugin.quicktime.version" : "qx.bom.client.Plugin.getQuicktimeVersion", "plugin.windowsmedia" : "qx.bom.client.Plugin.getWindowsMedia", "plugin.windowsmedia.version" : "qx.bom.client.Plugin.getWindowsMediaVersion", "plugin.divx" : "qx.bom.client.Plugin.getDivX", "plugin.divx.version" : "qx.bom.client.Plugin.getDivXVersion", "plugin.silverlight" : "qx.bom.client.Plugin.getSilverlight", "plugin.silverlight.version" : "qx.bom.client.Plugin.getSilverlightVersion", "plugin.flash" : "qx.bom.client.Flash.isAvailable", "plugin.flash.version" : "qx.bom.client.Flash.getVersion", "plugin.flash.express" : "qx.bom.client.Flash.getExpressInstall", "plugin.flash.strictsecurity" : "qx.bom.client.Flash.getStrictSecurityModel", "plugin.pdf" : "qx.bom.client.Plugin.getPdf", "plugin.pdf.version" : "qx.bom.client.Plugin.getPdfVersion", "io.maxrequests" : "qx.bom.client.Transport.getMaxConcurrentRequestCount", "io.ssl" : "qx.bom.client.Transport.getSsl", "io.xhr" : "qx.bom.client.Transport.getXmlHttpRequest", "event.touch" : "qx.bom.client.Event.getTouch", "event.pointer" : "qx.bom.client.Event.getPointer", "event.help" : "qx.bom.client.Event.getHelp", "event.hashchange" : "qx.bom.client.Event.getHashChange", "ecmascript.stacktrace" : "qx.bom.client.EcmaScript.getStackTrace", // @deprecated {2.1} "ecmascript.error.stacktrace" : "qx.bom.client.EcmaScript.getStackTrace", "ecmascript.array.indexof" : "qx.bom.client.EcmaScript.getArrayIndexOf", "ecmascript.array.lastindexof" : "qx.bom.client.EcmaScript.getArrayLastIndexOf", "ecmascript.array.foreach" : "qx.bom.client.EcmaScript.getArrayForEach", "ecmascript.array.filter" : "qx.bom.client.EcmaScript.getArrayFilter", "ecmascript.array.map" : "qx.bom.client.EcmaScript.getArrayMap", "ecmascript.array.some" : "qx.bom.client.EcmaScript.getArraySome", "ecmascript.array.every" : "qx.bom.client.EcmaScript.getArrayEvery", "ecmascript.array.reduce" : "qx.bom.client.EcmaScript.getArrayReduce", "ecmascript.array.reduceright" : "qx.bom.client.EcmaScript.getArrayReduceRight", "ecmascript.function.bind" : "qx.bom.client.EcmaScript.getFunctionBind", "ecmascript.object.keys" : "qx.bom.client.EcmaScript.getObjectKeys", "ecmascript.date.now" : "qx.bom.client.EcmaScript.getDateNow", "ecmascript.error.toString" : "qx.bom.client.EcmaScript.getErrorToString", "ecmascript.string.trim" : "qx.bom.client.EcmaScript.getStringTrim", "html.webworker" : "qx.bom.client.Html.getWebWorker", "html.filereader" : "qx.bom.client.Html.getFileReader", "html.geolocation" : "qx.bom.client.Html.getGeoLocation", "html.audio" : "qx.bom.client.Html.getAudio", "html.audio.ogg" : "qx.bom.client.Html.getAudioOgg", "html.audio.mp3" : "qx.bom.client.Html.getAudioMp3", "html.audio.wav" : "qx.bom.client.Html.getAudioWav", "html.audio.au" : "qx.bom.client.Html.getAudioAu", "html.audio.aif" : "qx.bom.client.Html.getAudioAif", "html.video" : "qx.bom.client.Html.getVideo", "html.video.ogg" : "qx.bom.client.Html.getVideoOgg", "html.video.h264" : "qx.bom.client.Html.getVideoH264", "html.video.webm" : "qx.bom.client.Html.getVideoWebm", "html.storage.local" : "qx.bom.client.Html.getLocalStorage", "html.storage.session" : "qx.bom.client.Html.getSessionStorage", "html.storage.userdata" : "qx.bom.client.Html.getUserDataStorage", "html.classlist" : "qx.bom.client.Html.getClassList", "html.xpath" : "qx.bom.client.Html.getXPath", "html.xul" : "qx.bom.client.Html.getXul", "html.canvas" : "qx.bom.client.Html.getCanvas", "html.svg" : "qx.bom.client.Html.getSvg", "html.vml" : "qx.bom.client.Html.getVml", "html.dataset" : "qx.bom.client.Html.getDataset", "html.dataurl" : "qx.bom.client.Html.getDataUrl", "html.console" : "qx.bom.client.Html.getConsole", "html.stylesheet.createstylesheet" : "qx.bom.client.Stylesheet.getCreateStyleSheet", "html.stylesheet.insertrule" : "qx.bom.client.Stylesheet.getInsertRule", "html.stylesheet.deleterule" : "qx.bom.client.Stylesheet.getDeleteRule", "html.stylesheet.addimport" : "qx.bom.client.Stylesheet.getAddImport", "html.stylesheet.removeimport" : "qx.bom.client.Stylesheet.getRemoveImport", "html.element.contains" : "qx.bom.client.Html.getContains", "html.element.compareDocumentPosition" : "qx.bom.client.Html.getCompareDocumentPosition", "html.element.textcontent" : "qx.bom.client.Html.getTextContent", "html.image.naturaldimensions" : "qx.bom.client.Html.getNaturalDimensions", "html.history.state" : "qx.bom.client.Html.getHistoryState", "json" : "qx.bom.client.Json.getJson", "css.textoverflow" : "qx.bom.client.Css.getTextOverflow", "css.placeholder" : "qx.bom.client.Css.getPlaceholder", "css.borderradius" : "qx.bom.client.Css.getBorderRadius", "css.borderimage" : "qx.bom.client.Css.getBorderImage", "css.borderimage.standardsyntax" : "qx.bom.client.Css.getBorderImageSyntax", "css.boxshadow" : "qx.bom.client.Css.getBoxShadow", "css.gradient.linear" : "qx.bom.client.Css.getLinearGradient", "css.gradient.filter" : "qx.bom.client.Css.getFilterGradient", "css.gradient.radial" : "qx.bom.client.Css.getRadialGradient", "css.gradient.legacywebkit" : "qx.bom.client.Css.getLegacyWebkitGradient", "css.boxmodel" : "qx.bom.client.Css.getBoxModel", "css.rgba" : "qx.bom.client.Css.getRgba", "css.userselect" : "qx.bom.client.Css.getUserSelect", "css.userselect.none" : "qx.bom.client.Css.getUserSelectNone", "css.usermodify" : "qx.bom.client.Css.getUserModify", "css.appearance" : "qx.bom.client.Css.getAppearance", "css.float" : "qx.bom.client.Css.getFloat", "css.boxsizing" : "qx.bom.client.Css.getBoxSizing", "css.animation" : "qx.bom.client.CssAnimation.getSupport", "css.animation.requestframe" : "qx.bom.client.CssAnimation.getRequestAnimationFrame", "css.transform" : "qx.bom.client.CssTransform.getSupport", "css.transform.3d" : "qx.bom.client.CssTransform.get3D", "css.inlineblock" : "qx.bom.client.Css.getInlineBlock", "css.opacity" : "qx.bom.client.Css.getOpacity", "css.overflowxy" : "qx.bom.client.Css.getOverflowXY", // @deprecated {2.1} "css.textShadow" : "qx.bom.client.Css.getTextShadow", "css.textShadow.filter" : "qx.bom.client.Css.getFilterTextShadow", "phonegap" : "qx.bom.client.PhoneGap.getPhoneGap", "phonegap.notification" : "qx.bom.client.PhoneGap.getNotification", "xml.implementation" : "qx.bom.client.Xml.getImplementation", "xml.domparser" : "qx.bom.client.Xml.getDomParser", "xml.selectsinglenode" : "qx.bom.client.Xml.getSelectSingleNode", "xml.selectnodes" : "qx.bom.client.Xml.getSelectNodes", "xml.getelementsbytagnamens" : "qx.bom.client.Xml.getElementsByTagNameNS", "xml.domproperties" : "qx.bom.client.Xml.getDomProperties", "xml.attributens" : "qx.bom.client.Xml.getAttributeNS", "xml.createnode" : "qx.bom.client.Xml.getCreateNode", "xml.getqualifieditem" : "qx.bom.client.Xml.getQualifiedItem", "xml.createelementns" : "qx.bom.client.Xml.getCreateElementNS" }, /** * The default accessor for the checks. It returns the value the current * environment has for the given key. The key could be something like * "qx.debug", "css.textoverflow" or "io.ssl". A complete list of * checks can be found in the class comment of this class. * * Please keep in mind that the result is cached. If you want to run the * check function again in case something could have been changed, take a * look at the {@link #invalidateCacheKey} function. * * @param key {String} The name of the check you want to query. * @return {var} The stored value depending on the given key. * (Details in the class doc) */ get : function(key){ if(qx.Bootstrap.DEBUG){ // @deprecated {2.1} if(key == "css.overflowxy"){ qx.Bootstrap.warn("The environment key 'css.overflowxy' is deprecated."); }; // @deprecated {2.1} if(key == "ecmascript.stacktrace"){ qx.Bootstrap.warn("The environment key 'ecmascript.stacktrace' is now 'ecmascript.error.stacktrace'."); key = "ecmascript.error.stacktrace"; }; }; // check the cache if(this.__cache[key] != undefined){ return this.__cache[key]; }; // search for a matching check var check = this._checks[key]; if(check){ // execute the check and write the result in the cache var value = check(); this.__cache[key] = value; return value; }; // try class lookup var classAndMethod = this._getClassNameFromEnvKey(key); if(classAndMethod[0] != undefined){ var clazz = classAndMethod[0]; var method = classAndMethod[1]; var value = clazz[method](); // call the check method this.__cache[key] = value; return value; }; // debug flag if(qx.Bootstrap.DEBUG){ qx.Bootstrap.warn(key + " is not a valid key. Please see the API-doc of " + "qx.core.Environment for a list of predefined keys."); qx.Bootstrap.trace(this); }; }, /** * Maps an environment key to a check class and method name. * * @param key {String} The name of the check you want to query. * @return {Array} [className, methodName] of * the corresponding implementation. */ _getClassNameFromEnvKey : function(key){ var envmappings = this._checksMap; if(envmappings[key] != undefined){ var implementation = envmappings[key]; // separate class from method var lastdot = implementation.lastIndexOf("."); if(lastdot > -1){ var classname = implementation.slice(0, lastdot); var methodname = implementation.slice(lastdot + 1); var clazz = qx.Bootstrap.getByName(classname); if(clazz != undefined){ return [clazz, methodname]; }; }; }; return [undefined, undefined]; }, /** * Invokes the callback as soon as the check has been done. If no check * could be found, a warning will be printed. * * @param key {String} The key of the asynchronous check. * @param callback {Function} The function to call as soon as the check is * done. The function should have one argument which is the result of the * check. * @param self {var} The context to use when invoking the callback. */ getAsync : function(key, callback, self){ // check the cache var env = this; if(this.__cache[key] != undefined){ // force async behavior window.setTimeout(function(){ callback.call(self, env.__cache[key]); }, 0); return; }; var check = this._asyncChecks[key]; if(check){ check(function(result){ env.__cache[key] = result; callback.call(self, result); }); return; }; // try class lookup var classAndMethod = this._getClassNameFromEnvKey(key); if(classAndMethod[0] != undefined){ var clazz = classAndMethod[0]; var method = classAndMethod[1]; clazz[method](function(result){ // call the check method env.__cache[key] = result; callback.call(self, result); }); return; }; // debug flag if(qx.Bootstrap.DEBUG){ qx.Bootstrap.warn(key + " is not a valid key. Please see the API-doc of " + "qx.core.Environment for a list of predefined keys."); qx.Bootstrap.trace(this); }; }, /** * Returns the proper value dependent on the check for the given key. * * @param key {String} The name of the check the select depends on. * @param values {Map} A map containing the values which should be returned * in any case. The "default" key could be used as a catch all statement. * @return {var} The value which is stored in the map for the given * check of the key. */ select : function(key, values){ return this.__pickFromValues(this.get(key), values); }, /** * Selects the proper function dependent on the asynchronous check. * * @param key {String} The key for the async check. * @param values {Map} A map containing functions. The map keys should * contain all possibilities which could be returned by the given check * key. The "default" key could be used as a catch all statement. * The called function will get one parameter, the result of the query. * @param self {var} The context which should be used when calling the * method in the values map. */ selectAsync : function(key, values, self){ this.getAsync(key, function(result){ var value = this.__pickFromValues(key, values); value.call(self, result); }, this); }, /** * Internal helper which tries to pick the given key from the given values * map. If that key is not found, it tries to use a key named "default". * If there is also no default key, it prints out a warning and returns * undefined. * * @param key {String} The key to search for in the values. * @param values {Map} A map containing some keys. * @return {var} The value stored as values[key] usually. */ __pickFromValues : function(key, values){ var value = values[key]; if(values.hasOwnProperty(key)){ return value; }; // check for piped values for(var id in values){ if(id.indexOf("|") != -1){ var ids = id.split("|"); for(var i = 0;i < ids.length;i++){ if(ids[i] == key){ return values[id]; }; }; }; }; if(values["default"] !== undefined){ return values["default"]; }; if(qx.Bootstrap.DEBUG){ throw new Error('No match for variant "' + key + '" (' + (typeof key) + ' type)' + ' in variants [' + qx.Bootstrap.keys(values) + '] found, and no default ("default") given'); }; }, /** * Takes a given map containing the check names as keys and converts * the map to an array only containing the values for check evaluating * to <code>true</code>. This is especially handy for conditional * includes of mixins. * @param map {Map} A map containing check names as keys and values. * @return {Array} An array containing the values. */ filter : function(map){ var returnArray = []; for(var check in map){ if(this.get(check)){ returnArray.push(map[check]); }; }; return returnArray; }, /** * Invalidates the cache for the given key. * * @param key {String} The key of the check. */ invalidateCacheKey : function(key){ delete this.__cache[key]; }, /** * Add a check to the environment class. If there is already a check * added for the given key, the add will be ignored. * * @param key {String} The key for the check e.g. html.featurexyz. * @param check {var} It could be either a function or a simple value. * The function should be responsible for the check and should return the * result of the check. */ add : function(key, check){ // ignore already added checks. if(this._checks[key] == undefined){ // add functions directly if(check instanceof Function){ this._checks[key] = check; } else { this._checks[key] = this.__createCheck(check); }; }; }, /** * Adds an asynchronous check to the environment. If there is already a check * added for the given key, the add will be ignored. * * @param key {String} The key of the check e.g. html.featureabc * @param check {Function} A function which should check for a specific * environment setting in an asynchronous way. The method should take two * arguments. First one is the callback and the second one is the context. */ addAsync : function(key, check){ if(this._checks[key] == undefined){ this._asyncChecks[key] = check; }; }, /** * Returns all currently defined synchronous checks. * * @internal * @return {Map} The map of synchronous checks */ getChecks : function(){ return this._checks; }, /** * Returns all currently defined asynchronous checks. * * @internal * @return {Map} The map of asynchronous checks */ getAsyncChecks : function(){ return this._asyncChecks; }, /** * Initializer for the default values of the framework settings. */ _initDefaultQxValues : function(){ // an always-true key (e.g. for use in qx.core.Environment.filter() calls) this.add("true", function(){ return true; }); // old settings this.add("qx.allowUrlSettings", function(){ return false; }); this.add("qx.allowUrlVariants", function(){ return false; }); this.add("qx.debug.property.level", function(){ return 0; }); // old variants // make sure to reflect all changes to qx.debug here in the bootstrap class! this.add("qx.debug", function(){ return true; }); this.add("qx.debug.ui.queue", function(){ return true; }); this.add("qx.aspects", function(){ return false; }); this.add("qx.dynlocale", function(){ return true; }); this.add("qx.mobile.emulatetouch", function(){ return false; }); this.add("qx.mobile.nativescroll", function(){ return false; }); this.add("qx.blankpage", function(){ return "qx/static/blank.html"; }); this.add("qx.dynamicmousewheel", function(){ return true; }); this.add("qx.debug.databinding", function(){ return false; }); this.add("qx.debug.dispose", function(){ return false; }); // generator optimization vectors this.add("qx.optimization.basecalls", function(){ return false; }); this.add("qx.optimization.comments", function(){ return false; }); this.add("qx.optimization.privates", function(){ return false; }); this.add("qx.optimization.strings", function(){ return false; }); this.add("qx.optimization.variables", function(){ return false; }); this.add("qx.optimization.variants", function(){ return false; }); // qooxdoo modules this.add("module.databinding", function(){ return true; }); this.add("module.logger", function(){ return true; }); this.add("module.property", function(){ return true; }); this.add("module.events", function(){ return true; }); }, /** * Import checks from global qx.$$environment into the Environment class. */ __importFromGenerator : function(){ // import the environment map if(qx && qx.$$environment){ for(var key in qx.$$environment){ var value = qx.$$environment[key]; this._checks[key] = this.__createCheck(value); }; }; }, /** * Checks the URL for environment settings and imports these into the * Environment class. */ __importFromUrl : function(){ if(window.document && window.document.location){ var urlChecks = window.document.location.search.slice(1).split("&"); for(var i = 0;i < urlChecks.length;i++){ var check = urlChecks[i].split(":"); if(check.length != 3 || check[0] != "qxenv"){ continue; }; var key = check[1]; var value = decodeURIComponent(check[2]); // implicit type conversion if(value == "true"){ value = true; } else if(value == "false"){ value = false; } else if(/^(\d|\.)+$/.test(value)){ value = parseFloat(value); };; this._checks[key] = this.__createCheck(value); }; }; }, /** * Internal helper which creates a function returning the given value. * * @param value {var} The value which should be returned. * @return {Function} A function which could be used by a test. */ __createCheck : function(value){ return qx.Bootstrap.bind(function(value){ return value; }, null, value); } }, defer : function(statics){ // create default values for the environment class statics._initDefaultQxValues(); // load the checks from the generator statics.__importFromGenerator(); // load the checks from the url if(statics.get("qx.allowUrlSettings") === true){ statics.__importFromUrl(); }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Martin Wittemann (martinwittemann) ====================================================================== This class contains code from: Copyright: 2011 Pocket Widget S.L., Spain, http://www.pocketwidget.com License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php Authors: * Javier Martinez Villacampa ************************************************************************ */ /** * This class comes with all relevant information regarding * the client's engine. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.Engine", { // General: http://en.wikipedia.org/wiki/Browser_timeline // Webkit: http://developer.apple.com/internet/safari/uamatrix.html // Firefox: http://en.wikipedia.org/wiki/History_of_Mozilla_Firefox // Maple: http://www.scribd.com/doc/46675822/2011-SDK2-0-Maple-Browser-Specification-V1-00 statics : { /** * Returns the version of the engine. * * @return {String} The version number of the current engine. * @internal */ getVersion : function(){ var agent = window.navigator.userAgent; var version = ""; if(qx.bom.client.Engine.__isOpera()){ // Opera has a special versioning scheme, where the second part is combined // e.g. 8.54 which should be handled like 8.5.4 to be compatible to the // common versioning system used by other browsers if(/Opera[\s\/]([0-9]+)\.([0-9])([0-9]*)/.test(agent)){ // opera >= 10 has as a first verison 9.80 and adds the proper version // in a separate "Version/" postfix // http://my.opera.com/chooseopera/blog/2009/05/29/changes-in-operas-user-agent-string-format if(agent.indexOf("Version/") != -1){ var match = agent.match(/Version\/(\d+)\.(\d+)/); // ignore the first match, its the whole version string version = match[1] + "." + match[2].charAt(0) + "." + match[2].substring(1, match[2].length); } else { version = RegExp.$1 + "." + RegExp.$2; if(RegExp.$3 != ""){ version += "." + RegExp.$3; }; }; }; } else if(qx.bom.client.Engine.__isWebkit()){ if(/AppleWebKit\/([^ ]+)/.test(agent)){ version = RegExp.$1; // We need to filter these invalid characters var invalidCharacter = RegExp("[^\\.0-9]").exec(version); if(invalidCharacter){ version = version.slice(0, invalidCharacter.index); }; }; } else if(qx.bom.client.Engine.__isGecko() || qx.bom.client.Engine.__isMaple()){ // Parse "rv" section in user agent string if(/rv\:([^\);]+)(\)|;)/.test(agent)){ version = RegExp.$1; }; } else if(qx.bom.client.Engine.__isMshtml()){ if(/MSIE\s+([^\);]+)(\)|;)/.test(agent)){ version = RegExp.$1; // If the IE8 or IE9 is running in the compatibility mode, the MSIE value // is set to an older version, but we need the correct version. The only // way is to compare the trident version. if(version < 8 && /Trident\/([^\);]+)(\)|;)/.test(agent)){ if(RegExp.$1 == "4.0"){ version = "8.0"; } else if(RegExp.$1 == "5.0"){ version = "9.0"; }; }; }; } else { var failFunction = window.qxFail; if(failFunction && typeof failFunction === "function"){ version = failFunction().FULLVERSION; } else { version = "1.9.0.0"; qx.Bootstrap.warn("Unsupported client: " + agent + "! Assumed gecko version 1.9.0.0 (Firefox 3.0)."); }; };;; return version; }, /** * Returns the name of the engine. * * @return {String} The name of the current engine. * @internal */ getName : function(){ var name; if(qx.bom.client.Engine.__isOpera()){ name = "opera"; } else if(qx.bom.client.Engine.__isWebkit()){ name = "webkit"; } else if(qx.bom.client.Engine.__isGecko() || qx.bom.client.Engine.__isMaple()){ name = "gecko"; } else if(qx.bom.client.Engine.__isMshtml()){ name = "mshtml"; } else { // check for the fallback var failFunction = window.qxFail; if(failFunction && typeof failFunction === "function"){ name = failFunction().NAME; } else { name = "gecko"; qx.Bootstrap.warn("Unsupported client: " + window.navigator.userAgent + "! Assumed gecko version 1.9.0.0 (Firefox 3.0)."); }; };;; return name; }, /** * Internal helper for checking for opera. * @return {Boolean} true, if its opera. */ __isOpera : function(){ return window.opera && Object.prototype.toString.call(window.opera) == "[object Opera]"; }, /** * Internal helper for checking for webkit. * @return {Boolean} true, if its webkit. */ __isWebkit : function(){ return window.navigator.userAgent.indexOf("AppleWebKit/") != -1; }, /** * Internal helper for checking for Maple . * Maple is used in Samsung SMART TV 2010-2011 models. It's based on Gecko * engine 1.8.1.11. * @return {Boolean} true, if its maple. */ __isMaple : function(){ return window.navigator.userAgent.indexOf("Maple") != -1; }, /** * Internal helper for checking for gecko. * @return {Boolean} true, if its gecko. */ __isGecko : function(){ return window.controllers && window.navigator.product === "Gecko" && window.navigator.userAgent.indexOf("Maple") == -1; }, /** * Internal helper to check for MSHTML. * @return {Boolean} true, if its MSHTML. */ __isMshtml : function(){ return window.navigator.cpuClass && /MSIE\s+([^\);]+)(\)|;)/.test(window.navigator.userAgent); } }, defer : function(statics){ qx.core.Environment.add("engine.version", statics.getVersion); qx.core.Environment.add("engine.name", statics.getName); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * The main purpose of this class to hold all checks about ECMAScript. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.EcmaScript", { statics : { /** * Returns the name of the Error object property that holds stack trace * information or null if the client does not provide any. * * @internal * @return {String|null} <code>stack</code>, <code>stacktrace</code> or * <code>null</code> */ getStackTrace : function(){ var propName; var e = new Error("e"); propName = e.stack ? "stack" : e.stacktrace ? "stacktrace" : null; // only thrown errors have the stack property in IE10 and PhantomJS if(!propName){ try{ throw e; } catch(ex) { e = ex; }; }; return e.stacktrace ? "stacktrace" : e.stack ? "stack" : null; }, /** * Checks if 'indexOf' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayIndexOf : function(){ return !!Array.prototype.indexOf; }, /** * Checks if 'lastIndexOf' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayLastIndexOf : function(){ return !!Array.prototype.lastIndexOf; }, /** * Checks if 'forEach' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayForEach : function(){ return !!Array.prototype.forEach; }, /** * Checks if 'filter' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayFilter : function(){ return !!Array.prototype.filter; }, /** * Checks if 'map' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayMap : function(){ return !!Array.prototype.map; }, /** * Checks if 'some' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArraySome : function(){ return !!Array.prototype.some; }, /** * Checks if 'every' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayEvery : function(){ return !!Array.prototype.every; }, /** * Checks if 'reduce' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayReduce : function(){ return !!Array.prototype.reduce; }, /** * Checks if 'reduceRight' is supported on the Array object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getArrayReduceRight : function(){ return !!Array.prototype.reduceRight; }, /** * Checks if 'toString' is supported on the Error object and * its working as expected. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getErrorToString : function(){ return typeof Error.prototype.toString == "function" && Error.prototype.toString() !== "[object Error]"; }, /** * Checks if 'bind' is supported on the Function object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getFunctionBind : function(){ return typeof Function.prototype.bind === "function"; }, /** * Checks if 'keys' is supported on the Object object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getObjectKeys : function(){ return !!Object.keys; }, /** * Checks if 'now' is supported on the Date object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getDateNow : function(){ return !!Date.now; }, /** * Checks if 'trim' is supported on the String object. * @internal * @return {Boolean} <code>true</code>, if the method is available. */ getStringTrim : function(){ return typeof String.prototype.trim === "function"; } }, defer : function(statics){ // array polyfill qx.core.Environment.add("ecmascript.array.indexof", statics.getArrayIndexOf); qx.core.Environment.add("ecmascript.array.lastindexof", statics.getArrayLastIndexOf); qx.core.Environment.add("ecmascript.array.foreach", statics.getArrayForEach); qx.core.Environment.add("ecmascript.array.filter", statics.getArrayFilter); qx.core.Environment.add("ecmascript.array.map", statics.getArrayMap); qx.core.Environment.add("ecmascript.array.some", statics.getArraySome); qx.core.Environment.add("ecmascript.array.every", statics.getArrayEvery); qx.core.Environment.add("ecmascript.array.reduce", statics.getArrayReduce); qx.core.Environment.add("ecmascript.array.reduceright", statics.getArrayReduceRight); // date polyfill qx.core.Environment.add("ecmascript.date.now", statics.getDateNow); // error bugfix qx.core.Environment.add("ecmascript.error.toString", statics.getErrorToString); qx.core.Environment.add("ecmascript.error.stacktrace", statics.getStackTrace); // function polyfill qx.core.Environment.add("ecmascript.function.bind", statics.getFunctionBind); // object polyfill qx.core.Environment.add("ecmascript.object.keys", statics.getObjectKeys); // string polyfill qx.core.Environment.add("ecmascript.string.trim", statics.getStringTrim); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This class takes care of the normalization of the native 'Array' object. * Therefore it checks the availability of the following methods and appends * it, if not available. This means you can use the methods during * development in every browser. For usage samples, check out the attached links. * * *indexOf*: * <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.14">Annotated ES5 Spec</a> * * *lastIndexOf*: * <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.15">Annotated ES5 Spec</a> * * *forEach*: * <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.18">Annotated ES5 Spec</a> * * *filter*: * <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.20">Annotated ES5 Spec</a> * * *map*: * <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.19">Annotated ES5 Spec</a> * * *some*: * <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.17">Annotated ES5 Spec</a> * * *every*: * <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.16">Annotated ES5 Spec</a> * * *reduce*: * <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.21">Annotated ES5 Spec</a> * * *reduceRight*: * <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduceRight">MDN documentation</a> | * <a href="http://es5.github.com/#x15.4.4.22">Annotated ES5 Spec</a> * * Here is a little sample of how to use <code>indexOf</code> e.g. * <pre class="javascript">var a = ["a", "b", "c"]; * a.indexOf("b"); // returns 1</pre> */ qx.Bootstrap.define("qx.lang.normalize.Array", { defer : function(){ // fix indexOf if(!qx.core.Environment.get("ecmascript.array.indexof")){ Array.prototype.indexOf = function(searchElement, fromIndex){ if(fromIndex == null){ fromIndex = 0; } else if(fromIndex < 0){ fromIndex = Math.max(0, this.length + fromIndex); }; for(var i = fromIndex;i < this.length;i++){ if(this[i] === searchElement){ return i; }; }; return -1; }; }; // lastIndexOf if(!qx.core.Environment.get("ecmascript.array.lastindexof")){ Array.prototype.lastIndexOf = function(searchElement, fromIndex){ if(fromIndex == null){ fromIndex = this.length - 1; } else if(fromIndex < 0){ fromIndex = Math.max(0, this.length + fromIndex); }; for(var i = fromIndex;i >= 0;i--){ if(this[i] === searchElement){ return i; }; }; return -1; }; }; // forEach if(!qx.core.Environment.get("ecmascript.array.foreach")){ Array.prototype.forEach = function(callback, obj){ var l = this.length; for(var i = 0;i < l;i++){ var value = this[i]; if(value !== undefined){ callback.call(obj || window, value, i, this); }; }; }; }; // filter if(!qx.core.Environment.get("ecmascript.array.filter")){ Array.prototype.filter = function(callback, obj){ var res = []; var l = this.length; for(var i = 0;i < l;i++){ var value = this[i]; if(value !== undefined){ if(callback.call(obj || window, value, i, this)){ res.push(this[i]); }; }; }; return res; }; }; // map if(!qx.core.Environment.get("ecmascript.array.map")){ Array.prototype.map = function(callback, obj){ var res = []; var l = this.length; for(var i = 0;i < l;i++){ var value = this[i]; if(value !== undefined){ res[i] = callback.call(obj || window, value, i, this); }; }; return res; }; }; // some if(!qx.core.Environment.get("ecmascript.array.some")){ Array.prototype.some = function(callback, obj){ var l = this.length; for(var i = 0;i < l;i++){ var value = this[i]; if(value !== undefined){ if(callback.call(obj || window, value, i, this)){ return true; }; }; }; return false; }; }; // every if(!qx.core.Environment.get("ecmascript.array.every")){ Array.prototype.every = function(callback, obj){ var l = this.length; for(var i = 0;i < l;i++){ var value = this[i]; if(value !== undefined){ if(!callback.call(obj || window, value, i, this)){ return false; }; }; }; return true; }; }; // reduce if(!qx.core.Environment.get("ecmascript.array.reduce")){ Array.prototype.reduce = function(callback, init){ if(typeof callback !== "function"){ throw new TypeError("First argument is not callable"); }; if(init === undefined && this.length === 0){ throw new TypeError("Length is 0 and no second argument given"); }; var ret = init === undefined ? this[0] : init; for(var i = init === undefined ? 1 : 0;i < this.length;i++){ if(i in this){ ret = callback.call(undefined, ret, this[i], i, this); }; }; return ret; }; }; // reduceRight if(!qx.core.Environment.get("ecmascript.array.reduceright")){ Array.prototype.reduceRight = function(callback, init){ if(typeof callback !== "function"){ throw new TypeError("First argument is not callable"); }; if(init === undefined && this.length === 0){ throw new TypeError("Length is 0 and no second argument given"); }; var ret = init === undefined ? this[this.length - 1] : init; for(var i = init === undefined ? this.length - 2 : this.length - 1;i >= 0;i--){ if(i in this){ ret = callback.call(undefined, ret, this[i], i, this); }; }; return ret; }; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2007-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ====================================================================== This class uses ideas and code snipplets presented at http://webreflection.blogspot.com/2008/05/habemus-array-unlocked-length-in-ie8.html http://webreflection.blogspot.com/2008/05/stack-and-arrayobject-how-to-create.html Author: Andrea Giammarchi License: MIT: http://www.opensource.org/licenses/mit-license.php ====================================================================== This class uses documentation of the native Array methods from the MDC documentation of Mozilla. License: CC Attribution-Sharealike License: http://creativecommons.org/licenses/by-sa/2.5/ ************************************************************************ */ /* ************************************************************************ #require(qx.bom.client.Engine) #require(qx.lang.normalize.Array) ************************************************************************ */ /** * This class is the common superclass for most array classes in * qooxdoo. It supports all of the shiny 1.6 JavaScript array features * like <code>forEach</code> and <code>map</code>. * * This class may be instantiated instead of the native Array if * one wants to work with a feature-unified Array instead of the native * one. This class uses native features whereever possible but fills * all missing implementations with custom ones. * * Through the ability to extend from this class one could add even * more utility features on top of it. */ qx.Bootstrap.define("qx.type.BaseArray", { extend : Array, /* ***************************************************************************** CONSTRUCTOR ***************************************************************************** */ /** * Creates a new Array with the given length or the listed elements. * * <pre class="javascript"> * var arr1 = new qx.type.BaseArray(arrayLength); * var arr2 = new qx.type.BaseArray(item0, item1, ..., itemN); * </pre> * * * <code>arrayLength</code>: The initial length of the array. You can access * this value using the length property. If the value specified is not a * number, an array of length 1 is created, with the first element having * the specified value. The maximum length allowed for an * array is 2^32-1, i.e. 4,294,967,295. * * <code>itemN</code>: A value for the element in that position in the * array. When this form is used, the array is initialized with the specified * values as its elements, and the array's length property is set to the * number of arguments. * * @param length_or_items {Integer|var?null} The initial length of the array * OR an argument list of values. */ construct : function(length_or_items){ }, /* ***************************************************************************** MEMBERS ***************************************************************************** */ members : { /** * Converts a base array to a native Array * * @signature function() * @return {Array} The native array */ toArray : null, /** * Returns the current number of items stored in the Array * * @signature function() * @return {Integer} number of items */ valueOf : null, /** * Removes the last element from an array and returns that element. * * This method modifies the array. * * @signature function() * @return {var} The last element of the array. */ pop : null, /** * Adds one or more elements to the end of an array and returns the new length of the array. * * This method modifies the array. * * @signature function(varargs) * @param varargs {var} The elements to add to the end of the array. * @return {Integer} The new array's length */ push : null, /** * Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first. * * This method modifies the array. * * @signature function() * @return {Array} Returns the modified array (works in place) */ reverse : null, /** * Removes the first element from an array and returns that element. * * This method modifies the array. * * @signature function() * @return {var} The first element of the array. */ shift : null, /** * Sorts the elements of an array. * * This method modifies the array. * * @signature function(compareFunction) * @param compareFunction {Function?null} Specifies a function that defines the sort order. If omitted, * the array is sorted lexicographically (in dictionary order) according to the string conversion of each element. * @return {Array} Returns the modified array (works in place) */ sort : null, /** * Adds and/or removes elements from an array. * * @signature function(index, howMany, varargs) * @param index {Integer} Index at which to start changing the array. If negative, will begin * that many elements from the end. * @param howMany {Integer} An integer indicating the number of old array elements to remove. * If <code>howMany</code> is 0, no elements are removed. In this case, you should specify * at least one new element. * @param varargs {var?null} The elements to add to the array. If you don't specify any elements, * splice simply removes elements from the array. * @return {BaseArray} New array with the removed elements. */ splice : null, /** * Adds one or more elements to the front of an array and returns the new length of the array. * * This method modifies the array. * * @signature function(varargs) * @param varargs {var} The elements to add to the front of the array. * @return {Integer} The new array's length */ unshift : null, /** * Returns a new array comprised of this array joined with other array(s) and/or value(s). * * This method does not modify the array and returns a modified copy of the original. * * @signature function(varargs) * @param varargs {Array|var} Arrays and/or values to concatenate to the resulting array. * @return {qx.type.BaseArray} New array built of the given arrays or values. */ concat : null, /** * Joins all elements of an array into a string. * * @signature function(separator) * @param separator {String} Specifies a string to separate each element of the array. The separator is * converted to a string if necessary. If omitted, the array elements are separated with a comma. * @return {String} The stringified values of all elements divided by the given separator. */ join : null, /** * Extracts a section of an array and returns a new array. * * @signature function(begin, end) * @param begin {Integer} Zero-based index at which to begin extraction. As a negative index, start indicates * an offset from the end of the sequence. slice(-2) extracts the second-to-last element and the last element * in the sequence. * @param end {Integer?length} Zero-based index at which to end extraction. slice extracts up to but not including end. * <code>slice(1,4)</code> extracts the second element through the fourth element (elements indexed 1, 2, and 3). * As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. * If end is omitted, slice extracts to the end of the sequence. * @return {BaseArray} An new array which contains a copy of the given region. */ slice : null, /** * Returns a string representing the array and its elements. Overrides the Object.prototype.toString method. * * @signature function() * @return {String} The string representation of the array. */ toString : null, /** * Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. * * @signature function(searchElement, fromIndex) * @param searchElement {var} Element to locate in the array. * @param fromIndex {Integer?0} The index at which to begin the search. Defaults to 0, i.e. the * whole array will be searched. If the index is greater than or equal to the length of the * array, -1 is returned, i.e. the array will not be searched. If negative, it is taken as * the offset from the end of the array. Note that even when the index is negative, the array * is still searched from front to back. If the calculated index is less than 0, the whole * array will be searched. * @return {Integer} The index of the given element */ indexOf : null, /** * Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found. * * @signature function(searchElement, fromIndex) * @param searchElement {var} Element to locate in the array. * @param fromIndex {Integer?length} The index at which to start searching backwards. Defaults to * the array's length, i.e. the whole array will be searched. If the index is greater than * or equal to the length of the array, the whole array will be searched. If negative, it * is taken as the offset from the end of the array. Note that even when the index is * negative, the array is still searched from back to front. If the calculated index is * less than 0, -1 is returned, i.e. the array will not be searched. * @return {Integer} The index of the given element */ lastIndexOf : null, /** * Executes a provided function once per array element. * * <code>forEach</code> executes the provided function (<code>callback</code>) once for each * element present in the array. <code>callback</code> is invoked only for indexes of the array * which have assigned values; it is not invoked for indexes which have been deleted or which * have never been assigned values. * * <code>callback</code> is invoked with three arguments: the value of the element, the index * of the element, and the Array object being traversed. * * If a <code>obj</code> parameter is provided to <code>forEach</code>, it will be used * as the <code>this</code> for each invocation of the <code>callback</code>. If it is not * provided, or is <code>null</code>, the global object associated with <code>callback</code> * is used instead. * * <code>forEach</code> does not mutate the array on which it is called. * * The range of elements processed by <code>forEach</code> is set before the first invocation of * <code>callback</code>. Elements which are appended to the array after the call to * <code>forEach</code> begins will not be visited by <code>callback</code>. If existing elements * of the array are changed, or deleted, their value as passed to <code>callback</code> will be * the value at the time <code>forEach</code> visits them; elements that are deleted are not visited. * * @signature function(callback, obj) * @param callback {Function} Function to execute for each element. * @param obj {Object} Object to use as this when executing callback. */ forEach : null, /** * Creates a new array with all elements that pass the test implemented by the provided * function. * * <code>filter</code> calls a provided <code>callback</code> function once for each * element in an array, and constructs a new array of all the values for which * <code>callback</code> returns a true value. <code>callback</code> is invoked only * for indexes of the array which have assigned values; it is not invoked for indexes * which have been deleted or which have never been assigned values. Array elements which * do not pass the <code>callback</code> test are simply skipped, and are not included * in the new array. * * <code>callback</code> is invoked with three arguments: the value of the element, the * index of the element, and the Array object being traversed. * * If a <code>obj</code> parameter is provided to <code>filter</code>, it will * be used as the <code>this</code> for each invocation of the <code>callback</code>. * If it is not provided, or is <code>null</code>, the global object associated with * <code>callback</code> is used instead. * * <code>filter</code> does not mutate the array on which it is called. The range of * elements processed by <code>filter</code> is set before the first invocation of * <code>callback</code>. Elements which are appended to the array after the call to * <code>filter</code> begins will not be visited by <code>callback</code>. If existing * elements of the array are changed, or deleted, their value as passed to <code>callback</code> * will be the value at the time <code>filter</code> visits them; elements that are deleted * are not visited. * * @signature function(callback, obj) * @param callback {Function} Function to test each element of the array. * @param obj {Object} Object to use as <code>this</code> when executing <code>callback</code>. * @return {BaseArray} The newly created array with all matching elements */ filter : null, /** * Creates a new array with the results of calling a provided function on every element in this array. * * <code>map</code> calls a provided <code>callback</code> function once for each element in an array, * in order, and constructs a new array from the results. <code>callback</code> is invoked only for * indexes of the array which have assigned values; it is not invoked for indexes which have been * deleted or which have never been assigned values. * * <code>callback</code> is invoked with three arguments: the value of the element, the index of the * element, and the Array object being traversed. * * If a <code>obj</code> parameter is provided to <code>map</code>, it will be used as the * <code>this</code> for each invocation of the <code>callback</code>. If it is not provided, or is * <code>null</code>, the global object associated with <code>callback</code> is used instead. * * <code>map</code> does not mutate the array on which it is called. * * The range of elements processed by <code>map</code> is set before the first invocation of * <code>callback</code>. Elements which are appended to the array after the call to <code>map</code> * begins will not be visited by <code>callback</code>. If existing elements of the array are changed, * or deleted, their value as passed to <code>callback</code> will be the value at the time * <code>map</code> visits them; elements that are deleted are not visited. * * @signature function(callback, obj) * @param callback {Function} Function produce an element of the new Array from an element of the current one. * @param obj {Object} Object to use as <code>this</code> when executing <code>callback</code>. * @return {BaseArray} A new array which contains the return values of every item executed through the given function */ map : null, /** * Tests whether some element in the array passes the test implemented by the provided function. * * <code>some</code> executes the <code>callback</code> function once for each element present in * the array until it finds one where <code>callback</code> returns a true value. If such an element * is found, <code>some</code> immediately returns <code>true</code>. Otherwise, <code>some</code> * returns <code>false</code>. <code>callback</code> is invoked only for indexes of the array which * have assigned values; it is not invoked for indexes which have been deleted or which have never * been assigned values. * * <code>callback</code> is invoked with three arguments: the value of the element, the index of the * element, and the Array object being traversed. * * If a <code>obj</code> parameter is provided to <code>some</code>, it will be used as the * <code>this</code> for each invocation of the <code>callback</code>. If it is not provided, or is * <code>null</code>, the global object associated with <code>callback</code> is used instead. * * <code>some</code> does not mutate the array on which it is called. * * The range of elements processed by <code>some</code> is set before the first invocation of * <code>callback</code>. Elements that are appended to the array after the call to <code>some</code> * begins will not be visited by <code>callback</code>. If an existing, unvisited element of the array * is changed by <code>callback</code>, its value passed to the visiting <code>callback</code> will * be the value at the time that <code>some</code> visits that element's index; elements that are * deleted are not visited. * * @signature function(callback, obj) * @param callback {Function} Function to test for each element. * @param obj {Object} Object to use as <code>this</code> when executing <code>callback</code>. * @return {Boolean} Whether at least one elements passed the test */ some : null, /** * Tests whether all elements in the array pass the test implemented by the provided function. * * <code>every</code> executes the provided <code>callback</code> function once for each element * present in the array until it finds one where <code>callback</code> returns a false value. If * such an element is found, the <code>every</code> method immediately returns <code>false</code>. * Otherwise, if <code>callback</code> returned a true value for all elements, <code>every</code> * will return <code>true</code>. <code>callback</code> is invoked only for indexes of the array * which have assigned values; it is not invoked for indexes which have been deleted or which have * never been assigned values. * * <code>callback</code> is invoked with three arguments: the value of the element, the index of * the element, and the Array object being traversed. * * If a <code>obj</code> parameter is provided to <code>every</code>, it will be used as * the <code>this</code> for each invocation of the <code>callback</code>. If it is not provided, * or is <code>null</code>, the global object associated with <code>callback</code> is used instead. * * <code>every</code> does not mutate the array on which it is called. The range of elements processed * by <code>every</code> is set before the first invocation of <code>callback</code>. Elements which * are appended to the array after the call to <code>every</code> begins will not be visited by * <code>callback</code>. If existing elements of the array are changed, their value as passed * to <code>callback</code> will be the value at the time <code>every</code> visits them; elements * that are deleted are not visited. * * @signature function(callback, obj) * @param callback {Function} Function to test for each element. * @param obj {Object} Object to use as <code>this</code> when executing <code>callback</code>. * @return {Boolean} Whether all elements passed the test */ every : null } }); (function(){ function createStackConstructor(stack){ // In IE don't inherit from Array but use an empty object as prototype // and copy the methods from Array if((qx.core.Environment.get("engine.name") == "mshtml")){ Stack.prototype = { length : 0, $$isArray : true }; var args = "pop.push.reverse.shift.sort.splice.unshift.join.slice".split("."); for(var length = args.length;length;){ Stack.prototype[args[--length]] = Array.prototype[args[length]]; }; }; // Remember Array's slice method var slice = Array.prototype.slice; // Fix "concat" method Stack.prototype.concat = function(){ var constructor = this.slice(0); for(var i = 0,length = arguments.length;i < length;i++){ var copy; if(arguments[i] instanceof Stack){ copy = slice.call(arguments[i], 0); } else if(arguments[i] instanceof Array){ copy = arguments[i]; } else { copy = [arguments[i]]; }; constructor.push.apply(constructor, copy); }; return constructor; }; // Fix "toString" method Stack.prototype.toString = function(){ return slice.call(this, 0).toString(); }; // Fix "toLocaleString" Stack.prototype.toLocaleString = function(){ return slice.call(this, 0).toLocaleString(); }; // Fix constructor Stack.prototype.constructor = Stack; // Add JS 1.6 Array features Stack.prototype.indexOf = Array.prototype.indexOf; Stack.prototype.lastIndexOf = Array.prototype.lastIndexOf; Stack.prototype.forEach = Array.prototype.forEach; Stack.prototype.some = Array.prototype.some; Stack.prototype.every = Array.prototype.every; var filter = Array.prototype.filter; var map = Array.prototype.map; // Fix methods which generates a new instance // to return an instance of the same class Stack.prototype.filter = function(){ var ret = new this.constructor; ret.push.apply(ret, filter.apply(this, arguments)); return ret; }; Stack.prototype.map = function(){ var ret = new this.constructor; ret.push.apply(ret, map.apply(this, arguments)); return ret; }; Stack.prototype.slice = function(){ var ret = new this.constructor; ret.push.apply(ret, Array.prototype.slice.apply(this, arguments)); return ret; }; Stack.prototype.splice = function(){ var ret = new this.constructor; ret.push.apply(ret, Array.prototype.splice.apply(this, arguments)); return ret; }; // Add new "toArray" method for convert a base array to a native Array Stack.prototype.toArray = function(){ return Array.prototype.slice.call(this, 0); }; // Add valueOf() to return the length Stack.prototype.valueOf = function(){ return this.length; }; // Return final class return Stack; }; function Stack(length){ if(arguments.length === 1 && typeof length === "number"){ this.length = -1 < length && length === length >> .5 ? length : this.push(length); } else if(arguments.length){ this.push.apply(this, arguments); }; }; function PseudoArray(){ }; PseudoArray.prototype = []; Stack.prototype = new PseudoArray; Stack.prototype.length = 0; qx.type.BaseArray = createStackConstructor(Stack); })(); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #ignore(q) ************************************************************************ */ /** * The Core module's responsibility is to query the DOM for elements and offer * these elements as a collection. The Core module itself does not offer any methods to * work with the collection. These methods are added by the other included modules, * such as Manipulating or Attributes. * * Core also provides the plugin API which allows modules to attach either * static functions to the global <code>q</code> object or define methods on the * collection it returns. * * By default, the core module is assigned to a global module named <code>q</code>. * In case <code>q</code> is already defined, the name <code>qxWeb</code> * is used instead. * * For further details, take a look at the documentation in the * <a href='http://manual.qooxdoo.org/${qxversion}/pages/website.html' target='_blank'>user manual</a>. */ qx.Bootstrap.define("qxWeb", { extend : qx.type.BaseArray, statics : { // internal storage for all initializers __init : [], // internal reference to the used qx namespace $$qx : qx, /** * Internal helper to initialize collections. * * @param arg {var} An array of Elements which will * be initialized as {@link q}. All items in the array which are not * either a window object or a node object will be ignored. * @return {q} A new initialized collection. */ $init : function(arg){ var clean = []; for(var i = 0;i < arg.length;i++){ var isNode = !!(arg[i] && arg[i].nodeType != null); if(isNode){ clean.push(arg[i]); continue; }; var isWindow = !!(arg[i] && arg[i].history && arg[i].location && arg[i].document); if(isWindow){ clean.push(arg[i]); }; }; // check for node or window object var col = qx.lang.Array.cast(clean, qxWeb); for(var i = 0;i < qxWeb.__init.length;i++){ qxWeb.__init[i].call(col); }; return col; }, /** * This is an API for module development and can be used to attach new methods * to {@link q}. * * @param module {Map} A map containing the methods to attach. */ $attach : function(module){ for(var name in module){ { }; qxWeb.prototype[name] = module[name]; }; }, /** * This is an API for module development and can be used to attach new methods * to {@link q}. * * @param module {Map} A map containing the methods to attach. */ $attachStatic : function(module){ for(var name in module){ { }; qxWeb[name] = module[name]; }; }, /** * This is an API for module development and can be used to attach new initialization * methods to {@link q} which will be called when a new collection is * created. * * @param init {Function} The initialization method for a module. */ $attachInit : function(init){ this.__init.push(init); }, /** * Define a new class using the qooxdoo class system. * * @signature function(name, config) * @param name {String?} Name of the class. If null, the class will not be * attached to a namespace. * @param config {Map} Class definition structure. * @return {Function} The defined class. */ define : function(name, config){ if(config == undefined){ config = name; name = null; }; return qx.Bootstrap.define.call(qx.Bootstrap, name, config); } }, /** * Accepts a selector string and returns a set of found items. The optional context * element can be used to reduce the amount of found elements to children of the * context element. * * <a href="http://sizzlejs.com/" target="_blank">Sizzle</a> is used as selector engine. * Check out the <a href="https://github.com/jquery/sizzle/wiki/Sizzle-Home" target="_blank">documentation</a> * for more details. * * @param selector {String|Element|Array} Valid selector (CSS3 + extensions) * or DOM element or Array of DOM Elements. * @param context {Element} Only the children of this element are considered. * @return {q} A collection of DOM elements. */ construct : function(selector, context){ if(!selector && this instanceof qxWeb){ return this; }; if(qx.Bootstrap.isString(selector)){ selector = qx.bom.Selector.query(selector, context); } else if(!(qx.Bootstrap.isArray(selector))){ selector = [selector]; }; return qxWeb.$init(selector); }, members : { /** * Gets a new collection containing only those elements that passed the * given filter. This can be either a selector expression or a filter * function. * * @param selector {String|Function} Selector expression or filter function * @return {q} New collection containing the elements that passed the filter */ filter : function(selector){ if(qx.lang.Type.isFunction(selector)){ return qxWeb.$init(Array.prototype.filter.call(this, selector)); }; return qxWeb.$init(qx.bom.Selector.matches(selector, this)); }, /** * Returns a copy of the collection within the given range. * * @param begin {Number} The index to begin. * @param end {Number?} The index to end. * @return {q} A new collection containing a slice of the original collection. */ slice : function(begin, end){ // Old IEs return an empty array if the second argument is undefined if(end){ return qxWeb.$init(Array.prototype.slice.call(this, begin, end)); } else { return qxWeb.$init(Array.prototype.slice.call(this, begin)); }; }, /** * Removes the given number of items and returns the removed items as a new collection. * This method can also add items. Take a look at the * <a href='https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice' target='_blank'>documentation of MDN</a> for more details. * * @param index {Number} The index to begin. * @param howMany {Number} the amount of items to remove. * @param varargs {var} As many items as you want to add. * @return {q} A new collection containing the removed items. */ splice : function(index, howMany, varargs){ return qxWeb.$init(Array.prototype.splice.apply(this, arguments)); }, /** * Returns a new collection containing the modified elements. For more details, check out the * <a href='https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map' target='_blank'>MDN documentation</a>. * * @param callback {Function} Function which produces the new element. * @param thisarg {var} Context of the callback. * @return {q} New collection containing the elements that passed the filter */ map : function(callback, thisarg){ return qxWeb.$init(Array.prototype.map.apply(this, arguments)); }, /** * Returns a copy of the collection including the given elements. * * @param varargs {var} As many items as you want to add. * @return {q} A new collection containing all items. */ concat : function(varargs){ var clone = Array.prototype.slice.call(this, 0); for(var i = 0;i < arguments.length;i++){ if(arguments[i] instanceof qxWeb){ clone = clone.concat(Array.prototype.slice.call(arguments[i], 0)); } else { clone.push(arguments[i]); }; }; return qxWeb.$init(clone); } }, /** * @lint ignoreUndefined(q) */ defer : function(statics){ if(window.q == undefined){ q = statics; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This class takes care of the normalization of the native 'Date' object. * Therefore it checks the availability of the following methods and appends * it, if not available. This means you can use the methods during * development in every browser. For usage samples, check out the attached links. * * *now*: * <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/now">MDN documentation</a> | * <a href="http://es5.github.com/#x15.9.4.4">Annotated ES5 Spec</a> */ qx.Bootstrap.define("qx.lang.normalize.Date", { defer : function(){ // Date.now if(!qx.core.Environment.get("ecmascript.date.now")){ Date.now = function(){ return +new Date(); }; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ====================================================================== This class contains code based on the following work: * jQuery http://jquery.com Version 1.3.1 Copyright: 2009 John Resig License: MIT: http://www.opensource.org/licenses/mit-license.php ************************************************************************ */ /* ************************************************************************ #ignore(qx.data.IListData) #ignore(qx.Class) #require(qx.lang.normalize.Date) ************************************************************************ */ /** * Static helper functions for arrays with a lot of often used convenience * methods like <code>remove</code> or <code>contains</code>. * * The native JavaScript Array is not modified by this class. However, * there are modifications to the native Array in {@link qx.lang.normalize.Array} for * browsers that do not support certain JavaScript features natively . */ qx.Bootstrap.define("qx.lang.Array", { statics : { /** * Converts array like constructions like the <code>argument</code> object, * node collections like the ones returned by <code>getElementsByTagName</code> * or extended array objects like <code>qx.type.BaseArray</code> to an * native Array instance. * * @deprecated {2.1} Please use cast with 'Array' as constructor. * @param object {var} any array like object * @param offset {Integer?0} position to start from * @return {Array} New array with the content of the incoming object */ toArray : function(object, offset){ { }; return this.cast(object, Array, offset); }, /** * Converts an array like object to any other array like * object. * * Attention: The returned array may be same * instance as the incoming one if the constructor is identical! * * @param object {var} any array-like object * @param constructor {Function} constructor of the new instance * @param offset {Integer?0} position to start from * @return {Array} the converted array */ cast : function(object, constructor, offset){ if(object.constructor === constructor){ return object; }; if(qx.data && qx.data.IListData){ if(qx.Class && qx.Class.hasInterface(object, qx.data.IListData)){ var object = object.toArray(); }; }; // Create from given constructor var ret = new constructor; // Some collections in mshtml are not able to be sliced. // These lines are a special workaround for this client. if((qx.core.Environment.get("engine.name") == "mshtml")){ if(object.item){ for(var i = offset || 0,l = object.length;i < l;i++){ ret.push(object[i]); }; return ret; }; }; // Copy over items if(Object.prototype.toString.call(object) === "[object Array]" && offset == null){ ret.push.apply(ret, object); } else { ret.push.apply(ret, Array.prototype.slice.call(object, offset || 0)); }; return ret; }, /** * Convert an arguments object into an array. * * @param args {arguments} arguments object * @param offset {Integer?0} position to start from * @return {Array} a newly created array (copy) with the content of the arguments object. */ fromArguments : function(args, offset){ return Array.prototype.slice.call(args, offset || 0); }, /** * Convert a (node) collection into an array * * @param coll {var} node collection * @return {Array} a newly created array (copy) with the content of the node collection. */ fromCollection : function(coll){ // The native Array.slice cannot be used with some Array-like objects // including NodeLists in older IEs if((qx.core.Environment.get("engine.name") == "mshtml")){ if(coll.item){ var arr = []; for(var i = 0,l = coll.length;i < l;i++){ arr[i] = coll[i]; }; return arr; }; }; return Array.prototype.slice.call(coll, 0); }, /** * Expand shorthand definition to a four element list. * This is an utility function for padding/margin and all other shorthand handling. * * @param input {Array} arr with one to four elements * @return {Array} an arr with four elements */ fromShortHand : function(input){ var len = input.length; var result = qx.lang.Array.clone(input); // Copy Values (according to the length) switch(len){case 1: result[1] = result[2] = result[3] = result[0]; break;case 2: result[2] = result[0];// no break here case 3: result[3] = result[1];}; // Return list with 4 items return result; }, /** * Return a copy of the given array * * @param arr {Array} the array to copy * @return {Array} copy of the array */ clone : function(arr){ return arr.concat(); }, /** * Insert an element at a given position into the array * * @param arr {Array} the array * @param obj {var} the element to insert * @param i {Integer} position where to insert the element into the array * @return {Array} the array */ insertAt : function(arr, obj, i){ arr.splice(i, 0, obj); return arr; }, /** * Insert an element into the array before a given second element. * * @param arr {Array} the array * @param obj {var} object to be inserted * @param obj2 {var} insert obj1 before this object * @return {Array} the array */ insertBefore : function(arr, obj, obj2){ var i = arr.indexOf(obj2); if(i == -1){ arr.push(obj); } else { arr.splice(i, 0, obj); }; return arr; }, /** * Insert an element into the array after a given second element. * * @param arr {Array} the array * @param obj {var} object to be inserted * @param obj2 {var} insert obj1 after this object * @return {Array} the array */ insertAfter : function(arr, obj, obj2){ var i = arr.indexOf(obj2); if(i == -1 || i == (arr.length - 1)){ arr.push(obj); } else { arr.splice(i + 1, 0, obj); }; return arr; }, /** * Remove an element from the array at the given index * * @param arr {Array} the array * @param i {Integer} index of the element to be removed * @return {var} The removed element. */ removeAt : function(arr, i){ return arr.splice(i, 1)[0]; }, /** * Remove all elements from the array * * @param arr {Array} the array * @return {Array} empty array */ removeAll : function(arr){ arr.length = 0; return this; }, /** * Append the elements of an array to the array * * @param arr1 {Array} the array * @param arr2 {Array} the elements of this array will be appended to other one * @return {Array} The modified array. * @throws {Error} if one of the arguments is not an array */ append : function(arr1, arr2){ { }; Array.prototype.push.apply(arr1, arr2); return arr1; }, /** * Modifies the first array as it removes all elements * which are listed in the second array as well. * * @param arr1 {Array} the array * @param arr2 {Array} the elements of this array will be excluded from the other one * @return {Array} The modified array. * @throws {Error} if one of the arguments is not an array */ exclude : function(arr1, arr2){ { }; for(var i = 0,il = arr2.length,index;i < il;i++){ index = arr1.indexOf(arr2[i]); if(index != -1){ arr1.splice(index, 1); }; }; return arr1; }, /** * Remove an element from the array. * * @param arr {Array} the array * @param obj {var} element to be removed from the array * @return {var} the removed element */ remove : function(arr, obj){ var i = arr.indexOf(obj); if(i != -1){ arr.splice(i, 1); return obj; }; }, /** * Whether the array contains the given element * * @param arr {Array} the array * @param obj {var} object to look for * @return {Boolean} whether the arr contains the element */ contains : function(arr, obj){ return arr.indexOf(obj) !== -1; }, /** * Check whether the two arrays have the same content. Checks only the * equality of the arrays' content. * * @param arr1 {Array} first array * @param arr2 {Array} second array * @return {Boolean} Whether the two arrays are equal */ equals : function(arr1, arr2){ var length = arr1.length; if(length !== arr2.length){ return false; }; for(var i = 0;i < length;i++){ if(arr1[i] !== arr2[i]){ return false; }; }; return true; }, /** * Returns the sum of all values in the given array. Supports * numeric values only. * * @param arr {Number[]} Array to process * @return {Number} The sum of all values. */ sum : function(arr){ var result = 0; for(var i = 0,l = arr.length;i < l;i++){ result += arr[i]; }; return result; }, /** * Returns the highest value in the given array. Supports * numeric values only. * * @param arr {Number[]} Array to process * @return {Number | null} The highest of all values or undefined if array is empty. */ max : function(arr){ { }; var i,len = arr.length,result = arr[0]; for(i = 1;i < len;i++){ if(arr[i] > result){ result = arr[i]; }; }; return result === undefined ? null : result; }, /** * Returns the lowest value in the given array. Supports * numeric values only. * * @param arr {Number[]} Array to process * @return {Number | null} The lowest of all values or undefined if array is empty. */ min : function(arr){ { }; var i,len = arr.length,result = arr[0]; for(i = 1;i < len;i++){ if(arr[i] < result){ result = arr[i]; }; }; return result === undefined ? null : result; }, /** * Recreates an array which is free of all duplicate elements from the original. * * This method do not modifies the original array! * * Keep in mind that this methods deletes undefined indexes. * * @param arr {Array} Incoming array * @return {Array} Returns a copy with no duplicates or the original array if no duplicates were found */ unique : function(arr){ var ret = [],doneStrings = { },doneNumbers = { },doneObjects = { }; var value,count = 0; var key = "qx" + Date.now(); var hasNull = false,hasFalse = false,hasTrue = false; // Rebuild array and omit duplicates for(var i = 0,len = arr.length;i < len;i++){ value = arr[i]; // Differ between null, primitives and reference types if(value === null){ if(!hasNull){ hasNull = true; ret.push(value); }; } else if(value === undefined){ } else if(value === false){ if(!hasFalse){ hasFalse = true; ret.push(value); }; } else if(value === true){ if(!hasTrue){ hasTrue = true; ret.push(value); }; } else if(typeof value === "string"){ if(!doneStrings[value]){ doneStrings[value] = 1; ret.push(value); }; } else if(typeof value === "number"){ if(!doneNumbers[value]){ doneNumbers[value] = 1; ret.push(value); }; } else { var hash = value[key]; if(hash == null){ hash = value[key] = count++; }; if(!doneObjects[hash]){ doneObjects[hash] = value; ret.push(value); }; };;;;; }; // Clear object hashs for(var hash in doneObjects){ try{ // TODO: The following delete seems to fail in IE7 delete doneObjects[hash][key]; } catch(ex) { try{ doneObjects[hash][key] = null; } catch(ex1) { throw new Error("Cannot clean-up map entry doneObjects[" + hash + "][" + key + "]"); }; }; }; return ret; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2008-2010 Sebastian Werner, http://sebastian-werner.net License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) * Andreas Ecker (ecker) ====================================================================== This class contains code based on the following work: * Sizzle CSS Selector Engine - v1.8.2 Homepage: http://sizzlejs.com/ Documentation: http://wiki.github.com/jeresig/sizzle Discussion: http://groups.google.com/group/sizzlejs Code: http://github.com/jeresig/sizzle/tree Copyright: (c) 2009, The Dojo Foundation License: MIT: http://www.opensource.org/licenses/mit-license.php ---------------------------------------------------------------------- Copyright (c) 2009 John Resig Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---------------------------------------------------------------------- Version: Snapshot taken on 2012-10-02, latest Sizzle commit on 2012-09-20: commit 41a7c2ce9be6c66e0c9b8b15e0a29c8e3ca6fb31 ************************************************************************ */ /** * The selector engine supports virtually all CSS 3 Selectors – this even * includes some parts that are infrequently implemented such as escaped * selectors (<code>.foo\\+bar</code>), Unicode selectors, and results returned * in document order. There are a few notable exceptions to the CSS 3 selector * support: * * * <code>:root</code> * * <code>:target</code> * * <code>:nth-last-child</code> * * <code>:nth-of-type</code> * * <code>:nth-last-of-type</code> * * <code>:first-of-type</code> * * <code>:last-of-type</code> * * <code>:only-of-type</code> * * <code>:lang()</code> * * In addition to the CSS 3 Selectors the engine supports the following * additional selectors or conventions. * * *Changes* * * * <code>:not(a.b)</code>: Supports non-simple selectors in <code>:not()</code> (most browsers only support <code>:not(a)</code>, for example). * * <code>:not(div > p)</code>: Supports full selectors in <code>:not()</code>. * * <code>:not(div, p)</code>: Supports multiple selectors in <code>:not()</code>. * * <code>[NAME=VALUE]</code>: Doesn't require quotes around the specified value in an attribute selector. * * *Additions* * * * <code>[NAME!=VALUE]</code>: Finds all elements whose <code>NAME</code> attribute doesn't match the specified value. Is equivalent to doing <code>:not([NAME=VALUE])</code>. * * <code>:contains(TEXT)</code>: Finds all elements whose textual context contains the word <code>TEXT</code> (case sensitive). * * <code>:header</code>: Finds all elements that are a header element (h1, h2, h3, h4, h5, h6). * * <code>:parent</code>: Finds all elements that contains another element. * * *Positional Selector Additions* * * * <code>:first</code>/</code>:last</code>: Finds the first or last matching element on the page. (e.g. <code>div:first</code> would find the first div on the page, in document order) * * <code>:even</code>/<code>:odd</code>: Finds every other element on the page (counting begins at 0, so <code>:even</code> would match the first element). * * <code>:eq</code>/<code>:nth</code>: Finds the Nth element on the page (e.g. <code>:eq(5)</code> finds the 6th element on the page). * * <code>:lt</code>/<code>:gt</code>: Finds all elements at positions less than or greater than the specified positions. * * *Form Selector Additions* * * * <code>:input</code>: Finds all input elements (includes textareas, selects, and buttons). * * <code>:text</code>, <code>:checkbox</code>, <code>:file</code>, <code>:password</code>, <code>:submit</code>, <code>:image</code>, <code>:reset</code>, <code>:button</code>: Finds the input element with the specified input type (<code>:button</code> also finds button elements). * * Based on Sizzle by John Resig, see: * * * http://sizzlejs.com/ * * For further usage details also have a look at the wiki page at: * * * https://github.com/jquery/sizzle/wiki/Sizzle-Home */ qx.Bootstrap.define("qx.bom.Selector", { statics : { /** * Queries the document for the given selector. Supports all CSS3 selectors * plus some extensions as mentioned in the class description. * * @signature function(selector, context) * @param selector {String} Valid selector (CSS3 + extensions) * @param context {Element} Context element (result elements must be children of this element) * @return {Array} Matching elements */ query : null, /** * Returns an reduced array which only contains the elements from the given * array which matches the given selector * * @signature function(selector, set) * @param selector {String} Selector to filter given set * @param set {Array} List to filter according to given selector * @return {Array} New array containing matching elements */ matches : null } }); /** * Below is the original Sizzle code. Snapshot date is mentioned in the head of * this file. * @lint ignoreUnused(j, rnot, rendsWithNot) */ /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function(window, undefined){ var cachedruns,assertGetIdNotName,Expr,getText,isXML,contains,compile,sortOrder,hasDuplicate,outermostContext,baseHasDuplicate = true,strundefined = "undefined",expando = ("sizcache" + Math.random()).replace(".", ""),Token = String,document = window.document,docElem = document.documentElement,dirruns = 0,done = 0,pop = [].pop,push = [].push,slice = [].slice,// Use a stripped-down indexOf if a native one is unavailable indexOf = [].indexOf || function(elem){ var i = 0,len = this.length; for(;i < len;i++){ if(this[i] === elem){ return i; }; }; return -1; },// Augment a function for special use by Sizzle markFunction = function(fn, value){ fn[expando] = value == null || value; return fn; },createCache = function(){ var cache = { },keys = []; return markFunction(function(key, value){ // Only keep the most recent entries if(keys.push(key) > Expr.cacheLength){ delete cache[keys.shift()]; }; return (cache[key] = value); }, cache); },classCache = createCache(),tokenCache = createCache(),compilerCache = createCache(),// Regex // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]",// http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",// Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors) // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace("w", "w#"),// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)",attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",// Prefer arguments not in parens/brackets, // then attribute selectors and non-pseudos (denoted by :), // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)",// For matchExpr.POS and matchExpr.needsContext pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)",// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp("^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g"),rcomma = new RegExp("^" + whitespace + "*," + whitespace + "*"),rcombinators = new RegExp("^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*"),rpseudo = new RegExp(pseudos),// Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,rnot = /^:not/,rsibling = /[\x20\t\r\n\f]*[+~]/,rendsWithNot = /:not\($/,rheader = /h\d/i,rinputs = /input|select|textarea|button/i,rbackslash = /\\(?!\\)/g,matchExpr = { "ID" : new RegExp("^#(" + characterEncoding + ")"), "CLASS" : new RegExp("^\\.(" + characterEncoding + ")"), "NAME" : new RegExp("^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]"), "TAG" : new RegExp("^(" + characterEncoding.replace("w", "w*") + ")"), "ATTR" : new RegExp("^" + attributes), "PSEUDO" : new RegExp("^" + pseudos), "POS" : new RegExp(pos, "i"), "CHILD" : new RegExp("^:(only|nth|first|last)-child(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i"), // For use in libraries implementing .is() "needsContext" : new RegExp("^" + whitespace + "*[>+~]|" + pos, "i") },// Support // Used for testing something on an element assert = function(fn){ var div = document.createElement("div"); try{ return fn(div); } catch(e) { return false; }finally{ // release memory in IE div = null; }; },// Check if getElementsByTagName("*") returns only elements assertTagNameNoComments = assert(function(div){ div.appendChild(document.createComment("")); return !div.getElementsByTagName("*").length; }),// Check if getAttribute returns normalized href attributes assertHrefNotNormalized = assert(function(div){ div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }),// Check if attributes should be retrieved by attribute nodes assertAttributes = assert(function(div){ div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }),// Check if getElementsByClassName can be trusted assertUsableClassName = assert(function(div){ // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if(!div.getElementsByClassName || !div.getElementsByClassName("e").length){ return false; }; // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }),// Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID assertUsableName = assert(function(div){ // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore(div, docElem.firstChild); // Test var pass = document.getElementsByName && // buggy browsers will return fewer than the correct 2 document.getElementsByName(expando).length === 2 + // buggy browsers will return more than the correct 0 document.getElementsByName(expando + 0).length; assertGetIdNotName = !document.getElementById(expando); // Cleanup docElem.removeChild(div); return pass; }); // If slice is not available, provide a backup try{ slice.call(docElem.childNodes, 0)[0].nodeType; } catch(e) { slice = function(i){ var elem,results = []; for(;(elem = this[i]);i++){ results.push(elem); }; return results; }; }; function Sizzle(selector, context, results, seed){ results = results || []; context = context || document; var match,elem,xml,m,nodeType = context.nodeType; if(!selector || typeof selector !== "string"){ return results; }; if(nodeType !== 1 && nodeType !== 9){ return []; }; xml = isXML(context); if(!xml && !seed){ if((match = rquickExpr.exec(selector))){ // Speed-up: Sizzle("#ID") if((m = match[1])){ if(nodeType === 9){ elem = context.getElementById(m); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if(elem && elem.parentNode){ // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if(elem.id === m){ results.push(elem); return results; }; } else { return results; }; } else { // Context is not a document if(context.ownerDocument && (elem = context.ownerDocument.getElementById(m)) && contains(context, elem) && elem.id === m){ results.push(elem); return results; }; }; } else if(match[2]){ push.apply(results, slice.call(context.getElementsByTagName(selector), 0)); return results; } else if((m = match[3]) && assertUsableClassName && context.getElementsByClassName){ push.apply(results, slice.call(context.getElementsByClassName(m), 0)); return results; };; }; }; // All others return select(selector.replace(rtrim, "$1"), context, results, seed, xml); }; Sizzle.matches = function(expr, elements){ return Sizzle(expr, null, null, elements); }; Sizzle.matchesSelector = function(elem, expr){ return Sizzle(expr, null, null, [elem]).length > 0; }; // Returns a function to use in pseudos for input types function createInputPseudo(type){ return function(elem){ var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; }; // Returns a function to use in pseudos for buttons function createButtonPseudo(type){ return function(elem){ var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; }; // Returns a function to use in pseudos for positionals function createPositionalPseudo(fn){ return markFunction(function(argument){ argument = +argument; return markFunction(function(seed, matches){ var j,matchIndexes = fn([], seed.length, argument),i = matchIndexes.length; // Match elements found at the specified indexes while(i--){ if(seed[(j = matchIndexes[i])]){ seed[j] = !(matches[j] = seed[j]); }; }; }); }); }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function(elem){ var node,ret = "",i = 0,nodeType = elem.nodeType; if(nodeType){ if(nodeType === 1 || nodeType === 9 || nodeType === 11){ // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if(typeof elem.textContent === "string"){ return elem.textContent; } else { // Traverse its children for(elem = elem.firstChild;elem;elem = elem.nextSibling){ ret += getText(elem); }; }; } else if(nodeType === 3 || nodeType === 4){ return elem.nodeValue; }; } else { // If no nodeType, this is expected to be an array for(;(node = elem[i]);i++){ // Do not traverse comment nodes ret += getText(node); }; }; return ret; }; isXML = Sizzle.isXML = function(elem){ // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Element contains another contains = Sizzle.contains = docElem.contains ? function(a, b){ var adown = a.nodeType === 9 ? a.documentElement : a,bup = b && b.parentNode; return a === bup || !!(bup && bup.nodeType === 1 && adown.contains && adown.contains(bup)); } : docElem.compareDocumentPosition ? function(a, b){ return b && !!(a.compareDocumentPosition(b) & 16); } : function(a, b){ while((b = b.parentNode)){ if(b === a){ return true; }; }; return false; }; Sizzle.attr = function(elem, name){ var val,xml = isXML(elem); if(!xml){ name = name.toLowerCase(); }; if((val = Expr.attrHandle[name])){ return val(elem); }; if(xml || assertAttributes){ return elem.getAttribute(name); }; val = elem.getAttributeNode(name); return val ? typeof elem[name] === "boolean" ? elem[name] ? name : null : val.specified ? val.value : null : null; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength : 50, createPseudo : markFunction, match : matchExpr, // IE6/7 return a modified href attrHandle : assertHrefNotNormalized ? { } : { "href" : function(elem){ return elem.getAttribute("href", 2); }, "type" : function(elem){ return elem.getAttribute("type"); } }, find : { "ID" : assertGetIdNotName ? function(id, context, xml){ if(typeof context.getElementById !== strundefined && !xml){ var m = context.getElementById(id); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; }; } : function(id, context, xml){ if(typeof context.getElementById !== strundefined && !xml){ var m = context.getElementById(id); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; }; }, "TAG" : assertTagNameNoComments ? function(tag, context){ if(typeof context.getElementsByTagName !== strundefined){ return context.getElementsByTagName(tag); }; } : function(tag, context){ var results = context.getElementsByTagName(tag); // Filter out possible comments if(tag === "*"){ var elem,tmp = [],i = 0; for(;(elem = results[i]);i++){ if(elem.nodeType === 1){ tmp.push(elem); }; }; return tmp; }; return results; }, "NAME" : assertUsableName && function(tag, context){ if(typeof context.getElementsByName !== strundefined){ return context.getElementsByName(name); }; }, "CLASS" : assertUsableClassName && function(className, context, xml){ if(typeof context.getElementsByClassName !== strundefined && !xml){ return context.getElementsByClassName(className); }; } }, relative : { ">" : { dir : "parentNode", first : true }, " " : { dir : "parentNode" }, "+" : { dir : "previousSibling", first : true }, "~" : { dir : "previousSibling" } }, preFilter : { "ATTR" : function(match){ match[1] = match[1].replace(rbackslash, ""); // Move the given value to match[3] whether quoted or unquoted match[3] = (match[4] || match[5] || "").replace(rbackslash, ""); if(match[2] === "~="){ match[3] = " " + match[3] + " "; }; return match.slice(0, 4); }, "CHILD" : function(match){ /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 3 xn-component of xn+y argument ([+-]?\d*n|) 4 sign of xn-component 5 x of xn-component 6 sign of y-component 7 y of y-component */ match[1] = match[1].toLowerCase(); if(match[1] === "nth"){ // nth-child requires argument if(!match[2]){ Sizzle.error(match[0]); }; // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[3] = +(match[3] ? match[4] + (match[5] || 1) : 2 * (match[2] === "even" || match[2] === "odd")); match[4] = +((match[6] + match[7]) || match[2] === "odd"); } else if(match[2]){ Sizzle.error(match[0]); }; return match; }, "PSEUDO" : function(match){ var unquoted,excess; if(matchExpr["CHILD"].test(match[0])){ return null; }; if(match[3]){ match[2] = match[3]; } else if((unquoted = match[4])){ // Only check arguments that contain a pseudo if(rpseudo.test(unquoted) && // Get excess from tokenize (recursively) (excess = tokenize(unquoted, true)) && // advance to the next closing parenthesis (excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length)){ // excess is a negative index unquoted = unquoted.slice(0, excess); match[0] = match[0].slice(0, excess); }; match[2] = unquoted; }; // Return only captures needed by the pseudo filter method (type and argument) return match.slice(0, 3); } }, filter : { "ID" : assertGetIdNotName ? function(id){ id = id.replace(rbackslash, ""); return function(elem){ return elem.getAttribute("id") === id; }; } : function(id){ id = id.replace(rbackslash, ""); return function(elem){ var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === id; }; }, "TAG" : function(nodeName){ if(nodeName === "*"){ return function(){ return true; }; }; nodeName = nodeName.replace(rbackslash, "").toLowerCase(); return function(elem){ return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS" : function(className){ var pattern = classCache[expando][className]; if(!pattern){ pattern = classCache(className, new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)")); }; return function(elem){ return pattern.test(elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || ""); }; }, "ATTR" : function(name, operator, check){ return function(elem, context){ var result = Sizzle.attr(elem, name); if(result == null){ return operator === "!="; }; if(!operator){ return true; }; result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf(check) === 0 : operator === "*=" ? check && result.indexOf(check) > -1 : operator === "$=" ? check && result.substr(result.length - check.length) === check : operator === "~=" ? (" " + result + " ").indexOf(check) > -1 : operator === "|=" ? result === check || result.substr(0, check.length + 1) === check + "-" : false; }; }, "CHILD" : function(type, argument, first, last){ if(type === "nth"){ return function(elem){ var node,diff,parent = elem.parentNode; if(first === 1 && last === 0){ return true; }; if(parent){ diff = 0; for(node = parent.firstChild;node;node = node.nextSibling){ if(node.nodeType === 1){ diff++; if(elem === node){ break; }; }; }; }; // Incorporate the offset (or cast to NaN), then check against cycle size diff -= last; return diff === first || (diff % first === 0 && diff / first >= 0); }; }; return function(elem){ var node = elem; switch(type){case "only":case "first": while((node = node.previousSibling)){ if(node.nodeType === 1){ return false; }; }; if(type === "first"){ return true; }; node = elem;/* falls through */ case "last": while((node = node.nextSibling)){ if(node.nodeType === 1){ return false; }; }; return true;}; }; }, "PSEUDO" : function(pseudo, argument){ // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args,fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error("unsupported pseudo: " + pseudo); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if(fn[expando]){ return fn(argument); }; // But maintain support for old signatures if(fn.length > 1){ args = [pseudo, pseudo, "", argument]; return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function(seed, matches){ var idx,matched = fn(seed, argument),i = matched.length; while(i--){ idx = indexOf.call(seed, matched[i]); seed[idx] = !(matches[idx] = matched[i]); }; }) : function(elem){ return fn(elem, 0, args); }; }; return fn; } }, pseudos : { "not" : markFunction(function(selector){ // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [],results = [],matcher = compile(selector.replace(rtrim, "$1")); return matcher[expando] ? markFunction(function(seed, matches, context, xml){ var elem,unmatched = matcher(seed, null, xml, []),i = seed.length; // Match elements unmatched by `matcher` while(i--){ if((elem = unmatched[i])){ seed[i] = !(matches[i] = elem); }; }; }) : function(elem, context, xml){ input[0] = elem; matcher(input, null, xml, results); return !results.pop(); }; }), "has" : markFunction(function(selector){ return function(elem){ return Sizzle(selector, elem).length > 0; }; }), "contains" : markFunction(function(text){ return function(elem){ return (elem.textContent || elem.innerText || getText(elem)).indexOf(text) > -1; }; }), "enabled" : function(elem){ return elem.disabled === false; }, "disabled" : function(elem){ return elem.disabled === true; }, "checked" : function(elem){ // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected" : function(elem){ // Accessing this property makes selected-by-default // options in Safari work properly if(elem.parentNode){ elem.parentNode.selectedIndex; }; return elem.selected === true; }, "parent" : function(elem){ return !Expr.pseudos["empty"](elem); }, "empty" : function(elem){ // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") var nodeType; elem = elem.firstChild; while(elem){ if(elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4){ return false; }; elem = elem.nextSibling; }; return true; }, "header" : function(elem){ return rheader.test(elem.nodeName); }, "text" : function(elem){ var type,attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && (type = elem.type) === "text" && ((attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type); }, // Input types "radio" : createInputPseudo("radio"), "checkbox" : createInputPseudo("checkbox"), "file" : createInputPseudo("file"), "password" : createInputPseudo("password"), "image" : createInputPseudo("image"), "submit" : createButtonPseudo("submit"), "reset" : createButtonPseudo("reset"), "button" : function(elem){ var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "input" : function(elem){ return rinputs.test(elem.nodeName); }, "focus" : function(elem){ var doc = elem.ownerDocument; return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href); }, "active" : function(elem){ return elem === elem.ownerDocument.activeElement; }, // Positional types "first" : createPositionalPseudo(function(matchIndexes, length, argument){ return [0]; }), "last" : createPositionalPseudo(function(matchIndexes, length, argument){ return [length - 1]; }), "eq" : createPositionalPseudo(function(matchIndexes, length, argument){ return [argument < 0 ? argument + length : argument]; }), "even" : createPositionalPseudo(function(matchIndexes, length, argument){ for(var i = 0;i < length;i += 2){ matchIndexes.push(i); }; return matchIndexes; }), "odd" : createPositionalPseudo(function(matchIndexes, length, argument){ for(var i = 1;i < length;i += 2){ matchIndexes.push(i); }; return matchIndexes; }), "lt" : createPositionalPseudo(function(matchIndexes, length, argument){ for(var i = argument < 0 ? argument + length : argument;--i >= 0;){ matchIndexes.push(i); }; return matchIndexes; }), "gt" : createPositionalPseudo(function(matchIndexes, length, argument){ for(var i = argument < 0 ? argument + length : argument;++i < length;){ matchIndexes.push(i); }; return matchIndexes; }) } }; function siblingCheck(a, b, ret){ if(a === b){ return ret; }; var cur = a.nextSibling; while(cur){ if(cur === b){ return -1; }; cur = cur.nextSibling; }; return 1; }; sortOrder = docElem.compareDocumentPosition ? function(a, b){ if(a === b){ hasDuplicate = true; return 0; }; return (!a.compareDocumentPosition || !b.compareDocumentPosition ? a.compareDocumentPosition : a.compareDocumentPosition(b) & 4) ? -1 : 1; } : function(a, b){ // The nodes are identical, we can exit early if(a === b){ hasDuplicate = true; return 0; } else if(a.sourceIndex && b.sourceIndex){ return a.sourceIndex - b.sourceIndex; }; var al,bl,ap = [],bp = [],aup = a.parentNode,bup = b.parentNode,cur = aup; // If the nodes are siblings (or identical) we can do a quick check if(aup === bup){ return siblingCheck(a, b); } else if(!aup){ return -1; } else if(!bup){ return 1; };; // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while(cur){ ap.unshift(cur); cur = cur.parentNode; }; cur = bup; while(cur){ bp.unshift(cur); cur = cur.parentNode; }; al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for(var i = 0;i < al && i < bl;i++){ if(ap[i] !== bp[i]){ return siblingCheck(ap[i], bp[i]); }; }; // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck(a, bp[i], -1) : siblingCheck(ap[i], b, 1); }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). [0, 0].sort(sortOrder); baseHasDuplicate = !hasDuplicate; // Document sorting and removing duplicates Sizzle.uniqueSort = function(results){ var elem,i = 1; hasDuplicate = baseHasDuplicate; results.sort(sortOrder); if(hasDuplicate){ for(;(elem = results[i]);i++){ if(elem === results[i - 1]){ results.splice(i--, 1); }; }; }; return results; }; Sizzle.error = function(msg){ throw new Error("Syntax error, unrecognized expression: " + msg); }; function tokenize(selector, parseOnly){ var matched,match,tokens,type,soFar,groups,preFilters,cached = tokenCache[expando][selector]; if(cached){ return parseOnly ? 0 : cached.slice(0); }; soFar = selector; groups = []; preFilters = Expr.preFilter; while(soFar){ // Comma and first run if(!matched || (match = rcomma.exec(soFar))){ if(match){ soFar = soFar.slice(match[0].length); }; groups.push(tokens = []); }; matched = false; // Combinators if((match = rcombinators.exec(soFar))){ tokens.push(matched = new Token(match.shift())); soFar = soFar.slice(matched.length); // Cast descendant combinators to space matched.type = match[0].replace(rtrim, " "); }; // Filters for(type in Expr.filter){ if((match = matchExpr[type].exec(soFar)) && (!preFilters[type] || // The last two arguments here are (context, xml) for backCompat (match = preFilters[type](match, document, true)))){ tokens.push(matched = new Token(match.shift())); soFar = soFar.slice(matched.length); matched.type = type; matched.matches = match; }; }; if(!matched){ break; }; }; // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : // Cache the tokens tokenCache(selector, groups).slice(0); }; function addCombinator(matcher, combinator, base){ var dir = combinator.dir,checkNonElements = base && combinator.dir === "parentNode",doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function(elem, context, xml){ while((elem = elem[dir])){ if(checkNonElements || elem.nodeType === 1){ return matcher(elem, context, xml); }; }; } : // Check against all ancestor/preceding elements function(elem, context, xml){ // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if(!xml){ var cache,dirkey = dirruns + " " + doneName + " ",cachedkey = dirkey + cachedruns; while((elem = elem[dir])){ if(checkNonElements || elem.nodeType === 1){ if((cache = elem[expando]) === cachedkey){ return elem.sizset; } else if(typeof cache === "string" && cache.indexOf(dirkey) === 0){ if(elem.sizset){ return elem; }; } else { elem[expando] = cachedkey; if(matcher(elem, context, xml)){ elem.sizset = true; return elem; }; elem.sizset = false; }; }; }; } else { while((elem = elem[dir])){ if(checkNonElements || elem.nodeType === 1){ if(matcher(elem, context, xml)){ return elem; }; }; }; }; }; }; function elementMatcher(matchers){ return matchers.length > 1 ? function(elem, context, xml){ var i = matchers.length; while(i--){ if(!matchers[i](elem, context, xml)){ return false; }; }; return true; } : matchers[0]; }; function condense(unmatched, map, filter, context, xml){ var elem,newUnmatched = [],i = 0,len = unmatched.length,mapped = map != null; for(;i < len;i++){ if((elem = unmatched[i])){ if(!filter || filter(elem, context, xml)){ newUnmatched.push(elem); if(mapped){ map.push(i); }; }; }; }; return newUnmatched; }; function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector){ if(postFilter && !postFilter[expando]){ postFilter = setMatcher(postFilter); }; if(postFinder && !postFinder[expando]){ postFinder = setMatcher(postFinder, postSelector); }; return markFunction(function(seed, results, context, xml){ // Positional selectors apply to seed elements, so it is invalid to follow them with relative ones if(seed && postFinder){ return; }; var i,elem,postFilterIn,preMap = [],postMap = [],preexisting = results.length,// Get initial elements from seed or context elems = seed || multipleContexts(selector || "*", context.nodeType ? [context] : context, [], seed),// Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && (seed || !selector) ? condense(elems, preMap, preFilter, context, xml) : elems,matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || (seed ? preFilter : preexisting || postFilter) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if(matcher){ matcher(matcherIn, matcherOut, context, xml); }; // Apply postFilter if(postFilter){ postFilterIn = condense(matcherOut, postMap); postFilter(postFilterIn, [], context, xml); // Un-match failing elements by moving them back to matcherIn i = postFilterIn.length; while(i--){ if((elem = postFilterIn[i])){ matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem); }; }; }; // Keep seed and results synchronized if(seed){ // Ignore postFinder because it can't coexist with seed i = preFilter && matcherOut.length; while(i--){ if((elem = matcherOut[i])){ seed[preMap[i]] = !(results[preMap[i]] = elem); }; }; } else { matcherOut = condense(matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut); if(postFinder){ postFinder(null, results, matcherOut, xml); } else { push.apply(results, matcherOut); }; }; }); }; function matcherFromTokens(tokens){ var checkContext,matcher,j,len = tokens.length,leadingRelative = Expr.relative[tokens[0].type],implicitRelative = leadingRelative || Expr.relative[" "],i = leadingRelative ? 1 : 0,// The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator(function(elem){ return elem === checkContext; }, implicitRelative, true),matchAnyContext = addCombinator(function(elem){ return indexOf.call(checkContext, elem) > -1; }, implicitRelative, true),matchers = [function(elem, context, xml){ return (!leadingRelative && (xml || context !== outermostContext)) || ((checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml)); }]; for(;i < len;i++){ if((matcher = Expr.relative[tokens[i].type])){ matchers = [addCombinator(elementMatcher(matchers), matcher)]; } else { // The concatenated values are (context, xml) for backCompat matcher = Expr.filter[tokens[i].type].apply(null, tokens[i].matches); // Return special upon seeing a positional matcher if(matcher[expando]){ // Find the next relative operator (if any) for proper handling j = ++i; for(;j < len;j++){ if(Expr.relative[tokens[j].type]){ break; }; }; return setMatcher(i > 1 && elementMatcher(matchers), i > 1 && tokens.slice(0, i - 1).join("").replace(rtrim, "$1"), matcher, i < j && matcherFromTokens(tokens.slice(i, j)), j < len && matcherFromTokens((tokens = tokens.slice(j))), j < len && tokens.join("")); }; matchers.push(matcher); }; }; return elementMatcher(matchers); }; function matcherFromGroupMatchers(elementMatchers, setMatchers){ var bySet = setMatchers.length > 0,byElement = elementMatchers.length > 0,superMatcher = function(seed, context, xml, results, expandContext){ var elem,j,matcher,setMatched = [],matchedCount = 0,i = "0",unmatched = seed && [],outermost = expandContext != null,contextBackup = outermostContext,// We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]("*", expandContext && context.parentNode || context),// Nested matchers should use non-integer dirruns dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); if(outermost){ outermostContext = context !== document && context; cachedruns = superMatcher.el; }; // Add elements passing elementMatchers directly to results for(;(elem = elems[i]) != null;i++){ if(byElement && elem){ for(j = 0;(matcher = elementMatchers[j]);j++){ if(matcher(elem, context, xml)){ results.push(elem); break; }; }; if(outermost){ dirruns = dirrunsUnique; cachedruns = ++superMatcher.el; }; }; // Track unmatched elements for set filters if(bySet){ // They will have gone through all possible matchers if((elem = !matcher && elem)){ matchedCount--; }; // Lengthen the array for every element, matched or not if(seed){ unmatched.push(elem); }; }; }; // Apply set filters to unmatched elements matchedCount += i; if(bySet && i !== matchedCount){ for(j = 0;(matcher = setMatchers[j]);j++){ matcher(unmatched, setMatched, context, xml); }; if(seed){ // Reintegrate element matches to eliminate the need for sorting if(matchedCount > 0){ while(i--){ if(!(unmatched[i] || setMatched[i])){ setMatched[i] = pop.call(results); }; }; }; // Discard index placeholder values to get only actual matches setMatched = condense(setMatched); }; // Add matches to results push.apply(results, setMatched); // Seedless set matches succeeding multiple successful matchers stipulate sorting if(outermost && !seed && setMatched.length > 0 && (matchedCount + setMatchers.length) > 1){ Sizzle.uniqueSort(results); }; }; // Override manipulation of globals by nested matchers if(outermost){ dirruns = dirrunsUnique; outermostContext = contextBackup; }; return unmatched; }; superMatcher.el = 0; return bySet ? markFunction(superMatcher) : superMatcher; }; compile = Sizzle.compile = function(selector, group){ var i,setMatchers = [],elementMatchers = [],cached = compilerCache[expando][selector]; if(!cached){ // Generate a function of recursive functions that can be used to check each element if(!group){ group = tokenize(selector); }; i = group.length; while(i--){ cached = matcherFromTokens(group[i]); if(cached[expando]){ setMatchers.push(cached); } else { elementMatchers.push(cached); }; }; // Cache the compiled function cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers)); }; return cached; }; function multipleContexts(selector, contexts, results, seed){ var i = 0,len = contexts.length; for(;i < len;i++){ Sizzle(selector, contexts[i], results, seed); }; return results; }; function select(selector, context, results, seed, xml){ var i,tokens,token,type,find,match = tokenize(selector),j = match.length; if(!seed){ // Try to minimize operations if there is only one group if(match.length === 1){ // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice(0); if(tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && !xml && Expr.relative[tokens[1].type]){ context = Expr.find["ID"](token.matches[0].replace(rbackslash, ""), context, xml)[0]; if(!context){ return results; }; selector = selector.slice(tokens.shift().length); }; // Fetch a seed set for right-to-left matching for(i = matchExpr["POS"].test(selector) ? -1 : tokens.length - 1;i >= 0;i--){ token = tokens[i]; // Abort if we hit a combinator if(Expr.relative[(type = token.type)]){ break; }; if((find = Expr.find[type])){ // Search, expanding context for leading sibling combinators if((seed = find(token.matches[0].replace(rbackslash, ""), rsibling.test(tokens[0].type) && context.parentNode || context, xml))){ // If seed is empty or no tokens remain, we can return early tokens.splice(i, 1); selector = seed.length && tokens.join(""); if(!selector){ push.apply(results, slice.call(seed, 0)); return results; }; break; }; }; }; }; }; // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile(selector, match)(seed, context, xml, results, rsibling.test(selector)); return results; }; if(document.querySelectorAll){ (function(){ var disconnectedMatch,oldSelect = select,rescape = /'|\\/g,rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,// qSa(:focus) reports false when true (Chrome 21), // A support test would require too much code (would include document ready) rbuggyQSA = [":focus"],// matchesSelector(:focus) reports false when true (Chrome 21), // matchesSelector(:active) reports false when true (IE9/Opera 11.5) // A support test would require too much code (would include document ready) // just skip matchesSelector for :active rbuggyMatches = [":active", ":focus"],matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector; // Build QSA regex // Regex strategy adopted from Diego Perini assert(function(div){ // Select is set to empty string on purpose // This is to test IE's treatment of not explictly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if(!div.querySelectorAll("[selected]").length){ rbuggyQSA.push("\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)"); }; // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here (do not put tests after this one) if(!div.querySelectorAll(":checked").length){ rbuggyQSA.push(":checked"); }; }); assert(function(div){ // Opera 10-12/IE9 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<p test=''></p>"; if(div.querySelectorAll("[test^='']").length){ rbuggyQSA.push("[*^$]=" + whitespace + "*(?:\"\"|'')"); }; // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here (do not put tests after this one) div.innerHTML = "<input type='hidden'/>"; if(!div.querySelectorAll(":enabled").length){ rbuggyQSA.push(":enabled", ":disabled"); }; }); // rbuggyQSA always contains :focus, so no need for a length check rbuggyQSA = /* rbuggyQSA.length && */ new RegExp(rbuggyQSA.join("|")); select = function(selector, context, results, seed, xml){ // Only use querySelectorAll when not filtering, // when this is not xml, // and when no QSA bugs apply if(!seed && !xml && (!rbuggyQSA || !rbuggyQSA.test(selector))){ var groups,i,old = true,nid = expando,newContext = context,newSelector = context.nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if(context.nodeType === 1 && context.nodeName.toLowerCase() !== "object"){ groups = tokenize(selector); if((old = context.getAttribute("id"))){ nid = old.replace(rescape, "\\$&"); } else { context.setAttribute("id", nid); }; nid = "[id='" + nid + "'] "; i = groups.length; while(i--){ groups[i] = nid + groups[i].join(""); }; newContext = rsibling.test(selector) && context.parentNode || context; newSelector = groups.join(","); }; if(newSelector){ try{ push.apply(results, slice.call(newContext.querySelectorAll(newSelector), 0)); return results; } catch(qsaError) { }finally{ if(!old){ context.removeAttribute("id"); }; }; }; }; return oldSelect(selector, context, results, seed, xml); }; if(matches){ assert(function(div){ // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) disconnectedMatch = matches.call(div, "div"); // This should fail with an exception // Gecko does not error, returns false instead try{ matches.call(div, "[test!='']:sizzle"); rbuggyMatches.push("!=", pseudos); } catch(e) { }; }); // rbuggyMatches always contains :active and :focus, so no need for a length check rbuggyMatches = /* rbuggyMatches.length && */ new RegExp(rbuggyMatches.join("|")); Sizzle.matchesSelector = function(elem, expr){ // Make sure that attribute selectors are quoted expr = expr.replace(rattributeQuotes, "='$1']"); // rbuggyMatches always contains :active, so no need for an existence check if(!isXML(elem) && !rbuggyMatches.test(expr) && (!rbuggyQSA || !rbuggyQSA.test(expr))){ try{ var ret = matches.call(elem, expr); // IE 9's matchesSelector returns false on disconnected nodes if(ret || disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11){ return ret; }; } catch(e) { }; }; return Sizzle(expr, null, null, [elem]).length > 0; }; }; })(); }; // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Back-compat function setFilters(){ }; Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // EXPOSE qooxdoo variant qx.bom.Selector.query = function(selector, context){ return Sizzle(selector, context); }; qx.bom.Selector.matches = function(selector, set){ return Sizzle(selector, null, null, set); }; })(window); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2007-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * Utility class with type check for all native JavaScript data types. */ qx.Bootstrap.define("qx.lang.Type", { statics : { /** * Get the internal class of the value. See * http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ * for details. * * @signature function(value) * @param value {var} value to get the class for * @return {String} the internal class of the value */ getClass : qx.Bootstrap.getClass, /** * Whether the value is a string. * * @signature function(value) * @param value {var} Value to check. * @return {Boolean} Whether the value is a string. */ isString : qx.Bootstrap.isString, /** * Whether the value is an array. * * @signature function(value) * @param value {var} Value to check. * @return {Boolean} Whether the value is an array. */ isArray : qx.Bootstrap.isArray, /** * Whether the value is an object. Note that built-in types like Window are * not reported to be objects. * * @signature function(value) * @param value {var} Value to check. * @return {Boolean} Whether the value is an object. */ isObject : qx.Bootstrap.isObject, /** * Whether the value is a function. * * @signature function(value) * @param value {var} Value to check. * @return {Boolean} Whether the value is a function. */ isFunction : qx.Bootstrap.isFunction, /** * Whether the value is a regular expression. * * @param value {var} Value to check. * @return {Boolean} Whether the value is a regular expression. */ isRegExp : function(value){ return this.getClass(value) == "RegExp"; }, /** * Whether the value is a number. * * @param value {var} Value to check. * @return {Boolean} Whether the value is a number. */ isNumber : function(value){ // Added "value !== null" because IE throws an exception "Object expected" // by executing "value instanceof Number" if value is a DOM element that // doesn't exist. It seems that there is an internal different between a // JavaScript null and a null returned from calling DOM. // e.q. by document.getElementById("ReturnedNull"). return (value !== null && (this.getClass(value) == "Number" || value instanceof Number)); }, /** * Whether the value is a boolean. * * @param value {var} Value to check. * @return {Boolean} Whether the value is a boolean. */ isBoolean : function(value){ // Added "value !== null" because IE throws an exception "Object expected" // by executing "value instanceof Boolean" if value is a DOM element that // doesn't exist. It seems that there is an internal different between a // JavaScript null and a null returned from calling DOM. // e.q. by document.getElementById("ReturnedNull"). return (value !== null && (this.getClass(value) == "Boolean" || value instanceof Boolean)); }, /** * Whether the value is a date. * * @param value {var} Value to check. * @return {Boolean} Whether the value is a date. */ isDate : function(value){ // Added "value !== null" because IE throws an exception "Object expected" // by executing "value instanceof Date" if value is a DOM element that // doesn't exist. It seems that there is an internal different between a // JavaScript null and a null returned from calling DOM. // e.q. by document.getElementById("ReturnedNull"). return (value !== null && (this.getClass(value) == "Date" || value instanceof Date)); }, /** * Whether the value is a Error. * * @param value {var} Value to check. * @return {Boolean} Whether the value is a Error. */ isError : function(value){ // Added "value !== null" because IE throws an exception "Object expected" // by executing "value instanceof Error" if value is a DOM element that // doesn't exist. It seems that there is an internal different between a // JavaScript null and a null returned from calling DOM. // e.q. by document.getElementById("ReturnedNull"). return (value !== null && (this.getClass(value) == "Error" || value instanceof Error)); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This module offers a cross browser storage implementation. The API is aligned * with the API of the HTML web storage (http://www.w3.org/TR/webstorage/) which is * also the preferred implementation used. As fallback for IE < 8, we use user data. * If both techniques are unsupported, we supply a in memory storage, which is * of course, not persistent. */ qx.Bootstrap.define("qx.module.Storage", { statics : { /** * Store an item in the storage. * * @attachStatic {qxWeb, localStorage.setItem} * @param key {String} The identifier key. * @param value {var} The data, which will be stored as JSON. */ setLocalItem : function(key, value){ qx.bom.Storage.getLocal().setItem(key, value); }, /** * Returns the stored item. * * @attachStatic {qxWeb, localStorage.getItem} * @param key {String} The identifier to get the data. * @return {var} The stored data. */ getLocalItem : function(key){ return qx.bom.Storage.getLocal().getItem(key); }, /** * Removes an item form the storage. * @attachStatic {qxWeb, localStorage.removeItem} * @param key {String} The identifier. */ removeLocalItem : function(key){ qx.bom.Storage.getLocal().removeItem(key); }, /** * Returns the amount of key-value pairs stored. * @attachStatic {qxWeb, localStorage.getLength} * @return {Number} The length of the storage. */ getLocalLength : function(){ return qx.bom.Storage.getLocal().getLength(); }, /** * Returns the named key at the given index. * @attachStatic {qxWeb, localStorage.getKey} * @param index {Number} The index in the storage. * @return {String} The key stored at the given index. */ getLocalKey : function(index){ return qx.bom.Storage.getLocal().getKey(index); }, /** * Deletes every stored item in the storage. * @attachStatic {qxWeb, localStorage.clear} */ clearLocal : function(){ qx.bom.Storage.getLocal().clear(); }, /** * Helper to access every stored item. * * @attachStatic {qxWeb, localStorage.forEach} * @param callback {Function} A function which will be called for every item. * The function will have two arguments, first the key and second the value * of the stored data. * @param scope {var} The scope of the function. */ forEachLocal : function(callback, scope){ qx.bom.Storage.getLocal().forEach(callback, scope); }, /** * Store an item in the storage. * * @attachStatic {qxWeb, sessionStorage.setItem} * @param key {String} The identifier key. * @param value {var} The data, which will be stored as JSON. */ setSessionItem : function(key, value){ qx.bom.Storage.getSession().setItem(key, value); }, /** * Returns the stored item. * * @attachStatic {qxWeb, sessionStorage.getItem} * @param key {String} The identifier to get the data. * @return {var} The stored data. */ getSessionItem : function(key){ return qx.bom.Storage.getSession().getItem(key); }, /** * Removes an item form the storage. * @attachStatic {qxWeb, sessionStorage.removeItem} * @param key {String} The identifier. */ removeSessionItem : function(key){ qx.bom.Storage.getSession().removeItem(key); }, /** * Returns the amount of key-value pairs stored. * @attachStatic {qxWeb, sessionStorage.getLength} * @return {Number} The length of the storage. */ getSessionLength : function(){ return qx.bom.Storage.getSession().getLength(); }, /** * Returns the named key at the given index. * @attachStatic {qxWeb, sessionStorage.getKey} * @param index {Number} The index in the storage. * @return {String} The key stored at the given index. */ getSessionKey : function(index){ return qx.bom.Storage.getSession().getKey(index); }, /** * Deletes every stored item in the storage. * @attachStatic {qxWeb, sessionStorage.clear} */ clearSession : function(){ qx.bom.Storage.getSession().clear(); }, /** * Helper to access every stored item. * * @attachStatic {qxWeb, sessionStorage.forEach} * @param callback {Function} A function which will be called for every item. * The function will have two arguments, first the key and second the value * of the stored data. * @param scope {var} The scope of the function. */ forEachSession : function(callback, scope){ qx.bom.Storage.getSession().forEach(callback, scope); } }, defer : function(statics){ qxWeb.$attachStatic({ "localStorage" : { setItem : statics.setLocalItem, getItem : statics.getLocalItem, removeItem : statics.removeLocalItem, getLength : statics.getLocalLength, getKey : statics.getLocalKey, clear : statics.clearLocal, forEach : statics.forEachLocal }, "sessionStorage" : { setItem : statics.setSessionItem, getItem : statics.getSessionItem, removeItem : statics.removeSessionItem, getLength : statics.getSessionLength, getKey : statics.getSessionKey, clear : statics.clearSession, forEach : statics.forEachSession } }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This is a cross browser storage implementation. The API is aligned with the * API of the HTML web storage (http://www.w3.org/TR/webstorage/) which is also * the preferred implementation used. As fallback for IE < 8, we use user data. * If both techniques are unsupported, we supply a in memory storage, which is * of course, not persistent. */ qx.Bootstrap.define("qx.bom.Storage", { statics : { __impl : null, /** * Get an instance of a local storage. * @return {qx.bom.storage.Web|qx.bom.storage.UserData|qx.bom.storage.Memory} * An instance of a storage implementation. */ getLocal : function(){ // always use HTML5 web storage if available if(qx.core.Environment.get("html.storage.local")){ return qx.bom.storage.Web.getLocal(); } else if(qx.core.Environment.get("html.storage.userdata")){ // IE <8 fallback // as fallback,use the userdata storage for IE5.5 - 8 return qx.bom.storage.UserData.getLocal(); }; // as last fallback, use a in memory storage (this one is not persistent) return qx.bom.storage.Memory.getLocal(); }, /** * Get an instance of a session storage. * @return {qx.bom.storage.Web|qx.bom.storage.UserData|qx.bom.storage.Memory} * An instance of a storage implementation. */ getSession : function(){ // always use HTML5 web storage if available if(qx.core.Environment.get("html.storage.local")){ return qx.bom.storage.Web.getSession(); } else if(qx.core.Environment.get("html.storage.userdata")){ // IE <8 fallback // as fallback,use the userdata storage for IE5.5 - 8 return qx.bom.storage.UserData.getSession(); }; // as last fallback, use a in memory storage (this one is not persistent) return qx.bom.storage.Memory.getSession(); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Internal class which contains the checks used by {@link qx.core.Environment}. * All checks in here are marked as internal which means you should never use * them directly. * * This class should contain all checks about HTML. * * @internal */ qx.Bootstrap.define("qx.bom.client.Html", { statics : { /** * Whether the client supports Web Workers. * * @internal * @return {Boolean} <code>true</code> if webworkers are supported */ getWebWorker : function(){ return window.Worker != null; }, /** * Whether the client supports File Readers * * @internal * @return {Boolean} <code>true</code> if FileReaders are supported */ getFileReader : function(){ return window.FileReader != null; }, /** * Whether the client supports Geo Location. * * @internal * @return {Boolean} <code>true</code> if geolocation supported */ getGeoLocation : function(){ return navigator.geolocation != null; }, /** * Whether the client supports audio. * * @internal * @return {Boolean} <code>true</code> if audio is supported */ getAudio : function(){ return !!document.createElement('audio').canPlayType; }, /** * Whether the client can play ogg audio format. * * @internal * @return {String} "" or "maybe" or "probably" */ getAudioOgg : function(){ if(!qx.bom.client.Html.getAudio()){ return ""; }; var a = document.createElement("audio"); return a.canPlayType("audio/ogg"); }, /** * Whether the client can play mp3 audio format. * * @internal * @return {String} "" or "maybe" or "probably" */ getAudioMp3 : function(){ if(!qx.bom.client.Html.getAudio()){ return ""; }; var a = document.createElement("audio"); return a.canPlayType("audio/mpeg"); }, /** * Whether the client can play wave audio wave format. * * @internal * @return {String} "" or "maybe" or "probably" */ getAudioWav : function(){ if(!qx.bom.client.Html.getAudio()){ return ""; }; var a = document.createElement("audio"); return a.canPlayType("audio/x-wav"); }, /** * Whether the client can play au audio format. * * @internal * @return {String} "" or "maybe" or "probably" */ getAudioAu : function(){ if(!qx.bom.client.Html.getAudio()){ return ""; }; var a = document.createElement("audio"); return a.canPlayType("audio/basic"); }, /** * Whether the client can play aif audio format. * * @internal * @return {String} "" or "maybe" or "probably" */ getAudioAif : function(){ if(!qx.bom.client.Html.getAudio()){ return ""; }; var a = document.createElement("audio"); return a.canPlayType("audio/x-aiff"); }, /** * Whether the client supports video. * * @internal * @return {Boolean} <code>true</code> if video is supported */ getVideo : function(){ return !!document.createElement('video').canPlayType; }, /** * Whether the client supports ogg video. * * @internal * @return {String} "" or "maybe" or "probably" */ getVideoOgg : function(){ if(!qx.bom.client.Html.getVideo()){ return ""; }; var v = document.createElement("video"); return v.canPlayType('video/ogg; codecs="theora, vorbis"'); }, /** * Whether the client supports mp4 video. * * @internal * @return {String} "" or "maybe" or "probably" */ getVideoH264 : function(){ if(!qx.bom.client.Html.getVideo()){ return ""; }; var v = document.createElement("video"); return v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"'); }, /** * Whether the client supports webm video. * * @internal * @return {String} "" or "maybe" or "probably" */ getVideoWebm : function(){ if(!qx.bom.client.Html.getVideo()){ return ""; }; var v = document.createElement("video"); return v.canPlayType('video/webm; codecs="vp8, vorbis"'); }, /** * Whether the client supports local storage. * * @internal * @return {Boolean} <code>true</code> if local storage is supported */ getLocalStorage : function(){ try{ return window.localStorage != null; } catch(exc) { // Firefox Bug: Local execution of window.sessionStorage throws error // see https://bugzilla.mozilla.org/show_bug.cgi?id=357323 return false; }; }, /** * Whether the client supports session storage. * * @internal * @return {Boolean} <code>true</code> if session storage is supported */ getSessionStorage : function(){ try{ return window.sessionStorage != null; } catch(exc) { // Firefox Bug: Local execution of window.sessionStorage throws error // see https://bugzilla.mozilla.org/show_bug.cgi?id=357323 return false; }; }, /** * Whether the client supports user data to persist data. This is only * relevant for IE < 8. * * @internal * @return {Boolean} <code>true</code> if the user data is supported. */ getUserDataStorage : function(){ var el = document.createElement("div"); el.style["display"] = "none"; document.getElementsByTagName("head")[0].appendChild(el); var supported = false; try{ el.addBehavior("#default#userdata"); el.load("qxtest"); supported = true; } catch(e) { }; document.getElementsByTagName("head")[0].removeChild(el); return supported; }, /** * Whether the browser supports CSS class lists. * https://developer.mozilla.org/en/DOM/element.classList * * @internal * @return {Boolean} <code>true</code> if class list is supported. */ getClassList : function(){ return !!(document.documentElement.classList && qx.Bootstrap.getClass(document.documentElement.classList) === "DOMTokenList"); }, /** * Checks if XPath could be used. * * @internal * @return {Boolean} <code>true</code> if xpath is supported. */ getXPath : function(){ return !!document.evaluate; }, /** * Checks if XUL could be used. * * @internal * @return {Boolean} <code>true</code> if XUL is supported. */ getXul : function(){ try{ document.createElementNS("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul", "label"); return true; } catch(e) { return false; }; }, /** * Checks if SVG could be used * * @internal * @return {Boolean} <code>true</code> if SVG is supported. */ getSvg : function(){ return document.implementation && document.implementation.hasFeature && (document.implementation.hasFeature("org.w3c.dom.svg", "1.0") || document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); }, /** * Checks if VML is supported * * @internal * @return {Boolean} <code>true</code> if VML is supported. */ getVml : function(){ var el = document.createElement("div"); document.body.appendChild(el); el.innerHTML = '<v:shape id="vml_flag1" adj="1" />'; el.firstChild.style.behavior = "url(#default#VML)"; var hasVml = typeof el.firstChild.adj == "object"; document.body.removeChild(el); return hasVml; }, /** * Checks if canvas could be used * * @internal * @return {Boolean} <code>true</code> if canvas is supported. */ getCanvas : function(){ return !!window.CanvasRenderingContext2D; }, /** * Asynchronous check for using data urls. * * @internal * @param callback {Function} The function which should be executed as * soon as the check is done. */ getDataUrl : function(callback){ var data = new Image(); data.onload = data.onerror = function(){ // wrap that into a timeout because IE might execute it synchronously window.setTimeout(function(){ callback.call(null, (data.width == 1 && data.height == 1)); }, 0); }; data.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="; }, /** * Checks if dataset could be used * * @internal * @return {Boolean} <code>true</code> if dataset is supported. */ getDataset : function(){ return !!document.documentElement.dataset; }, /** * Check for element.contains * * @internal * @return {Boolean} <code>true</code> if element.contains is supported */ getContains : function(){ // "object" in IE6/7/8, "function" in IE9 return (typeof document.documentElement.contains !== "undefined"); }, /** * Check for element.compareDocumentPosition * * @internal * @return {Boolean} <code>true</code> if element.compareDocumentPosition is supported */ getCompareDocumentPosition : function(){ return (typeof document.documentElement.compareDocumentPosition === "function"); }, /** * Check for element.textContent. Legacy IEs do not support this, use * innerText instead. * * @internal * @return {Boolean} <code>true</code> if textContent is supported */ getTextContent : function(){ var el = document.createElement("span"); return (typeof el.textContent !== "undefined"); }, /** * Check for a console object. * * @internal * @return {Boolean} <code>true</code> if a console is available. */ getConsole : function(){ return typeof window.console !== "undefined"; }, /** * Check for the <code>naturalHeight</code> and <code>naturalWidth</code> * image element attributes. * * @internal * @return {Boolean} <code>true</code> if both attributes are supported */ getNaturalDimensions : function(){ var img = document.createElement("img"); return typeof img.naturalHeight === "number" && typeof img.naturalWidth === "number"; }, /** * Check for HTML5 history manipulation support. * @internal * @return {Boolean} <code>true</code> if the HTML5 history API is supported */ getHistoryState : function(){ return (typeof window.onpopstate !== "undefined" && typeof window.history.replaceState !== "undefined" && typeof window.history.pushState !== "undefined"); } }, defer : function(statics){ qx.core.Environment.add("html.webworker", statics.getWebWorker); qx.core.Environment.add("html.filereader", statics.getFileReader); qx.core.Environment.add("html.geolocation", statics.getGeoLocation); qx.core.Environment.add("html.audio", statics.getAudio); qx.core.Environment.add("html.audio.ogg", statics.getAudioOgg); qx.core.Environment.add("html.audio.mp3", statics.getAudioMp3); qx.core.Environment.add("html.audio.wav", statics.getAudioWav); qx.core.Environment.add("html.audio.au", statics.getAudioAu); qx.core.Environment.add("html.audio.aif", statics.getAudioAif); qx.core.Environment.add("html.video", statics.getVideo); qx.core.Environment.add("html.video.ogg", statics.getVideoOgg); qx.core.Environment.add("html.video.h264", statics.getVideoH264); qx.core.Environment.add("html.video.webm", statics.getVideoWebm); qx.core.Environment.add("html.storage.local", statics.getLocalStorage); qx.core.Environment.add("html.storage.session", statics.getSessionStorage); qx.core.Environment.add("html.storage.userdata", statics.getUserDataStorage); qx.core.Environment.add("html.classlist", statics.getClassList); qx.core.Environment.add("html.xpath", statics.getXPath); qx.core.Environment.add("html.xul", statics.getXul); qx.core.Environment.add("html.canvas", statics.getCanvas); qx.core.Environment.add("html.svg", statics.getSvg); qx.core.Environment.add("html.vml", statics.getVml); qx.core.Environment.add("html.dataset", statics.getDataset); qx.core.Environment.addAsync("html.dataurl", statics.getDataUrl); qx.core.Environment.add("html.element.contains", statics.getContains); qx.core.Environment.add("html.element.compareDocumentPosition", statics.getCompareDocumentPosition); qx.core.Environment.add("html.element.textcontent", statics.getTextContent); qx.core.Environment.add("html.console", statics.getConsole); qx.core.Environment.add("html.image.naturaldimensions", statics.getNaturalDimensions); qx.core.Environment.add("html.history.state", statics.getHistoryState); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.bom.storage.Web#getLength) #require(qx.bom.storage.Web#setItem) #require(qx.bom.storage.Web#getItem) #require(qx.bom.storage.Web#removeItem) #require(qx.bom.storage.Web#clear) #require(qx.bom.storage.Web#getKey) #require(qx.bom.storage.Web#forEach) ************************************************************************ */ /** * Storage implementation using HTML web storage: * http://www.w3.org/TR/webstorage/ */ qx.Bootstrap.define("qx.bom.storage.Web", { statics : { __local : null, __session : null, /** * Static accessor for the local storage. * @return {qx.bom.storage.Web} An instance of a local storage. */ getLocal : function(){ if(this.__local){ return this.__local; }; return this.__local = new qx.bom.storage.Web("local"); }, /** * Static accessor for the session storage. * @return {qx.bom.storage.Web} An instance of a session storage. */ getSession : function(){ if(this.__session){ return this.__session; }; return this.__session = new qx.bom.storage.Web("session"); } }, /** * Create a new instance. Usually, you should take the static * accessors to get your instance. * * @param type {String} type of storage, either * <code>local</code> or <code>session</code>. */ construct : function(type){ this.__type = type; }, members : { __type : null, /** * Returns the internal used storage (the native object). * * @internal * @return {Storage} The native storage implementation. */ getStorage : function(){ return window[this.__type + "Storage"]; }, /** * Returns the amount of key-value pairs stored. * @return {Integer} The length of the storage. */ getLength : function(){ return this.getStorage(this.__type).length; }, /** * Store an item in the storage. * * @param key {String} The identifier key. * @param value {var} The data, which will be stored as JSON. */ setItem : function(key, value){ value = qx.lang.Json.stringify(value); try{ this.getStorage(this.__type).setItem(key, value); } catch(e) { throw new Error("Storage full."); }; }, /** * Returns the stored item. * * @param key {String} The identifier to get the data. * @return {var} The stored data. */ getItem : function(key){ var item = this.getStorage(this.__type).getItem(key); if(qx.lang.Type.isString(item)){ item = qx.lang.Json.parse(item); } else if(item && item.value && qx.lang.Type.isString(item.value)){ item = qx.lang.Json.parse(item.value); }; return item; }, /** * Removes an item form the storage. * @param key {String} The identifier. */ removeItem : function(key){ this.getStorage(this.__type).removeItem(key); }, /** * Deletes every stored item in the storage. */ clear : function(){ var storage = this.getStorage(this.__type); if(!storage.clear){ for(var i = storage.length - 1;i >= 0;i--){ storage.removeItem(storage.key(i)); }; } else { storage.clear(); }; }, /** * Returns the named key at the given index. * @param index {Integer} The index in the storage. * @return {String} The key stored at the given index. */ getKey : function(index){ return this.getStorage(this.__type).key(index); }, /** * Helper to access every stored item. * * @param callback {Function} A function which will be called for every item. * The function will have two arguments, first the key and second the value * of the stored data. * @param scope {var} The scope of the function. */ forEach : function(callback, scope){ var length = this.getLength(); for(var i = 0;i < length;i++){ var key = this.getKey(i); callback.call(scope, key, this.getItem(key)); }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ________________________________________________________________________ This class contains code based on the following work: http://www.JSON.org/json2.js 2009-06-29 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html ************************************************************************ */ /** * Pure JavaScript implementation of the EcmaScript 3.1 JSON object. This class * is used, if the browser does not support it natively. * * @internal */ qx.Bootstrap.define("qx.lang.JsonImpl", { extend : Object, construct : function(){ // bind parse and stringify so they can be called without a context. this.stringify = qx.lang.Function.bind(this.stringify, this); this.parse = qx.lang.Function.bind(this.parse, this); }, members : { __gap : null, __indent : null, __rep : null, __stack : null, /** * This method produces a JSON text from a JavaScript value. * * @param value {var} any JavaScript value, usually an object or array. * * @param replacer {Function?} an optional parameter that determines how * object values are stringified for objects. It can be a function or an * array of strings. * * @param space {String?} an optional parameter that specifies the * indentation of nested structures. If it is omitted, the text will * be packed without extra whitespace. If it is a number, it will specify * the number of spaces to indent at each level. If it is a string * (such as '\t' or '&nbsp;'), it contains the characters used to indent * at each level. * * @return {String} The JSON string of the value */ stringify : function(value, replacer, space){ this.__gap = ''; this.__indent = ''; this.__stack = []; if(qx.lang.Type.isNumber(space)){ // If the space parameter is a number, make an indent string containing that // many spaces. var space = Math.min(10, Math.floor(space)); for(var i = 0;i < space;i += 1){ this.__indent += ' '; }; } else if(qx.lang.Type.isString(space)){ if(space.length > 10){ space = space.slice(0, 10); }; // If the space parameter is a string, it will be used as the indent string. this.__indent = space; }; // If there is a replacer, it must be a function or an array. // Otherwise, ignore it. if(replacer && (qx.lang.Type.isFunction(replacer) || qx.lang.Type.isArray(replacer))){ this.__rep = replacer; } else { this.__rep = null; }; // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return this.__str('', { '' : value }); }, /** * Produce a string from holder[key]. * * @param key {String} the map key * @param holder {Object} an object with the given key * @return {String} The string representation of holder[key] */ __str : function(key, holder){ var mind = this.__gap,partial,value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if(value && qx.lang.Type.isFunction(value.toJSON)){ value = value.toJSON(key); } else if(qx.lang.Type.isDate(value)){ value = this.dateToJSON(value); }; // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if(typeof this.__rep === 'function'){ value = this.__rep.call(holder, key, value); }; if(value === null){ return 'null'; }; if(value === undefined){ return undefined; }; // What happens next depends on the value's type. switch(qx.lang.Type.getClass(value)){case 'String': return this.__quote(value);case 'Number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null';case 'Boolean': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value);case 'Array': // Make an array to hold the partial results of stringifying this array value. this.__gap += this.__indent; partial = []; if(this.__stack.indexOf(value) !== -1){ throw new TypeError("Cannot stringify a recursive object."); }; this.__stack.push(value); // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. var length = value.length; for(var i = 0;i < length;i += 1){ partial[i] = this.__str(i, value) || 'null'; }; this.__stack.pop(); // Join all of the elements together, separated with commas, and wrap them in // brackets. if(partial.length === 0){ var string = '[]'; } else if(this.__gap){ string = '[\n' + this.__gap + partial.join(',\n' + this.__gap) + '\n' + mind + ']'; } else { string = '[' + partial.join(',') + ']'; }; this.__gap = mind; return string;case 'Object': // Make an array to hold the partial results of stringifying this object value. this.__gap += this.__indent; partial = []; if(this.__stack.indexOf(value) !== -1){ throw new TypeError("Cannot stringify a recursive object."); }; this.__stack.push(value); // If the replacer is an array, use it to select the members to be stringified. if(this.__rep && typeof this.__rep === 'object'){ var length = this.__rep.length; for(var i = 0;i < length;i += 1){ var k = this.__rep[i]; if(typeof k === 'string'){ var v = this.__str(k, value); if(v){ partial.push(this.__quote(k) + (this.__gap ? ': ' : ':') + v); }; }; }; } else { // Otherwise, iterate through all of the keys in the object. for(var k in value){ if(Object.hasOwnProperty.call(value, k)){ var v = this.__str(k, value); if(v){ partial.push(this.__quote(k) + (this.__gap ? ': ' : ':') + v); }; }; }; }; this.__stack.pop(); // Join all of the member texts together, separated with commas, // and wrap them in braces. if(partial.length === 0){ var string = '{}'; } else if(this.__gap){ string = '{\n' + this.__gap + partial.join(',\n' + this.__gap) + '\n' + mind + '}'; } else { string = '{' + partial.join(',') + '}'; }; this.__gap = mind; return string;}; }, /** * Convert a date to JSON * * @param date {Date} The date to convert * @return {String} The JSON representation of the date */ dateToJSON : function(date){ // Format integers to have at least two digits. var f2 = function(n){ return n < 10 ? '0' + n : n; }; var f3 = function(n){ var value = f2(n); return n < 100 ? '0' + value : value; }; return isFinite(date.valueOf()) ? date.getUTCFullYear() + '-' + f2(date.getUTCMonth() + 1) + '-' + f2(date.getUTCDate()) + 'T' + f2(date.getUTCHours()) + ':' + f2(date.getUTCMinutes()) + ':' + f2(date.getUTCSeconds()) + '.' + f3(date.getUTCMilliseconds()) + 'Z' : null; }, /** * If the string contains no control characters, no quote characters, and no * backslash characters, then we can safely slap some quotes around it. * Otherwise we must also replace the offending characters with safe escape * sequences. * * @param string {String} The string to quote * @return {String} The quoted string */ __quote : function(string){ var meta = { // table of character substitutions '\b' : '\\b', '\t' : '\\t', '\n' : '\\n', '\f' : '\\f', '\r' : '\\r', '"' : '\\"', '\\' : '\\\\' }; var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; escapable.lastIndex = 0; if(escapable.test(string)){ return '"' + string.replace(escapable, function(a){ var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"'; } else { return '"' + string + '"'; }; }, /** * This method parses a JSON text to produce an object or array. * It can throw a SyntaxError exception. * * @param text {String} JSON string to parse * * @param reviver {Function?} Optional reviver function to filter and * transform the results * * @return {Object} The parsed JSON object * * @lint ignoreDeprecated(eval) */ parse : function(text, reviver){ var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; cx.lastIndex = 0; // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. if(cx.test(text)){ text = text.replace(cx, function(a){ return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); }; // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))){ // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. var j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? this.__walk({ '' : j }, '', reviver) : j; }; // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }, /** * The walk method is used to recursively walk the resulting structure so * that modifications can be made. * * @param holder {Object} the root object * @param key {String} walk holder[key] * @param reviver {Function} callback, which is called on every node. * @return {var} The reviver's return value */ __walk : function(holder, key, reviver){ var value = holder[key]; if(value && typeof value === 'object'){ for(var k in value){ if(Object.hasOwnProperty.call(value, k)){ var v = this.__walk(value, k, reviver); if(v !== undefined){ value[k] = v; } else { delete value[k]; }; }; }; }; return reviver.call(holder, key, value); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ====================================================================== This class contains code based on the following work: * Mootools http://mootools.net Version 1.1.1 Copyright: 2007 Valerio Proietti License: MIT: http://www.opensource.org/licenses/mit-license.php ************************************************************************ */ /* ************************************************************************ #require(qx.lang.Array) #ignore(qx.core.Object) #ignore(qx.event.GlobalError) ************************************************************************ */ /** * Collection of helper methods operating on functions. */ qx.Bootstrap.define("qx.lang.Function", { statics : { /** * Extract the caller of a function from the arguments variable. * This will not work in Opera < 9.6. * * @param args {arguments} The local arguments variable * @return {Function} A reference to the calling function or "undefined" if caller is not supported. */ getCaller : function(args){ return args.caller ? args.caller.callee : args.callee.caller; }, /** * Try to get a sensible textual description of a function object. * This may be the class/mixin and method name of a function * or at least the signature of the function. * * @param fcn {Function} function the get the name for. * @return {String} Name of the function. */ getName : function(fcn){ if(fcn.displayName){ return fcn.displayName; }; if(fcn.$$original || fcn.wrapper || fcn.classname){ return fcn.classname + ".constructor()"; }; if(fcn.$$mixin){ //members for(var key in fcn.$$mixin.$$members){ if(fcn.$$mixin.$$members[key] == fcn){ return fcn.$$mixin.name + ".prototype." + key + "()"; }; }; // statics for(var key in fcn.$$mixin){ if(fcn.$$mixin[key] == fcn){ return fcn.$$mixin.name + "." + key + "()"; }; }; }; if(fcn.self){ var clazz = fcn.self.constructor; if(clazz){ // members for(var key in clazz.prototype){ if(clazz.prototype[key] == fcn){ return clazz.classname + ".prototype." + key + "()"; }; }; // statics for(var key in clazz){ if(clazz[key] == fcn){ return clazz.classname + "." + key + "()"; }; }; }; }; var fcnReResult = fcn.toString().match(/function\s*(\w*)\s*\(.*/); if(fcnReResult && fcnReResult.length >= 1 && fcnReResult[1]){ return fcnReResult[1] + "()"; }; return 'anonymous()'; }, /** * Evaluates JavaScript code globally * * @lint ignoreDeprecated(eval) * * @param data {String} JavaScript commands * @return {var} Result of the execution */ globalEval : function(data){ if(window.execScript){ return window.execScript(data); } else { return eval.call(window, data); }; }, /** * empty function * @deprecated {2.1} Please use a new empty function. */ empty : function(){ }, /** * Simply return true. * @deprecated {2.1} Please use a custom function. * @return {Boolean} Always returns true. */ returnTrue : function(){ return true; }, /** * Simply return false. * @deprecated {2.1} Please use a custom function. * @return {Boolean} Always returns false. */ returnFalse : function(){ return false; }, /** * Simply return null. * @deprecated {2.1} Please use a custom function. * @return {var} Always returns null. */ returnNull : function(){ return null; }, /** * Return "this". * @deprecated {2.1} Please use a custom function. * @return {Object} Always returns "this". */ returnThis : function(){ return this; }, /** * Simply return 0. * @deprecated {2.1} Please use a custom function. * @return {Number} Always returns 0. */ returnZero : function(){ return 0; }, /** * Base function for creating functional closures which is used by most other methods here. * * *Syntax* * * <pre class='javascript'>var createdFunction = qx.lang.Function.create(myFunction, [options]);</pre> * * @param func {Function} Original function to wrap * @param options {Map?} Map of options * <ul> * <li><strong>self</strong>: The object that the "this" of the function will refer to. Default is the same as the wrapper function is called.</li> * <li><strong>args</strong>: An array of arguments that will be passed as arguments to the function when called. * Default is no custom arguments; the function will receive the standard arguments when called.</li> * <li><strong>delay</strong>: If set, the returned function will delay the actual execution by this amount of milliseconds and return a timer handle when called. * Default is no delay.</li> * <li><strong>periodical</strong>: If set the returned function will periodically perform the actual execution with this specified interval * and return a timer handle when called. Default is no periodical execution.</li> * <li><strong>attempt</strong>: If set to true, the returned function will try to execute and return either the results or false on error. Default is false.</li> * </ul> * * @return {Function} Wrapped function */ create : function(func, options){ { }; // Nothing to be done when there are no options. if(!options){ return func; }; // Check for at least one attribute. if(!(options.self || options.args || options.delay != null || options.periodical != null || options.attempt)){ return func; }; return function(event){ { }; // Convert (and copy) incoming arguments var args = qx.lang.Array.fromArguments(arguments); // Prepend static arguments if(options.args){ args = options.args.concat(args); }; if(options.delay || options.periodical){ var returns = function(){ return func.apply(options.self || this, args); }; if(qx.core.Environment.get("qx.globalErrorHandling")){ returns = qx.event.GlobalError.observeMethod(returns); }; if(options.delay){ return window.setTimeout(returns, options.delay); }; if(options.periodical){ return window.setInterval(returns, options.periodical); }; } else if(options.attempt){ var ret = false; try{ ret = func.apply(options.self || this, args); } catch(ex) { }; return ret; } else { return func.apply(options.self || this, args); }; }; }, /** * Returns a function whose "this" is altered. * * * *Native way* * * This is also a feature of JavaScript 1.8.5 and will be supplied * by modern browsers. Including {@link qx.lang.normalize.Function} * will supply a cross browser normalization of the native * implementation. We like to encourage you to use the native function! * * * *Syntax* * * <pre class='javascript'>qx.lang.Function.bind(myFunction, [self, [varargs...]]);</pre> * * *Example* * * <pre class='javascript'> * function myFunction() * { * this.setStyle('color', 'red'); * // note that 'this' here refers to myFunction, not an element * // we'll need to bind this function to the element we want to alter * }; * * var myBoundFunction = qx.lang.Function.bind(myFunction, myElement); * myBoundFunction(); // this will make the element myElement red. * </pre> * * If you find yourself using this static method a lot, you may be * interested in the bindTo() method in the mixin qx.core.MBindTo. * * @see qx.core.MBindTo * * @param func {Function} Original function to wrap * @param self {Object ? null} The object that the "this" of the function will refer to. * @param varargs {arguments ? null} The arguments to pass to the function. * @return {Function} The bound function. */ bind : function(func, self, varargs){ return this.create(func, { self : self, args : arguments.length > 2 ? qx.lang.Array.fromArguments(arguments, 2) : null }); }, /** * Returns a function whose arguments are pre-configured. * * *Syntax* * * <pre class='javascript'>qx.lang.Function.curry(myFunction, [varargs...]);</pre> * * *Example* * * <pre class='javascript'> * function myFunction(elem) { * elem.setStyle('color', 'red'); * }; * * var myBoundFunction = qx.lang.Function.curry(myFunction, myElement); * myBoundFunction(); // this will make the element myElement red. * </pre> * * @param func {Function} Original function to wrap * @param varargs {arguments} The arguments to pass to the function. * @return {var} The pre-configured function. */ curry : function(func, varargs){ return this.create(func, { args : arguments.length > 1 ? qx.lang.Array.fromArguments(arguments, 1) : null }); }, /** * Returns a function which could be used as a listener for a native event callback. * * *Syntax* * * <pre class='javascript'>qx.lang.Function.listener(myFunction, [self, [varargs...]]);</pre> * * @param func {Function} Original function to wrap * @param self {Object ? null} The object that the "this" of the function will refer to. * @param varargs {arguments ? null} The arguments to pass to the function. * @return {var} The bound function. */ listener : function(func, self, varargs){ if(arguments.length < 3){ return function(event){ // Directly execute, but force first parameter to be the event object. return func.call(self || this, event || window.event); }; } else { var optargs = qx.lang.Array.fromArguments(arguments, 2); return function(event){ var args = [event || window.event]; // Append static arguments args.push.apply(args, optargs); // Finally execute original method func.apply(self || this, args); }; }; }, /** * Tries to execute the function. * * *Syntax* * * <pre class='javascript'>var result = qx.lang.Function.attempt(myFunction, [self, [varargs...]]);</pre> * * *Example* * * <pre class='javascript'> * var myObject = { * 'cow': 'moo!' * }; * * var myFunction = function() * { * for(var i = 0; i < arguments.length; i++) { * if(!this[arguments[i]]) throw('doh!'); * } * }; * * var result = qx.lang.Function.attempt(myFunction, myObject, 'pig', 'cow'); // false * </pre> * * @param func {Function} Original function to wrap * @param self {Object ? null} The object that the "this" of the function will refer to. * @param varargs {arguments ? null} The arguments to pass to the function. * @return {Boolean|var} <code>false</code> if an exception is thrown, else the function's return. */ attempt : function(func, self, varargs){ return this.create(func, { self : self, attempt : true, args : arguments.length > 2 ? qx.lang.Array.fromArguments(arguments, 2) : null })(); }, /** * Delays the execution of a function by a specified duration. * * *Syntax* * * <pre class='javascript'>var timeoutID = qx.lang.Function.delay(myFunction, [delay, [self, [varargs...]]]);</pre> * * *Example* * * <pre class='javascript'> * var myFunction = function(){ alert('moo! Element id is: ' + this.id); }; * //wait 50 milliseconds, then call myFunction and bind myElement to it * qx.lang.Function.delay(myFunction, 50, myElement); // alerts: 'moo! Element id is: ... ' * * // An anonymous function, example * qx.lang.Function.delay(function(){ alert('one second later...'); }, 1000); //wait a second and alert * </pre> * * @param func {Function} Original function to wrap * @param delay {Integer} The duration to wait (in milliseconds). * @param self {Object ? null} The object that the "this" of the function will refer to. * @param varargs {arguments ? null} The arguments to pass to the function. * @return {Integer} The JavaScript Timeout ID (useful for clearing delays). */ delay : function(func, delay, self, varargs){ return this.create(func, { delay : delay, self : self, args : arguments.length > 3 ? qx.lang.Array.fromArguments(arguments, 3) : null })(); }, /** * Executes a function in the specified intervals of time * * *Syntax* * * <pre class='javascript'>var intervalID = qx.lang.Function.periodical(myFunction, [period, [self, [varargs...]]]);</pre> * * *Example* * * <pre class='javascript'> * var Site = { counter: 0 }; * var addCount = function(){ this.counter++; }; * qx.lang.Function.periodical(addCount, 1000, Site); // will add the number of seconds at the Site * </pre> * * @param func {Function} Original function to wrap * @param interval {Integer} The duration of the intervals between executions. * @param self {Object ? null} The object that the "this" of the function will refer to. * @param varargs {arguments ? null} The arguments to pass to the function. * @return {Integer} The Interval ID (useful for clearing a periodical). */ periodical : function(func, interval, self, varargs){ return this.create(func, { periodical : interval, self : self, args : arguments.length > 3 ? qx.lang.Array.fromArguments(arguments, 3) : null })(); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ________________________________________________________________________ This class contains code based on the following work: http://www.JSON.org/json2.js 2009-06-29 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html ************************************************************************ */ /** * JSON (JavaScript Object Notation) parser, serializer for qooxdoo * * This class implements EcmaScript 3.1 JSON support. * * http://wiki.ecmascript.org/doku.php?id=es3.1:json_support * * If the browser supports native JSON the browser implementation is used. */ qx.Bootstrap.define("qx.lang.Json", { statics : { /** * {JSON} The JSON object to use. If the browser has native JSON support * this member points to <code>window.JSON</code>. Otherwise it points to * the qooxdoo implementation {@link JsonImpl}. */ JSON : true ? window.JSON : new qx.lang.JsonImpl(), /** * This method produces a JSON text from a JavaScript value. * * When an object value is found, if the object contains a toJSON * method, its toJSON method will be called and the result will be * stringified. A toJSON method does not serialize: it returns the * value represented by the name/value pair that should be serialized, * or undefined if nothing should be serialized. The toJSON method * will be passed the key associated with the value, and this will be * bound to the object holding the key. * * For example, this would serialize Dates as ISO strings. * * <pre class="javascript"> * Date.prototype.toJSON = function (key) { * function f(n) { * // Format integers to have at least two digits. * return n < 10 ? '0' + n : n; * } * * return this.getUTCFullYear() + '-' + * f(this.getUTCMonth() + 1) + '-' + * f(this.getUTCDate()) + 'T' + * f(this.getUTCHours()) + ':' + * f(this.getUTCMinutes()) + ':' + * f(this.getUTCSeconds()) + 'Z'; * }; * </pre> * * You can provide an optional replacer method. It will be passed the * key and value of each member, with this bound to the containing * object. The value that is returned from your method will be * serialized. If your method returns undefined, then the member will * be excluded from the serialization. * * If the replacer parameter is an array of strings, then it will be * used to select the members to be serialized. It filters the results * such that only members with keys listed in the replacer array are * stringified. * * Values that do not have JSON representations, such as undefined or * functions, will not be serialized. Such values in objects will be * dropped; in arrays they will be replaced with null. You can use * a replacer function to replace those with JSON values. * JSON.stringify(undefined) returns undefined. * * The optional space parameter produces a stringification of the * value that is filled with line breaks and indentation to make it * easier to read. * * If the space parameter is a non-empty string, then that string will * be used for indentation. If the space parameter is a number, then * the indentation will be that many spaces. * * Example: * * <pre class="javascript"> * text = JSON.stringify(['e', {pluribus: 'unum'}]); * // text is '["e",{"pluribus":"unum"}]' * * * text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); * // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' * * text = JSON.stringify([new Date()], function (key, value) { * return this[key] instanceof Date ? * 'Date(' + this[key] + ')' : value; * }); * // text is '["Date(---current time---)"]' * </pre> * * @signature function(value, replacer, space) * * @param value {var} any JavaScript value, usually an object or array. * * @param replacer {Function?} an optional parameter that determines how * object values are stringified for objects. It can be a function or an * array of strings. * * @param space {String?} an optional parameter that specifies the * indentation of nested structures. If it is omitted, the text will * be packed without extra whitespace. If it is a number, it will specify * the number of spaces to indent at each level. If it is a string * (such as '\t' or '&nbsp;'), it contains the characters used to indent * at each level. * * @return {String} The JSON string of the value */ stringify : null, // will be set in the defer block /** * This method parses a JSON text to produce an object or array. * It can throw a SyntaxError exception. * * The optional reviver parameter is a function that can filter and * transform the results. It receives each of the keys and values, * and its return value is used instead of the original value. * If it returns what it received, then the structure is not modified. * If it returns undefined then the member is deleted. * * Example: * * <pre class="javascript"> * // Parse the text. Values that look like ISO date strings will * // be converted to Date objects. * * myData = JSON.parse(text, function (key, value) * { * if (typeof value === 'string') * { * var a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); * if (a) { * return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); * } * } * return value; * }); * * myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { * var d; * if (typeof value === 'string' && * value.slice(0, 5) === 'Date(' && * value.slice(-1) === ')') { * d = new Date(value.slice(5, -1)); * if (d) { * return d; * } * } * return value; * }); * </pre> * * @signature function(text, reviver) * * @param text {String} JSON string to parse * * @param reviver {Function?} Optional reviver function to filter and * transform the results * * @return {Object} The parsed JSON object */ parse : null }, defer : function(statics){ statics.stringify = statics.JSON.stringify; statics.parse = statics.JSON.parse; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.bom.storage.UserData#getLength) #require(qx.bom.storage.UserData#setItem) #require(qx.bom.storage.UserData#getItem) #require(qx.bom.storage.UserData#removeItem) #require(qx.bom.storage.UserData#clear) #require(qx.bom.storage.UserData#getKey) #require(qx.bom.storage.UserData#forEach) ************************************************************************ */ /** * Fallback storage implementation usable in IE browsers. It is recommended to use * these implementation only in IE < 8 because IE >= 8 supports * {@link qx.bom.storage.Web}. */ qx.Bootstrap.define("qx.bom.storage.UserData", { statics : { __local : null, __session : null, // global id used as key for the storage __id : 0, /** * Returns an instance of {@link qx.bom.storage.UserData} used to store * data persistent. * @return {qx.bom.storage.UserData} A storage instance. */ getLocal : function(){ if(this.__local){ return this.__local; }; return this.__local = new qx.bom.storage.UserData("local"); }, /** * Returns an instance of {@link qx.bom.storage.UserData} used to store * data persistent. * @return {qx.bom.storage.UserData} A storage instance. */ getSession : function(){ if(this.__session){ return this.__session; }; return this.__session = new qx.bom.storage.UserData("session"); } }, /** * Create a new instance. Usually, you should take the static * accessors to get your instance. * * @param storeName {String} type of storage. */ construct : function(storeName){ // create a dummy DOM element used for storage this.__el = document.createElement("div"); this.__el.style["display"] = "none"; document.getElementsByTagName("head")[0].appendChild(this.__el); this.__el.addBehavior("#default#userdata"); this.__storeName = storeName; // load the inital data which might be stored this.__el.load(this.__storeName); // set up the internal reference maps this.__storage = { }; this.__reference = { }; // initialize var value = this.__el.getAttribute("qx" + qx.bom.storage.UserData.__id); while(value != undefined){ value = qx.lang.Json.parse(value); // save the data in the internal storage this.__storage[value.key] = value.value; // save the reference this.__reference[value.key] = "qx" + qx.bom.storage.UserData.__id; qx.bom.storage.UserData.__id++; value = this.__el.getAttribute("qx" + qx.bom.storage.UserData.__id); }; }, members : { __el : null, __storeName : "qxtest", // storage which holds the key and the value __storage : null, // reference store which holds the key and the key used to store __reference : null, /** * Returns the map used to keep a in memory copy of the stored data. * @return {Map} The stored data. * @internal */ getStorage : function(){ return this.__storage; }, /** * Returns the amount of key-value pairs stored. * @return {Integer} The length of the storage. */ getLength : function(){ return Object.keys(this.__storage).length; }, /** * Store an item in the storage. * * @param key {String} The identifier key. * @param value {var} The data, which will be stored as JSON. */ setItem : function(key, value){ // override case if(this.__reference[key]){ var storageKey = this.__reference[key]; } else { var storageKey = "qx" + qx.bom.storage.UserData.__id; qx.bom.storage.UserData.__id++; }; // build and save the data used to store both, key and value var storageValue = qx.lang.Json.stringify({ key : key, value : value }); this.__el.setAttribute(storageKey, storageValue); this.__el.save(this.__storeName); // also update the internal mappings this.__storage[key] = value; this.__reference[key] = storageKey; }, /** * Returns the stored item. * * @param key {String} The identifier to get the data. * @return {var} The stored data. */ getItem : function(key){ return this.__storage[key] || null; }, /** * Removes an item form the storage. * @param key {String} The identifier. */ removeItem : function(key){ // check if the item is availabel var storageName = this.__reference[key]; if(storageName == undefined){ return; }; // remove the item this.__el.removeAttribute(storageName); // decrease the id because we removed one item qx.bom.storage.UserData.__id--; // update the internal maps delete this.__storage[key]; delete this.__reference[key]; // check if we have deleted the last item var lastStoreName = "qx" + qx.bom.storage.UserData.__id; if(this.__el.getAttribute(lastStoreName)){ // if not, move the last item to the deleted spot var lastItem = this.__el.getAttribute("qx" + qx.bom.storage.UserData.__id); this.__el.removeAttribute(lastStoreName); this.__el.setAttribute(storageName, lastItem); // update the reference map var lastKey = qx.lang.Json.parse(lastItem).key; this.__reference[lastKey] = storageName; }; this.__el.save(this.__storeName); }, /** * Deletes every stored item in the storage. */ clear : function(){ // delete all entries from the storage for(var key in this.__reference){ this.__el.removeAttribute(this.__reference[key]); }; this.__el.save(this.__storeName); // reset the internal maps this.__storage = { }; this.__reference = { }; }, /** * Returns the named key at the given index. * @param index {Integer} The index in the storage. * @return {String} The key stored at the given index. */ getKey : function(index){ return Object.keys(this.__storage)[index]; }, /** * Helper to access every stored item. * * @param callback {Function} A function which will be called for every item. * The function will have two arguments, first the key and second the value * of the stored data. * @param scope {var} The scope of the function. */ forEach : function(callback, scope){ var length = this.getLength(); for(var i = 0;i < length;i++){ var key = this.getKey(i); callback.call(scope, key, this.getItem(key)); }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.bom.storage.Memory#getLength) #require(qx.bom.storage.Memory#setItem) #require(qx.bom.storage.Memory#getItem) #require(qx.bom.storage.Memory#removeItem) #require(qx.bom.storage.Memory#clear) #require(qx.bom.storage.Memory#getKey) #require(qx.bom.storage.Memory#forEach) ************************************************************************ */ /** * Fallback storage implementation which offers the same API as every other storage * but is not persistent. Basically, its just a storage API on a JavaScript map. */ qx.Bootstrap.define("qx.bom.storage.Memory", { statics : { __local : null, __session : null, /** * Returns an instance of {@link qx.bom.storage.Memory} which is of course * not persisted on reload. * @return {qx.bom.storage.Memory} A memory storage. */ getLocal : function(){ if(this.__local){ return this.__local; }; return this.__local = new qx.bom.storage.Memory(); }, /** * Returns an instance of {@link qx.bom.storage.Memory} which is of course * not persisted on reload. * @return {qx.bom.storage.Memory} A memory storage. */ getSession : function(){ if(this.__session){ return this.__session; }; return this.__session = new qx.bom.storage.Memory(); } }, construct : function(){ this.__storage = { }; }, members : { __storage : null, /** * Returns the internal used map. * @return {Map} The storage. * @internal */ getStorage : function(){ return this.__storage; }, /** * Returns the amount of key-value pairs stored. * @return {Integer} The length of the storage. */ getLength : function(){ return Object.keys(this.__storage).length; }, /** * Store an item in the storage. * * @param key {String} The identifier key. * @param value {var} The data, which will be stored as JSON. */ setItem : function(key, value){ value = qx.lang.Json.stringify(value); this.__storage[key] = value; }, /** * Returns the stored item. * * @param key {String} The identifier to get the data. * @return {var} The stored data. */ getItem : function(key){ var item = this.__storage[key]; if(qx.lang.Type.isString(item)){ item = qx.lang.Json.parse(item); }; return item; }, /** * Removes an item form the storage. * @param key {String} The identifier. */ removeItem : function(key){ delete this.__storage[key]; }, /** * Deletes every stored item in the storage. */ clear : function(){ this.__storage = { }; }, /** * Returns the named key at the given index. * @param index {Integer} The index in the storage. * @return {String} The key stored at the given index. */ getKey : function(index){ var keys = Object.keys(this.__storage); return keys[index]; }, /** * Helper to access every stored item. * * @param callback {Function} A function which will be called for every item. * The function will have two arguments, first the key and second the value * of the stored data. * @param scope {var} The scope of the function. */ forEach : function(callback, scope){ var length = this.getLength(); for(var i = 0;i < length;i++){ var key = this.getKey(i); callback.call(scope, key, this.getItem(key)); }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2011-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) * Daniel Wagner (danielwagner) ************************************************************************ */ /** * CSS/Style property manipulation module */ qx.Bootstrap.define("qx.module.Css", { statics : { /** * Modifies the given style property on all elements in the collection. * * @attach {qxWeb} * @param name {String} Name of the style property to modify * @param value {var} The value to apply * @return {qxWeb} The collection for chaining */ setStyle : function(name, value){ if(/\w-\w/.test(name)){ name = qx.lang.String.camelCase(name); }; for(var i = 0;i < this.length;i++){ qx.bom.element.Style.set(this[i], name, value); }; return this; }, /** * Returns the value of the given style property for the first item in the * collection. * * @attach {qxWeb} * @param name {String} Style property name * @return {var} Style property value */ getStyle : function(name){ if(this[0]){ if(/\w-\w/.test(name)){ name = qx.lang.String.camelCase(name); }; return qx.bom.element.Style.get(this[0], name); }; return null; }, /** * Sets multiple style properties for each item in the collection. * * @attach {qxWeb} * @param styles {Map} A map of style property name/value pairs * @return {qxWeb} The collection for chaining */ setStyles : function(styles){ for(var name in styles){ this.setStyle(name, styles[name]); }; return this; }, /** * Returns the values of multiple style properties for each item in the * collection * * @attach {qxWeb} * @param names {String[]} List of style property names * @return {Map} Map of style property name/value pairs */ getStyles : function(names){ var styles = { }; for(var i = 0;i < names.length;i++){ styles[names[i]] = this.getStyle(names[i]); }; return styles; }, /** * Adds a class name to each element in the collection * * @attach {qxWeb} * @param name {String} Class name * @return {qxWeb} The collection for chaining */ addClass : function(name){ for(var i = 0;i < this.length;i++){ qx.bom.element.Class.add(this[i], name); }; return this; }, /** * Adds multiple class names to each element in the collection * * @attach {qxWeb} * @param names {String[]} List of class names to add * @return {qxWeb} The collection for chaining */ addClasses : function(names){ for(var i = 0;i < this.length;i++){ qx.bom.element.Class.addClasses(this[i], names); }; return this; }, /** * Removes a class name from each element in the collection * * @attach {qxWeb} * @param name {String} The class name to remove * @return {qxWeb} The collection for chaining */ removeClass : function(name){ for(var i = 0;i < this.length;i++){ qx.bom.element.Class.remove(this[i], name); }; return this; }, /** * Removes multiple class names from each element in the collection * * @attach {qxWeb} * @param names {String[]} List of class names to remove * @return {qxWeb} The collection for chaining */ removeClasses : function(names){ for(var i = 0;i < this.length;i++){ qx.bom.element.Class.removeClasses(this[i], names); }; return this; }, /** * Checks if the first element in the collection has the given class name * * @attach {qxWeb} * @param name {String} Class name to check for * @return {Boolean} <code>true</code> if the first item has the given class name */ hasClass : function(name){ if(!this[0]){ return false; }; return qx.bom.element.Class.has(this[0], name); }, /** * Returns the class name of the first element in the collection * * @attach {qxWeb} * @return {String} Class name */ getClass : function(){ if(!this[0]){ return ""; }; return qx.bom.element.Class.get(this[0]); }, /** * Toggles the given class name on each item in the collection * * @attach {qxWeb} * @param name {String} Class name * @return {qxWeb} The collection for chaining */ toggleClass : function(name){ var bCls = qx.bom.element.Class; for(var i = 0,l = this.length;i < l;i++){ bCls.has(this[i], name) ? bCls.remove(this[i], name) : bCls.add(this[i], name); }; return this; }, /** * Toggles the given list of class names on each item in the collection * * @attach {qxWeb} * @param names {String[]} Class names * @return {qxWeb} The collection for chaining */ toggleClasses : function(names){ for(var i = 0,l = names.length;i < l;i++){ this.toggleClass(names[i]); }; return this; }, /** * Replaces a class name on each element in the collection * * @attach {qxWeb} * @param oldName {String} Class name to remove * @param newName {String} Class name to add * @return {qxWeb} The collection for chaining */ replaceClass : function(oldName, newName){ for(var i = 0,l = this.length;i < l;i++){ qx.bom.element.Class.replace(this[i], oldName, newName); }; return this; }, /** * Returns the rendered height of the first element in the collection. * @attach {qxWeb} * @return {Number} The first item's rendered height */ getHeight : function(){ var elem = this[0]; if(elem){ if(qx.dom.Node.isElement(elem)){ return qx.bom.element.Dimension.getHeight(elem); } else if(qx.dom.Node.isDocument(elem)){ return qx.bom.Document.getHeight(qx.dom.Node.getWindow(elem)); } else if(qx.dom.Node.isWindow(elem)){ return qx.bom.Viewport.getHeight(elem); };; }; return null; }, /** * Returns the rendered width of the first element in the collection * @attach {qxWeb} * @return {Number} The first item's rendered width */ getWidth : function(){ var elem = this[0]; if(elem){ if(qx.dom.Node.isElement(elem)){ return qx.bom.element.Dimension.getWidth(elem); } else if(qx.dom.Node.isDocument(elem)){ return qx.bom.Document.getWidth(qx.dom.Node.getWindow(elem)); } else if(qx.dom.Node.isWindow(elem)){ return qx.bom.Viewport.getWidth(elem); };; }; return null; }, /** * Returns the computed location of the given element in the context of the * document dimensions. * * @attach {qxWeb} * @return {Map} A map with the keys <code>left<code/>, <code>top<code/>, * <code>right<code/> and <code>bottom<code/> which contains the distance * of the element relative to the document. */ getOffset : function(){ var elem = this[0]; if(elem){ return qx.bom.element.Location.get(elem); }; return null; }, /** * Returns the content height of the first element in the collection. * This is the maximum height the element can use, excluding borders, * margins, padding or scroll bars. * @attach {qxWeb} * @return {Number} Computed content height */ getContentHeight : function(){ var obj = this[0]; if(qx.dom.Node.isElement(obj)){ return qx.bom.element.Dimension.getContentHeight(obj); }; return null; }, /** * Returns the content width of the first element in the collection. * This is the maximum width the element can use, excluding borders, * margins, padding or scroll bars. * @attach {qxWeb} * @return {Number} Computed content width */ getContentWidth : function(){ var obj = this[0]; if(qx.dom.Node.isElement(obj)){ return qx.bom.element.Dimension.getContentWidth(obj); }; return null; }, /** * Returns the distance between the first element in the collection and its * offset parent * * @attach {qxWeb} * @return {Map} a map with the keys <code>left</code> and <code>top</code> * containing the distance between the elements */ getPosition : function(){ var obj = this[0]; if(qx.dom.Node.isElement(obj)){ return qx.bom.element.Location.getPosition(obj); }; return null; }, /** * Includes a Stylesheet file * * @attachStatic {qxWeb} * @param uri {String} The stylesheet's URI * @param doc {Document?} Document to modify */ includeStylesheet : function(uri, doc){ qx.bom.Stylesheet.includeFile(uri, doc); }, /** * Hides all elements in the collection by setting their "display" * style to "none". The previous value is stored so it can be re-applied * when {@link #show} is called. * * @attach {qxWeb} * @return {qxWeb} The collection for chaining */ hide : function(){ for(var i = 0,l = this.length;i < l;i++){ var item = this.slice(i, i + 1); var prevStyle = item.getStyle("display"); if(prevStyle !== "none"){ item[0].$$qPrevDisp = prevStyle; item.setStyle("display", "none"); }; }; return this; }, /** * Shows any elements with "display: none" in the collection. If an element * was hidden by using the {@link #hide} method, its previous * "display" style value will be re-applied. Otherwise, the * default "display" value for the element type will be applied. * * @attach {qxWeb} * @return {qxWeb} The collection for chaining */ show : function(){ for(var i = 0,l = this.length;i < l;i++){ var item = this.slice(i, i + 1); var currentVal = item.getStyle("display"); var prevVal = item[0].$$qPrevDisp; var newVal; if(currentVal == "none"){ if(prevVal && prevVal != "none"){ newVal = prevVal; } else { var doc = qxWeb.getDocument(item[0]); newVal = qx.module.Css.__getDisplayDefault(item[0].tagName, doc); }; item.setStyle("display", newVal); item[0].$$qPrevDisp = "none"; }; }; return this; }, /** * Maps HTML elements to their default "display" style values. */ __displayDefaults : { }, /** * Attempts tp determine the default "display" style value for * elements with the given tag name. * * @param tagName {String} Tag name * @param doc {Document?} Document element. Default: The current document * @return {String} The default "display" value, e.g. <code>inline</code> * or <code>block</code> */ __getDisplayDefault : function(tagName, doc){ var defaults = qx.module.Css.__displayDefaults; if(!defaults[tagName]){ var docu = doc || document; var tempEl = qxWeb(docu.createElement(tagName)).appendTo(doc.body); defaults[tagName] = tempEl.getStyle("display"); tempEl.remove(); }; return defaults[tagName] || ""; } }, defer : function(statics){ qxWeb.$attach({ "setStyle" : statics.setStyle, "getStyle" : statics.getStyle, "setStyles" : statics.setStyles, "getStyles" : statics.getStyles, "addClass" : statics.addClass, "addClasses" : statics.addClasses, "removeClass" : statics.removeClass, "removeClasses" : statics.removeClasses, "hasClass" : statics.hasClass, "getClass" : statics.getClass, "toggleClass" : statics.toggleClass, "toggleClasses" : statics.toggleClasses, "replaceClass" : statics.replaceClass, "getHeight" : statics.getHeight, "getWidth" : statics.getWidth, "getOffset" : statics.getOffset, "getContentHeight" : statics.getContentHeight, "getContentWidth" : statics.getContentWidth, "getPosition" : statics.getPosition, "hide" : statics.hide, "show" : statics.show }); qxWeb.$attachStatic({ "includeStylesheet" : statics.includeStylesheet }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This class takes care of the normalization of the native 'String' object. * Therefore it checks the availability of the following methods and appends * it, if not available. This means you can use the methods during * development in every browser. For usage samples, check out the attached links. * * *trim*: * <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/Trim">MDN documentation</a> | * <a href="http://es5.github.com/#x15.5.4.20">Annotated ES5 Spec</a> */ qx.Bootstrap.define("qx.lang.normalize.String", { defer : function(){ // trim if(!qx.core.Environment.get("ecmascript.string.trim")){ String.prototype.trim = function(context){ return this.replace(/^\s+|\s+$/g, ''); }; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ====================================================================== This class contains code based on the following work: * Mootools http://mootools.net/ Version 1.1.1 Copyright: (c) 2007 Valerio Proietti License: MIT: http://www.opensource.org/licenses/mit-license.php and * XRegExp http://xregexp.com/ Version 1.5 Copyright: (c) 2006-2007, Steven Levithan <http://stevenlevithan.com> License: MIT: http://www.opensource.org/licenses/mit-license.php Authors: * Steven Levithan ************************************************************************ */ /* ************************************************************************ #require(qx.lang.normalize.String) ************************************************************************ */ /** * String helper functions * * The native JavaScript String is not modified by this class. However, * there are modifications to the native String in {@link qx.lang.normalize.String} for * browsers that do not support certain features. */ qx.Bootstrap.define("qx.lang.String", { statics : { /** * Unicode letters. they are taken from Steve Levithan's excellent XRegExp library [http://xregexp.com/plugins/xregexp-unicode-base.js] */ __unicodeLetters : "0041-005A0061-007A00AA00B500BA00C0-00D600D8-00F600F8-02C102C6-02D102E0-02E402EC02EE0370-037403760377037A-037D03860388-038A038C038E-03A103A3-03F503F7-0481048A-05250531-055605590561-058705D0-05EA05F0-05F20621-064A066E066F0671-06D306D506E506E606EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA07F407F507FA0800-0815081A082408280904-0939093D09500958-0961097109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E460E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EC60EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10A0-10C510D0-10FA10FC1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317D717DC1820-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541AA71B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C7D1CE9-1CEC1CEE-1CF11D00-1DBF1E00-1F151F18-1F1D1F20-1F451F48-1F4D1F50-1F571F591F5B1F5D1F5F-1F7D1F80-1FB41FB6-1FBC1FBE1FC2-1FC41FC6-1FCC1FD0-1FD31FD6-1FDB1FE0-1FEC1FF2-1FF41FF6-1FFC2071207F2090-209421022107210A-211321152119-211D212421262128212A-212D212F-2139213C-213F2145-2149214E218321842C00-2C2E2C30-2C5E2C60-2CE42CEB-2CEE2D00-2D252D30-2D652D6F2D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE2E2F300530063031-3035303B303C3041-3096309D-309F30A1-30FA30FC-30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A48CA4D0-A4FDA500-A60CA610-A61FA62AA62BA640-A65FA662-A66EA67F-A697A6A0-A6E5A717-A71FA722-A788A78BA78CA7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2A9CFAA00-AA28AA40-AA42AA44-AA4BAA60-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADB-AADDABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB00-FB06FB13-FB17FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF21-FF3AFF41-FF5AFF66-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC", /** * A RegExp that matches the first letter in a word - unicode aware */ __unicodeFirstLetterInWordRegexp : null, /** * {Map} Cache for often used string operations [camelCasing and hyphenation] * e.g. marginTop => margin-top */ __stringsMap : { }, /** * Converts a hyphenated string (separated by '-') to camel case. * * Example: * <pre class='javascript'>qx.lang.String.camelCase("I-like-cookies"); //returns "ILikeCookies"</pre> * The implementation does not force a lowerCamelCase or upperCamelCase version. * (think java variables that start with lower case versus classnames that start with capital letter) * The first letter of the parameter keeps its case. * * @param str {String} hyphenated string * @return {String} camelcase string */ camelCase : function(str){ var result = this.__stringsMap[str]; if(!result){ result = str.replace(/\-([a-z])/g, function(match, chr){ return chr.toUpperCase(); }); this.__stringsMap[str] = result; }; return result; }, /** * Converts a camelcased string to a hyphenated (separated by '-') string. * * Example: * <pre class='javascript'>qx.lang.String.hyphenate("ILikeCookies"); //returns "I-like-cookies"</pre> * The implementation does not force a lowerCamelCase or upperCamelCase version. * (think java variables that start with lower case versus classnames that start with capital letter) * The first letter of the parameter keeps its case. * * @param str {String} camelcased string * @return {String} hyphenated string */ hyphenate : function(str){ var result = this.__stringsMap[str]; if(!result){ result = str.replace(/[A-Z]/g, function(match){ return ('-' + match.charAt(0).toLowerCase()); }); this.__stringsMap[str] = result; }; return result; }, /** * Converts a string to camel case. * * Example: * <pre class='javascript'>qx.lang.String.camelCase("i like cookies"); //returns "I Like Cookies"</pre> * * @param str {String} any string * @return {String} capitalized string */ capitalize : function(str){ if(this.__unicodeFirstLetterInWordRegexp === null){ var unicodeEscapePrefix = '\\u'; this.__unicodeFirstLetterInWordRegexp = new RegExp("(^|[^" + this.__unicodeLetters.replace(/[0-9A-F]{4}/g, function(match){ return unicodeEscapePrefix + match; }) + "])[" + this.__unicodeLetters.replace(/[0-9A-F]{4}/g, function(match){ return unicodeEscapePrefix + match; }) + "]", "g"); }; return str.replace(this.__unicodeFirstLetterInWordRegexp, function(match){ return match.toUpperCase(); }); }, /** * Removes all extraneous whitespace from a string and trims it * * Example: * * <code> * qx.lang.String.clean(" i like cookies \n\n"); * </code> * * Returns "i like cookies" * * @param str {String} the string to clean up * @return {String} Cleaned up string */ clean : function(str){ return str.replace(/\s+/g, ' ').trim(); }, /** * removes white space from the left side of a string * * @param str {String} the string to trim * @return {String} the trimmed string */ trimLeft : function(str){ return str.replace(/^\s+/, ""); }, /** * removes white space from the right side of a string * * @param str {String} the string to trim * @return {String} the trimmed string */ trimRight : function(str){ return str.replace(/\s+$/, ""); }, /** * removes white space from the left and the right side of a string * * @deprecated {2.1} please use the native trim method. * @param str {String} the string to trim * @return {String} the trimmed string */ trim : function(str){ { }; return str.replace(/^\s+|\s+$/g, ""); }, /** * Check whether the string starts with the given substring * * @param fullstr {String} the string to search in * @param substr {String} the substring to look for * @return {Boolean} whether the string starts with the given substring */ startsWith : function(fullstr, substr){ return fullstr.indexOf(substr) === 0; }, /** * Check whether the string ends with the given substring * * @param fullstr {String} the string to search in * @param substr {String} the substring to look for * @return {Boolean} whether the string ends with the given substring */ endsWith : function(fullstr, substr){ return fullstr.substring(fullstr.length - substr.length, fullstr.length) === substr; }, /** * Returns a string, which repeats a string 'length' times * * @param str {String} string used to repeat * @param times {Integer} the number of repetitions * @return {String} repeated string */ repeat : function(str, times){ return str.length > 0 ? new Array(times + 1).join(str) : ""; }, /** * Pad a string up to a given length. Padding characters are added to the left of the string. * * @param str {String} the string to pad * @param length {Integer} the final length of the string * @param ch {String} character used to fill up the string * @return {String} padded string */ pad : function(str, length, ch){ var padLength = length - str.length; if(padLength > 0){ if(typeof ch === "undefined"){ ch = "0"; }; return this.repeat(ch, padLength) + str; } else { return str; }; }, /** * Convert the first character of the string to upper case. * * @signature function(str) * @param str {String} the string * @return {String} the string with an upper case first character */ firstUp : qx.Bootstrap.firstUp, /** * Convert the first character of the string to lower case. * * @signature function(str) * @param str {String} the string * @return {String} the string with a lower case first character */ firstLow : qx.Bootstrap.firstLow, /** * Check whether the string contains a given substring * * @param str {String} the string * @param substring {String} substring to search for * @return {Boolean} whether the string contains the substring */ contains : function(str, substring){ return str.indexOf(substring) != -1; }, /** * Print a list of arguments using a format string * In the format string occurrences of %n are replaced by the n'th element of the args list. * Example: * <pre class='javascript'>qx.lang.String.format("Hello %1, my name is %2", ["Egon", "Franz"]) == "Hello Egon, my name is Franz"</pre> * * @param pattern {String} format string * @param args {Array} array of arguments to insert into the format string * @return {String} the formatted string */ format : function(pattern, args){ var str = pattern; var i = args.length; while(i--){ // be sure to always use a string for replacement. str = str.replace(new RegExp("%" + (i + 1), "g"), args[i] + ""); }; return str; }, /** * Escapes all chars that have a special meaning in regular expressions * * @param str {String} the string where to escape the chars. * @return {String} the string with the escaped chars. */ escapeRegexpChars : function(str){ return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); }, /** * Converts a string to an array of characters. * <pre>"hello" => [ "h", "e", "l", "l", "o" ];</pre> * * @param str {String} the string which should be split * @return {Array} the result array of characters */ toArray : function(str){ return str.split(/\B|\b/g); }, /** * Remove HTML/XML tags from a string * Example: * <pre class='javascript'>qx.lang.String.stripTags("&lt;h1>Hello&lt;/h1>") == "Hello"</pre> * * @param str {String} string containing tags * @return {String} the string with stripped tags */ stripTags : function(str){ return str.replace(/<\/?[^>]+>/gi, ""); }, /** * Strips <script> tags including its content from the given string. * * @param str {String} string containing tags * @param exec {Boolean?false} Whether the filtered code should be executed * @return {String} The filtered string */ stripScripts : function(str, exec){ var scripts = ""; var text = str.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(){ scripts += arguments[1] + '\n'; return ""; }); if(exec === true){ qx.lang.Function.globalEval(scripts); }; return text; }, /** * Quotes the given string. * @param str {String} String to quote. * @return {String} The quoted string. */ quote : function(str){ return '"' + str.replace(/\\/g, "\\\\").replace(/\"/g, "\\\"") + '"'; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /* ************************************************************************ #ignore(WebKitCSSMatrix) ************************************************************************ */ /** * The purpose of this class is to contain all checks about css. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.Css", { statics : { __WEBKIT_LEGACY_GRADIENT : null, /** * Checks what box model is used in the current environemnt. * @return {String} It either returns "content" or "border". * @internal */ getBoxModel : function(){ var content = qx.bom.client.Engine.getName() !== "mshtml" || !qx.bom.client.Browser.getQuirksMode(); return content ? "content" : "border"; }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>textOverflow</code> style property. * * @return {String|null} textOverflow property name or <code>null</code> if * textOverflow is not supported. * @internal */ getTextOverflow : function(){ return qx.bom.Style.getPropertyName("textOverflow"); }, /** * Checks if a placeholder could be used. * @return {Boolean} <code>true</code>, if it could be used. * @internal */ getPlaceholder : function(){ var i = document.createElement("input"); return "placeholder" in i; }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>appearance</code> style property. * * @return {String|null} appearance property name or <code>null</code> if * appearance is not supported. * @internal */ getAppearance : function(){ return qx.bom.Style.getPropertyName("appearance"); }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>borderRadius</code> style property. * * @return {String|null} borderRadius property name or <code>null</code> if * borderRadius is not supported. * @internal */ getBorderRadius : function(){ return qx.bom.Style.getPropertyName("borderRadius"); }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>boxShadow</code> style property. * * @return {String|null} boxShadow property name or <code>null</code> if * boxShadow is not supported. * @internal */ getBoxShadow : function(){ return qx.bom.Style.getPropertyName("boxShadow"); }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>borderImage</code> style property. * * @return {String|null} borderImage property name or <code>null</code> if * borderImage is not supported. * @internal */ getBorderImage : function(){ return qx.bom.Style.getPropertyName("borderImage"); }, /** * Returns the type of syntax this client supports for its CSS border-image * implementation. Some browsers do not support the "fill" keyword defined * in the W3C draft (http://www.w3.org/TR/css3-background/) and will not * show the border image if it's set. Others follow the standard closely and * will omit the center image if "fill" is not set. * * @return {Boolean|null} <code>true</code> if the standard syntax is supported. * <code>null</code> if the supported syntax could not be detected. * @internal */ getBorderImageSyntax : function(){ var styleName = qx.bom.client.Css.getBorderImage(); if(!styleName){ return null; }; var el = document.createElement("div"); if(styleName === "borderImage"){ // unprefixed implementation: check individual properties el.style[styleName] = 'url("foo.png") 4 4 4 4 fill stretch'; if(el.style.borderImageSource.indexOf("foo.png") >= 0 && el.style.borderImageSlice.indexOf("4 fill") >= 0 && el.style.borderImageRepeat.indexOf("stretch") >= 0){ return true; }; } else { // prefixed implementation, assume no support for "fill" el.style[styleName] = 'url("foo.png") 4 4 4 4 stretch'; // serialized value is unreliable, so just a simple check if(el.style[styleName].indexOf("foo.png") >= 0){ return false; }; }; // unable to determine syntax return null; }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>userSelect</code> style property. * * @return {String|null} userSelect property name or <code>null</code> if * userSelect is not supported. * @internal */ getUserSelect : function(){ return qx.bom.Style.getPropertyName("userSelect"); }, /** * Returns the (possibly vendor-prefixed) value for the * <code>userSelect</code> style property that disables selection. For Gecko, * "-moz-none" is returned since "none" only makes the target element appear * as if its text could not be selected * * @internal * @return {String|null} the userSelect property value that disables * selection or <code>null</code> if userSelect is not supported */ getUserSelectNone : function(){ var styleProperty = qx.bom.client.Css.getUserSelect(); if(styleProperty){ var el = document.createElement("span"); el.style[styleProperty] = "-moz-none"; return el.style[styleProperty] === "-moz-none" ? "-moz-none" : "none"; }; return null; }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>userModify</code> style property. * * @return {String|null} userModify property name or <code>null</code> if * userModify is not supported. * @internal */ getUserModify : function(){ return qx.bom.Style.getPropertyName("userModify"); }, /** * Returns the vendor-specific name of the <code>float</code> style property * * @return {String|null} <code>cssFloat</code> for standards-compliant * browsers, <code>styleFloat</code> for legacy IEs, <code>null</code> if * the client supports neither property. * @internal */ getFloat : function(){ var style = document.documentElement.style; return style.cssFloat !== undefined ? "cssFloat" : style.styleFloat !== undefined ? "styleFloat" : null; }, /** * Checks if translate3d can be used. * @return {Boolean} <code>true</code>, if it could be used. * @internal * @lint ignoreUndefined(WebKitCSSMatrix) */ getTranslate3d : function(){ return 'WebKitCSSMatrix' in window && 'm11' in new WebKitCSSMatrix(); }, /** * Returns the (possibly vendor-prefixed) name this client uses for * <code>linear-gradient</code>. * http://dev.w3.org/csswg/css3-images/#linear-gradients * * @return {String|null} Prefixed linear-gradient name or <code>null</code> * if linear gradients are not supported * @internal */ getLinearGradient : function(){ qx.bom.client.Css.__WEBKIT_LEGACY_GRADIENT = false; var value = "linear-gradient(0deg, #fff, #000)"; var el = document.createElement("div"); var style = qx.bom.Style.getAppliedStyle(el, "backgroundImage", value); if(!style){ //try old WebKit syntax (versions 528 - 534.16) value = "-webkit-gradient(linear,0% 0%,100% 100%,from(white), to(red))"; var style = qx.bom.Style.getAppliedStyle(el, "backgroundImage", value, false); if(style){ qx.bom.client.Css.__WEBKIT_LEGACY_GRADIENT = true; }; }; // not supported if(!style){ return null; }; var match = /(.*?)\(/.exec(style); return match ? match[1] : null; }, /** * Returns <code>true</code> if the browser supports setting gradients * using the filter style. This usually only applies for IE browsers * starting from IE5.5. * http://msdn.microsoft.com/en-us/library/ms532997(v=vs.85).aspx * * @return {Boolean} <code>true</code> if supported. * @internal */ getFilterGradient : function(){ return qx.bom.client.Css.__isFilterSupported("DXImageTransform.Microsoft.Gradient", "startColorStr=#550000FF, endColorStr=#55FFFF00"); }, /** * Returns the (possibly vendor-prefixed) name this client uses for * <code>radial-gradient</code>. * * @return {String|null} Prefixed radial-gradient name or <code>null</code> * if radial gradients are not supported * @internal */ getRadialGradient : function(){ var value = "radial-gradient(0px 0px, cover, red 50%, blue 100%)"; var el = document.createElement("div"); var style = qx.bom.Style.getAppliedStyle(el, "backgroundImage", value); if(!style){ return null; }; var match = /(.*?)\(/.exec(style); return match ? match[1] : null; }, /** * Checks if **only** the old WebKit (version < 534.16) syntax for * linear gradients is supported, e.g. * <code>linear-gradient(0deg, #fff, #000)</code> * * @return {Boolean} <code>true</code> if the legacy syntax must be used * @internal */ getLegacyWebkitGradient : function(){ if(qx.bom.client.Css.__WEBKIT_LEGACY_GRADIENT === null){ qx.bom.client.Css.getLinearGradient(); }; return qx.bom.client.Css.__WEBKIT_LEGACY_GRADIENT; }, /** * Checks if rgba colors can be used: * http://www.w3.org/TR/2010/PR-css3-color-20101028/#rgba-color * * @return {Boolean} <code>true</code>, if rgba colors are supported. * @internal */ getRgba : function(){ var el; try{ el = document.createElement("div"); } catch(ex) { el = document.createElement(); }; // try catch for IE try{ el.style["color"] = "rgba(1, 2, 3, 0.5)"; if(el.style["color"].indexOf("rgba") != -1){ return true; }; } catch(ex) { }; return false; }, /** * Returns the (possibly vendor-prefixed) name the browser uses for the * <code>boxSizing</code> style property. * * @return {String|null} boxSizing property name or <code>null</code> if * boxSizing is not supported. * @internal */ getBoxSizing : function(){ return qx.bom.Style.getPropertyName("boxSizing"); }, /** * Returns the browser-specific name used for the <code>display</code> style * property's <code>inline-block</code> value. * * @internal * @return {String|null} */ getInlineBlock : function(){ var el = document.createElement("span"); el.style.display = "inline-block"; if(el.style.display == "inline-block"){ return "inline-block"; }; el.style.display = "-moz-inline-box"; if(el.style.display !== "-moz-inline-box"){ return "-moz-inline-box"; }; return null; }, /** * Checks if CSS opacity is supported * * @internal * @return {Boolean} <code>true</code> if opacity is supported */ getOpacity : function(){ return (typeof document.documentElement.style.opacity == "string"); }, /** * Checks if the overflowX and overflowY style properties are supported * * @internal * @return {Boolean} <code>true</code> if overflow-x and overflow-y can be * used * @deprecated {2.1} */ getOverflowXY : function(){ return (typeof document.documentElement.style.overflowX == "string") && (typeof document.documentElement.style.overflowY == "string"); }, /** * Checks if CSS texShadow is supported * * @internal * @return {Boolean} <code>true</code> if textShadow is supported */ getTextShadow : function(){ var value = "red 1px 1px 3px"; var el = document.createElement("div"); var style = qx.bom.Style.getAppliedStyle(el, "textShadow", value); return !style; }, /** * Returns <code>true</code> if the browser supports setting text shadow * using the filter style. This usually only applies for IE browsers * starting from IE5.5. * * @internal * @return {Boolean} <code>true</code> if textShadow is supported */ getFilterTextShadow : function(){ return qx.bom.client.Css.__isFilterSupported("DXImageTransform.Microsoft.Shadow", "color=#666666,direction=45"); }, /** * Checks if the given filter is supported. * * @param filterClass {String} The name of the filter class * @param initParams {String} Init values for the filter * @return {Boolean} <code>true</code> if the given filter is supported */ __isFilterSupported : function(filterClass, initParams){ var supported = false; var value = "progid:" + filterClass + "(" + initParams + ");"; var el = document.createElement("div"); document.body.appendChild(el); el.style.filter = value; if(el.filters && el.filters.length > 0 && el.filters.item(filterClass).enabled == true){ supported = true; }; document.body.removeChild(el); return supported; } }, defer : function(statics){ qx.core.Environment.add("css.textoverflow", statics.getTextOverflow); qx.core.Environment.add("css.placeholder", statics.getPlaceholder); qx.core.Environment.add("css.borderradius", statics.getBorderRadius); qx.core.Environment.add("css.boxshadow", statics.getBoxShadow); qx.core.Environment.add("css.gradient.linear", statics.getLinearGradient); qx.core.Environment.add("css.gradient.filter", statics.getFilterGradient); qx.core.Environment.add("css.gradient.radial", statics.getRadialGradient); qx.core.Environment.add("css.gradient.legacywebkit", statics.getLegacyWebkitGradient); qx.core.Environment.add("css.boxmodel", statics.getBoxModel); qx.core.Environment.add("css.rgba", statics.getRgba); qx.core.Environment.add("css.borderimage", statics.getBorderImage); qx.core.Environment.add("css.borderimage.standardsyntax", statics.getBorderImageSyntax); qx.core.Environment.add("css.usermodify", statics.getUserModify); qx.core.Environment.add("css.userselect", statics.getUserSelect); qx.core.Environment.add("css.userselect.none", statics.getUserSelectNone); qx.core.Environment.add("css.appearance", statics.getAppearance); qx.core.Environment.add("css.float", statics.getFloat); qx.core.Environment.add("css.boxsizing", statics.getBoxSizing); qx.core.Environment.add("css.inlineblock", statics.getInlineBlock); qx.core.Environment.add("css.opacity", statics.getOpacity); qx.core.Environment.add("css.overflowxy", statics.getOverflowXY); qx.core.Environment.add("css.textShadow", statics.getTextShadow); qx.core.Environment.add("css.textShadow.filter", statics.getFilterTextShadow); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) * Sebastian Fastner (fastner) ************************************************************************ */ /** * This class is responsible for checking the operating systems name. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.OperatingSystem", { statics : { /** * Checks for the name of the operating system. * @return {String} The name of the operating system. * @internal */ getName : function(){ if(!navigator){ return ""; }; var input = navigator.platform || ""; var agent = navigator.userAgent || ""; if(input.indexOf("Windows") != -1 || input.indexOf("Win32") != -1 || input.indexOf("Win64") != -1){ return "win"; } else if(input.indexOf("Macintosh") != -1 || input.indexOf("MacPPC") != -1 || input.indexOf("MacIntel") != -1 || input.indexOf("Mac OS X") != -1){ return "osx"; } else if(agent.indexOf("RIM Tablet OS") != -1){ return "rim_tabletos"; } else if(agent.indexOf("webOS") != -1){ return "webos"; } else if(input.indexOf("iPod") != -1 || input.indexOf("iPhone") != -1 || input.indexOf("iPad") != -1){ return "ios"; } else if(agent.indexOf("Android") != -1){ return "android"; } else if(input.indexOf("Linux") != -1){ return "linux"; } else if(input.indexOf("X11") != -1 || input.indexOf("BSD") != -1 || input.indexOf("Darwin") != -1){ return "unix"; } else if(input.indexOf("SymbianOS") != -1){ return "symbian"; } else if(input.indexOf("BlackBerry") != -1){ return "blackberry"; };;;;;;;;; // don't know return ""; }, /** Maps user agent names to system IDs */ __ids : { // Windows "Windows NT 6.2" : "8", "Windows NT 6.1" : "7", "Windows NT 6.0" : "vista", "Windows NT 5.2" : "2003", "Windows NT 5.1" : "xp", "Windows NT 5.0" : "2000", "Windows 2000" : "2000", "Windows NT 4.0" : "nt4", "Win 9x 4.90" : "me", "Windows CE" : "ce", "Windows 98" : "98", "Win98" : "98", "Windows 95" : "95", "Win95" : "95", // OS X "Mac OS X 10_7" : "10.7", "Mac OS X 10.7" : "10.7", "Mac OS X 10_6" : "10.6", "Mac OS X 10.6" : "10.6", "Mac OS X 10_5" : "10.5", "Mac OS X 10.5" : "10.5", "Mac OS X 10_4" : "10.4", "Mac OS X 10.4" : "10.4", "Mac OS X 10_3" : "10.3", "Mac OS X 10.3" : "10.3", "Mac OS X 10_2" : "10.2", "Mac OS X 10.2" : "10.2", "Mac OS X 10_1" : "10.1", "Mac OS X 10.1" : "10.1", "Mac OS X 10_0" : "10.0", "Mac OS X 10.0" : "10.0" }, /** * Checks for the version of the operating system using the internal map. * * @internal * @return {String} The version as strin or an empty string if the version * could not be detected. */ getVersion : function(){ var version = qx.bom.client.OperatingSystem.__getVersionForDesktopOs(navigator.userAgent); if(version == null){ version = qx.bom.client.OperatingSystem.__getVersionForMobileOs(navigator.userAgent); }; if(version != null){ return version; } else { return ""; }; }, /** * Detect OS version for desktop devices * @param userAgent {String} userAgent parameter, needed for detection. * @return {String} version number as string or null. */ __getVersionForDesktopOs : function(userAgent){ var str = []; for(var key in qx.bom.client.OperatingSystem.__ids){ str.push(key); }; var reg = new RegExp("(" + str.join("|").replace(/\./g, "\.") + ")", "g"); var match = reg.exec(userAgent); if(match && match[1]){ return qx.bom.client.OperatingSystem.__ids[match[1]]; }; return null; }, /** * Detect OS version for mobile devices * @param userAgent {String} userAgent parameter, needed for detection. * @return {String} version number as string or null. */ __getVersionForMobileOs : function(userAgent){ var android = userAgent.indexOf("Android") != -1; var iOs = userAgent.match(/(iPad|iPhone|iPod)/i) ? true : false; if(android){ var androidVersionRegExp = new RegExp(/ Android (\d+(?:\.\d+)+)/i); var androidMatch = androidVersionRegExp.exec(userAgent); if(androidMatch && androidMatch[1]){ return androidMatch[1]; }; } else if(iOs){ var iOsVersionRegExp = new RegExp(/(CPU|iPhone|iPod) OS (\d+)_(\d+)\s+/); var iOsMatch = iOsVersionRegExp.exec(userAgent); if(iOsMatch && iOsMatch[2] && iOsMatch[3]){ return iOsMatch[2] + "." + iOsMatch[3]; }; }; return null; } }, defer : function(statics){ qx.core.Environment.add("os.name", statics.getName); qx.core.Environment.add("os.version", statics.getVersion); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Christian Hagendorn (chris_schmidt) * Martin Wittemann (martinwittemann) ====================================================================== This class contains code from: Copyright: 2009 Deutsche Telekom AG, Germany, http://telekom.com License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php Authors: * Sebastian Werner (wpbasti) ====================================================================== This class contains code from: Copyright: 2011 Pocket Widget S.L., Spain, http://www.pocketwidget.com License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php Authors: * Javier Martinez Villacampa ************************************************************************ */ /** #require(qx.bom.client.OperatingSystem#getVersion) */ /** * Basic browser detection for qooxdoo. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.Browser", { statics : { /** * Checks for the name of the browser and returns it. * @return {String} The name of the current browser. * @internal */ getName : function(){ var agent = navigator.userAgent; var reg = new RegExp("(" + qx.bom.client.Browser.__agents + ")(/| )([0-9]+\.[0-9])"); var match = agent.match(reg); if(!match){ return ""; }; var name = match[1].toLowerCase(); var engine = qx.bom.client.Engine.getName(); if(engine === "webkit"){ if(name === "android"){ // Fix Chrome name (for instance wrongly defined in user agent on Android 1.6) name = "mobile chrome"; } else if(agent.indexOf("Mobile Safari") !== -1 || agent.indexOf("Mobile/") !== -1){ // Fix Safari name name = "mobile safari"; }; } else if(engine === "mshtml"){ if(name === "msie"){ name = "ie"; // Fix IE mobile before Microsoft added IEMobile string if(qx.bom.client.OperatingSystem.getVersion() === "ce"){ name = "iemobile"; }; }; } else if(engine === "opera"){ if(name === "opera mobi"){ name = "operamobile"; } else if(name === "opera mini"){ name = "operamini"; }; } else if(engine === "gecko"){ if(agent.indexOf("Maple") !== -1){ name = "maple"; }; };;; return name; }, /** * Determines the version of the current browser. * @return {String} The name of the current browser. * @internal */ getVersion : function(){ var agent = navigator.userAgent; var reg = new RegExp("(" + qx.bom.client.Browser.__agents + ")(/| )([0-9]+\.[0-9])"); var match = agent.match(reg); if(!match){ return ""; }; var name = match[1].toLowerCase(); var version = match[3]; // Support new style version string used by Opera and Safari if(agent.match(/Version(\/| )([0-9]+\.[0-9])/)){ version = RegExp.$2; }; if(qx.bom.client.Engine.getName() == "mshtml"){ // Use the Engine version, because IE8 and higher change the user agent // string to an older version in compatibility mode version = qx.bom.client.Engine.getVersion(); if(name === "msie" && qx.bom.client.OperatingSystem.getVersion() == "ce"){ // Fix IE mobile before Microsoft added IEMobile string version = "5.0"; }; }; if(qx.bom.client.Browser.getName() == "maple"){ // Fix version detection for Samsung Smart TVs Maple browser from 2010 and 2011 models reg = new RegExp("(Maple )([0-9]+\.[0-9]+\.[0-9]*)"); match = agent.match(reg); if(!match){ return ""; }; version = match[2]; }; return version; }, /** * Returns in which document mode the current document is (only for IE). * * @internal * @return {Number} The mode in which the browser is. */ getDocumentMode : function(){ if(document.documentMode){ return document.documentMode; }; return 0; }, /** * Check if in quirks mode. * * @internal * @return {Boolean} <code>true</code>, if the environment is in quirks mode */ getQuirksMode : function(){ if(qx.bom.client.Engine.getName() == "mshtml" && parseFloat(qx.bom.client.Engine.getVersion()) >= 8){ return qx.bom.client.Engine.DOCUMENT_MODE === 5; } else { return document.compatMode !== "CSS1Compat"; }; }, /** * Internal helper map for picking the right browser names to check. */ __agents : { // Safari should be the last one to check, because some other Webkit-based browsers // use this identifier together with their own one. // "Version" is used in Safari 4 to define the Safari version. After "Safari" they place the // Webkit version instead. Silly. // Palm Pre uses both Safari (contains Webkit version) and "Version" contains the "Pre" version. But // as "Version" is not Safari here, we better detect this as the Pre-Browser version. So place // "Pre" in front of both "Version" and "Safari". "webkit" : "AdobeAIR|Titanium|Fluid|Chrome|Android|Epiphany|Konqueror|iCab|OmniWeb|Maxthon|Pre|Mobile Safari|Safari", // Better security by keeping Firefox the last one to match "gecko" : "prism|Fennec|Camino|Kmeleon|Galeon|Netscape|SeaMonkey|Namoroka|Firefox", // No idea what other browsers based on IE's engine "mshtml" : "IEMobile|Maxthon|MSIE", // Keep "Opera" the last one to correctly prefer/match the mobile clients "opera" : "Opera Mini|Opera Mobi|Opera" }[qx.bom.client.Engine.getName()] }, defer : function(statics){ qx.core.Environment.add("browser.name", statics.getName),qx.core.Environment.add("browser.version", statics.getVersion),qx.core.Environment.add("browser.documentmode", statics.getDocumentMode),qx.core.Environment.add("browser.quirksmode", statics.getQuirksMode); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) * Daniel Wagner (danielwagner) ************************************************************************ */ /** * Responsible class for everything concerning styles without the need of * an element. * * If you want to query or modify styles of HTML elements, * take a look at {@see qx.bom.element.Style}. */ qx.Bootstrap.define("qx.bom.Style", { statics : { /** Vendor-specific style property prefixes **/ VENDOR_PREFIXES : ["Webkit", "Moz", "O", "ms", "Khtml"], /** * Takes the name of a style property and returns the name the browser uses * for its implementation, which might include a vendor prefix. * * @param propertyName {String} Style property name to check * @return {String|null} The supported property name or <code>null</code> if * not supported */ getPropertyName : function(propertyName){ var style = document.documentElement.style; if(style[propertyName] !== undefined){ return propertyName; }; for(var i = 0,l = this.VENDOR_PREFIXES.length;i < l;i++){ var prefixedProp = this.VENDOR_PREFIXES[i] + qx.lang.String.firstUp(propertyName); if(style[prefixedProp] !== undefined){ return prefixedProp; }; }; return null; }, /** * Detects CSS support by applying a style to a DOM element of the given type * and verifying the result. Also checks for vendor-prefixed variants of the * value, e.g. "linear-gradient" -> "-webkit-linear-gradient". Returns the * (possibly vendor-prefixed) value if successful or <code>null</code> if * the property and/or value are not supported. * * @param element {Element} element to be used for the detection * @param propertyName {String} the style property to be tested * @param value {String} style property value to be tested * @param prefixed {Boolean?} try to determine the appropriate vendor prefix * for the value. Default: <code>true</code> * @return {String|null} prefixed style value or <code>null</code> if not supported * @internal */ getAppliedStyle : function(element, propertyName, value, prefixed){ var vendorPrefixes = (prefixed !== false) ? [null].concat(this.VENDOR_PREFIXES) : [null]; for(var i = 0,l = vendorPrefixes.length;i < l;i++){ var prefixedVal = vendorPrefixes[i] ? "-" + vendorPrefixes[i].toLowerCase() + "-" + value : value; // IE might throw an exception try{ element.style[propertyName] = prefixedVal; if(typeof element.style[propertyName] == "string" && element.style[propertyName] !== ""){ return prefixedVal; }; } catch(ex) { }; }; return null; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Christian Hagendorn (chris_schmidt) ====================================================================== This class contains code based on the following work: * Prototype JS http://www.prototypejs.org/ Version 1.5 Copyright: (c) 2006-2007, Prototype Core Team License: MIT: http://www.opensource.org/licenses/mit-license.php Authors: * Prototype Core Team ---------------------------------------------------------------------- Copyright (c) 2005-2008 Sam Stephenson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ************************************************************************ */ /** * Cross-browser opacity support. * * Optimized for animations (contains workarounds for typical flickering * in some browsers). Reduced class dependencies for optimal size and * performance. */ qx.Bootstrap.define("qx.bom.element.Opacity", { statics : { /** * {Boolean} <code>true</code> when the style attribute "opacity" is supported, * <code>false</code> otherwise. * @deprecated {2.1} Please use qx.core.Environment.get("css.opacity") instead. */ SUPPORT_CSS3_OPACITY : false, /** * Compiles the given opacity value into a cross-browser CSS string. * Accepts numbers between zero and one * where "0" means transparent, "1" means opaque. * * @signature function(opacity) * @param opacity {Float} A float number between 0 and 1 * @return {String} CSS compatible string */ compile : qx.core.Environment.select("engine.name", { "mshtml" : function(opacity){ if(opacity >= 1){ opacity = 1; }; if(opacity < 0.00001){ opacity = 0; }; if(qx.core.Environment.get("css.opacity")){ return "opacity:" + opacity + ";"; } else { return "zoom:1;filter:alpha(opacity=" + (opacity * 100) + ");"; }; }, "default" : function(opacity){ if(opacity >= 1){ return ""; }; return "opacity:" + opacity + ";"; } }), /** * Sets opacity of given element. Accepts numbers between zero and one * where "0" means transparent, "1" means opaque. * * @param element {Element} DOM element to modify * @param opacity {Float} A float number between 0 and 1 * @signature function(element, opacity) */ set : qx.core.Environment.select("engine.name", { "mshtml" : function(element, opacity){ if(qx.core.Environment.get("css.opacity")){ if(opacity >= 1){ opacity = ""; }; element.style.opacity = opacity; } else { // Read in computed filter var filter = qx.bom.element.Style.get(element, "filter", qx.bom.element.Style.COMPUTED_MODE, false); if(opacity >= 1){ opacity = 1; }; if(opacity < 0.00001){ opacity = 0; }; // IE has trouble with opacity if it does not have layout (hasLayout) // Force it by setting the zoom level if(!element.currentStyle || !element.currentStyle.hasLayout){ element.style.zoom = 1; }; // Remove old alpha filter and add new one element.style.filter = filter.replace(/alpha\([^\)]*\)/gi, "") + "alpha(opacity=" + opacity * 100 + ")"; }; }, "default" : function(element, opacity){ if(opacity >= 1){ opacity = ""; }; element.style.opacity = opacity; } }), /** * Resets opacity of given element. * * @param element {Element} DOM element to modify * @signature function(element) */ reset : qx.core.Environment.select("engine.name", { "mshtml" : function(element){ if(qx.core.Environment.get("css.opacity")){ element.style.opacity = ""; } else { // Read in computed filter var filter = qx.bom.element.Style.get(element, "filter", qx.bom.element.Style.COMPUTED_MODE, false); // Remove old alpha filter element.style.filter = filter.replace(/alpha\([^\)]*\)/gi, ""); }; }, "default" : function(element){ element.style.opacity = ""; } }), /** * Gets computed opacity of given element. Accepts numbers between zero and one * where "0" means transparent, "1" means opaque. * * @param element {Element} DOM element to modify * @param mode {Number} Choose one of the modes {@link qx.bom.element.Style#COMPUTED_MODE}, * {@link qx.bom.element.Style#CASCADED_MODE}, {@link qx.bom.element.Style#LOCAL_MODE}. * The computed mode is the default one. * @return {Float} A float number between 0 and 1 * @signature function(element, mode) */ get : qx.core.Environment.select("engine.name", { "mshtml" : function(element, mode){ if(qx.core.Environment.get("css.opacity")){ var opacity = qx.bom.element.Style.get(element, "opacity", mode, false); if(opacity != null){ return parseFloat(opacity); }; return 1.0; } else { var filter = qx.bom.element.Style.get(element, "filter", mode, false); if(filter){ var opacity = filter.match(/alpha\(opacity=(.*)\)/); if(opacity && opacity[1]){ return parseFloat(opacity[1]) / 100; }; }; return 1.0; }; }, "default" : function(element, mode){ var opacity = qx.bom.element.Style.get(element, "opacity", mode, false); if(opacity != null){ return parseFloat(opacity); }; return 1.0; } }) }, // @deprecated {2.1} defer : function(statics){ statics.SUPPORT_CSS3_OPACITY = qx.core.Environment.get("css.opacity"); } }); { }; /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /* ************************************************************************ #require(qx.lang.normalize.String) ************************************************************************ */ /** * Contains methods to control and query the element's clip property */ qx.Bootstrap.define("qx.bom.element.Clip", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** * Compiles the given clipping into a CSS compatible string. This * is a simple square which describes the visible area of an DOM element. * Changing the clipping does not change the dimensions of * an element. * * @param map {Map} Map which contains <code>left</code>, <code>top</code> * <code>width</code> and <code>height</code> of the clipped area. * @return {String} CSS compatible string */ compile : function(map){ if(!map){ return "clip:auto;"; }; var left = map.left; var top = map.top; var width = map.width; var height = map.height; var right,bottom; if(left == null){ right = (width == null ? "auto" : width + "px"); left = "auto"; } else { right = (width == null ? "auto" : left + width + "px"); left = left + "px"; }; if(top == null){ bottom = (height == null ? "auto" : height + "px"); top = "auto"; } else { bottom = (height == null ? "auto" : top + height + "px"); top = top + "px"; }; return "clip:rect(" + top + "," + right + "," + bottom + "," + left + ");"; }, /** * Gets the clipping of the given element. * * @param element {Element} DOM element to query * @param mode {Number} Choose one of the modes {@link qx.bom.element.Style#COMPUTED_MODE}, * {@link qx.bom.element.Style#CASCADED_MODE}, {@link qx.bom.element.Style#LOCAL_MODE}. * The computed mode is the default one. * @return {Map} Map which contains <code>left</code>, <code>top</code> * <code>width</code> and <code>height</code> of the clipped area. * Each one could be null or any integer value. */ get : function(element, mode){ var clip = qx.bom.element.Style.get(element, "clip", mode, false); var left,top,width,height; var right,bottom; if(typeof clip === "string" && clip !== "auto" && clip !== ""){ clip = clip.trim(); // Do not use "global" here. This will break Firefox because of // an issue that the lastIndex will not be resetted on separate calls. if(/\((.*)\)/.test(clip)){ var result = RegExp.$1; // Process result // Some browsers store values space-separated, others comma-separated. // Handle both cases by means of feature-detection. if(/,/.test(result)){ var split = result.split(","); } else { var split = result.split(" "); }; top = split[0].trim(); right = split[1].trim(); bottom = split[2].trim(); left = split[3].trim(); // Normalize "auto" to null if(left === "auto"){ left = null; }; if(top === "auto"){ top = null; }; if(right === "auto"){ right = null; }; if(bottom === "auto"){ bottom = null; }; // Convert to integer values if(top != null){ top = parseInt(top, 10); }; if(right != null){ right = parseInt(right, 10); }; if(bottom != null){ bottom = parseInt(bottom, 10); }; if(left != null){ left = parseInt(left, 10); }; // Compute width and height if(right != null && left != null){ width = right - left; } else if(right != null){ width = right; }; if(bottom != null && top != null){ height = bottom - top; } else if(bottom != null){ height = bottom; }; } else { throw new Error("Could not parse clip string: " + clip); }; }; // Return map when any value is available. return { left : left || null, top : top || null, width : width || null, height : height || null }; }, /** * Sets the clipping of the given element. This is a simple * square which describes the visible area of an DOM element. * Changing the clipping does not change the dimensions of * an element. * * @param element {Element} DOM element to modify * @param map {Map} A map with one or more of these available keys: * <code>left</code>, <code>top</code>, <code>width</code>, <code>height</code>. */ set : function(element, map){ if(!map){ element.style.clip = "rect(auto,auto,auto,auto)"; return; }; var left = map.left; var top = map.top; var width = map.width; var height = map.height; var right,bottom; if(left == null){ right = (width == null ? "auto" : width + "px"); left = "auto"; } else { right = (width == null ? "auto" : left + width + "px"); left = left + "px"; }; if(top == null){ bottom = (height == null ? "auto" : height + "px"); top = "auto"; } else { bottom = (height == null ? "auto" : top + height + "px"); top = top + "px"; }; element.style.clip = "rect(" + top + "," + right + "," + bottom + "," + left + ")"; }, /** * Resets the clipping of the given DOM element. * * @param element {Element} DOM element to modify */ reset : function(element){ element.style.clip = "rect(auto, auto, auto, auto)"; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /** * Contains methods to control and query the element's cursor property */ qx.Bootstrap.define("qx.bom.element.Cursor", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** Internal helper structure to map cursor values to supported ones */ __map : { }, /** * Compiles the given cursor into a CSS compatible string. * * @param cursor {String} Valid CSS cursor name * @return {String} CSS string */ compile : function(cursor){ return "cursor:" + (this.__map[cursor] || cursor) + ";"; }, /** * Returns the computed cursor style for the given element. * * @param element {Element} The element to query * @param mode {Number} Choose one of the modes {@link qx.bom.element.Style#COMPUTED_MODE}, * {@link qx.bom.element.Style#CASCADED_MODE}, {@link qx.bom.element.Style#LOCAL_MODE}. * The computed mode is the default one. * @return {String} Computed cursor value of the given element. */ get : function(element, mode){ return qx.bom.element.Style.get(element, "cursor", mode, false); }, /** * Applies a new cursor style to the given element * * @param element {Element} The element to modify * @param value {String} New cursor value to set */ set : function(element, value){ element.style.cursor = this.__map[value] || value; }, /** * Removes the local cursor style applied to the element * * @param element {Element} The element to modify */ reset : function(element){ element.style.cursor = ""; } }, defer : function(statics){ // < IE 9 if(qx.core.Environment.get("engine.name") == "mshtml" && ((parseFloat(qx.core.Environment.get("engine.version")) < 9 || qx.core.Environment.get("browser.documentmode") < 9) && !qx.core.Environment.get("browser.quirksmode"))){ statics.__map["nesw-resize"] = "ne-resize"; statics.__map["nwse-resize"] = "nw-resize"; // < IE 8 if(((parseFloat(qx.core.Environment.get("engine.version")) < 8 || qx.core.Environment.get("browser.documentmode") < 8) && !qx.core.Environment.get("browser.quirksmode"))){ statics.__map["ew-resize"] = "e-resize"; statics.__map["ns-resize"] = "n-resize"; }; } else if(qx.core.Environment.get("engine.name") == "opera" && parseInt(qx.core.Environment.get("engine.version")) < 12){ statics.__map["nesw-resize"] = "ne-resize"; statics.__map["nwse-resize"] = "nw-resize"; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This class takes care of the normalization of the native 'Object' object. * Therefore it checks the availability of the following methods and appends * it, if not available. This means you can use the methods during * development in every browser. For usage samples, check out the attached links. * * *keys*: * <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys">MDN documentation</a> | * <a href="http://es5.github.com/#x15.2.3.14">Annotated ES5 Spec</a> */ qx.Bootstrap.define("qx.lang.normalize.Object", { defer : function(){ // keys if(!qx.core.Environment.get("ecmascript.object.keys")){ Object.keys = qx.Bootstrap.keys; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ************************************************************************ */ /* ************************************************************************ #require(qx.lang.normalize.Object) ************************************************************************ */ /** * Helper functions to handle Object as a Hash map. */ qx.Bootstrap.define("qx.lang.Object", { statics : { /** * Clears the map from all values * * @param map {Object} the map to clear */ empty : function(map){ { }; for(var key in map){ if(map.hasOwnProperty(key)){ delete map[key]; }; }; }, /** * Check if the hash has any keys * * @signature function(map) * @param map {Object} the map to check * @return {Boolean} whether the map has any keys * @lint ignoreUnused(key) */ isEmpty : function(map){ { }; for(var key in map){ return false; }; return true; }, /** * Check whether the number of objects in the maps is at least "length" * * @signature function(map, minLength) * @param map {Object} the map to check * @param minLength {Integer} minimum number of objects in the map * @deprecated {2.1} Please use a check and 'qx.lang.Object.getLength'. * @return {Boolean} whether the map contains at least "length" objects. * @lint ignoreUnused(key) */ hasMinLength : function(map, minLength){ { }; if(minLength <= 0){ return true; }; var length = 0; for(var key in map){ if((++length) >= minLength){ return true; }; }; return false; }, /** * Get the number of objects in the map * * @signature function(map) * @param map {Object} the map * @return {Integer} number of objects in the map */ getLength : qx.Bootstrap.objectGetLength, /** * Get the keys of a map as array as returned by a "for ... in" statement. * * @deprecated {2.1.} Please use Object.keys instead. * @signature function(map) * @param map {Object} the map * @return {Array} array of the keys of the map */ getKeys : qx.Bootstrap.getKeys, /** * Get the keys of a map as string * * @signature function(map) * @param map {Object} the map * @deprecated {2.1} Object.keys(map).join(). * @return {String} String of the keys of the map * The keys are separated by ", " */ getKeysAsString : qx.Bootstrap.getKeysAsString, /** * Get the values of a map as array * * @param map {Object} the map * @return {Array} array of the values of the map */ getValues : function(map){ { }; var arr = []; var keys = Object.keys(map); for(var i = 0,l = keys.length;i < l;i++){ arr.push(map[keys[i]]); }; return arr; }, /** * Inserts all keys of the source object into the * target objects. Attention: The target map gets modified. * * @signature function(target, source, overwrite) * @param target {Object} target object * @param source {Object} object to be merged * @param overwrite {Boolean ? true} If enabled existing keys will be overwritten * @return {Object} Target with merged values from the source object */ mergeWith : qx.Bootstrap.objectMergeWith, /** * Inserts all key/value pairs of the source object into the * target object but doesn't override existing keys * * @param target {Object} target object * @param source {Object} object to be merged * @return {Object} target with merged values from source * @deprecated {2.1} please use mergeWith instead with override set to false */ carefullyMergeWith : function(target, source){ { }; return qx.lang.Object.mergeWith(target, source, false); }, /** * Merge a number of objects. * * @param target {Object} target object * @param varargs {Object} variable number of objects to merged with target * @return {Object} target with merged values from the other objects * @deprecated {2.1} Please use mergeWith instead. */ merge : function(target, varargs){ { }; var len = arguments.length; for(var i = 1;i < len;i++){ qx.lang.Object.mergeWith(target, arguments[i]); }; return target; }, /** * Return a copy of an Object * * @param source {Object} Object to copy * @param deep {Boolean} If the clone should be a deep clone. * @return {Object} A copy of the object */ clone : function(source, deep){ if(qx.lang.Type.isObject(source)){ var clone = { }; for(var key in source){ if(deep){ clone[key] = qx.lang.Object.clone(source[key], deep); } else { clone[key] = source[key]; }; }; return clone; } else if(qx.lang.Type.isArray(source)){ var clone = []; for(var i = 0;i < source.length;i++){ if(deep){ clone[i] = qx.lang.Object.clone(source[i]); } else { clone[i] = source[i]; }; }; return clone; }; return source; }, /** * Inverts a map by exchanging the keys with the values. * * If the map has the same values for different keys, information will get lost. * The values will be converted to strings using the toString methods. * * @param map {Object} Map to invert * @return {Object} inverted Map */ invert : function(map){ { }; var result = { }; for(var key in map){ result[map[key].toString()] = key; }; return result; }, /** * Get the key of the given value from a map. * If the map has more than one key matching the value, the first match is returned. * If the map does not contain the value, <code>null</code> is returned. * * @param map {Object} Map to search for the key * @param value {var} Value to look for * @return {String|null} Name of the key (null if not found). */ getKeyFromValue : function(map, value){ { }; for(var key in map){ if(map.hasOwnProperty(key) && map[key] === value){ return key; }; }; return null; }, /** * Whether the map contains the given value. * * @param map {Object} Map to search for the value * @param value {var} Value to look for * @return {Boolean} Whether the value was found in the map. */ contains : function(map, value){ { }; return this.getKeyFromValue(map, value) !== null; }, /** * Selects the value with the given key from the map. * * @param key {String} name of the key to get the value from * @param map {Object} map to get the value from * @return {var} value for the given key from the map * @deprecated {2.1} */ select : function(key, map){ { }; { }; return map[key]; }, /** * Convert an array into a map. * * All elements of the array become keys of the returned map by * calling <code>toString</code> on the array elements. The values of the * map are set to <code>true</code> * * @param array {Array} array to convert * @return {Map} the array converted to a map. */ fromArray : function(array){ { }; var obj = { }; for(var i = 0,l = array.length;i < l;i++){ { }; obj[array[i].toString()] = true; }; return obj; }, /** * Serializes an object to URI parameters (also known as query string). * * Escapes characters that have a special meaning in URIs as well as * umlauts. Uses the global function encodeURIComponent, see * https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent * * Note: For URI parameters that are to be sent as * application/x-www-form-urlencoded (POST), spaces should be encoded * with "+". * * @param obj {Object} Object to serialize. * @param post {Boolean} Whether spaces should be encoded with "+". * @return {String} Serialized object. Safe to append to URIs or send as * URL encoded string. * @deprecated {2.1} Please use qx.util.Uri.toParameter instead. */ toUriParameter : function(obj, post){ { }; return qx.util.Uri.toParameter(obj, post); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Tristan Koch (tristankoch) ************************************************************************ */ /** * Static helpers for parsing and modifying URIs. */ qx.Bootstrap.define("qx.util.Uri", { statics : { /** * Split URL * * Code taken from: * parseUri 1.2.2 * (c) Steven Levithan <stevenlevithan.com> * MIT License * * * @param str {String} String to parse as URI * @param strict {Boolean} Whether to parse strictly by the rules * @return {Object} Map with parts of URI as properties */ parseUri : function(str, strict){ var options = { key : ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"], q : { name : "queryKey", parser : /(?:^|&)([^&=]*)=?([^&]*)/g }, parser : { strict : /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, loose : /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ } }; var o = options,m = options.parser[strict ? "strict" : "loose"].exec(str),uri = { },i = 14; while(i--){ uri[o.key[i]] = m[i] || ""; }; uri[o.q.name] = { }; uri[o.key[12]].replace(o.q.parser, function($0, $1, $2){ if($1){ uri[o.q.name][$1] = $2; }; }); return uri; }, /** * Append string to query part of URL. Respects existing query. * * @param url {String} URL to append string to. * @param params {String} Parameters to append to URL. * @return {String} URL with string appended in query part. */ appendParamsToUrl : function(url, params){ if(params === undefined){ return url; }; { }; if(qx.lang.Type.isObject(params)){ params = qx.util.Uri.toParameter(params); }; if(!params){ return url; }; return url += (/\?/).test(url) ? "&" + params : "?" + params; }, /** * Serializes an object to URI parameters (also known as query string). * * Escapes characters that have a special meaning in URIs as well as * umlauts. Uses the global function encodeURIComponent, see * https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent * * Note: For URI parameters that are to be sent as * application/x-www-form-urlencoded (POST), spaces should be encoded * with "+". * * @param obj {Object} Object to serialize. * @param post {Boolean} Whether spaces should be encoded with "+". * @return {String} Serialized object. Safe to append to URIs or send as * URL encoded string. */ toParameter : function(obj, post){ var key,parts = []; for(key in obj){ if(obj.hasOwnProperty(key)){ var value = obj[key]; if(value instanceof Array){ for(var i = 0;i < value.length;i++){ this.__toParameterPair(key, value[i], parts, post); }; } else { this.__toParameterPair(key, value, parts, post); }; }; }; return parts.join("&"); }, /** * Encodes key/value to URI safe string and pushes to given array. * * @param key {String} Key. * @param value {String} Value. * @param parts {Array} Array to push to. * @param post {Boolean} Whether spaces should be encoded with "+". */ __toParameterPair : function(key, value, parts, post){ var encode = window.encodeURIComponent; if(post){ parts.push(encode(key).replace(/%20/g, "+") + "=" + encode(value).replace(/%20/g, "+")); } else { parts.push(encode(key) + "=" + encode(value)); }; }, /** * Takes a relative URI and returns an absolute one. * * @param uri {String} relative URI * @return {String} absolute URI */ getAbsolute : function(uri){ var div = document.createElement("div"); div.innerHTML = '<a href="' + uri + '">0</a>'; return div.firstChild.href; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /** * Contains methods to control and query the element's box-sizing property. * * Supported values: * * * "content-box" = W3C model (dimensions are content specific) * * "border-box" = Microsoft model (dimensions are box specific incl. border and padding) */ qx.Bootstrap.define("qx.bom.element.BoxSizing", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** {Map} Internal data structure for __usesNativeBorderBox() */ __nativeBorderBox : { tags : { button : true, select : true }, types : { search : true, button : true, submit : true, reset : true, checkbox : true, radio : true } }, /** * Whether the given elements defaults to the "border-box" Microsoft model in all cases. * * @param element {Element} DOM element to query * @return {Boolean} true when the element uses "border-box" independently from the doctype */ __usesNativeBorderBox : function(element){ var map = this.__nativeBorderBox; return map.tags[element.tagName.toLowerCase()] || map.types[element.type]; }, /** * Compiles the given box sizing into a CSS compatible string. * * @param value {String} Valid CSS box-sizing value * @return {String} CSS string */ compile : function(value){ if(qx.core.Environment.get("css.boxsizing")){ var prop = qx.lang.String.hyphenate(qx.core.Environment.get("css.boxsizing")); return prop + ":" + value + ";"; } else { { }; }; }, /** * Returns the box sizing for the given element. * * @param element {Element} The element to query * @return {String} Box sizing value of the given element. */ get : function(element){ if(qx.core.Environment.get("css.boxsizing")){ return qx.bom.element.Style.get(element, "boxSizing", null, false) || ""; }; if(qx.bom.Document.isStandardMode(qx.dom.Node.getWindow(element))){ if(!this.__usesNativeBorderBox(element)){ return "content-box"; }; }; return "border-box"; }, /** * Applies a new box sizing to the given element * * @param element {Element} The element to modify * @param value {String} New box sizing value to set */ set : function(element, value){ if(qx.core.Environment.get("css.boxsizing")){ // IE8 bombs when trying to apply an unsupported value try{ element.style[qx.core.Environment.get("css.boxsizing")] = value; } catch(ex) { { }; }; } else { { }; }; }, /** * Removes the local box sizing applied to the element * * @param element {Element} The element to modify */ reset : function(element){ this.set(element, ""); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ====================================================================== This class contains code based on the following work: * Prototype JS http://www.prototypejs.org/ Version 1.5 Copyright: (c) 2006-2007, Prototype Core Team License: MIT: http://www.opensource.org/licenses/mit-license.php Authors: * Prototype Core Team ---------------------------------------------------------------------- Copyright (c) 2005-2008 Sam Stephenson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ************************************************************************ */ /* ************************************************************************ #require(qx.lang.String) #require(qx.bom.client.Css) #require(qx.bom.element.Clip#set) #require(qx.bom.element.Cursor#set) #require(qx.bom.element.Opacity#set) #require(qx.bom.element.BoxSizing#set) #require(qx.bom.element.Clip#get) #require(qx.bom.element.Cursor#get) #require(qx.bom.element.Opacity#get) #require(qx.bom.element.BoxSizing#get) #require(qx.bom.element.Clip#reset) #require(qx.bom.element.Cursor#reset) #require(qx.bom.element.Opacity#reset) #require(qx.bom.element.BoxSizing#reset) #require(qx.bom.element.Clip#compile) #require(qx.bom.element.Cursor#compile) #require(qx.bom.element.Opacity#compile) #require(qx.bom.element.BoxSizing#compile) ************************************************************************ */ /** * Style querying and modification of HTML elements. * * Automatically normalizes cross-browser differences for setting and reading * CSS attributes. Optimized for performance. */ qx.Bootstrap.define("qx.bom.element.Style", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { __styleNames : null, __cssNames : null, /** * Detect vendor specific properties. */ __detectVendorProperties : function(){ var styleNames = { "appearance" : qx.core.Environment.get("css.appearance"), "userSelect" : qx.core.Environment.get("css.userselect"), "textOverflow" : qx.core.Environment.get("css.textoverflow"), "borderImage" : qx.core.Environment.get("css.borderimage"), "float" : qx.core.Environment.get("css.float"), "userModify" : qx.core.Environment.get("css.usermodify"), "boxSizing" : qx.core.Environment.get("css.boxsizing") }; this.__cssNames = { }; for(var key in qx.lang.Object.clone(styleNames)){ if(!styleNames[key]){ delete styleNames[key]; } else { this.__cssNames[key] = key == "float" ? "float" : qx.lang.String.hyphenate(styleNames[key]); }; }; this.__styleNames = styleNames; }, /** * Gets the (possibly vendor-prefixed) name of a style property and stores * it to avoid multiple checks. * * @param name {String} Style property name to check * @return {String|null} The client-specific name of the property, or * <code>null</code> if it's not supported. */ __getStyleName : function(name){ var styleName = qx.bom.Style.getPropertyName(name); if(styleName){ this.__styleNames[name] = styleName; }; return styleName; }, /** * Mshtml has proprietary pixel* properties for locations and dimensions * which return the pixel value. Used by getComputed() in mshtml variant. * * @internal */ __mshtmlPixel : { width : "pixelWidth", height : "pixelHeight", left : "pixelLeft", right : "pixelRight", top : "pixelTop", bottom : "pixelBottom" }, /** * Whether a special class is available for the processing of this style. * * @internal */ __special : { clip : qx.bom.element.Clip, cursor : qx.bom.element.Cursor, opacity : qx.bom.element.Opacity, boxSizing : qx.bom.element.BoxSizing }, /* --------------------------------------------------------------------------- COMPILE SUPPORT --------------------------------------------------------------------------- */ /** * Compiles the given styles into a string which can be used to * concat a HTML string for innerHTML usage. * * @param map {Map} Map of style properties to compile * @return {String} Compiled string of given style properties. */ compile : function(map){ var html = []; var special = this.__special; var cssNames = this.__cssNames; var name,value; for(name in map){ // read value value = map[name]; if(value == null){ continue; }; // normalize name name = this.__styleNames[name] || this.__getStyleName(name) || name; // process special properties if(special[name]){ html.push(special[name].compile(value)); } else { if(!cssNames[name]){ cssNames[name] = qx.lang.String.hyphenate(name); }; html.push(cssNames[name], ":", value, ";"); }; }; return html.join(""); }, /* --------------------------------------------------------------------------- CSS TEXT SUPPORT --------------------------------------------------------------------------- */ /** * Set the full CSS content of the style attribute * * @param element {Element} The DOM element to modify * @param value {String} The full CSS string */ setCss : function(element, value){ if(qx.core.Environment.get("engine.name") === "mshtml" && parseInt(qx.core.Environment.get("browser.documentmode"), 10) < 8){ element.style.cssText = value; } else { element.setAttribute("style", value); }; }, /** * Returns the full content of the style attribute. * * @param element {Element} The DOM element to query * @return {String} the full CSS string * @signature function(element) */ getCss : function(element){ if(qx.core.Environment.get("engine.name") === "mshtml" && parseInt(qx.core.Environment.get("browser.documentmode"), 10) < 8){ return element.style.cssText.toLowerCase(); } else { return element.getAttribute("style"); }; }, /* --------------------------------------------------------------------------- STYLE ATTRIBUTE SUPPORT --------------------------------------------------------------------------- */ /** * Checks whether the browser supports the given CSS property. * * @param propertyName {String} The name of the property * @return {Boolean} Whether the property id supported */ isPropertySupported : function(propertyName){ return (this.__special[propertyName] || this.__styleNames[propertyName] || propertyName in document.documentElement.style); }, /** {Integer} Computed value of a style property. Compared to the cascaded style, * this one also interprets the values e.g. translates <code>em</code> units to * <code>px</code>. */ COMPUTED_MODE : 1, /** {Integer} Cascaded value of a style property. */ CASCADED_MODE : 2, /** * {Integer} Local value of a style property. Ignores inheritance cascade. * Does not interpret values. */ LOCAL_MODE : 3, /** * Sets the value of a style property * * @param element {Element} The DOM element to modify * @param name {String} Name of the style attribute (js variant e.g. marginTop, wordSpacing) * @param value {var} The value for the given style * @param smart {Boolean?true} Whether the implementation should automatically use * special implementations for some properties */ set : function(element, name, value, smart){ { }; // normalize name name = this.__styleNames[name] || this.__getStyleName(name) || name; // special handling for specific properties // through this good working switch this part costs nothing when // processing non-smart properties if(smart !== false && this.__special[name]){ this.__special[name].set(element, value); } else { element.style[name] = value !== null ? value : ""; }; }, /** * Convenience method to modify a set of styles at once. * * @param element {Element} The DOM element to modify * @param styles {Map} a map where the key is the name of the property * and the value is the value to use. * @param smart {Boolean?true} Whether the implementation should automatically use * special implementations for some properties */ setStyles : function(element, styles, smart){ { }; // inline calls to "set" and "reset" because this method is very // performance critical! var styleNames = this.__styleNames; var special = this.__special; var style = element.style; for(var key in styles){ var value = styles[key]; var name = styleNames[key] || this.__getStyleName(key) || key; if(value === undefined){ if(smart !== false && special[name]){ special[name].reset(element); } else { style[name] = ""; }; } else { if(smart !== false && special[name]){ special[name].set(element, value); } else { style[name] = value !== null ? value : ""; }; }; }; }, /** * Resets the value of a style property * * @param element {Element} The DOM element to modify * @param name {String} Name of the style attribute (js variant e.g. marginTop, wordSpacing) * @param smart {Boolean?true} Whether the implementation should automatically use * special implementations for some properties */ reset : function(element, name, smart){ // normalize name name = this.__styleNames[name] || this.__getStyleName(name) || name; // special handling for specific properties if(smart !== false && this.__special[name]){ this.__special[name].reset(element); } else { element.style[name] = ""; }; }, /** * Gets the value of a style property. * * *Computed* * * Returns the computed value of a style property. Compared to the cascaded style, * this one also interprets the values e.g. translates <code>em</code> units to * <code>px</code>. * * *Cascaded* * * Returns the cascaded value of a style property. * * *Local* * * Ignores inheritance cascade. Does not interpret values. * * @signature function(element, name, mode, smart) * @param element {Element} The DOM element to modify * @param name {String} Name of the style attribute (js variant e.g. marginTop, wordSpacing) * @param mode {Number} Choose one of the modes {@link #COMPUTED_MODE}, {@link #CASCADED_MODE}, * {@link #LOCAL_MODE}. The computed mode is the default one. * @param smart {Boolean?true} Whether the implementation should automatically use * special implementations for some properties * @return {var} The value of the property */ get : qx.core.Environment.select("engine.name", { "mshtml" : function(element, name, mode, smart){ // normalize name name = this.__styleNames[name] || this.__getStyleName(name) || name; // special handling if(smart !== false && this.__special[name]){ return this.__special[name].get(element, mode); }; // if the element is not inserted into the document "currentStyle" // may be undefined. In this case always return the local style. if(!element.currentStyle){ return element.style[name] || ""; }; // switch to right mode switch(mode){case this.LOCAL_MODE: return element.style[name] || "";case this.CASCADED_MODE: return element.currentStyle[name] || "";default: // Read cascaded style var currentStyle = element.currentStyle[name] || ""; // Pixel values are always OK if(/^-?[\.\d]+(px)?$/i.test(currentStyle)){ return currentStyle; }; // Try to convert non-pixel values var pixel = this.__mshtmlPixel[name]; if(pixel){ // Backup local and runtime style var localStyle = element.style[name]; // Overwrite local value with cascaded value // This is needed to have the pixel value setupped element.style[name] = currentStyle || 0; // Read pixel value and add "px" var value = element.style[pixel] + "px"; // Recover old local value element.style[name] = localStyle; // Return value return value; }; // Just the current style return currentStyle;}; }, "default" : function(element, name, mode, smart){ // normalize name name = this.__styleNames[name] || this.__getStyleName(name) || name; // special handling if(smart !== false && this.__special[name]){ return this.__special[name].get(element, mode); }; // switch to right mode switch(mode){case this.LOCAL_MODE: return element.style[name] || "";case this.CASCADED_MODE: // Currently only supported by Opera and Internet Explorer if(element.currentStyle){ return element.currentStyle[name] || ""; }; throw new Error("Cascaded styles are not supported in this browser!");// Support for the DOM2 getComputedStyle method // // Safari >= 3 & Gecko > 1.4 expose all properties to the returned // CSSStyleDeclaration object. In older browsers the function // "getPropertyValue" is needed to access the values. // // On a computed style object all properties are read-only which is // identical to the behavior of MSHTML's "currentStyle". default: // Opera, Mozilla and Safari 3+ also have a global getComputedStyle which is identical // to the one found under document.defaultView. // The problem with this is however that this does not work correctly // when working with frames and access an element of another frame. // Then we must use the <code>getComputedStyle</code> of the document // where the element is defined. var doc = qx.dom.Node.getDocument(element); var computed = doc.defaultView.getComputedStyle(element, null); // All relevant browsers expose the configured style properties to // the CSSStyleDeclaration objects return computed ? computed[name] : "";}; } }) }, defer : function(statics){ statics.__detectVendorProperties(); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /** * Basic node creation and type detection */ qx.Bootstrap.define("qx.dom.Node", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /* --------------------------------------------------------------------------- NODE TYPES --------------------------------------------------------------------------- */ /** * {Map} Node type: * * * ELEMENT * * ATTRIBUTE * * TEXT * * CDATA_SECTION * * ENTITY_REFERENCE * * ENTITY * * PROCESSING_INSTRUCTION * * COMMENT * * DOCUMENT * * DOCUMENT_TYPE * * DOCUMENT_FRAGMENT * * NOTATION */ ELEMENT : 1, ATTRIBUTE : 2, TEXT : 3, CDATA_SECTION : 4, ENTITY_REFERENCE : 5, ENTITY : 6, PROCESSING_INSTRUCTION : 7, COMMENT : 8, DOCUMENT : 9, DOCUMENT_TYPE : 10, DOCUMENT_FRAGMENT : 11, NOTATION : 12, /* --------------------------------------------------------------------------- DOCUMENT ACCESS --------------------------------------------------------------------------- */ /** * Returns the owner document of the given node * * @param node {Node|Document|Window} the node which should be tested * @return {Document|null} The document of the given DOM node */ getDocument : function(node){ return node.nodeType === this.DOCUMENT ? node : // is document already node.ownerDocument || // is DOM node node.document; }, /** * Returns the DOM2 <code>defaultView</code> (window). * * @param node {Node|Document|Window} node to inspect * @return {Window} the <code>defaultView</code> of the given node */ getWindow : function(node){ // is a window already if(node.nodeType == null){ return node; }; // jump to document if(node.nodeType !== this.DOCUMENT){ node = node.ownerDocument; }; // jump to window return node.defaultView || node.parentWindow; }, /** * Returns the document element. (Logical root node) * * This is a convenience attribute that allows direct access to the child * node that is the root element of the document. For HTML documents, * this is the element with the tagName "HTML". * * @param node {Node|Document|Window} node to inspect * @return {Element} document element of the given node */ getDocumentElement : function(node){ return this.getDocument(node).documentElement; }, /** * Returns the body element. (Visual root node) * * This normally only makes sense for HTML documents. It returns * the content area of the HTML document. * * @param node {Node|Document|Window} node to inspect * @return {Element} document body of the given node */ getBodyElement : function(node){ return this.getDocument(node).body; }, /* --------------------------------------------------------------------------- TYPE TESTS --------------------------------------------------------------------------- */ /** * Whether the given object is a DOM node * * @param node {Node} the node which should be tested * @return {Boolean} true if the node is a DOM node */ isNode : function(node){ return !!(node && node.nodeType != null); }, /** * Whether the given object is a DOM element node * * @param node {Node} the node which should be tested * @return {Boolean} true if the node is a DOM element */ isElement : function(node){ return !!(node && node.nodeType === this.ELEMENT); }, /** * Whether the given object is a DOM document node * * @param node {Node} the node which should be tested * @return {Boolean} true when the node is a DOM document */ isDocument : function(node){ return !!(node && node.nodeType === this.DOCUMENT); }, /** * Whether the given object is a DOM text node * * @param node {Node} the node which should be tested * @return {Boolean} true if the node is a DOM text node */ isText : function(node){ return !!(node && node.nodeType === this.TEXT); }, /** * Check whether the given object is a browser window object. * * @param obj {Object} the object which should be tested * @return {Boolean} true if the object is a window object */ isWindow : function(obj){ return !!(obj && obj.history && obj.location && obj.document); }, /** * Whether the node has the given node name * * @param node {Node} the node * @param nodeName {String} the node name to check for * @return {Boolean} Whether the node has the given node name */ isNodeName : function(node, nodeName){ if(!nodeName || !node || !node.nodeName){ return false; }; return nodeName.toLowerCase() == qx.dom.Node.getName(node); }, /* --------------------------------------------------------------------------- UTILITIES --------------------------------------------------------------------------- */ /** * Get the node name as lower case string * * @param node {Node} the node * @return {String} the node name */ getName : function(node){ if(!node || !node.nodeName){ return null; }; return node.nodeName.toLowerCase(); }, /** * Returns the text content of an node where the node may be of node type * NODE_ELEMENT, NODE_ATTRIBUTE, NODE_TEXT or NODE_CDATA * * @param node {Node} the node from where the search should start. * If the node has subnodes the text contents are recursively retreived and joined. * @return {String} the joined text content of the given node or null if not appropriate. * @signature function(node) */ getText : function(node){ if(!node || !node.nodeType){ return null; }; switch(node.nodeType){case 1: // NODE_ELEMENT var i,a = [],nodes = node.childNodes,length = nodes.length; for(i = 0;i < length;i++){ a[i] = this.getText(nodes[i]); }; return a.join("");case 2:// NODE_ATTRIBUTE case 3:// NODE_TEXT case 4: // CDATA return node.nodeValue;}; return null; }, /** * Checks if the given node is a block node * * @param node {Node} Node * @return {Boolean} whether it is a block node */ isBlockNode : function(node){ if(!qx.dom.Node.isElement(node)){ return false; }; node = qx.dom.Node.getName(node); return /^(body|form|textarea|fieldset|ul|ol|dl|dt|dd|li|div|hr|p|h[1-6]|quote|pre|table|thead|tbody|tfoot|tr|td|th|iframe|address|blockquote)$/.test(node); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ====================================================================== This class contains code based on the following work: * Yahoo! UI Library http://developer.yahoo.com/yui Version 2.2.0 Copyright: (c) 2007, Yahoo! Inc. License: BSD: http://developer.yahoo.com/yui/license.txt ---------------------------------------------------------------------- http://developer.yahoo.com/yui/license.html Copyright (c) 2009, Yahoo! Inc. All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Yahoo! Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of Yahoo! Inc. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ************************************************************************ */ /** * Includes library functions to work with the current document. */ qx.Bootstrap.define("qx.bom.Document", { statics : { /** * Whether the document is in quirks mode (e.g. non XHTML, HTML4 Strict or missing doctype) * * @signature function(win) * @param win {Window?window} The window to query * @return {Boolean} true when containing document is in quirks mode */ isQuirksMode : qx.core.Environment.select("engine.name", { "mshtml" : function(win){ if(qx.core.Environment.get("engine.version") >= 8){ return (win || window).document.documentMode === 5; } else { return (win || window).document.compatMode !== "CSS1Compat"; }; }, "webkit" : function(win){ if(document.compatMode === undefined){ var el = (win || window).document.createElement("div"); el.style.cssText = "position:absolute;width:0;height:0;width:1"; return el.style.width === "1px" ? true : false; } else { return (win || window).document.compatMode !== "CSS1Compat"; }; }, "default" : function(win){ return (win || window).document.compatMode !== "CSS1Compat"; } }), /** * Whether the document is in standard mode (e.g. XHTML, HTML4 Strict or doctype defined) * * @param win {Window?window} The window to query * @return {Boolean} true when containing document is in standard mode */ isStandardMode : function(win){ return !this.isQuirksMode(win); }, /** * Returns the width of the document. * * Internet Explorer in standard mode stores the proprietary <code>scrollWidth</code> property * on the <code>documentElement</code>, but in quirks mode on the body element. All * other known browsers simply store the correct value on the <code>documentElement</code>. * * If the viewport is wider than the document the viewport width is returned. * * As the html element has no visual appearance it also can not scroll. This * means that we must use the body <code>scrollWidth</code> in all non mshtml clients. * * Verified to correctly work with: * * * Mozilla Firefox 2.0.0.4 * * Opera 9.2.1 * * Safari 3.0 beta (3.0.2) * * Internet Explorer 7.0 * * @param win {Window?window} The window to query * @return {Integer} The width of the actual document (which includes the body and its margin). * * NOTE: Opera 9.5x and 9.6x have wrong value for the scrollWidth property, * if an element use negative value for top and left to be outside the viewport! * See: http://bugzilla.qooxdoo.org/show_bug.cgi?id=2869 */ getWidth : function(win){ var doc = (win || window).document; var view = qx.bom.Viewport.getWidth(win); var scroll = this.isStandardMode(win) ? doc.documentElement.scrollWidth : doc.body.scrollWidth; return Math.max(scroll, view); }, /** * Returns the height of the document. * * Internet Explorer in standard mode stores the proprietary <code>scrollHeight</code> property * on the <code>documentElement</code>, but in quirks mode on the body element. All * other known browsers simply store the correct value on the <code>documentElement</code>. * * If the viewport is higher than the document the viewport height is returned. * * As the html element has no visual appearance it also can not scroll. This * means that we must use the body <code>scrollHeight</code> in all non mshtml clients. * * Verified to correctly work with: * * * Mozilla Firefox 2.0.0.4 * * Opera 9.2.1 * * Safari 3.0 beta (3.0.2) * * Internet Explorer 7.0 * * @param win {Window?window} The window to query * @return {Integer} The height of the actual document (which includes the body and its margin). * * NOTE: Opera 9.5x and 9.6x have wrong value for the scrollWidth property, * if an element use negative value for top and left to be outside the viewport! * See: http://bugzilla.qooxdoo.org/show_bug.cgi?id=2869 */ getHeight : function(win){ var doc = (win || window).document; var view = qx.bom.Viewport.getHeight(win); var scroll = this.isStandardMode(win) ? doc.documentElement.scrollHeight : doc.body.scrollHeight; return Math.max(scroll, view); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Sebastian Fastner (fastner) * Tino Butz (tbtz) ====================================================================== This class contains code based on the following work: * Unify Project Homepage: http://unify-project.org Copyright: 2009-2010 Deutsche Telekom AG, Germany, http://telekom.com License: MIT: http://www.opensource.org/licenses/mit-license.php * Yahoo! UI Library http://developer.yahoo.com/yui Version 2.2.0 Copyright: (c) 2007, Yahoo! Inc. License: BSD: http://developer.yahoo.com/yui/license.txt ---------------------------------------------------------------------- http://developer.yahoo.com/yui/license.html Copyright (c) 2009, Yahoo! Inc. All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Yahoo! Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of Yahoo! Inc. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ************************************************************************ */ /** * Includes library functions to work with the client's viewport (window). * Orientation related functions are point to window.top as default. */ qx.Bootstrap.define("qx.bom.Viewport", { statics : { /** * Returns the current width of the viewport (excluding the vertical scrollbar * if present). * * @param win {Window?window} The window to query * @return {Integer} The width of the viewable area of the page (excluding scrollbars). */ getWidth : function(win){ var win = win || window; var doc = win.document; return qx.bom.Document.isStandardMode(win) ? doc.documentElement.clientWidth : doc.body.clientWidth; }, /** * Returns the current height of the viewport (excluding the horizontal scrollbar * if present). * * @param win {Window?window} The window to query * @return {Integer} The Height of the viewable area of the page (excluding scrollbars). */ getHeight : function(win){ var win = win || window; var doc = win.document; return qx.bom.Document.isStandardMode(win) ? doc.documentElement.clientHeight : doc.body.clientHeight; }, /** * Returns the scroll position of the viewport * * All clients except IE < 9 support the non-standard property <code>pageXOffset</code>. * As this is easier to evaluate we prefer this property over <code>scrollLeft</code>. * Since the window could differ from the one the application is running in, we can't * use a one-time environment check to decide which property to use. * * @param win {Window?window} The window to query * @return {Integer} Scroll position in pixels from left edge, always a positive integer or zero */ getScrollLeft : function(win){ var win = win ? win : window; if(typeof win.pageXOffset !== "undefined"){ return win.pageXOffset; }; // Firefox is using 'documentElement.scrollLeft' and Chrome is using // 'document.body.scrollLeft'. For the other value each browser is returning // 0, so we can use this check to get the positive value without using specific // browser checks. var doc = win.document; return doc.documentElement.scrollLeft || doc.body.scrollLeft; }, /** * Returns the scroll position of the viewport * * All clients except MSHTML support the non-standard property <code>pageYOffset</code>. * As this is easier to evaluate we prefer this property over <code>scrollTop</code>. * Since the window could differ from the one the application is running in, we can't * use a one-time environment check to decide which property to use. * * @param win {Window?window} The window to query * @return {Integer} Scroll position in pixels from top edge, always a positive integer or zero */ getScrollTop : function(win){ var win = win ? win : window; if(typeof win.pageYOffeset !== "undefined"){ return win.pageYOffset; }; // Firefox is using 'documentElement.scrollTop' and Chrome is using // 'document.body.scrollTop'. For the other value each browser is returning // 0, so we can use this check to get the positive value without using specific // browser checks. var doc = win.document; return doc.documentElement.scrollTop || doc.body.scrollTop; }, /** * Returns an orientation normalizer value that should be added to device orientation * to normalize behaviour on different devices. * * @param win {Window} The window to query * @return {Map} Orientation normalizing value */ __getOrientationNormalizer : function(win){ // Calculate own understanding of orientation (0 = portrait, 90 = landscape) var currentOrientation = this.getWidth(win) > this.getHeight(win) ? 90 : 0; var deviceOrientation = win.orientation; if(deviceOrientation == null || Math.abs(deviceOrientation % 180) == currentOrientation){ // No device orientation available or device orientation equals own understanding of orientation return { "-270" : 90, "-180" : 180, "-90" : -90, "0" : 0, "90" : 90, "180" : 180, "270" : -90 }; } else { // Device orientation is not equal to own understanding of orientation return { "-270" : 180, "-180" : -90, "-90" : 0, "0" : 90, "90" : 180, "180" : -90, "270" : 0 }; }; }, // Cache orientation normalizer map on start __orientationNormalizer : null, /** * Returns the current orientation of the viewport in degree. * * All possible values and their meaning: * * * <code>-90</code>: "Landscape" * * <code>0</code>: "Portrait" * * <code>90</code>: "Landscape" * * <code>180</code>: "Portrait" * * @param win {Window?window.top} The window to query. (Default = top window) * @return {Integer} The current orientation in degree */ getOrientation : function(win){ // Set window.top as default, because orientationChange event is only fired top window var win = win || window.top; // The orientation property of window does not have the same behaviour over all devices // iPad has 0degrees = Portrait, Playbook has 90degrees = Portrait, same for Android Honeycomb // // To fix this an orientationNormalizer map is calculated on application start // // The calculation of getWidth and getHeight returns wrong values if you are in an input field // on iPad and rotate your device! var orientation = win.orientation; if(orientation == null){ // Calculate orientation from window width and window height orientation = this.getWidth(win) > this.getHeight(win) ? 90 : 0; } else { if(this.__orientationNormalizer == null){ this.__orientationNormalizer = this.__getOrientationNormalizer(win); }; // Normalize orientation value orientation = this.__orientationNormalizer[orientation]; }; return orientation; }, /** * Whether the viewport orientation is currently in landscape mode. * * @param win {Window?window} The window to query * @return {Boolean} <code>true</code> when the viewport orientation * is currently in landscape mode. */ isLandscape : function(win){ return this.getWidth(win) >= this.getHeight(win); }, /** * Whether the viewport orientation is currently in portrait mode. * * @param win {Window?window} The window to query * @return {Boolean} <code>true</code> when the viewport orientation * is currently in portrait mode. */ isPortrait : function(win){ return this.getWidth(win) < this.getHeight(win); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ====================================================================== This class contains code based on the following work: * Base2 http://code.google.com/p/base2/ Version 0.9 Copyright: (c) 2006-2007, Dean Edwards License: MIT: http://www.opensource.org/licenses/mit-license.php Authors: * Dean Edwards ************************************************************************ */ /** * CSS class name support for HTML elements. Supports multiple class names * for each element. Can query and apply class names to HTML elements. */ qx.Bootstrap.define("qx.bom.element.Class", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** {RegExp} Regular expressions to split class names */ __splitter : /\s+/g, /** {RegExp} String trim regular expression. */ __trim : /^\s+|\s+$/g, /** * Adds a className to the given element * If successfully added the given className will be returned * * @signature function(element, name) * @param element {Element} The element to modify * @param name {String} The class name to add * @return {String} The added classname (if so) */ add : { "native" : function(element, name){ element.classList.add(name); return name; }, "default" : function(element, name){ if(!this.has(element, name)){ element.className += (element.className ? " " : "") + name; }; return name; } }[qx.core.Environment.get("html.classlist") ? "native" : "default"], /** * Adds multiple classes to the given element * * @signature function(element, classes) * @param element {Element} DOM element to modify * @param classes {String[]} List of classes to add. * @return {String} The resulting class name which was applied */ addClasses : { "native" : function(element, classes){ for(var i = 0;i < classes.length;i++){ element.classList.add(classes[i]); }; return element.className; }, "default" : function(element, classes){ var keys = { }; var result; var old = element.className; if(old){ result = old.split(this.__splitter); for(var i = 0,l = result.length;i < l;i++){ keys[result[i]] = true; }; for(var i = 0,l = classes.length;i < l;i++){ if(!keys[classes[i]]){ result.push(classes[i]); }; }; } else { result = classes; }; return element.className = result.join(" "); } }[qx.core.Environment.get("html.classlist") ? "native" : "default"], /** * Gets the classname of the given element * * @param element {Element} The element to query * @return {String} The retrieved classname */ get : function(element){ var className = element.className; if(typeof className.split !== 'function'){ if(typeof className === 'object'){ if(qx.Bootstrap.getClass(className) == 'SVGAnimatedString'){ className = className.baseVal; } else { { }; className = ''; }; }; if(typeof className === 'undefined'){ { }; className = ''; }; }; return className; }, /** * Whether the given element has the given className. * * @signature function(element, name) * @param element {Element} The DOM element to check * @param name {String} The class name to check for * @return {Boolean} true when the element has the given classname */ has : { "native" : function(element, name){ return element.classList.contains(name); }, "default" : function(element, name){ var regexp = new RegExp("(^|\\s)" + name + "(\\s|$)"); return regexp.test(element.className); } }[qx.core.Environment.get("html.classlist") ? "native" : "default"], /** * Removes a className from the given element * * @signature function(element, name) * @param element {Element} The DOM element to modify * @param name {String} The class name to remove * @return {String} The removed class name */ remove : { "native" : function(element, name){ element.classList.remove(name); return name; }, "default" : function(element, name){ var regexp = new RegExp("(^|\\s)" + name + "(\\s|$)"); element.className = element.className.replace(regexp, "$2"); return name; } }[qx.core.Environment.get("html.classlist") ? "native" : "default"], /** * Removes multiple classes from the given element * * @signature function(element, classes) * @param element {Element} DOM element to modify * @param classes {String[]} List of classes to remove. * @return {String} The resulting class name which was applied */ removeClasses : { "native" : function(element, classes){ for(var i = 0;i < classes.length;i++){ element.classList.remove(classes[i]); }; return element.className; }, "default" : function(element, classes){ var reg = new RegExp("\\b" + classes.join("\\b|\\b") + "\\b", "g"); return element.className = element.className.replace(reg, "").replace(this.__trim, "").replace(this.__splitter, " "); } }[qx.core.Environment.get("html.classlist") ? "native" : "default"], /** * Replaces the first given class name with the second one * * @param element {Element} The DOM element to modify * @param oldName {String} The class name to remove * @param newName {String} The class name to add * @return {String} The added class name */ replace : function(element, oldName, newName){ this.remove(element, oldName); return this.add(element, newName); }, /** * Toggles a className of the given element * * @signature function(element, name, toggle) * @param element {Element} The DOM element to modify * @param name {String} The class name to toggle * @param toggle {Boolean?null} Whether to switch class on/off. Without * the parameter an automatic toggling would happen. * @return {String} The class name */ toggle : { "native" : function(element, name, toggle){ if(toggle === undefined){ element.classList.toggle(name); } else { toggle ? this.add(element, name) : this.remove(element, name); }; return name; }, "default" : function(element, name, toggle){ if(toggle == null){ toggle = !this.has(element, name); }; toggle ? this.add(element, name) : this.remove(element, name); return name; } }[qx.core.Environment.get("html.classlist") ? "native" : "default"] } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * Contains support for calculating dimensions of HTML elements. * * We differ between the box (or border) size which is available via * {@link #getWidth} and {@link #getHeight} and the content or scroll * sizes which are available via {@link #getContentWidth} and * {@link #getContentHeight}. */ qx.Bootstrap.define("qx.bom.element.Dimension", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** * Returns the rendered width of the given element. * * This is the visible width of the object, which need not to be identical * to the width configured via CSS. This highly depends on the current * box-sizing for the document and maybe even for the element. * * @signature function(element) * @param element {Element} element to query * @return {Integer} width of the element */ getWidth : qx.core.Environment.select("engine.name", { "gecko" : function(element){ // offsetWidth in Firefox does not always return the rendered pixel size // of an element. // Starting with Firefox 3 the rendered size can be determined by using // getBoundingClientRect // https://bugzilla.mozilla.org/show_bug.cgi?id=450422 if(element.getBoundingClientRect){ var rect = element.getBoundingClientRect(); return Math.round(rect.right) - Math.round(rect.left); } else { return element.offsetWidth; }; }, "default" : function(element){ return element.offsetWidth; } }), /** * Returns the rendered height of the given element. * * This is the visible height of the object, which need not to be identical * to the height configured via CSS. This highly depends on the current * box-sizing for the document and maybe even for the element. * * @signature function(element) * @param element {Element} element to query * @return {Integer} height of the element */ getHeight : qx.core.Environment.select("engine.name", { "gecko" : function(element){ if(element.getBoundingClientRect){ var rect = element.getBoundingClientRect(); return Math.round(rect.bottom) - Math.round(rect.top); } else { return element.offsetHeight; }; }, "default" : function(element){ return element.offsetHeight; } }), /** * Returns the rendered size of the given element. * * @param element {Element} element to query * @return {Map} map containing the width and height of the element */ getSize : function(element){ return { width : this.getWidth(element), height : this.getHeight(element) }; }, /** {Map} Contains all overflow values where scrollbars are invisible */ __hiddenScrollbars : { visible : true, hidden : true }, /** * Returns the content width. * * The content width is basically the maximum * width used or the maximum width which can be used by the content. This * excludes all kind of styles of the element like borders, paddings, margins, * and even scrollbars. * * Please note that with visible scrollbars the content width returned * may be larger than the box width returned via {@link #getWidth}. * * @param element {Element} element to query * @return {Integer} Computed content width */ getContentWidth : function(element){ var Style = qx.bom.element.Style; var overflowX = qx.bom.element.Style.get(element, "overflowX"); var paddingLeft = parseInt(Style.get(element, "paddingLeft") || "0px", 10); var paddingRight = parseInt(Style.get(element, "paddingRight") || "0px", 10); if(this.__hiddenScrollbars[overflowX]){ var contentWidth = element.clientWidth; if((qx.core.Environment.get("engine.name") == "opera") || qx.dom.Node.isBlockNode(element)){ contentWidth = contentWidth - paddingLeft - paddingRight; }; return contentWidth; } else { if(element.clientWidth >= element.scrollWidth){ // Scrollbars visible, but not needed? We need to substract both paddings return Math.max(element.clientWidth, element.scrollWidth) - paddingLeft - paddingRight; } else { // Scrollbars visible and needed. We just remove the left padding, // as the right padding is not respected in rendering. var width = element.scrollWidth - paddingLeft; // IE renders the paddingRight as well with scrollbars on if(qx.core.Environment.get("engine.name") == "mshtml" && qx.core.Environment.get("engine.version") >= 6){ width -= paddingRight; }; return width; }; }; }, /** * Returns the content height. * * The content height is basically the maximum * height used or the maximum height which can be used by the content. This * excludes all kind of styles of the element like borders, paddings, margins, * and even scrollbars. * * Please note that with visible scrollbars the content height returned * may be larger than the box height returned via {@link #getHeight}. * * @param element {Element} element to query * @return {Integer} Computed content height */ getContentHeight : function(element){ var Style = qx.bom.element.Style; var overflowY = qx.bom.element.Style.get(element, "overflowY"); var paddingTop = parseInt(Style.get(element, "paddingTop") || "0px", 10); var paddingBottom = parseInt(Style.get(element, "paddingBottom") || "0px", 10); if(this.__hiddenScrollbars[overflowY]){ return element.clientHeight - paddingTop - paddingBottom; } else { if(element.clientHeight >= element.scrollHeight){ // Scrollbars visible, but not needed? We need to substract both paddings return Math.max(element.clientHeight, element.scrollHeight) - paddingTop - paddingBottom; } else { // Scrollbars visible and needed. We just remove the top padding, // as the bottom padding is not respected in rendering. var height = element.scrollHeight - paddingTop; // IE renders the paddingBottom as well with scrollbars on if(qx.core.Environment.get("engine.name") == "mshtml" && qx.core.Environment.get("engine.version") == 6){ height -= paddingBottom; }; return height; }; }; }, /** * Returns the rendered content size of the given element. * * @param element {Element} element to query * @return {Map} map containing the content width and height of the element */ getContentSize : function(element){ return { width : this.getContentWidth(element), height : this.getContentHeight(element) }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ====================================================================== This class contains code based on the following work: * jQuery Dimension Plugin http://jquery.com/ Version 1.1.3 Copyright: (c) 2007, Paul Bakaus & Brandon Aaron License: MIT: http://www.opensource.org/licenses/mit-license.php Authors: Paul Bakaus Brandon Aaron ************************************************************************ */ /** * Query the location of an arbitrary DOM element in relation to its top * level body element. Works in all major browsers: * * * Mozilla 1.5 + 2.0 * * Internet Explorer 6.0 + 7.0 (both standard & quirks mode) * * Opera 9.2 * * Safari 3.0 beta */ qx.Bootstrap.define("qx.bom.element.Location", { statics : { /** * Queries a style property for the given element * * @param elem {Element} DOM element to query * @param style {String} Style property * @return {String} Value of given style property */ __style : function(elem, style){ return qx.bom.element.Style.get(elem, style, qx.bom.element.Style.COMPUTED_MODE, false); }, /** * Queries a style property for the given element and parses it to an integer value * * @param elem {Element} DOM element to query * @param style {String} Style property * @return {Integer} Value of given style property */ __num : function(elem, style){ return parseInt(qx.bom.element.Style.get(elem, style, qx.bom.element.Style.COMPUTED_MODE, false), 10) || 0; }, /** * Computes the scroll offset of the given element relative to the document * <code>body</code>. * * @param elem {Element} DOM element to query * @return {Map} Map which contains the <code>left</code> and <code>top</code> scroll offsets */ __computeScroll : function(elem){ var left = 0,top = 0; // Find window var win = qx.dom.Node.getWindow(elem); left -= qx.bom.Viewport.getScrollLeft(win); top -= qx.bom.Viewport.getScrollTop(win); return { left : left, top : top }; }, /** * Computes the offset of the given element relative to the document * <code>body</code>. * * @param elem {Element} DOM element to query * @return {Map} Map which contains the <code>left</code> and <code>top</code> offsets */ __computeBody : qx.core.Environment.select("engine.name", { "mshtml" : function(elem){ // Find body element var doc = qx.dom.Node.getDocument(elem); var body = doc.body; var left = 0; var top = 0; left -= body.clientLeft + doc.documentElement.clientLeft; top -= body.clientTop + doc.documentElement.clientTop; if(!qx.core.Environment.get("browser.quirksmode")){ left += this.__num(body, "borderLeftWidth"); top += this.__num(body, "borderTopWidth"); }; return { left : left, top : top }; }, "webkit" : function(elem){ // Find body element var doc = qx.dom.Node.getDocument(elem); var body = doc.body; // Start with the offset var left = body.offsetLeft; var top = body.offsetTop; // only for safari < version 4.0 if(parseFloat(qx.core.Environment.get("engine.version")) < 530.17){ left += this.__num(body, "borderLeftWidth"); top += this.__num(body, "borderTopWidth"); }; return { left : left, top : top }; }, "gecko" : function(elem){ // Find body element var body = qx.dom.Node.getDocument(elem).body; // Start with the offset var left = body.offsetLeft; var top = body.offsetTop; // add the body margin for firefox 3.0 and below if(parseFloat(qx.core.Environment.get("engine.version")) < 1.9){ left += this.__num(body, "marginLeft"); top += this.__num(body, "marginTop"); }; // Correct substracted border (only in content-box mode) if(qx.bom.element.BoxSizing.get(body) !== "border-box"){ left += this.__num(body, "borderLeftWidth"); top += this.__num(body, "borderTopWidth"); }; return { left : left, top : top }; }, // At the moment only correctly supported by Opera "default" : function(elem){ // Find body element var body = qx.dom.Node.getDocument(elem).body; // Start with the offset var left = body.offsetLeft; var top = body.offsetTop; return { left : left, top : top }; } }), /** * Computes the sum of all offsets of the given element node. * * Traditionally this is a loop which goes up the whole parent tree * and sums up all found offsets. * * But both <code>mshtml</code> and <code>gecko >= 1.9</code> support * <code>getBoundingClientRect</code> which allows a * much faster access to the offset position. * * Please note: When gecko 1.9 does not use the <code>getBoundingClientRect</code> * implementation, and therefore use the traditional offset calculation * the gecko 1.9 fix in <code>__computeBody</code> must not be applied. * * @signature function(elem) * @param elem {Element} DOM element to query * @return {Map} Map which contains the <code>left</code> and <code>top</code> offsets */ __computeOffset : qx.core.Environment.select("engine.name", { "gecko" : function(elem){ // Use faster getBoundingClientRect() if available (gecko >= 1.9) if(elem.getBoundingClientRect){ var rect = elem.getBoundingClientRect(); // Firefox 3.0 alpha 6 (gecko 1.9) returns floating point numbers // use Math.round() to round them to style compatible numbers // MSHTML returns integer numbers var left = Math.round(rect.left); var top = Math.round(rect.top); } else { var left = 0; var top = 0; // Stop at the body var body = qx.dom.Node.getDocument(elem).body; var box = qx.bom.element.BoxSizing; if(box.get(elem) !== "border-box"){ left -= this.__num(elem, "borderLeftWidth"); top -= this.__num(elem, "borderTopWidth"); }; while(elem && elem !== body){ // Add node offsets left += elem.offsetLeft; top += elem.offsetTop; // Mozilla does not add the borders to the offset // when using box-sizing=content-box if(box.get(elem) !== "border-box"){ left += this.__num(elem, "borderLeftWidth"); top += this.__num(elem, "borderTopWidth"); }; // Mozilla does not add the border for a parent that has // overflow set to anything but visible if(elem.parentNode && this.__style(elem.parentNode, "overflow") != "visible"){ left += this.__num(elem.parentNode, "borderLeftWidth"); top += this.__num(elem.parentNode, "borderTopWidth"); }; // One level up (offset hierarchy) elem = elem.offsetParent; }; }; return { left : left, top : top }; }, "default" : function(elem){ var doc = qx.dom.Node.getDocument(elem); // Use faster getBoundingClientRect() if available if(elem.getBoundingClientRect){ var rect = elem.getBoundingClientRect(); var left = Math.round(rect.left); var top = Math.round(rect.top); } else { // Offset of the incoming element var left = elem.offsetLeft; var top = elem.offsetTop; // Start with the first offset parent elem = elem.offsetParent; // Stop at the body var body = doc.body; // Border correction is only needed for each parent // not for the incoming element itself while(elem && elem != body){ // Add node offsets left += elem.offsetLeft; top += elem.offsetTop; // Fix missing border left += this.__num(elem, "borderLeftWidth"); top += this.__num(elem, "borderTopWidth"); // One level up (offset hierarchy) elem = elem.offsetParent; }; }; return { left : left, top : top }; } }), /** * Computes the location of the given element in context of * the document dimensions. * * Supported modes: * * * <code>margin</code>: Calculate from the margin box of the element (bigger than the visual appearance: including margins of given element) * * <code>box</code>: Calculates the offset box of the element (default, uses the same size as visible) * * <code>border</code>: Calculate the border box (useful to align to border edges of two elements). * * <code>scroll</code>: Calculate the scroll box (relevant for absolute positioned content). * * <code>padding</code>: Calculate the padding box (relevant for static/relative positioned content). * * @param elem {Element} DOM element to query * @param mode {String?box} A supported option. See comment above. * @return {Map} Returns a map with <code>left</code>, <code>top</code>, * <code>right</code> and <code>bottom</code> which contains the distance * of the element relative to the document. */ get : function(elem, mode){ if(elem.tagName == "BODY"){ var location = this.__getBodyLocation(elem); var left = location.left; var top = location.top; } else { var body = this.__computeBody(elem); var offset = this.__computeOffset(elem); // Reduce by viewport scrolling. // Hint: getBoundingClientRect returns the location of the // element in relation to the viewport which includes // the scrolling var scroll = this.__computeScroll(elem); var left = offset.left + body.left - scroll.left; var top = offset.top + body.top - scroll.top; }; var right = left + elem.offsetWidth; var bottom = top + elem.offsetHeight; if(mode){ // In this modes we want the size as seen from a child what means that we want the full width/height // which may be higher than the outer width/height when the element has scrollbars. if(mode == "padding" || mode == "scroll"){ var overX = qx.bom.element.Style.get(elem, "overflowX"); if(overX == "scroll" || overX == "auto"){ right += elem.scrollWidth - elem.offsetWidth + this.__num(elem, "borderLeftWidth") + this.__num(elem, "borderRightWidth"); }; var overY = qx.bom.element.Style.get(elem, "overflowY"); if(overY == "scroll" || overY == "auto"){ bottom += elem.scrollHeight - elem.offsetHeight + this.__num(elem, "borderTopWidth") + this.__num(elem, "borderBottomWidth"); }; }; switch(mode){case "padding": left += this.__num(elem, "paddingLeft"); top += this.__num(elem, "paddingTop"); right -= this.__num(elem, "paddingRight"); bottom -= this.__num(elem, "paddingBottom");// no break here case "scroll": left -= elem.scrollLeft; top -= elem.scrollTop; right -= elem.scrollLeft; bottom -= elem.scrollTop;// no break here case "border": left += this.__num(elem, "borderLeftWidth"); top += this.__num(elem, "borderTopWidth"); right -= this.__num(elem, "borderRightWidth"); bottom -= this.__num(elem, "borderBottomWidth"); break;case "margin": left -= this.__num(elem, "marginLeft"); top -= this.__num(elem, "marginTop"); right += this.__num(elem, "marginRight"); bottom += this.__num(elem, "marginBottom"); break;}; }; return { left : left, top : top, right : right, bottom : bottom }; }, /** * Get the location of the body element relative to the document. * @param body {Element} The body element. * @return {Map} map with the keys <code>left</code> and <code>top</code> */ __getBodyLocation : function(body){ var top = body.offsetTop; var left = body.offsetLeft; if(qx.core.Environment.get("engine.name") !== "mshtml" || !((parseFloat(qx.core.Environment.get("engine.version")) < 8 || qx.core.Environment.get("browser.documentmode") < 8) && !qx.core.Environment.get("browser.quirksmode"))){ top += this.__num(body, "marginTop"); left += this.__num(body, "marginLeft"); }; if(qx.core.Environment.get("engine.name") === "gecko"){ top += this.__num(body, "borderLeftWidth"); left += this.__num(body, "borderTopWidth"); }; return { left : left, top : top }; }, /** * Computes the location of the given element in context of * the document dimensions. For supported modes please * have a look at the {@link qx.bom.element.Location#get} method. * * @param elem {Element} DOM element to query * @param mode {String} A supported option. See comment above. * @return {Integer} The left distance * of the element relative to the document. */ getLeft : function(elem, mode){ return this.get(elem, mode).left; }, /** * Computes the location of the given element in context of * the document dimensions. For supported modes please * have a look at the {@link qx.bom.element.Location#get} method. * * @param elem {Element} DOM element to query * @param mode {String} A supported option. See comment above. * @return {Integer} The top distance * of the element relative to the document. */ getTop : function(elem, mode){ return this.get(elem, mode).top; }, /** * Computes the location of the given element in context of * the document dimensions. For supported modes please * have a look at the {@link qx.bom.element.Location#get} method. * * @param elem {Element} DOM element to query * @param mode {String} A supported option. See comment above. * @return {Integer} The right distance * of the element relative to the document. */ getRight : function(elem, mode){ return this.get(elem, mode).right; }, /** * Computes the location of the given element in context of * the document dimensions. For supported modes please * have a look at the {@link qx.bom.element.Location#get} method. * * @param elem {Element} DOM element to query * @param mode {String} A supported option. See comment above. * @return {Integer} The bottom distance * of the element relative to the document. */ getBottom : function(elem, mode){ return this.get(elem, mode).bottom; }, /** * Returns the distance between two DOM elements. For supported modes please * have a look at the {@link qx.bom.element.Location#get} method. * * @param elem1 {Element} First element * @param elem2 {Element} Second element * @param mode1 {String?null} Mode for first element * @param mode2 {String?null} Mode for second element * @return {Map} Returns a map with <code>left</code> and <code>top</code> * which contains the distance of the elements from each other. */ getRelative : function(elem1, elem2, mode1, mode2){ var loc1 = this.get(elem1, mode1); var loc2 = this.get(elem2, mode2); return { left : loc1.left - loc2.left, top : loc1.top - loc2.top, right : loc1.right - loc2.right, bottom : loc1.bottom - loc2.bottom }; }, /** * Returns the distance between the given element to its offset parent. * * @param elem {Element} DOM element to query * @return {Map} Returns a map with <code>left</code> and <code>top</code> * which contains the distance of the elements from each other. */ getPosition : function(elem){ return this.getRelative(elem, this.getOffsetParent(elem)); }, /** * Detects the offset parent of the given element * * @param element {Element} Element to query for offset parent * @return {Element} Detected offset parent */ getOffsetParent : function(element){ var offsetParent = element.offsetParent || document.body; var Style = qx.bom.element.Style; while(offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && Style.get(offsetParent, "position") === "static")){ offsetParent = offsetParent.offsetParent; }; return offsetParent; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de 2006 STZ-IDA, Germany, http://www.stz-ida.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Andreas Junghans (lucidcake) ************************************************************************ */ /** * Cross-browser wrapper to work with CSS stylesheets. */ qx.Bootstrap.define("qx.bom.Stylesheet", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** * Include a CSS file * * <em>Note:</em> Using a resource ID as the <code>href</code> parameter * will no longer be supported. Call * <code>qx.util.ResourceManager.getInstance().toUri(href)</code> to get * valid URI to be used with this method. * * @param href {String} Href value * @param doc {Document?} Document to modify */ includeFile : function(href, doc){ if(!doc){ doc = document; }; var el = doc.createElement("link"); el.type = "text/css"; el.rel = "stylesheet"; el.href = href; var head = doc.getElementsByTagName("head")[0]; head.appendChild(el); }, /** * Create a new Stylesheet node and append it to the document * * @param text {String?} optional string of css rules * @return {Stylesheet} the generates stylesheet element */ createElement : function(text){ if(qx.core.Environment.get("html.stylesheet.createstylesheet")){ var sheet = document.createStyleSheet(); if(text){ sheet.cssText = text; }; return sheet; } else { var elem = document.createElement("style"); elem.type = "text/css"; if(text){ elem.appendChild(document.createTextNode(text)); }; document.getElementsByTagName("head")[0].appendChild(elem); return elem.sheet; }; }, /** * Insert a new CSS rule into a given Stylesheet * * @param sheet {Object} the target Stylesheet object * @param selector {String} the selector * @param entry {String} style rule */ addRule : function(sheet, selector, entry){ if(qx.core.Environment.get("html.stylesheet.insertrule")){ sheet.insertRule(selector + "{" + entry + "}", sheet.cssRules.length); } else { sheet.addRule(selector, entry); }; }, /** * Remove a CSS rule from a stylesheet * * @param sheet {Object} the Stylesheet * @param selector {String} the Selector of the rule to remove */ removeRule : function(sheet, selector){ if(qx.core.Environment.get("html.stylesheet.deleterule")){ var rules = sheet.cssRules; var len = rules.length; for(var i = len - 1;i >= 0;--i){ if(rules[i].selectorText == selector){ sheet.deleteRule(i); }; }; } else { var rules = sheet.rules; var len = rules.length; for(var i = len - 1;i >= 0;--i){ if(rules[i].selectorText == selector){ sheet.removeRule(i); }; }; }; }, /** * Remove the given sheet from its owner. * @param sheet {Object} the stylesheet object */ removeSheet : function(sheet){ var owner = sheet.ownerNode ? sheet.ownerNode : sheet.owningElement; qx.dom.Element.removeChild(owner, owner.parentNode); }, /** * Remove all CSS rules from a stylesheet * * @param sheet {Object} the stylesheet object */ removeAllRules : function(sheet){ if(qx.core.Environment.get("html.stylesheet.deleterule")){ var rules = sheet.cssRules; var len = rules.length; for(var i = len - 1;i >= 0;i--){ sheet.deleteRule(i); }; } else { var rules = sheet.rules; var len = rules.length; for(var i = len - 1;i >= 0;i--){ sheet.removeRule(i); }; }; }, /** * Add an import of an external CSS file to a stylesheet * * @param sheet {Object} the stylesheet object * @param url {String} URL of the external stylesheet file */ addImport : function(sheet, url){ if(qx.core.Environment.get("html.stylesheet.addimport")){ sheet.addImport(url); } else { sheet.insertRule('@import "' + url + '";', sheet.cssRules.length); }; }, /** * Removes an import from a stylesheet * * @param sheet {Object} the stylesheet object * @param url {String} URL of the imported CSS file */ removeImport : function(sheet, url){ if(qx.core.Environment.get("html.stylesheet.removeimport")){ var imports = sheet.imports; var len = imports.length; for(var i = len - 1;i >= 0;i--){ if(imports[i].href == url || imports[i].href == qx.util.Uri.getAbsolute(url)){ sheet.removeImport(i); }; }; } else { var rules = sheet.cssRules; var len = rules.length; for(var i = len - 1;i >= 0;i--){ if(rules[i].href == url){ sheet.deleteRule(i); }; }; }; }, /** * Remove all imports from a stylesheet * * @param sheet {Object} the stylesheet object */ removeAllImports : function(sheet){ if(qx.core.Environment.get("html.stylesheet.removeimport")){ var imports = sheet.imports; var len = imports.length; for(var i = len - 1;i >= 0;i--){ sheet.removeImport(i); }; } else { var rules = sheet.cssRules; var len = rules.length; for(var i = len - 1;i >= 0;i--){ if(rules[i].type == rules[i].IMPORT_RULE){ sheet.deleteRule(i); }; }; }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (d_wagner) ************************************************************************ */ /** * Internal class which contains the checks used by {@link qx.core.Environment}. * All checks in here are marked as internal which means you should never use * them directly. * * This class contains checks related to Stylesheet objects. * * @internal */ qx.Bootstrap.define("qx.bom.client.Stylesheet", { statics : { /** * Returns a stylesheet to be used for feature checks * * @return {Stylesheet} Stylesheet element */ __getStylesheet : function(){ if(!qx.bom.client.Stylesheet.__stylesheet){ qx.bom.client.Stylesheet.__stylesheet = qx.bom.Stylesheet.createElement(); }; return qx.bom.client.Stylesheet.__stylesheet; }, /** * Check for IE's non-standard document.createStyleSheet function. * In IE9 (standards mode), the typeof check returns "function" so false is * returned. This is intended since IE9 supports the DOM-standard * createElement("style") which should be used instead. * * @internal * @return {Boolean} <code>true</code> if the browser supports * document.createStyleSheet */ getCreateStyleSheet : function(){ return typeof document.createStyleSheet === "object"; }, /** * Check for stylesheet.insertRule. Legacy IEs do not support this. * * @internal * @return {Boolean} <code>true</code> if insertRule is supported */ getInsertRule : function(){ return typeof qx.bom.client.Stylesheet.__getStylesheet().insertRule === "function"; }, /** * Check for stylesheet.deleteRule. Legacy IEs do not support this. * * @internal * @return {Boolean} <code>true</code> if deleteRule is supported */ getDeleteRule : function(){ return typeof qx.bom.client.Stylesheet.__getStylesheet().deleteRule === "function"; }, /** * Decides whether to use the legacy IE-only stylesheet.addImport or the * DOM-standard stylesheet.insertRule('@import [...]') * * @internal * @return {Boolean} <code>true</code> if stylesheet.addImport is supported */ getAddImport : function(){ return (typeof qx.bom.client.Stylesheet.__getStylesheet().addImport === "object"); }, /** * Decides whether to use the legacy IE-only stylesheet.removeImport or the * DOM-standard stylesheet.deleteRule('@import [...]') * * @internal * @return {Boolean} <code>true</code> if stylesheet.removeImport is supported */ getRemoveImport : function(){ return (typeof qx.bom.client.Stylesheet.__getStylesheet().removeImport === "object"); } }, defer : function(statics){ qx.core.Environment.add("html.stylesheet.createstylesheet", statics.getCreateStyleSheet); qx.core.Environment.add("html.stylesheet.insertrule", statics.getInsertRule); qx.core.Environment.add("html.stylesheet.deleterule", statics.getDeleteRule); qx.core.Environment.add("html.stylesheet.addimport", statics.getAddImport); qx.core.Environment.add("html.stylesheet.removeimport", statics.getRemoveImport); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ************************************************************************ */ /** * Manages children structures of an element. Easy and convenient APIs * to insert, remove and replace children. */ qx.Bootstrap.define("qx.dom.Element", { statics : { /** * {Map} A list of all attributes which needs to be part of the initial element to work correctly * * @internal */ __initialAttributes : { "onload" : true, "onpropertychange" : true, "oninput" : true, "onchange" : true, "name" : true, "type" : true, "checked" : true, "disabled" : true }, /** * Whether the given <code>child</code> is a child of <code>parent</code> * * @param parent {Element} parent element * @param child {Node} child node * @return {Boolean} true when the given <code>child</code> is a child of <code>parent</code> */ hasChild : function(parent, child){ return child.parentNode === parent; }, /** * Whether the given <code>element</code> has children. * * @param element {Element} element to test * @return {Boolean} true when the given <code>element</code> has at least one child node */ hasChildren : function(element){ return !!element.firstChild; }, /** * Whether the given <code>element</code> has any child elements. * * @param element {Element} element to test * @return {Boolean} true when the given <code>element</code> has at least one child element */ hasChildElements : function(element){ element = element.firstChild; while(element){ if(element.nodeType === 1){ return true; }; element = element.nextSibling; }; return false; }, /** * Returns the parent element of the given element. * * @param element {Element} Element to find the parent for * @return {Element} The parent element */ getParentElement : function(element){ return element.parentNode; }, /** * Checks if the <code>element</code> is in the DOM, but note that * the method is very expensive! * * @param element {Element} The DOM element to check. * @param win {Window} The window to check for. * @return {Boolean} <code>true</code> if the <code>element</code> is in * the DOM, <code>false</code> otherwise. */ isInDom : function(element, win){ if(!win){ win = window; }; var domElements = win.document.getElementsByTagName(element.nodeName); for(var i = 0,l = domElements.length;i < l;i++){ if(domElements[i] === element){ return true; }; }; return false; }, /* --------------------------------------------------------------------------- INSERTION --------------------------------------------------------------------------- */ /** * Inserts <code>node</code> at the given <code>index</code> * inside <code>parent</code>. * * @param node {Node} node to insert * @param parent {Element} parent element node * @param index {Integer} where to insert * @return {Boolean} returns true (successful) */ insertAt : function(node, parent, index){ var ref = parent.childNodes[index]; if(ref){ parent.insertBefore(node, ref); } else { parent.appendChild(node); }; return true; }, /** * Insert <code>node</code> into <code>parent</code> as first child. * Indexes of other children will be incremented by one. * * @param node {Node} Node to insert * @param parent {Element} parent element node * @return {Boolean} returns true (successful) */ insertBegin : function(node, parent){ if(parent.firstChild){ this.insertBefore(node, parent.firstChild); } else { parent.appendChild(node); }; return true; }, /** * Insert <code>node</code> into <code>parent</code> as last child. * * @param node {Node} Node to insert * @param parent {Element} parent element node * @return {Boolean} returns true (successful) */ insertEnd : function(node, parent){ parent.appendChild(node); return true; }, /** * Inserts <code>node</code> before <code>ref</code> in the same parent. * * @param node {Node} Node to insert * @param ref {Node} Node which will be used as reference for insertion * @return {Boolean} returns true (successful) */ insertBefore : function(node, ref){ ref.parentNode.insertBefore(node, ref); return true; }, /** * Inserts <code>node</code> after <code>ref</code> in the same parent. * * @param node {Node} Node to insert * @param ref {Node} Node which will be used as reference for insertion * @return {Boolean} returns true (successful) */ insertAfter : function(node, ref){ var parent = ref.parentNode; if(ref == parent.lastChild){ parent.appendChild(node); } else { return this.insertBefore(node, ref.nextSibling); }; return true; }, /* --------------------------------------------------------------------------- REMOVAL --------------------------------------------------------------------------- */ /** * Removes the given <code>node</code> from its parent element. * * @param node {Node} Node to remove * @return {Boolean} <code>true</code> when node was successfully removed, * otherwise <code>false</code> */ remove : function(node){ if(!node.parentNode){ return false; }; node.parentNode.removeChild(node); return true; }, /** * Removes the given <code>node</code> from the <code>parent</code>. * * @param node {Node} Node to remove * @param parent {Element} parent element which contains the <code>node</code> * @return {Boolean} <code>true</code> when node was successfully removed, * otherwise <code>false</code> */ removeChild : function(node, parent){ if(node.parentNode !== parent){ return false; }; parent.removeChild(node); return true; }, /** * Removes the node at the given <code>index</code> * from the <code>parent</code>. * * @param index {Integer} position of the node which should be removed * @param parent {Element} parent DOM element * @return {Boolean} <code>true</code> when node was successfully removed, * otherwise <code>false</code> */ removeChildAt : function(index, parent){ var child = parent.childNodes[index]; if(!child){ return false; }; parent.removeChild(child); return true; }, /* --------------------------------------------------------------------------- REPLACE --------------------------------------------------------------------------- */ /** * Replaces <code>oldNode</code> with <code>newNode</code> in the current * parent of <code>oldNode</code>. * * @param newNode {Node} DOM node to insert * @param oldNode {Node} DOM node to remove * @return {Boolean} <code>true</code> when node was successfully replaced */ replaceChild : function(newNode, oldNode){ if(!oldNode.parentNode){ return false; }; oldNode.parentNode.replaceChild(newNode, oldNode); return true; }, /** * Replaces the node at <code>index</code> with <code>newNode</code> in * the given parent. * * @param newNode {Node} DOM node to insert * @param index {Integer} position of old DOM node * @param parent {Element} parent DOM element * @return {Boolean} <code>true</code> when node was successfully replaced */ replaceAt : function(newNode, index, parent){ var oldNode = parent.childNodes[index]; if(!oldNode){ return false; }; parent.replaceChild(newNode, oldNode); return true; }, /** * Stores helper element for element creation in WebKit * * @internal */ __helperElement : { }, /** * Saves whether a helper element is needed for each window. * * @internal */ __allowMarkup : { }, /** * Detects if the DOM support a <code>document.createElement</code> call with a * <code>String</code> as markup like: * * <pre class="javascript"> * document.createElement("<INPUT TYPE='RADIO' NAME='RADIOTEST' VALUE='Second Choice'>"); * </pre> * * Element creation with markup is not standard compatible with Document Object Model (Core) Level 1, but * Internet Explorer supports it. With an exception that IE9 in IE9 standard mode is standard compatible and * doesn't support element creation with markup. * * @param win {Window?} Window to check for * @return {Boolean} <code>true</code> if the DOM supports it, <code>false</code> otherwise. */ _allowCreationWithMarkup : function(win){ if(!win){ win = window; }; // key is needed to allow using different windows var key = win.location.href; if(qx.dom.Element.__allowMarkup[key] == undefined){ try{ win.document.createElement("<INPUT TYPE='RADIO' NAME='RADIOTEST' VALUE='Second Choice'>"); qx.dom.Element.__allowMarkup[key] = true; } catch(e) { qx.dom.Element.__allowMarkup[key] = false; }; }; return qx.dom.Element.__allowMarkup[key]; }, /** * Creates and returns a DOM helper element. * * @param win {Window?} Window to create the element for * @return {Element} The created element node */ getHelperElement : function(win){ if(!win){ win = window; }; // key is needed to allow using different windows var key = win.location.href; if(!qx.dom.Element.__helperElement[key]){ var helper = qx.dom.Element.__helperElement[key] = win.document.createElement("div"); // innerHTML will only parsed correctly if element is appended to document if(qx.core.Environment.get("engine.name") == "webkit"){ helper.style.display = "none"; win.document.body.appendChild(helper); }; }; return qx.dom.Element.__helperElement[key]; }, /** * Creates a DOM element. * * Attributes may be given directly with this call. This is critical * for some attributes e.g. name, type, ... in many clients. * * Depending on the kind of attributes passed, <code>innerHTML</code> may be * used internally to assemble the element. Please make sure you understand * the security implications. See {@link qx.bom.Html#clean}. * * @param name {String} Tag name of the element * @param attributes {Map?} Map of attributes to apply * @param win {Window?} Window to create the element for * @return {Element} The created element node */ create : function(name, attributes, win){ if(!win){ win = window; }; if(!name){ throw new Error("The tag name is missing!"); }; var initial = this.__initialAttributes; var attributesHtml = ""; for(var key in attributes){ if(initial[key]){ attributesHtml += key + "='" + attributes[key] + "' "; }; }; var element; // If specific attributes are defined we need to process // the element creation in a more complex way. if(attributesHtml != ""){ if(qx.dom.Element._allowCreationWithMarkup(win)){ element = win.document.createElement("<" + name + " " + attributesHtml + ">"); } else { var helper = qx.dom.Element.getHelperElement(win); helper.innerHTML = "<" + name + " " + attributesHtml + "></" + name + ">"; element = helper.firstChild; }; } else { element = win.document.createElement(name); }; for(var key in attributes){ if(!initial[key]){ qx.bom.element.Attribute.set(element, key, attributes[key]); }; }; return element; }, /** * Removes all content from the given element * * @param element {Element} element to clean * @return {String} empty string (new HTML content) */ empty : function(element){ return element.innerHTML = ""; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2010 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Alexander Steitz (aback) ====================================================================== This class contains code based on the following work: * Prototype JS http://www.prototypejs.org/ Version 1.5 Copyright: (c) 2006-2007, Prototype Core Team License: MIT: http://www.opensource.org/licenses/mit-license.php Authors: * Prototype Core Team ---------------------------------------------------------------------- Copyright (c) 2005-2008 Sam Stephenson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ************************************************************************ */ /** * Attribute/Property handling for DOM HTML elements. * * Also includes support for HTML properties like <code>checked</code> * or <code>value</code>. This feature set is supported cross-browser * through one common interface and is independent of the differences between * the multiple implementations. * * Supports applying text and HTML content using the attribute names * <code>text</code> and <code>html</code>. */ qx.Bootstrap.define("qx.bom.element.Attribute", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** Internal map of attribute conversions */ __hints : { // Name translation table (camelcase is important for some attributes) names : { "class" : "className", "for" : "htmlFor", html : "innerHTML", text : qx.core.Environment.get("html.element.textcontent") ? "textContent" : "innerText", colspan : "colSpan", rowspan : "rowSpan", valign : "vAlign", datetime : "dateTime", accesskey : "accessKey", tabindex : "tabIndex", maxlength : "maxLength", readonly : "readOnly", longdesc : "longDesc", cellpadding : "cellPadding", cellspacing : "cellSpacing", frameborder : "frameBorder", usemap : "useMap" }, // Attributes which are only applyable on a DOM element (not using compile()) runtime : { "html" : 1, "text" : 1 }, // Attributes which are (forced) boolean bools : { compact : 1, nowrap : 1, ismap : 1, declare : 1, noshade : 1, checked : 1, disabled : 1, readOnly : 1, multiple : 1, selected : 1, noresize : 1, defer : 1, allowTransparency : 1 }, // Interpreted as property (element.property) property : { // Used by qx.html.Element $$html : 1, // Used by qx.ui.core.Widget $$widget : 1, // Native properties disabled : 1, checked : 1, readOnly : 1, multiple : 1, selected : 1, value : 1, maxLength : 1, className : 1, innerHTML : 1, innerText : 1, textContent : 1, htmlFor : 1, tabIndex : 1 }, qxProperties : { $$widget : 1, $$html : 1 }, // Default values when "null" is given to a property propertyDefault : { disabled : false, checked : false, readOnly : false, multiple : false, selected : false, value : "", className : "", innerHTML : "", innerText : "", textContent : "", htmlFor : "", tabIndex : 0, maxLength : qx.core.Environment.select("engine.name", { "mshtml" : 2147483647, "webkit" : 524288, "default" : -1 }) }, // Properties which can be removed to reset them removeableProperties : { disabled : 1, multiple : 1, maxLength : 1 }, // Use getAttribute(name, 2) for these to query for the real value, not // the interpreted one. original : { href : 1, src : 1, type : 1 } }, /** * Compiles an incoming attribute map to a string which * could be used when building HTML blocks using innerHTML. * * This method silently ignores runtime attributes like * <code>html</code> or <code>text</code>. * * @param map {Map} Map of attributes. The key is the name of the attribute. * @return {String} Returns a compiled string ready for usage. */ compile : function(map){ var html = []; var runtime = this.__hints.runtime; for(var key in map){ if(!runtime[key]){ html.push(key, "='", map[key], "'"); }; }; return html.join(""); }, /** * Returns the value of the given HTML attribute * * @param element {Element} The DOM element to query * @param name {String} Name of the attribute * @return {var} The value of the attribute */ get : function(element, name){ var hints = this.__hints; var value; // normalize name name = hints.names[name] || name; // respect original values // http://msdn2.microsoft.com/en-us/library/ms536429.aspx if(qx.core.Environment.get("engine.name") == "mshtml" && parseInt(qx.core.Environment.get("browser.documentmode"), 10) < 8 && hints.original[name]){ value = element.getAttribute(name, 2); } else if(hints.property[name]){ value = element[name]; if(typeof hints.propertyDefault[name] !== "undefined" && value == hints.propertyDefault[name]){ // only return null for all non-boolean properties if(typeof hints.bools[name] === "undefined"){ return null; } else { return value; }; }; } else { // fallback to attribute value = element.getAttribute(name); }; if(hints.bools[name]){ return !!value; }; return value; }, /** * Sets an HTML attribute on the given DOM element * * @param element {Element} The DOM element to modify * @param name {String} Name of the attribute * @param value {var} New value of the attribute */ set : function(element, name, value){ if(typeof value === "undefined"){ return; }; var hints = this.__hints; // normalize name name = hints.names[name] || name; // respect booleans if(hints.bools[name]){ value = !!value; }; // apply attribute // only properties which can be applied by the browser or qxProperties // otherwise use the attribute methods if(hints.property[name] && (!(element[name] === undefined) || hints.qxProperties[name])){ // resetting the attribute/property if(value == null){ // for properties which need to be removed for a correct reset if(hints.removeableProperties[name]){ element.removeAttribute(name); return; } else if(typeof hints.propertyDefault[name] !== "undefined"){ value = hints.propertyDefault[name]; }; }; element[name] = value; } else { if(value === true){ element.setAttribute(name, name); } else if(value === false || value === null){ element.removeAttribute(name); } else { element.setAttribute(name, value); }; }; }, /** * Resets an HTML attribute on the given DOM element * * @param element {Element} The DOM element to modify * @param name {String} Name of the attribute */ reset : function(element, name){ this.set(element, name, null); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * Utility for checking the type of a variable. * It adds a <code>type</code> key static to q and offers the given method. * * <pre class="javascript"> * q.type.get("abc"); // return "String" e.g. * </pre> */ qx.Bootstrap.define("qx.module.util.Type", { statics : { /** * Get the internal class of the value. The following classes are possible: * <code>"String"</code>, * <code>"Array"</code>, * <code>"Object"</code>, * <code>"RegExp"</code>, * <code>"Number"</code>, * <code>"Boolean"</code>, * <code>"Date"</code>, * <code>"Function"</code>, * <code>"Error"</code> * </pre> * @attachStatic {qxWeb, type.get} * @signature function(value) * @param value {var} Value to get the class for. * @return {String} The internal class of the value. */ get : qx.Bootstrap.getClass }, defer : function(statics){ qxWeb.$attachStatic({ type : { get : statics.get } }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ====================================================================== This class contains code based on the following work: * es5-shim Code: https://github.com/kriskowal/es5-shim/ Copyright: (c) 2009, 2010 Kristopher Michael Kowal License: https://github.com/kriskowal/es5-shim/blob/master/LICENSE ---------------------------------------------------------------------- Copyright 2009, 2010 Kristopher Michael Kowal. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---------------------------------------------------------------------- Version: Snapshot taken on 2012-07-25,: commit 9f539abd9aa9950e1d907077a4be7f5133a00e52 ************************************************************************ */ /** * This class takes care of the normalization of the native 'Function' object. * Therefore it checks the availability of the following methods and appends * it, if not available. This means you can use the methods during * development in every browser. For usage samples, check out the attached links. * * *bind*: * <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind">MDN documentation</a> | * <a href="http://es5.github.com/#x15.3.4.5">Annotated ES5 Spec</a> */ qx.Bootstrap.define("qx.lang.normalize.Function", { defer : function(){ // bind if(!qx.core.Environment.get("ecmascript.function.bind")){ var slice = Array.prototype.slice; Function.prototype.bind = function(that){ // .length is 1 // 1. Let Target be the this value. var target = this; // 2. If IsCallable(Target) is false, throw a TypeError exception. if(typeof target != "function"){ throw new TypeError("Function.prototype.bind called on incompatible " + target); }; // 3. Let A be a new (possibly empty) internal list of all of the // argument values provided after thisArg (arg1, arg2 etc), in order. // XXX slicedArgs will stand in for "A" if used var args = slice.call(arguments, 1); // for normal call // 4. Let F be a new native ECMAScript object. // 11. Set the [[Prototype]] internal property of F to the standard // built-in Function prototype object as specified in 15.3.3.1. // 12. Set the [[Call]] internal property of F as described in // 15.3.4.5.1. // 13. Set the [[Construct]] internal property of F as described in // 15.3.4.5.2. // 14. Set the [[HasInstance]] internal property of F as described in // 15.3.4.5.3. var bound = function(){ if(this instanceof bound){ // 15.3.4.5.2 [[Construct]] // When the [[Construct]] internal method of a function object, // F that was created using the bind function is called with a // list of arguments ExtraArgs, the following steps are taken: // 1. Let target be the value of F's [[TargetFunction]] // internal property. // 2. If target has no [[Construct]] internal method, a // TypeError exception is thrown. // 3. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Construct]] internal // method of target providing args as the arguments. var F = function(){ }; F.prototype = target.prototype; var self = new F; var result = target.apply(self, args.concat(slice.call(arguments))); if(Object(result) === result){ return result; }; return self; } else { // 15.3.4.5.1 [[Call]] // When the [[Call]] internal method of a function object, F, // which was created using the bind function is called with a // this value and a list of arguments ExtraArgs, the following // steps are taken: // 1. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 2. Let boundThis be the value of F's [[BoundThis]] internal // property. // 3. Let target be the value of F's [[TargetFunction]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Call]] internal method // of target providing boundThis as the this value and // providing args as the arguments. // equiv: target.call(this, ...boundArgs, ...args) return target.apply(that, args.concat(slice.call(arguments))); }; }; // XXX bound.length is never writable, so don't even try // // 15. If the [[Class]] internal property of Target is "Function", then // a. Let L be the length property of Target minus the length of A. // b. Set the length own property of F to either 0 or L, whichever is // larger. // 16. Else set the length own property of F to 0. // 17. Set the attributes of the length own property of F to the values // specified in 15.3.5.1. // TODO // 18. Set the [[Extensible]] internal property of F to true. // TODO // 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3). // 20. Call the [[DefineOwnProperty]] internal method of F with // arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]: // thrower, [[Enumerable]]: false, [[Configurable]]: false}, and // false. // 21. Call the [[DefineOwnProperty]] internal method of F with // arguments "arguments", PropertyDescriptor {[[Get]]: thrower, // [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false}, // and false. // NOTE Function objects created using Function.prototype.bind do not // have a prototype property or the [[Code]], [[FormalParameters]], and // [[Scope]] internal properties. // XXX can't delete prototype in pure-js. // 22. Return F. return bound; }; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This class takes care of the normalization of the native 'Error' object. * It contains a simple bugfix for toString which might not print out the proper * error message. * * *toString*: * <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/toString">MDN documentation</a> | * <a href="http://es5.github.com/#x15.11.4.4">Annotated ES5 Spec</a> */ qx.Bootstrap.define("qx.lang.normalize.Error", { defer : function(){ // toString if(!qx.core.Environment.get("ecmascript.error.toString")){ Error.prototype.toString = function(){ var name = this.name || "Error"; var message = this.message || ""; if(name === "" && message === ""){ return "Error"; }; if(name === ""){ return message; }; if(message === ""){ return name; }; return name + ": " + message; }; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.lang.normalize.Function) #require(qx.lang.normalize.String) #require(qx.lang.normalize.Date) #require(qx.lang.normalize.Array) #require(qx.lang.normalize.Error) #require(qx.lang.normalize.Object) ************************************************************************ */ /** * Adds JavaScript features that may not be supported by all clients. */ qx.Bootstrap.define("qx.module.Polyfill", { }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2011-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Polyfill) ************************************************************************ */ /** * Support for native and custom events. */ qx.Bootstrap.define("qx.module.Event", { statics : { /** * Event normalization registry * * @type {Map} * @internal */ __normalizations : { }, /** * Registry of event hooks * @internal */ __hooks : { on : { }, off : { } }, /** * Registers a listener for the given event type on each item in the * collection. This can be either native or custom events. * * @attach {qxWeb} * @param type {String} Type of the event to listen for * @param listener {Function} Listener callback * @param context {Object?} Context the callback function will be executed in. * Default: The element on which the listener was registered * @return {qxWeb} The collection for chaining */ on : function(type, listener, context){ for(var i = 0;i < this.length;i++){ var el = this[i]; var ctx = context || qxWeb(el); // call hooks var hooks = qx.module.Event.__hooks.on; // generic var typeHooks = hooks["*"] || []; // type specific if(hooks[type]){ typeHooks = typeHooks.concat(hooks[type]); }; for(var j = 0,m = typeHooks.length;j < m;j++){ typeHooks[j](el, type, listener, context); }; var bound = function(event){ // apply normalizations var registry = qx.module.Event.__normalizations; // generic var normalizations = registry["*"] || []; // type specific if(registry[type]){ normalizations = normalizations.concat(registry[type]); }; for(var x = 0,y = normalizations.length;x < y;x++){ event = normalizations[x](event, el, type); }; // call original listener with normalized event listener.apply(this, [event]); }.bind(ctx); bound.original = listener; // add native listener if(qx.bom.Event.supportsEvent(el, type)){ qx.bom.Event.addNativeListener(el, type, bound); }; // create an emitter if necessary if(!el.__emitter){ el.__emitter = new qx.event.Emitter(); }; var id = el.__emitter.on(type, bound, ctx); if(!el.__listener){ el.__listener = { }; }; if(!el.__listener[type]){ el.__listener[type] = { }; }; el.__listener[type][id] = bound; if(!context){ // store a reference to the dynamically created context so we know // what to check for when removing the listener if(!el.__ctx){ el.__ctx = { }; }; el.__ctx[id] = ctx; }; }; return this; }, /** * Unregisters event listeners for the given type from each element in the * collection. * * @attach {qxWeb} * @param type {String} Type of the event * @param listener {Function} Listener callback * @param context {Object?} Listener callback context * @return {qxWeb} The collection for chaining */ off : function(type, listener, context){ for(var j = 0;j < this.length;j++){ var el = this[j]; // continue if no listener are available if(!el.__listener){ continue; }; for(var id in el.__listener[type]){ var storedListener = el.__listener[type][id]; if(storedListener == listener || storedListener.original == listener){ // get the stored context var hasStoredContext = typeof el.__ctx !== "undefined" && el.__ctx[id]; if(!context && hasStoredContext){ var storedContext = el.__ctx[id]; }; // remove the listener from the emitter el.__emitter.off(type, storedListener, storedContext || context); // check if it's a bound listener which means it was a native event if(storedListener.original == listener){ // remove the native listener qx.bom.Event.removeNativeListener(el, type, storedListener); }; delete el.__listener[type][id]; if(hasStoredContext){ delete el.__ctx[id]; }; }; }; // call hooks var hooks = qx.module.Event.__hooks.off; // generic var typeHooks = hooks["*"] || []; // type specific if(hooks[type]){ typeHooks = typeHooks.concat(hooks[type]); }; for(var i = 0,m = typeHooks.length;i < m;i++){ typeHooks[i](el, type, listener, context); }; }; return this; }, /** * Fire an event of the given type. * * @attach {qxWeb} * @param type {String} Event type * @param data {var?} Optional data that will be passed to the listener * callback function. * @return {qxWeb} The collection for chaining */ emit : function(type, data){ for(var j = 0;j < this.length;j++){ var el = this[j]; if(el.__emitter){ el.__emitter.emit(type, data); }; }; return this; }, /** * Attaches a listener for the given event that will be executed only once. * * @attach {qxWeb} * @param type {String} Type of the event to listen for * @param listener {Function} Listener callback * @param context {Object?} Context the callback function will be executed in. * Default: The element on which the listener was registered * @return {qxWeb} The collection for chaining */ once : function(type, listener, context){ var self = this; var wrappedListener = function(data){ self.off(type, wrappedListener, context); listener.call(this, data); }; this.on(type, wrappedListener, context); return this; }, /** * Checks if one or more listeners for the given event type are attached to * the first element in the collection * * @attach {qxWeb} * @param type {String} Event type, e.g. <code>mousedown</code> * @return {Boolean} <code>true</code> if one or more listeners are attached */ hasListener : function(type){ if(!this[0] || !this[0].__emitter || !this[0].__emitter.getListeners()[type]){ return false; }; return this[0].__emitter.getListeners()[type].length > 0; }, /** * Copies any event listeners that are attached to the elements in the * collection to the provided target element * * @internal * @param target {Element} Element to attach the copied listeners to */ copyEventsTo : function(target){ var source = this.concat(); // get all children of source and target for(var i = source.length - 1;i >= 0;i--){ var descendants = source[i].getElementsByTagName("*"); for(var j = 0;j < descendants.length;j++){ source.push(descendants[j]); }; }; for(var i = target.length - 1;i >= 0;i--){ var descendants = target[i].getElementsByTagName("*"); for(var j = 0;j < descendants.length;j++){ target.push(descendants[j]); }; }; // make sure no emitter object has been copied target.forEach(function(el){ el.__emitter = null; }); for(var i = 0;i < source.length;i++){ var el = source[i]; if(!el.__emitter){ continue; }; var storage = el.__emitter.getListeners(); for(var name in storage){ for(var j = storage[name].length - 1;j >= 0;j--){ var listener = storage[name][j].listener; if(listener.original){ listener = listener.original; }; qxWeb(target[i]).on(name, listener, storage[name][j].ctx); }; }; }; }, __isReady : false, /** * Executes the given function once the document is ready. * * @attachStatic {qxWeb} * @param callback {Function} callback function */ ready : function(callback){ // DOM is already ready if(document.readyState === "complete"){ window.setTimeout(callback, 1); return; }; // listen for the load event so the callback is executed no matter what var onWindowLoad = function(){ qx.module.Event.__isReady = true; callback(); }; qxWeb(window).on("load", onWindowLoad); var wrappedCallback = function(){ qxWeb(window).off("load", onWindowLoad); callback(); }; // Listen for DOMContentLoaded event if available (no way to reliably detect // support) if(qxWeb.env.get("engine.name") !== "mshtml" || qxWeb.env.get("browser.documentmode") > 8){ qx.bom.Event.addNativeListener(document, "DOMContentLoaded", wrappedCallback); } else { // Continually check to see if the document is ready var timer = function(){ // onWindowLoad already executed if(qx.module.Event.__isReady){ return; }; try{ // If DOMContentLoaded is unavailable, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); if(document.body){ wrappedCallback(); }; } catch(error) { window.setTimeout(timer, 100); }; }; timer(); }; }, /** * Registers a normalization function for the given event types. Listener * callbacks for these types will be called with the return value of the * normalization function instead of the regular event object. * * The normalizer will be called with two arguments: The original event * object and the element on which the event was triggered * * @attachStatic {qxWeb, $registerEventNormalization} * @param types {String[]} List of event types to be normalized. Use an * asterisk (<code>*</code>) to normalize all event types * @param normalizer {Function} Normalizer function */ $registerNormalization : function(types, normalizer){ if(!qx.lang.Type.isArray(types)){ types = [types]; }; var registry = qx.module.Event.__normalizations; for(var i = 0,l = types.length;i < l;i++){ var type = types[i]; if(qx.lang.Type.isFunction(normalizer)){ if(!registry[type]){ registry[type] = []; }; registry[type].push(normalizer); }; }; }, /** * Unregisters a normalization function from the given event types. * * @attachStatic {qxWeb, $unregisterEventNormalization} * @param types {String[]} List of event types * @param normalizer {Function} Normalizer function */ $unregisterNormalization : function(types, normalizer){ if(!qx.lang.Type.isArray(types)){ types = [types]; }; var registry = qx.module.Event.__normalizations; for(var i = 0,l = types.length;i < l;i++){ var type = types[i]; if(registry[type]){ qx.lang.Array.remove(registry[type], normalizer); }; }; }, /** * Returns all registered event normalizers * * @attachStatic {qxWeb, $getEventNormalizationRegistry} * @return {Map} Map of event types/normalizer functions */ $getRegistry : function(){ return qx.module.Event.__normalizations; }, /** * Registers an event hook for the given event types. * * @attachStatic {qxWeb, $registerEventHook} * @param types {String[]} List of event types * @param registerHook {Function} Hook function to be called on event registration * @param unregisterHook {Function?} Hook function to be called on event deregistration * @internal */ $registerEventHook : function(types, registerHook, unregisterHook){ if(!qx.lang.Type.isArray(types)){ types = [types]; }; var onHooks = qx.module.Event.__hooks.on; for(var i = 0,l = types.length;i < l;i++){ var type = types[i]; if(qx.lang.Type.isFunction(registerHook)){ if(!onHooks[type]){ onHooks[type] = []; }; onHooks[type].push(registerHook); }; }; if(!unregisterHook){ return; }; var offHooks = qx.module.Event.__hooks.off; for(var i = 0,l = types.length;i < l;i++){ var type = types[i]; if(qx.lang.Type.isFunction(unregisterHook)){ if(!offHooks[type]){ offHooks[type] = []; }; offHooks[type].push(unregisterHook); }; }; }, /** * Unregisters a hook from the given event types. * * @attachStatic {qxWeb, $unregisterEventHooks} * @param types {String[]} List of event types * @param registerHook {Function} Hook function to be called on event registration * @param unregisterHook {Function?} Hook function to be called on event deregistration * @internal */ $unregisterEventHook : function(types, registerHook, unregisterHook){ if(!qx.lang.Type.isArray(types)){ types = [types]; }; var onHooks = qx.module.Event.__hooks.on; for(var i = 0,l = types.length;i < l;i++){ var type = types[i]; if(onHooks[type]){ qx.lang.Array.remove(onHooks[type], registerHook); }; }; if(!unregisterHook){ return; }; var offHooks = qx.module.Event.__hooks.off; for(var i = 0,l = types.length;i < l;i++){ var type = types[i]; if(offHooks[type]){ qx.lang.Array.remove(offHooks[type], unregisterHook); }; }; }, /** * Returns all registered event hooks * * @attachStatic {qxWeb, $getEventHookRegistry} * @return {Map} Map of event types/registration hook functions * @internal */ $getHookRegistry : function(){ return qx.module.Event.__hooks; } }, defer : function(statics){ qxWeb.$attach({ "on" : statics.on, "off" : statics.off, "once" : statics.once, "emit" : statics.emit, "hasListener" : statics.hasListener, "copyEventsTo" : statics.copyEventsTo }); qxWeb.$attachStatic({ "ready" : statics.ready, "$registerEventNormalization" : statics.$registerNormalization, "$unregisterEventNormalization" : statics.$unregisterNormalization, "$getEventNormalizationRegistry" : statics.$getRegistry, "$registerEventHook" : statics.$registerEventHook, "$unregisterEventHook" : statics.$unregisterEventHook, "$getEventHookRegistry" : statics.$getHookRegistry }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2007-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) * Sebastian Werner (wpbasti) * Alexander Steitz (aback) * Christian Hagendorn (chris_schmidt) ====================================================================== This class contains code based on the following work: * Juriy Zaytsev http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ Copyright (c) 2009 Juriy Zaytsev Licence: BSD: http://github.com/kangax/iseventsupported/blob/master/LICENSE ---------------------------------------------------------------------- http://github.com/kangax/iseventsupported/blob/master/LICENSE Copyright (c) 2009 Juriy Zaytsev Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ************************************************************************ */ /** * Wrapper around native event management capabilities of the browser. * This class should not be used directly normally. It's better * to use {@link qx.event.Registration} instead. */ qx.Bootstrap.define("qx.bom.Event", { statics : { /** * Use the low level browser functionality to attach event listeners * to DOM nodes. * * Use this with caution. This is only thought for event handlers and * qualified developers. These are not mem-leak protected! * * @param target {Object} Any valid native event target * @param type {String} Name of the event * @param listener {Function} The pointer to the function to assign * @param useCapture {Boolean ? false} A Boolean value that specifies the event phase to add * the event handler for the capturing phase or the bubbling phase. */ addNativeListener : function(target, type, listener, useCapture){ if(target.addEventListener){ target.addEventListener(type, listener, !!useCapture); } else if(target.attachEvent){ target.attachEvent("on" + type, listener); } else if(typeof target["on" + type] != "undefined"){ target["on" + type] = listener; } else { { }; };; }, /** * Use the low level browser functionality to remove event listeners * from DOM nodes. * * @param target {Object} Any valid native event target * @param type {String} Name of the event * @param listener {Function} The pointer to the function to assign * @param useCapture {Boolean ? false} A Boolean value that specifies the event phase to remove * the event handler for the capturing phase or the bubbling phase. */ removeNativeListener : function(target, type, listener, useCapture){ if(target.removeEventListener){ target.removeEventListener(type, listener, !!useCapture); } else if(target.detachEvent){ try{ target.detachEvent("on" + type, listener); } catch(e) { // IE7 sometimes dispatches "unload" events on protected windows // Ignore the "permission denied" errors. if(e.number !== -2146828218){ throw e; }; }; } else if(typeof target["on" + type] != "undefined"){ target["on" + type] = null; } else { { }; };; }, /** * Returns the target of the event. * * @param e {Event} Native event object * @return {Object} Any valid native event target */ getTarget : function(e){ return e.target || e.srcElement; }, /** * Computes the related target from the native DOM event * * @param e {Event} Native DOM event object * @return {Element} The related target */ getRelatedTarget : function(e){ if(e.relatedTarget !== undefined){ // In Firefox the related target of mouse events is sometimes an // anonymous div inside of a text area, which raises an exception if // the nodeType is read. This is why the try/catch block is needed. if((qx.core.Environment.get("engine.name") == "gecko")){ try{ e.relatedTarget && e.relatedTarget.nodeType; } catch(ex) { return null; }; }; return e.relatedTarget; } else if(e.fromElement !== undefined && e.type === "mouseover"){ return e.fromElement; } else if(e.toElement !== undefined){ return e.toElement; } else { return null; };; }, /** * Prevent the native default of the event to be processed. * * This is useful to stop native keybindings, native selection * and other native functionality behind events. * * @param e {Event} Native event object */ preventDefault : function(e){ if(e.preventDefault){ e.preventDefault(); } else { try{ // this allows us to prevent some key press events in IE. // See bug #1049 e.keyCode = 0; } catch(ex) { }; e.returnValue = false; }; }, /** * Stops the propagation of the given event to the parent element. * * Only useful for events which bubble e.g. mousedown. * * @param e {Event} Native event object */ stopPropagation : function(e){ if(e.stopPropagation){ e.stopPropagation(); } else { e.cancelBubble = true; }; }, /** * Fires a synthetic native event on the given element. * * @param target {Element} DOM element to fire event on * @param type {String} Name of the event to fire * @return {Boolean} A value that indicates whether any of the event handlers called {@link #preventDefault}. * <code>true</code> The default action is permitted, <code>false</code> the caller should prevent the default action. */ fire : function(target, type){ // dispatch for standard first if(document.createEvent){ var evt = document.createEvent("HTMLEvents"); evt.initEvent(type, true, true); return !target.dispatchEvent(evt); } else { var evt = document.createEventObject(); return target.fireEvent("on" + type, evt); }; }, /** * Whether the given target supports the given event type. * * Useful for testing for support of new features like * touch events, gesture events, orientation change, on/offline, etc. * * @signature function(target, type) * @param target {var} Any valid target e.g. window, dom node, etc. * @param type {String} Type of the event e.g. click, mousedown * @return {Boolean} Whether the given event is supported */ supportsEvent : function(target, type){ var eventName = "on" + type; var supportsEvent = (eventName in target); if(!supportsEvent){ supportsEvent = typeof target[eventName] == "function"; if(!supportsEvent && target.setAttribute){ target.setAttribute(eventName, "return;"); supportsEvent = typeof target[eventName] == "function"; target.removeAttribute(eventName); }; }; return supportsEvent; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * EXPERIMENTAL - NOT READY FOR PRODUCTION * * Basic implementation for an event emitter. This supplies a basic and * minimalistic event mechanism. */ qx.Bootstrap.define("qx.event.Emitter", { extend : Object, statics : { /** Static storage for all event listener */ __storage : [] }, members : { __listener : null, __any : null, /** * Attach a listener to the event emitter. The given <code>name</code> * will define the type of event. Handing in a <code>'*'</code> will * listen to all events emitted by the event emitter. * * @param name {String} The name of the event to listen to. * @param listener {Function} The function execute on {@link #emit}. * @param ctx {var?Window} The context of the listener. * @return {Integer} An unique <code>id</code> for the attached listener. */ on : function(name, listener, ctx){ var id = qx.event.Emitter.__storage.length; this.__getStorage(name).push({ listener : listener, ctx : ctx, id : id }); qx.event.Emitter.__storage.push({ name : name, listener : listener, ctx : ctx }); return id; }, /** * Attach a listener to the event emitter which will be executed only once. * The given <code>name</code> will define the type of event. Handing in a * <code>'*'</code> will listen to all events emitted by the event emitter. * * @param name {String} The name of the event to listen to. * @param listener {Function} The function execute on {@link #emit}. * @param ctx {var?Window} The context of the listener. * @return {Integer} An unique <code>id</code> for the attached listener. */ once : function(name, listener, ctx){ var id = qx.event.Emitter.__storage.length; this.__getStorage(name).push({ listener : listener, ctx : ctx, once : true, id : id }); qx.event.Emitter.__storage.push({ name : name, listener : listener, ctx : ctx }); return id; }, /** * Remove a listener from the event emitter. The given <code>name</code> * will define the type of event. * * @param name {String} The name of the event to listen to. * @param listener {Function} The function execute on {@link #emit}. * @param ctx {var?Window} The context of the listener. * @return {Integer|null} The listener's id if it was removed or * <code>null</code> if it wasn't found */ off : function(name, listener, ctx){ var storage = this.__getStorage(name); for(var i = storage.length - 1;i >= 0;i--){ var entry = storage[i]; if(entry.listener == listener && entry.ctx == ctx){ storage.splice(i, 1); qx.event.Emitter.__storage[entry.id] = null; return entry.id; }; }; return null; }, /** * Removes the listener identified by the given <code>id</code>. The id * will be return on attaching the listener and can be stored for removing. * * @param id {Integer} The id of the listener. */ offById : function(id){ var entry = qx.event.Emitter.__storage[id]; this.off(entry.name, entry.listener, entry.ctx); }, /** * Alternative for {@link #on}. * @param name {String} The name of the event to listen to. * @param listener {Function} The function execute on {@link #emit}. * @param ctx {var?Window} The context of the listener. * @return {Integer} An unique <code>id</code> for the attached listener. */ addListener : function(name, listener, ctx){ return this.on(name, listener, ctx); }, /** * Alternative for {@link #once}. * @param name {String} The name of the event to listen to. * @param listener {Function} The function execute on {@link #emit}. * @param ctx {var?Window} The context of the listener. * @return {Integer} An unique <code>id</code> for the attached listener. */ addListenerOnce : function(name, listener, ctx){ return this.once(name, listener, ctx); }, /** * Alternative for {@link #off}. * @param name {String} The name of the event to listen to. * @param listener {Function} The function execute on {@link #emit}. * @param ctx {var?Window} The context of the listener. */ removeListener : function(name, listener, ctx){ this.off(name, listener, ctx); }, /** * Alternative for {@link #offById}. * @param id {Integer} The id of the listener. */ removeListenerById : function(id){ this.offById(id); }, /** * Emits an event with the given name. The data will be passed * to the listener. * @param name {String} The name of the event to emit. * @param data {var?undefined} The data which should be passed to the listener. */ emit : function(name, data){ var storage = this.__getStorage(name); for(var i = 0;i < storage.length;i++){ var entry = storage[i]; entry.listener.call(entry.ctx, data); if(entry.once){ storage.splice(i, 1); i--; }; }; // call on any storage = this.__getStorage("*"); for(var i = storage.length - 1;i >= 0;i--){ var entry = storage[i]; entry.listener.call(entry.ctx, data); }; }, /** * Returns the internal attached listener. * @internal * @return {Map} A map which has the event name as key. The values are * arrays containing a map with 'listener' and 'ctx'. */ getListeners : function(){ return this.__listener; }, /** * Internal helper which will return the storage for the given name. * @param name {String} The name of the event. * @return {Array} An array which is the storage for the listener and * the given event name. */ __getStorage : function(name){ if(this.__listener == null){ this.__listener = { }; }; if(this.__listener[name] == null){ this.__listener[name] = []; }; return this.__listener[name]; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Event) ************************************************************************ */ /** * Normalization for touch events */ qx.Bootstrap.define("qx.module.event.Touch", { statics : { /** * List of event types to be normalized * @type {Array} */ TYPES : ["tap", "swipe"], /** * Manipulates the native event object, adding methods if they're not * already present * * @param event {Event} Native event object * @param element {Element} DOM element the listener was attached to * @param type {String} Event type * @return {Event} Normalized event object * @internal */ normalize : function(event, element, type){ if(!event){ return event; }; event._type = type; return event; } }, defer : function(statics){ qxWeb.$registerEventNormalization(statics.TYPES, statics.normalize); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * The class is responsible for device detection. This is specially usefull * if you are on a mobile device. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.Device", { statics : { /** Maps user agent names to device IDs */ __ids : { "iPod" : "ipod", "iPad" : "ipad", "iPhone" : "iPhone", "PSP" : "psp", "PLAYSTATION 3" : "ps3", "Nintendo Wii" : "wii", "Nintendo DS" : "ds", "XBOX" : "xbox", "Xbox" : "xbox" }, /** * Returns the name of the current device if detectable. It falls back to * <code>pc</code> if the detection for other devices fails. * * @internal * @return {String} The string of the device found. */ getName : function(){ var str = []; for(var key in this.__ids){ str.push(key); }; var reg = new RegExp("(" + str.join("|").replace(/\./g, "\.") + ")", "g"); var match = reg.exec(navigator.userAgent); if(match && match[1]){ return qx.bom.client.Device.__ids[match[1]]; }; return "pc"; }, /** * Determines on what type of device the application is running. * Valid values are: "mobile", "tablet" or "desktop". * @return {String} The device type name of determined device. */ getType : function(){ return qx.bom.client.Device.detectDeviceType(navigator.userAgent); }, /** * Detects the device type, based on given userAgentString. * * @param userAgentString {String} userAgent parameter, needed for decision. * @return {String} The device type name of determined device: "mobile","desktop","tablet" */ detectDeviceType : function(userAgentString){ if(qx.bom.client.Device.detectTabletDevice(userAgentString)){ return "tablet"; } else if(qx.bom.client.Device.detectMobileDevice(userAgentString)){ return "mobile"; }; return "desktop"; }, /** * Detects if a device is a mobile phone. (Tablets excluded.) * @param userAgentString {String} userAgent parameter, needed for decision. * @return {Boolean} Flag which indicates whether it is a mobile device. */ detectMobileDevice : function(userAgentString){ return /android.+mobile|ip(hone|od)|bada\/|blackberry|maemo|opera m(ob|in)i|fennec|NetFront|phone|psp|symbian|windows (ce|phone)|xda/i.test(userAgentString); }, /** * Detects if a device is a tablet device. * @param userAgentString {String} userAgent parameter, needed for decision. * @return {Boolean} Flag which indicates whether it is a tablet device. */ detectTabletDevice : function(userAgentString){ return !(/Fennec|HTC.Magic|Nexus|android.+mobile/i.test(userAgentString)) && (/Android|ipad|tablet|playbook|silk|kindle|psp/i.test(userAgentString)); } }, defer : function(statics){ qx.core.Environment.add("device.name", statics.getName); qx.core.Environment.add("device.type", statics.getType); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * Module for querying information about the environment / runtime. * It adds a static key <code>env</code> to qxWeb and offers the given methods. * * <pre class="javascript"> * q.env.get("engine.name"); // return "webkit" e.g. * </pre> * * The following values are predefined: * * * <code>browser.name</code> : The name of the browser * * <code>browser.version</code> : The version of the browser * * <code>browser.quirksmode</code> : <code>true</code> if the browser is in quirksmode * * <code>browser.documentmode</code> : The document mode of the browser * * * <code>device.name</code> : The name of the device e.g. <code>iPad</code>. * * <code>device.type</code> : Either <code>desktop</code>, <code>tablet</code> or <code>mobile</code>. * * * <code>engine.name</code> : The name of the browser engine * * <code>engine.version</code> : The version of the browser engine */ qx.Bootstrap.define("qx.module.Environment", { statics : { /** * Get the value stored for the given key. * * @attachStatic {qxWeb, env.get} * @param key {String} The key to check for. * @return {var} The value stored for the given key. * @lint environmentNonLiteralKey(key) */ get : function(key){ return qx.core.Environment.get(key); }, /** * Adds a new environment setting which can be queried via {@link #get}. * @param key {String} The key to store the value for. * * @attachStatic {qxWeb, env.add} * @param value {var} The value to store. * @return {qxWeb} The collection for chaining. */ add : function(key, value){ qx.core.Environment.add(key, value); return this; } }, defer : function(statics){ // make sure the desired keys are available (browser.* and engine.*) qx.core.Environment.get("browser.name"); qx.core.Environment.get("browser.version"); qx.core.Environment.get("browser.quirksmode"); qx.core.Environment.get("browser.documentmode"); qx.core.Environment.get("engine.name"); qx.core.Environment.get("engine.version"); qx.core.Environment.get("device.type"); qxWeb.$attachStatic({ "env" : { get : statics.get, add : statics.add } }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Environment) #require(qx.module.Event) ************************************************************************ */ /** * Normalization for native mouse events */ qx.Bootstrap.define("qx.module.event.Mouse", { statics : { /** * List of event types to be normalized */ TYPES : ["click", "dblclick", "mousedown", "mouseup", "mouseover", "mousemove", "mouseout"], /** * List qx.module.event.Mouse methods to be attached to native mouse event * objects * @internal */ BIND_METHODS : ["getButton", "getViewportLeft", "getViewportTop", "getDocumentLeft", "getDocumentTop", "getScreenLeft", "getScreenTop"], /** * Standard mouse button mapping */ BUTTONS_DOM2 : { '0' : "left", '2' : "right", '1' : "middle" }, /** * Legacy Internet Explorer mouse button mapping */ BUTTONS_MSHTML : { '1' : "left", '2' : "right", '4' : "middle" }, /** * Returns the identifier of the mouse button that change state when the * event was triggered * * @return {String} One of <code>left</code>, <code>right</code> or * <code>middle</code> */ getButton : function(){ switch(this.type){case "contextmenu": return "right";case "click": // IE does not support buttons on click --> assume left button if(qxWeb.env.get("browser.name") === "ie" && qxWeb.env.get("browser.documentmode") < 9){ return "left"; };default: if(this.target !== undefined){ return qx.module.event.Mouse.BUTTONS_DOM2[this.button] || "none"; } else { return qx.module.event.Mouse.BUTTONS_MSHTML[this.button] || "none"; };}; }, /** * Get the horizontal coordinate at which the event occurred relative * to the viewport. * * @return {Number} The horizontal mouse position */ getViewportLeft : function(){ return this.clientX; }, /** * Get the vertical coordinate at which the event occurred relative * to the viewport. * * @return {Number} The vertical mouse position * @signature function() */ getViewportTop : function(){ return this.clientY; }, /** * Get the horizontal position at which the event occurred relative to the * left of the document. This property takes into account any scrolling of * the page. * * @return {Number} The horizontal mouse position in the document. */ getDocumentLeft : function(){ if(this.pageX !== undefined){ return this.pageX; } else { var win = qx.dom.Node.getWindow(this.srcElement); return this.clientX + qx.bom.Viewport.getScrollLeft(win); }; }, /** * Get the vertical position at which the event occurred relative to the * top of the document. This property takes into account any scrolling of * the page. * * @return {Number} The vertical mouse position in the document. */ getDocumentTop : function(){ if(this.pageY !== undefined){ return this.pageY; } else { var win = qx.dom.Node.getWindow(this.srcElement); return this.clientY + qx.bom.Viewport.getScrollTop(win); }; }, /** * Get the horizontal coordinate at which the event occurred relative to * the origin of the screen coordinate system. * * Note: This value is usually not very useful unless you want to * position a native popup window at this coordinate. * * @return {Number} The horizontal mouse position on the screen. */ getScreenLeft : function(){ return this.screenX; }, /** * Get the vertical coordinate at which the event occurred relative to * the origin of the screen coordinate system. * * Note: This value is usually not very useful unless you want to * position a native popup window at this coordinate. * * @return {Number} The vertical mouse position on the screen. */ getScreenTop : function(){ return this.screenY; }, /** * Manipulates the native event object, adding methods if they're not * already present * * @param event {Event} Native event object * @param element {Element} DOM element the listener was attached to * @return {Event} Normalized event object * @internal */ normalize : function(event, element){ if(!event){ return event; }; var bindMethods = qx.module.event.Mouse.BIND_METHODS; for(var i = 0,l = bindMethods.length;i < l;i++){ if(typeof event[bindMethods[i]] != "function"){ event[bindMethods[i]] = qx.module.event.Mouse[bindMethods[i]].bind(event); }; }; return event; } }, defer : function(statics){ qxWeb.$registerEventNormalization(qx.module.event.Mouse.TYPES, statics.normalize); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Tino Butz (tbtz) * Martin Wittemann (wittemann) ************************************************************************ */ /** * Define messages to react on certain channels. * * The channel names will be used in the {@link #on} method to define handlers which will * be called on certain channels and routes. The {@link #emit} method can be used * to execute a given route on a channel. {@link #onAny} defines a handler on any channel. * * *Example* * * Here is a little example of how to use the messaging. * * <pre class='javascript'> * var m = new qx.event.Messaging(); * * m.on("get", "/address/{id}", function(data) { * var id = data.params.id; // 1234 * // do something with the id... * },this); * * m.emit("get", "/address/1234"); * </pre> */ qx.Bootstrap.define("qx.event.Messaging", { construct : function(){ this._listener = { },this.__listenerIdCount = 0; this.__channelToIdMapping = { }; }, members : { _listener : null, __listenerIdCount : null, __channelToIdMapping : null, /** * Adds a route handler for the given channel. The route is called * if the {@link #emit} method finds a match. * * @param channel {String} The channel of the message. * @param type {String|RegExp} The type, used for checking if the executed path matches. * @param handler {Function} The handler to call if the route matches the executed path. * @param scope {var ? null} The scope of the handler. * @return {String} The id of the route used to remove the route. */ on : function(channel, type, handler, scope){ return this._addListener(channel, type, handler, scope); }, /** * Adds a handler for the "any" channel. The "any" channel is called * before all other channels. * * @param type {String|RegExp} The route, used for checking if the executed path matches * @param handler {Function} The handler to call if the route matches the executed path * @param scope {var ? null} The scope of the handler. * @return {String} The id of the route used to remove the route. */ onAny : function(type, handler, scope){ return this._addListener("any", type, handler, scope); }, /** * Adds a listener for a certain channel. * * @param channel {String} The channel the route should be registered for * @param type {String|RegExp} The type, used for checking if the executed path matches * @param handler {Function} The handler to call if the route matches the executed path * @param scope {var ? null} The scope of the handler. * @return {String} The id of the route used to remove the route. */ _addListener : function(channel, type, handler, scope){ var listeners = this._listener[channel] = this._listener[channel] || { }; var id = this.__listenerIdCount++; var params = []; var param = null; // Convert the route to a regular expression. if(qx.lang.Type.isString(type)){ var paramsRegexp = /\{([\w\d]+)\}/g; while((param = paramsRegexp.exec(type)) !== null){ params.push(param[1]); }; type = new RegExp("^" + type.replace(paramsRegexp, "([^\/]+)") + "$"); }; listeners[id] = { regExp : type, params : params, handler : handler, scope : scope }; this.__channelToIdMapping[id] = channel; return id; }, /** * Removes a registered listener by the given id. * * @param id {String} The id of the registered listener. */ remove : function(id){ var channel = this.__channelToIdMapping[id]; var listener = this._listener[channel]; delete listener[id]; delete this.__channelToIdMapping[id]; }, /** * Sends a message on the given channel and informs all matching route handlers. * * @param channel {String} The channel of the message. * @param path {String} The path to execute * @param params {Map} The given parameters that should be propagated * @param customData {var} The given custom data that should be propagated */ emit : function(channel, path, params, customData){ this._emit(channel, path, params, customData); }, /** * Executes a certain channel with a given path. Informs all * route handlers that match with the path. * * @param channel {String} The channel to execute. * @param path {String} The path to check * @param params {Map} The given parameters that should be propagated * @param customData {var} The given custom data that should be propagated */ _emit : function(channel, path, params, customData){ var listenerMatchedAny = false; var listener = this._listener["any"]; listenerMatchedAny = this._emitListeners(channel, path, listener, params, customData); var listenerMatched = false; listener = this._listener[channel]; listenerMatched = this._emitListeners(channel, path, listener, params, customData); if(!listenerMatched && !listenerMatchedAny){ qx.Bootstrap.info("No listener found for " + path); }; }, /** * Executes all given listener for a certain channel. Checks all listeners if they match * with the given path and executes the stored handler of the matching route. * * @param channel {String} The channel to execute. * @param path {String} The path to check * @param listeners {Map[]} All routes to test and execute. * @param params {Map} The given parameters that should be propagated * @param customData {var} The given custom data that should be propagated * * @return {Boolean} Whether the route has been executed */ _emitListeners : function(channel, path, listeners, params, customData){ if(!listeners || qx.lang.Object.isEmpty(listeners)){ return false; }; var listenerMatched = false; for(var id in listeners){ var listener = listeners[id]; listenerMatched |= this._emitRoute(channel, path, listener, params, customData); }; return listenerMatched; }, /** * Executes a certain listener. Checks if the listener matches the given path and * executes the stored handler of the route. * * @param channel {String} The channel to execute. * @param path {String} The path to check * @param listener {Map} The route data. * @param params {Map} The given parameters that should be propagated * @param customData {var} The given custom data that should be propagated * * @return {Boolean} Whether the route has been executed */ _emitRoute : function(channel, path, listener, params, customData){ var match = listener.regExp.exec(path); if(match){ var params = params || { }; var param = null; var value = null; match.shift(); // first match is the whole path for(var i = 0;i < match.length;i++){ value = match[i]; param = listener.params[i]; if(param){ params[param] = value; } else { params[i] = value; }; }; listener.handler.call(listener.scope, { path : path, params : params, customData : customData }); }; return match != undefined; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.event.Messaging#on) #require(qx.event.Messaging#onAny) #require(qx.event.Messaging#remove) #require(qx.event.Messaging#emit) ************************************************************************ */ /** * Define messages to react on certain channels. * * The channel names will be used in the q.messaging.on method to define handlers which will * be called on certain channels and routes. The q.messaging.emit method can be used * to execute a given route on a channel. q.messaging.onAny defines a handler on any channel. */ qx.Bootstrap.define("qx.module.Messaging", { statics : { /** * Adds a route handler for the given channel. The route is called * if the {@link #emit} method finds a match. * * @attachStatic{qxWeb, messaging.on} * @param channel {String} The channel of the message. * @param type {String|RegExp} The type, used for checking if the executed path matches. * @param handler {Function} The handler to call if the route matches the executed path. * @param scope {var ? null} The scope of the handler. * @return {String} The id of the route used to remove the route. * @signature function(channel, type, handler, scope) */ on : null, /** * Adds a handler for the "any" channel. The "any" channel is called * before all other channels. * * @attachStatic{qxWeb, messaging.onAny} * @param type {String|RegExp} The route, used for checking if the executed path matches * @param handler {Function} The handler to call if the route matches the executed path * @param scope {var ? null} The scope of the handler. * @return {String} The id of the route used to remove the route. * @signature function(type, handler, scope) */ onAny : null, /** * Removes a registered listener by the given id. * * @attachStatic{qxWeb, messaging.remove} * @param id {String} The id of the registered listener. * @signature function(id) */ remove : null, /** * Sends a message on the given channel and informs all matching route handlers. * * @attachStatic{qxWeb, messaging.emit} * @param channel {String} The channel of the message. * @param path {String} The path to execute * @param params {Map} The given parameters that should be propagated * @param customData {var} The given custom data that should be propagated * @signature function(channel, path, params, customData) */ emit : null }, defer : function(statics){ qxWeb.$attachStatic({ "messaging" : new qx.event.Messaging() }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * Utility module to give some support to work with arrays. */ qx.Bootstrap.define("qx.module.util.Array", { statics : { /** * Converts an array like object to any other array like * object. * * Attention: The returned array may be same * instance as the incoming one if the constructor is identical! * * @signature function(object, constructor, offset) * @attachStatic {qxWeb, array.cast} * * @param object {var} any array-like object * @param constructor {Function} constructor of the new instance * @param offset {Number?0} position to start from * @return {Array} the converted array */ cast : qx.lang.Array.cast, /** * Check whether the two arrays have the same content. Checks only the * equality of the arrays' content. * * @signature function(arr1, arr2) * @attachStatic {qxWeb, array.equals} * * @param arr1 {Array} first array * @param arr2 {Array} second array * @return {Boolean} Whether the two arrays are equal */ equals : qx.lang.Array.equals, /** * Modifies the first array as it removes all elements * which are listed in the second array as well. * * @signature function(arr1, arr2) * @attachStatic {qxWeb, array.exclude} * * @param arr1 {Array} the array * @param arr2 {Array} the elements of this array will be excluded from the other one * @return {Array} The modified array. */ exclude : qx.lang.Array.exclude, /** * Convert an arguments object into an array. * * @signature function(args, offset) * @attachStatic {qxWeb, array.fromArguments} * * @param args {arguments} arguments object * @param offset {Number?0} position to start from * @return {Array} a newly created array (copy) with the content of the arguments object. */ fromArguments : qx.lang.Array.fromArguments, /** * Insert an element into the array after a given second element. * * @signature function(arr, obj, obj2) * @attachStatic {qxWeb, array.insertAfter} * * @param arr {Array} the array * @param obj {var} object to be inserted * @param obj2 {var} insert obj1 after this object * @return {Array} The given array. */ insertAfter : qx.lang.Array.insertAfter, /** * Insert an element into the array before a given second element. * * @signature function(arr, obj, obj2) * @attachStatic {qxWeb, array.insertBefore} * * @param arr {Array} the array * @param obj {var} object to be inserted * @param obj2 {var} insert obj1 before this object * @return {Array} The given array. */ insertBefore : qx.lang.Array.insertBefore, /** * Returns the highest value in the given array. Supports * numeric values only. * * @signature function(arr) * @attachStatic {qxWeb, array.max} * * @param arr {Array} Array to process. * @return {Number | undefined} The highest of all values or undefined if array is empty. */ max : qx.lang.Array.max, /** * Returns the lowest value in the given array. Supports * numeric values only. * * @signature function(arr) * @attachStatic {qxWeb, array.min} * * @param arr {Array} Array to process. * @return {Number | undefined} The lowest of all values or undefined if array is empty. */ min : qx.lang.Array.min, /** * Remove an element from the array. * * @signature function(arr, obj) * @attachStatic {qxWeb, array.remove} * * @param arr {Array} the array * @param obj {var} element to be removed from the array * @return {var} the removed element */ remove : qx.lang.Array.remove, /** * Remove all elements from the array * * @signature function(arr) * @attachStatic {qxWeb, array.removeAll} * * @param arr {Array} the array * @return {Array} empty array */ removeAll : qx.lang.Array.removeAll, /** * Recreates an array which is free of all duplicate elements from the original. * This method do not modifies the original array! * Keep in mind that this methods deletes undefined indexes. * * @signature function(arr) * @attachStatic {qxWeb, array.unique} * * @param arr {Array} Incoming array * @return {Array} Returns a copy with no duplicates * or the original array if no duplicates were found. */ unique : qx.lang.Array.unique }, defer : function(statics){ qxWeb.$attachStatic({ array : { cast : statics.cast, equals : statics.equals, exclude : statics.exclude, fromArguments : statics.fromArguments, insertAfter : statics.insertAfter, insertBefore : statics.insertBefore, max : statics.max, min : statics.min, remove : statics.remove, removeAll : statics.removeAll, unique : statics.unique } }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * Utility module to give some support to work with strings. */ qx.Bootstrap.define("qx.module.util.String", { statics : { /** * Converts a hyphenated string (separated by '-') to camel case. * * Example: * <pre class='javascript'>q.string.camelCase("I-like-cookies"); //returns "ILikeCookies"</pre> * The implementation does not force a lowerCamelCase or upperCamelCase version. * The first letter of the parameter keeps its case. * * @attachStatic {qxWeb, string.camelCase} * @param str {String} hyphenated string * @return {String} camelcase string */ camelCase : function(str){ return qx.lang.String.camelCase.call(qx.lang.String, str); }, /** * Converts a camelcased string to a hyphenated (separated by '-') string. * * Example: * <pre class='javascript'>q.string.hyphenate("ILikeCookies"); //returns "I-like-cookies"</pre> * The implementation does not force a lowerCamelCase or upperCamelCase version. * The first letter of the parameter keeps its case. * * @attachStatic {qxWeb, string.hyphenate} * @param str {String} camelcased string * @return {String} hyphenated string */ hyphenate : function(str){ return qx.lang.String.hyphenate.call(qx.lang.String, str); }, /** * Convert the first character of the string to upper case. * * @attachStatic {qxWeb, string.firstUp} * @signature function(str) * @param str {String} the string * @return {String} the string with an upper case first character */ firstUp : qx.lang.String.firstUp, /** * Convert the first character of the string to lower case. * * @attachStatic {qxWeb, string.firstLow} * @signature function(str) * @param str {String} the string * @return {String} the string with a lower case first character */ firstLow : qx.lang.String.firstLow, /** * Check whether the string starts with the given substring. * * @attachStatic {qxWeb, string.startsWith} * @signature function(fullstr, substr) * @param fullstr {String} the string to search in * @param substr {String} the substring to look for * @return {Boolean} whether the string starts with the given substring */ startsWith : qx.lang.String.startsWith, /** * Check whether the string ends with the given substring. * * @attachStatic {qxWeb, string.endsWith} * @signature function(fullstr, substr) * @param fullstr {String} the string to search in * @param substr {String} the substring to look for * @return {Boolean} whether the string ends with the given substring */ endsWith : qx.lang.String.endsWith, /** * Escapes all chars that have a special meaning in regular expressions. * * @attachStatic {qxWeb, string.escapeRegexpChars} * @signature function(str) * @param str {String} the string where to escape the chars. * @return {String} the string with the escaped chars. */ escapeRegexpChars : qx.lang.String.escapeRegexpChars }, defer : function(statics){ qxWeb.$attachStatic({ string : { camelCase : statics.camelCase, hyphenate : statics.hyphenate, firstUp : statics.firstUp, firstLow : statics.firstLow, startsWith : statics.startsWith, endsWith : statics.endsWith, escapeRegexpChars : statics.escapeRegexpChars } }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This class is responsible for applying CSS3 transforms to the collection. * The implementation is mostly a cross browser wrapper for applying the * transforms. * The API is keep to the spec as close as possible. * * http://www.w3.org/TR/css3-3d-transforms/ */ qx.Bootstrap.define("qx.module.Transform", { statics : { /** * Method to apply multiple transforms at once to the given element. It * takes a map containing the transforms you want to apply plus the values * e.g.<code>{scale: 2, rotate: "5deg"}</code>. * The values can be either singular, which means a single value will * be added to the CSS. If you give an array, the values will be split up * and each array entry will be used for the X, Y or Z dimension in that * order e.g. <code>{scale: [2, 0.5]}</code> will result in a element * double the size in X direction and half the size in Y direction. * Make sure your browser supports all transformations you apply. * * @attach {qxWeb} * @param transforms {Map} The map containing the transforms and value. * @return {qxWeb} This reference for chaining. */ transform : function(transforms){ this.forEach(function(el){ qx.bom.element.Transform.transform(el, transforms); }); return this; }, /** * Translates by the given value. For further details, take * a look at the {@link #transform} method. * * @attach {qxWeb} * @param value {String|Array} The value to translate e.g. <code>"10px"</code>. * @return {qxWeb} This reference for chaining. */ translate : function(value){ return this.transform({ translate : value }); }, /** * Scales by the given value. For further details, take * a look at the {@link #transform} method. * * @attach {qxWeb} * @param value {Number|Array} The value to scale. * @return {qxWeb} This reference for chaining. */ scale : function(value){ return this.transform({ scale : value }); }, /** * Rotates by the given value. For further details, take * a look at the {@link #transform} method. * @param value {String|Array} The value to rotate e.g. <code>"90deg"</code>. * @return {qxWeb} This reference for chaining. */ rotate : function(value){ return this.transform({ rotate : value }); }, /** * Skews by the given value. For further details, take * a look at the {@link #transform} method. * * @attach {qxWeb} * @param value {String|Array} The value to skew e.g. <code>"90deg"</code>. * @return {qxWeb} This reference for chaining. */ skew : function(value){ return this.transform({ skew : value }); }, /** * Sets the transform-origin property. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-origin-property * * @attach {qxWeb} * @param value {String} CSS position values like <code>50% 50%</code> or * <code>left top</code>. * @return {qxWeb} This reference for chaining. */ setTransformOrigin : function(value){ this.forEach(function(el){ qx.bom.element.Transform.setOrigin(el, value); }); return this; }, /** * Returns the transform-origin property of the first element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-origin-property * * @attach {qxWeb} * @return {String} The set property, e.g. <code>50% 50%</code> or null, * of the collection is empty. */ getTransformOrigin : function(){ if(this[0]){ return qx.bom.element.Transform.getOrigin(this[0]); }; return ""; }, /** * Sets the transform-style property. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-style-property * * @attach {qxWeb} * @param value {String} Either <code>flat</code> or <code>preserve-3d</code>. * @return {qxWeb} This reference for chaining. */ setTransformStyle : function(value){ this.forEach(function(el){ qx.bom.element.Transform.setStyle(el, value); }); return this; }, /** * Returns the transform-style property of the first element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-style-property * * @attach {qxWeb} * @return {String} The set property, either <code>flat</code> or * <code>preserve-3d</code>. */ getTransformStyle : function(){ if(this[0]){ return qx.bom.element.Transform.getStyle(this[0]); }; return ""; }, /** * Sets the perspective property. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-property * * @attach {qxWeb} * @param value {Number} The perspective layer. Numbers between 100 * and 5000 give the best results. * @return {qxWeb} This reference for chaining. */ setTransformPerspective : function(value){ this.forEach(function(el){ qx.bom.element.Transform.setPerspective(el, value); }); return this; }, /** * Returns the perspective property of the first element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-property * * @attach {qxWeb} * @return {String} The set property, e.g. <code>500</code> */ getTransformPerspective : function(){ if(this[0]){ return qx.bom.element.Transform.getPerspective(this[0]); }; return ""; }, /** * Sets the perspective-origin property. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-origin-property * * @attach {qxWeb} * @param value {String} CSS position values like <code>50% 50%</code> or * <code>left top</code>. * @return {qxWeb} This reference for chaining. */ setTransformPerspectiveOrigin : function(value){ this.forEach(function(el){ qx.bom.element.Transform.setPerspectiveOrigin(el, value); }); return this; }, /** * Returns the perspective-origin property of the first element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-origin-property * * @attach {qxWeb} * @return {String} The set property, e.g. <code>50% 50%</code> */ getTransformPerspectiveOrigin : function(){ if(this[0]){ return qx.bom.element.Transform.getPerspectiveOrigin(this[0]); }; return ""; }, /** * Sets the backface-visibility property. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#backface-visibility-property * * @attach {qxWeb} * @param value {Boolean} <code>true</code> if the backface should be visible. * @return {qxWeb} This reference for chaining. */ setTransformBackfaceVisibility : function(value){ this.forEach(function(el){ qx.bom.element.Transform.setBackfaceVisibility(el, value); }); return this; }, /** * Returns the backface-visibility property of the first element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#backface-visibility-property * * @attach {qxWeb} * @return {Boolean} <code>true</code>, if the backface is visible. */ getTransformBackfaceVisibility : function(){ if(this[0]){ return qx.bom.element.Transform.getBackfaceVisibility(this[0]); }; return ""; } }, defer : function(statics){ qxWeb.$attach({ "transform" : statics.transform, "translate" : statics.translate, "rotate" : statics.rotate, "skew" : statics.skew, "scale" : statics.scale, "setTransformStyle" : statics.setTransformStyle, "getTransformStyle" : statics.getTransformStyle, "setTransformOrigin" : statics.setTransformOrigin, "getTransformOrigin" : statics.getTransformOrigin, "setTransformPerspective" : statics.setTransformPerspective, "getTransformPerspective" : statics.getTransformPerspective, "setTransformPerspectiveOrigin" : statics.setTransformPerspectiveOrigin, "getTransformPerspectiveOrigin" : statics.getTransformPerspectiveOrigin, "setTransformBackfaceVisibility" : statics.setTransformBackfaceVisibility, "getTransformBackfaceVisibility" : statics.getTransformBackfaceVisibility }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * Responsible for checking all relevant CSS transform properties. * * Specs: * http://www.w3.org/TR/css3-2d-transforms/ * http://www.w3.org/TR/css3-3d-transforms/ * * @internal */ qx.Bootstrap.define("qx.bom.client.CssTransform", { statics : { /** * Main check method which returns an object if CSS animations are * supported. This object contains all necessary keys to work with CSS * animations. * <ul> * <li><code>name</code> The name of the css transform style</li> * <li><code>style</code> The name of the css transform-style style</li> * <li><code>origin</code> The name of the transform-origin style</li> * <li><code>3d</code> Whether 3d transforms are supported</li> * <li><code>perspective</code> The name of the perspective style</li> * <li><code>perspective-origin</code> The name of the perspective-origin style</li> * <li><code>backface-visibility</code> The name of the backface-visibility style</li> * </ul> * * @internal * @return {Object|null} The described object or null, if animations are * not supported. */ getSupport : function(){ var name = qx.bom.client.CssTransform.getName(); if(name != null){ return { "name" : name, "style" : qx.bom.client.CssTransform.getStyle(), "origin" : qx.bom.client.CssTransform.getOrigin(), "3d" : qx.bom.client.CssTransform.get3D(), "perspective" : qx.bom.client.CssTransform.getPerspective(), "perspective-origin" : qx.bom.client.CssTransform.getPerspectiveOrigin(), "backface-visibility" : qx.bom.client.CssTransform.getBackFaceVisibility() }; }; return null; }, /** * Checks for the style name used to set the transform origin. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getStyle : function(){ return qx.bom.Style.getPropertyName("transformStyle"); }, /** * Checks for the style name used to set the transform origin. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getPerspective : function(){ return qx.bom.Style.getPropertyName("perspective"); }, /** * Checks for the style name used to set the perspective origin. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getPerspectiveOrigin : function(){ return qx.bom.Style.getPropertyName("perspectiveOrigin"); }, /** * Checks for the style name used to set the backface visibility. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getBackFaceVisibility : function(){ return qx.bom.Style.getPropertyName("backfaceVisibility"); }, /** * Checks for the style name used to set the transform origin. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getOrigin : function(){ return qx.bom.Style.getPropertyName("transformOrigin"); }, /** * Checks for the style name used for transforms. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getName : function(){ return qx.bom.Style.getPropertyName("transform"); }, /** * Checks if 3D transforms are supported. * @internal * @return {Boolean} <code>true</code>, if 3D transformations are supported */ get3D : function(){ return qx.bom.client.CssTransform.getPerspective() != null; } }, defer : function(statics){ qx.core.Environment.add("css.transform", statics.getSupport); qx.core.Environment.add("css.transform.3d", statics.get3D); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This class is responsible for applying CSS3 transforms to plain DOM elements. * The implementation is mostly a cross browser wrapper for applying the * transforms. * The API is keep to the spec as close as possible. * * http://www.w3.org/TR/css3-3d-transforms/ */ qx.Bootstrap.define("qx.bom.element.Transform", { statics : { /** The dimensions of the transforms */ __dimensions : ["X", "Y", "Z"], /** Internal storage of the CSS names */ __cssKeys : qx.core.Environment.get("css.transform"), /** * Method to apply multiple transforms at once to the given element. It * takes a map containing the transforms you want to apply plus the values * e.g.<code>{scale: 2, rotate: "5deg"}</code>. * The values can be either singular, which means a single value will * be added to the CSS. If you give an array, the values will be split up * and each array entry will be used for the X, Y or Z dimension in that * order e.g. <code>{scale: [2, 0.5]}</code> will result in a element * double the size in X direction and half the size in Y direction. * Make sure your browser supports all transformations you apply. * @param el {Element} The element to apply the transformation. * @param transforms {Map} The map containing the transforms and value. */ transform : function(el, transforms){ var transformCss = this.__mapToCss(transforms); if(this.__cssKeys != null){ var style = this.__cssKeys["name"]; el.style[style] = transformCss; }; }, /** * Translates the given element by the given value. For further details, take * a look at the {@link #transform} method. * @param el {Element} The element to apply the transformation. * @param value {String|Array} The value to translate e.g. <code>"10px"</code>. */ translate : function(el, value){ this.transform(el, { translate : value }); }, /** * Scales the given element by the given value. For further details, take * a look at the {@link #transform} method. * @param el {Element} The element to apply the transformation. * @param value {Number|Array} The value to scale. */ scale : function(el, value){ this.transform(el, { scale : value }); }, /** * Rotates the given element by the given value. For further details, take * a look at the {@link #transform} method. * @param el {Element} The element to apply the transformation. * @param value {String|Array} The value to rotate e.g. <code>"90deg"</code>. */ rotate : function(el, value){ this.transform(el, { rotate : value }); }, /** * Skews the given element by the given value. For further details, take * a look at the {@link #transform} method. * @param el {Element} The element to apply the transformation. * @param value {String|Array} The value to skew e.g. <code>"90deg"</code>. */ skew : function(el, value){ this.transform(el, { skew : value }); }, /** * Converts the given map to a string which chould ba added to a css * stylesheet. * @param transforms {Map} The transforms map. For a detailed description, * take a look at the {@link #transform} method. * @return {String} The CSS value. */ getCss : function(transforms){ var transformCss = this.__mapToCss(transforms); if(this.__cssKeys != null){ var style = this.__cssKeys["name"]; return qx.lang.String.hyphenate(style) + ":" + transformCss + ";"; }; return ""; }, /** * Sets the transform-origin property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-origin-property * @param el {Element} The dom element to set the property. * @param value {String} CSS position values like <code>50% 50%</code> or * <code>left top</code>. */ setOrigin : function(el, value){ if(this.__cssKeys != null){ el.style[this.__cssKeys["origin"]] = value; }; }, /** * Returns the transform-origin property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-origin-property * @param el {Element} The dom element to read the property. * @return {String} The set property, e.g. <code>50% 50%</code> */ getOrigin : function(el){ if(this.__cssKeys != null){ return el.style[this.__cssKeys["origin"]]; }; return ""; }, /** * Sets the transform-style property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-style-property * @param el {Element} The dom element to set the property. * @param value {String} Either <code>flat</code> or <code>preserve-3d</code>. */ setStyle : function(el, value){ if(this.__cssKeys != null){ el.style[this.__cssKeys["style"]] = value; }; }, /** * Returns the transform-style property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#transform-style-property * @param el {Element} The dom element to read the property. * @return {String} The set property, either <code>flat</code> or * <code>preserve-3d</code>. */ getStyle : function(el){ if(this.__cssKeys != null){ return el.style[this.__cssKeys["style"]]; }; return ""; }, /** * Sets the perspective property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-property * @param el {Element} The dom element to set the property. * @param value {Number} The perspective layer. Numbers between 100 * and 5000 give the best results. */ setPerspective : function(el, value){ if(this.__cssKeys != null){ el.style[this.__cssKeys["perspective"]] = value + "px"; }; }, /** * Returns the perspective property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-property * @param el {Element} The dom element to read the property. * @return {String} The set property, e.g. <code>500</code> */ getPerspective : function(el){ if(this.__cssKeys != null){ return el.style[this.__cssKeys["perspective"]]; }; return ""; }, /** * Sets the perspective-origin property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-origin-property * @param el {Element} The dom element to set the property. * @param value {String} CSS position values like <code>50% 50%</code> or * <code>left top</code>. */ setPerspectiveOrigin : function(el, value){ if(this.__cssKeys != null){ el.style[this.__cssKeys["perspective-origin"]] = value; }; }, /** * Returns the perspective-origin property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#perspective-origin-property * @param el {Element} The dom element to read the property. * @return {String} The set property, e.g. <code>50% 50%</code> */ getPerspectiveOrigin : function(el){ if(this.__cssKeys != null){ var value = el.style[this.__cssKeys["perspective-origin"]]; if(value != ""){ return value; } else { var valueX = el.style[this.__cssKeys["perspective-origin"] + "X"]; var valueY = el.style[this.__cssKeys["perspective-origin"] + "Y"]; if(valueX != ""){ return valueX + " " + valueY; }; }; }; return ""; }, /** * Sets the backface-visibility property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#backface-visibility-property * @param el {Element} The dom element to set the property. * @param value {Boolean} <code>true</code> if the backface should be visible. */ setBackfaceVisibility : function(el, value){ if(this.__cssKeys != null){ el.style[this.__cssKeys["backface-visibility"]] = value ? "visible" : "hidden"; }; }, /** * Returns the backface-visibility property of the given element. * * Spec: http://www.w3.org/TR/css3-3d-transforms/#backface-visibility-property * @param el {Element} The dom element to read the property. * @return {Boolean} <code>true</code>, if the backface is visible. */ getBackfaceVisibility : function(el){ if(this.__cssKeys != null){ return el.style[this.__cssKeys["backface-visibility"]] == "visible"; }; return true; }, /** * Internal helper which converts the given transforms map to a valid CSS * string. * @param transforms {Map} A map containing the transforms. * @return {String} The CSS transforms. */ __mapToCss : function(transforms){ var value = ""; for(var func in transforms){ var params = transforms[func]; // if an array is given if(qx.Bootstrap.isArray(params)){ for(var i = 0;i < params.length;i++){ if(params[i] == undefined){ continue; }; value += func + this.__dimensions[i] + "("; value += params[i]; value += ") "; }; } else { // single value case value += func + "(" + transforms[func] + ") "; }; }; return value; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Event) #require(qx.bom.Event#getTarget) #require(qx.bom.Event#getRelatedTarget) ************************************************************************ */ /** * Common normalizations for native events */ qx.Bootstrap.define("qx.module.event.Native", { statics : { /** * List of event types to be normalized */ TYPES : ["*"], /** * List of qx.bom.Event methods to be attached to native event objects * @internal */ FORWARD_METHODS : ["getTarget", "getRelatedTarget"], /** * List of qx.module.event.Native methods to be attached to native event objects * @internal */ BIND_METHODS : ["preventDefault", "stopPropagation", "getType"], /** * Prevent the native default behavior of the event. */ preventDefault : function(){ try{ // this allows us to prevent some key press events in IE. // See bug #1049 this.keyCode = 0; } catch(ex) { }; this.returnValue = false; }, /** * Stops the event's propagation to the element's parent */ stopPropagation : function(){ this.cancelBubble = true; }, /** * Returns the event's type * * @return {String} event type */ getType : function(){ return this._type || this.type; }, /** * Manipulates the native event object, adding methods if they're not * already present * * @param event {Event} Native event object * @param element {Element} DOM element the listener was attached to * @return {Event} Normalized event object * @internal */ normalize : function(event, element){ if(!event){ return event; }; var fwdMethods = qx.module.event.Native.FORWARD_METHODS; for(var i = 0,l = fwdMethods.length;i < l;i++){ event[fwdMethods[i]] = qx.lang.Function.curry(qx.bom.Event[fwdMethods[i]], event); }; var bindMethods = qx.module.event.Native.BIND_METHODS; for(var i = 0,l = bindMethods.length;i < l;i++){ if(typeof event[bindMethods[i]] != "function"){ event[bindMethods[i]] = qx.module.event.Native[bindMethods[i]].bind(event); }; }; event.getCurrentTarget = function(){ return event.currentTarget || element; }; return event; } }, defer : function(statics){ qxWeb.$registerEventNormalization(statics.TYPES, statics.normalize); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ====================================================================== This class contains code based on the following work: * Prototype JS http://www.prototypejs.org/ Version 1.5 Copyright: (c) 2006-2007, Prototype Core Team License: MIT: http://www.opensource.org/licenses/mit-license.php Authors: * Prototype Core Team ---------------------------------------------------------------------- Copyright (c) 2005-2008 Sam Stephenson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ************************************************************************ */ /** * Methods to operate on nodes and elements on a DOM tree. This contains * special getters to query for child nodes, siblings, etc. This class also * supports to operate on one element and reorganize the content with * the insertion of new HTML or nodes. */ qx.Bootstrap.define("qx.dom.Hierarchy", { statics : { /** * Returns the DOM index of the given node * * @param node {Node} Node to look for * @return {Integer} The DOM index */ getNodeIndex : function(node){ var index = 0; while(node && (node = node.previousSibling)){ index++; }; return index; }, /** * Returns the DOM index of the given element (ignoring non-elements) * * @param element {Element} Element to look for * @return {Integer} The DOM index */ getElementIndex : function(element){ var index = 0; var type = qx.dom.Node.ELEMENT; while(element && (element = element.previousSibling)){ if(element.nodeType == type){ index++; }; }; return index; }, /** * Return the next element to the supplied element * * "nextSibling" is not good enough as it might return a text or comment element * * @param element {Element} Starting element node * @return {Element | null} Next element node */ getNextElementSibling : function(element){ while(element && (element = element.nextSibling) && !qx.dom.Node.isElement(element)){ continue; }; return element || null; }, /** * Return the previous element to the supplied element * * "previousSibling" is not good enough as it might return a text or comment element * * @param element {Element} Starting element node * @return {Element | null} Previous element node */ getPreviousElementSibling : function(element){ while(element && (element = element.previousSibling) && !qx.dom.Node.isElement(element)){ continue; }; return element || null; }, /** * Whether the first element contains the second one * * Uses native non-standard contains() in Internet Explorer, * Opera and Webkit (supported since Safari 3.0 beta) * * @param element {Element} Parent element * @param target {Node} Child node * @return {Boolean} */ contains : function(element, target){ if(qx.core.Environment.get("html.element.contains")){ if(qx.dom.Node.isDocument(element)){ var doc = qx.dom.Node.getDocument(target); return element && doc == element; } else if(qx.dom.Node.isDocument(target)){ return false; } else { return element.contains(target); }; } else if(qx.core.Environment.get("html.element.compareDocumentPosition")){ // http://developer.mozilla.org/en/docs/DOM:Node.compareDocumentPosition return !!(element.compareDocumentPosition(target) & 16); } else { while(target){ if(element == target){ return true; }; target = target.parentNode; }; return false; }; }, /** * Whether the element is inserted into the document * for which it was created. * * @param element {Element} DOM element to check * @return {Boolean} <code>true</code> when the element is inserted * into the document. */ isRendered : function(element){ var doc = element.ownerDocument || element.document; if(qx.core.Environment.get("html.element.contains")){ // Fast check for all elements which are not in the DOM if(!element.parentNode || !element.offsetParent){ return false; }; return doc.body.contains(element); } else if(qx.core.Environment.get("html.element.compareDocumentPosition")){ // Gecko way, DOM3 method return !!(doc.compareDocumentPosition(element) & 16); } else { while(element){ if(element == doc.body){ return true; }; element = element.parentNode; }; return false; }; }, /** * Checks if <code>element</code> is a descendant of <code>ancestor</code>. * * @param element {Element} first element * @param ancestor {Element} second element * @return {Boolean} Element is a descendant of ancestor */ isDescendantOf : function(element, ancestor){ return this.contains(ancestor, element); }, /** * Get the common parent element of two given elements. Returns * <code>null</code> when no common element has been found. * * Uses native non-standard contains() in Opera and Internet Explorer * * @param element1 {Element} First element * @param element2 {Element} Second element * @return {Element} the found parent, if none was found <code>null</code> */ getCommonParent : function(element1, element2){ if(element1 === element2){ return element1; }; if(qx.core.Environment.get("html.element.contains")){ while(element1 && qx.dom.Node.isElement(element1)){ if(element1.contains(element2)){ return element1; }; element1 = element1.parentNode; }; return null; } else { var known = []; while(element1 || element2){ if(element1){ if(qx.lang.Array.contains(known, element1)){ return element1; }; known.push(element1); element1 = element1.parentNode; }; if(element2){ if(qx.lang.Array.contains(known, element2)){ return element2; }; known.push(element2); element2 = element2.parentNode; }; }; return null; }; }, /** * Collects all of element's ancestors and returns them as an array of * elements. * * @param element {Element} DOM element to query for ancestors * @return {Array} list of all parents */ getAncestors : function(element){ return this._recursivelyCollect(element, "parentNode"); }, /** * Returns element's children. * * @param element {Element} DOM element to query for child elements * @return {Array} list of all child elements */ getChildElements : function(element){ element = element.firstChild; if(!element){ return []; }; var arr = this.getNextSiblings(element); if(element.nodeType === 1){ arr.unshift(element); }; return arr; }, /** * Collects all of element's descendants (deep) and returns them as an array * of elements. * * @param element {Element} DOM element to query for child elements * @return {Array} list of all found elements */ getDescendants : function(element){ return qx.lang.Array.fromCollection(element.getElementsByTagName("*")); }, /** * Returns the first child that is an element. This is opposed to firstChild DOM * property which will return any node (whitespace in most usual cases). * * @param element {Element} DOM element to query for first descendant * @return {Element} the first descendant */ getFirstDescendant : function(element){ element = element.firstChild; while(element && element.nodeType != 1){ element = element.nextSibling; }; return element; }, /** * Returns the last child that is an element. This is opposed to lastChild DOM * property which will return any node (whitespace in most usual cases). * * @param element {Element} DOM element to query for last descendant * @return {Element} the last descendant */ getLastDescendant : function(element){ element = element.lastChild; while(element && element.nodeType != 1){ element = element.previousSibling; }; return element; }, /** * Collects all of element's previous siblings and returns them as an array of elements. * * @param element {Element} DOM element to query for previous siblings * @return {Array} list of found DOM elements */ getPreviousSiblings : function(element){ return this._recursivelyCollect(element, "previousSibling"); }, /** * Collects all of element's next siblings and returns them as an array of * elements. * * @param element {Element} DOM element to query for next siblings * @return {Array} list of found DOM elements */ getNextSiblings : function(element){ return this._recursivelyCollect(element, "nextSibling"); }, /** * Recursively collects elements whose relationship is specified by * property. <code>property</code> has to be a property (a method won't * do!) of element that points to a single DOM node. Returns an array of * elements. * * @param element {Element} DOM element to start with * @param property {String} property to look for * @return {Array} result list */ _recursivelyCollect : function(element, property){ var list = []; while(element = element[property]){ if(element.nodeType == 1){ list.push(element); }; }; return list; }, /** * Collects all of element's siblings and returns them as an array of elements. * * @param element {var} DOM element to start with * @return {Array} list of all found siblings */ getSiblings : function(element){ return this.getPreviousSiblings(element).reverse().concat(this.getNextSiblings(element)); }, /** * Whether the given element is empty. * Inspired by Base2 (Dean Edwards) * * @param element {Element} The element to check * @return {Boolean} true when the element is empty */ isEmpty : function(element){ element = element.firstChild; while(element){ if(element.nodeType === qx.dom.Node.ELEMENT || element.nodeType === qx.dom.Node.TEXT){ return false; }; element = element.nextSibling; }; return true; }, /** * Removes all of element's text nodes which contain only whitespace * * @param element {Element} Element to cleanup */ cleanWhitespace : function(element){ var node = element.firstChild; while(node){ var nextNode = node.nextSibling; if(node.nodeType == 3 && !/\S/.test(node.nodeValue)){ element.removeChild(node); }; node = nextNode; }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2011-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.dom.Hierarchy#getSiblings) #require(qx.dom.Hierarchy#getNextSiblings) #require(qx.dom.Hierarchy#getPreviousSiblings) ************************************************************************ */ /** * DOM traversal module */ qx.Bootstrap.define("qx.module.Traversing", { statics : { /** * Adds an element to the collection * * @attach {qxWeb} * @param el {Element} DOM element to add to the collection * @return {qxWeb} The collection for chaining */ add : function(el){ this.push(el); return this; }, /** * Gets a set of elements containing all of the unique immediate children of * each of the matched set of elements. * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String?null} Optional selector to match * @return {qxWeb} Collection containing the child elements */ getChildren : function(selector){ var children = []; for(var i = 0;i < this.length;i++){ var found = qx.dom.Hierarchy.getChildElements(this[i]); if(selector){ found = qx.bom.Selector.matches(selector, found); }; children = children.concat(found); }; return qxWeb.$init(children); }, /** * Executes the provided callback function once for each item in the * collection. * * @attach {qxWeb} * @param fn {Function} Callback function * @param ctx {Object} Context object * @return {qxWeb} The collection for chaining */ forEach : function(fn, ctx){ for(var i = 0;i < this.length;i++){ fn.call(ctx, this[i], i, this); }; return this; }, /** * Gets a set of elements containing the parent of each element in the * collection. * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String?null} Optional selector to match * @return {qxWeb} Collection containing the parent elements */ getParents : function(selector){ var parents = []; for(var i = 0;i < this.length;i++){ var found = qx.dom.Element.getParentElement(this[i]); if(selector){ found = qx.bom.Selector.matches(selector, [found]); }; parents = parents.concat(found); }; return qxWeb.$init(parents); }, /** * Gets a set of elements containing all ancestors of each element in the * collection. * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param filter {String?null} Optional selector to match * @return {qxWeb} Collection containing the ancestor elements */ getAncestors : function(filter){ return this.__getAncestors(null, filter); }, /** * Gets a set of elements containing all ancestors of each element in the * collection, up to (but not including) the element matched by the provided * selector. * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String} Selector that indicates where to stop including * ancestor elements * @param filter {String?null} Optional selector to match * @return {qxWeb} Collection containing the ancestor elements */ getAncestorsUntil : function(selector, filter){ return this.__getAncestors(selector, filter); }, /** * Internal helper for getAncestors and getAncestorsUntil * * @attach {qxWeb} * @param selector {String} Selector that indicates where to stop including * ancestor elements * @param filter {String?null} Optional selector to match * @return {qxWeb} Collection containing the ancestor elements * @internal */ __getAncestors : function(selector, filter){ var ancestors = []; for(var i = 0;i < this.length;i++){ var parent = qx.dom.Element.getParentElement(this[i]); while(parent){ var found = [parent]; if(selector && qx.bom.Selector.matches(selector, found).length > 0){ break; }; if(filter){ found = qx.bom.Selector.matches(filter, found); }; ancestors = ancestors.concat(found); parent = qx.dom.Element.getParentElement(parent); }; }; return qxWeb.$init(ancestors); }, /** * Gets a set containing the closest matching ancestor for each item in * the collection. * If the item itself matches, it is added to the new set. Otherwise, the * item's parent chain will be traversed until a match is found. * * @attach {qxWeb} * @param selector {String} Selector expression to match * @return {qxWeb} New collection containing the closest matching ancestors */ getClosest : function(selector){ var closest = []; var findClosest = function findClosest(current){ var found = qx.bom.Selector.matches(selector, current); if(found.length){ closest.push(found[0]); } else { current = current.getParents(); // One up if(current[0] && current[0].parentNode){ findClosest(current); }; }; }; for(var i = 0;i < this.length;i++){ findClosest(qxWeb(this[i])); }; return qxWeb.$init(closest); }, /** * Searches the child elements of each item in the collection and returns * a new collection containing the children that match the provided selector * * @attach {qxWeb} * @param selector {String} Selector expression to match the child elements * against * @return {qxWeb} New collection containing the matching child elements */ find : function(selector){ var found = []; for(var i = 0;i < this.length;i++){ found = found.concat(qx.bom.Selector.query(selector, this[i])); }; return qxWeb.$init(found); }, /** * Gets a new set of elements containing the child nodes of each item in the * current set. * * @attach {qxWeb} * @return {qxWeb} New collection containing the child nodes */ getContents : function(){ var found = []; for(var i = 0;i < this.length;i++){ found = found.concat(qx.lang.Array.fromCollection(this[i].childNodes)); }; return qxWeb.$init(found); }, /** * Checks if at least one element in the collection passes the provided * filter. This can be either a selector expression or a filter * function * * @attach {qxWeb} * @param selector {String|Function} Selector expression or filter function * @return {Boolean} <code>true</code> if at least one element matches */ is : function(selector){ if(qx.lang.Type.isFunction(selector)){ return this.filter(selector).length > 0; }; return !!selector && qx.bom.Selector.matches(selector, this).length > 0; }, /** * Reduce the set of matched elements to a single element. * * @attach {qxWeb} * @param index {Number} The position of the element in the collection * @return {qxWeb} A new collection containing one element */ eq : function(index){ return this.slice(index, +index + 1); }, /** * Reduces the collection to the first element. * * @attach {qxWeb} * @return {qxWeb} A new collection containing one element */ getFirst : function(){ return this.slice(0, 1); }, /** * Reduces the collection to the last element. * * @attach {qxWeb} * @return {qxWeb} A new collection containing one element */ getLast : function(){ return this.slice(this.length - 1); }, /** * Gets a collection containing only the elements that have descendants * matching the given selector * * @attach {qxWeb} * @param selector {String} Selector expression * @return {qxWeb} a new collection containing only elements with matching descendants */ has : function(selector){ var found = []; for(var i = 0;i < this.length;i++){ var descendants = qx.bom.Selector.matches(selector, this.eq(i).getContents()); if(descendants.length > 0){ found.push(this[i]); }; }; return qxWeb.$init(found); }, /** * Gets a collection containing the next sibling element of each item in * the current set (ignoring text and comment nodes). * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String?} Optional selector expression * @return {qxWeb} New set containing next siblings */ getNext : function(selector){ var found = this.map(qx.dom.Hierarchy.getNextElementSibling, qx.dom.Hierarchy); if(selector){ found = qx.bom.Selector.matches(selector, found); }; return found; }, /** * Gets a collection containing all following sibling elements of each * item in the current set (ignoring text and comment nodes). * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String?} Optional selector expression * @return {qxWeb} New set containing following siblings */ getNextAll : function(selector){ var ret = qx.module.Traversing.__hierarchyHelper(this, "getNextSiblings", selector); return qxWeb.$init(ret); }, /** * Gets a collection containing the following sibling elements of each * item in the current set (ignoring text and comment nodes) up to but not * including any element that matches the given selector. * * @attach {qxWeb} * @param selector {String?} Optional selector expression * @return {qxWeb} New set containing following siblings */ getNextUntil : function(selector){ var found = []; this.forEach(function(item, index){ var nextSiblings = qx.dom.Hierarchy.getNextSiblings(item); for(var i = 0,l = nextSiblings.length;i < l;i++){ if(qx.bom.Selector.matches(selector, [nextSiblings[i]]).length > 0){ break; }; found.push(nextSiblings[i]); }; }); return qxWeb.$init(found); }, /** * Gets a collection containing the previous sibling element of each item in * the current set (ignoring text and comment nodes). * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String?} Optional selector expression * @return {qxWeb} New set containing previous siblings */ getPrev : function(selector){ var found = this.map(qx.dom.Hierarchy.getPreviousElementSibling, qx.dom.Hierarchy); if(selector){ found = qx.bom.Selector.matches(selector, found); }; return found; }, /** * Gets a collection containing all preceding sibling elements of each * item in the current set (ignoring text and comment nodes). * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String?} Optional selector expression * @return {qxWeb} New set containing preceding siblings */ getPrevAll : function(selector){ var ret = qx.module.Traversing.__hierarchyHelper(this, "getPreviousSiblings", selector); return qxWeb.$init(ret); }, /** * Gets a collection containing the preceding sibling elements of each * item in the current set (ignoring text and comment nodes) up to but not * including any element that matches the given selector. * * @attach {qxWeb} * @param selector {String?} Optional selector expression * @return {qxWeb} New set containing preceding siblings */ getPrevUntil : function(selector){ var found = []; this.forEach(function(item, index){ var previousSiblings = qx.dom.Hierarchy.getPreviousSiblings(item); for(var i = 0,l = previousSiblings.length;i < l;i++){ if(qx.bom.Selector.matches(selector, [previousSiblings[i]]).length > 0){ break; }; found.push(previousSiblings[i]); }; }); return qxWeb.$init(found); }, /** * Gets a collection containing all sibling elements of the items in the * current set. * This set can be filtered with an optional expression that will cause only * elements matching the selector to be collected. * * @attach {qxWeb} * @param selector {String?} Optional selector expression * @return {qxWeb} New set containing sibling elements */ getSiblings : function(selector){ var ret = qx.module.Traversing.__hierarchyHelper(this, "getSiblings", selector); return qxWeb.$init(ret); }, /** * Remove elements from the collection that do not pass the given filter. * This can be either a selector expression or a filter function * * @attach {qxWeb} * @param selector {String|Function} Selector or filter function * @return {qxWeb} Reduced collection */ not : function(selector){ if(qx.lang.Type.isFunction(selector)){ return this.filter(function(item, index, obj){ return !selector(item, index, obj); }); }; var res = qx.bom.Selector.matches(selector, this); return this.filter(function(value){ return res.indexOf(value) === -1; }); }, /** * Gets a new collection containing the offset parent of each item in the * current set. * * @attach {qxWeb} * @return {qxWeb} New collection containing offset parents */ getOffsetParent : function(){ return this.map(qx.bom.element.Location.getOffsetParent); }, /** * Whether the first element in the collection is inserted into * the document for which it was created. * * @return {Boolean} <code>true</code> when the element is inserted * into the document. */ isRendered : function(){ if(!this[0]){ return false; }; return qx.dom.Hierarchy.isRendered(this[0]); }, /** * Checks if the given object is a DOM element * * @attachStatic{qxWeb} * @param element {Object} Object to check * @return {Boolean} <code>true</code> if the object is a DOM element */ isElement : function(element){ return qx.dom.Node.isElement(element); }, /** * Checks if the given object is a DOM node * * @attachStatic{qxWeb} * @param node {Object} Object to check * @return {Boolean} <code>true</code> if the object is a DOM node */ isNode : function(node){ return qx.dom.Node.isNode(node); }, /** * Checks if the given object is a DOM document object * * @attachStatic{qxWeb} * @param node {Object} Object to check * @return {Boolean} <code>true</code> if the object is a DOM document */ isDocument : function(node){ return qx.dom.Node.isDocument(node); }, /** * Returns the DOM2 <code>defaultView</code> (window) for the given node. * * @attachStatic{qxWeb} * @param node {Node|Document|Window} Node to inspect * @return {Window} the <code>defaultView</code> for the given node */ getWindow : function(node){ return qx.dom.Node.getWindow(node); }, /** * Returns the owner document of the given node * * @attachStatic{qxWeb} * @param node {Node } Node to get the document for * @return {Document|null} The document of the given DOM node */ getDocument : function(node){ return qx.dom.Node.getDocument(node); }, /** * Helper function that iterates over a set of items and applies the given * qx.dom.Hierarchy method to each entry, storing the results in a new Array. * Duplicates are removed and the items are filtered if a selector is * provided. * * @attach{qxWeb} * @param collection {Array} Collection to iterate over (any Array-like object) * @param method {String} Name of the qx.dom.Hierarchy method to apply * @param selector {String?} Optional selector that elements to be included * must match * @return {Array} Result array * @internal */ __hierarchyHelper : function(collection, method, selector){ // Iterate ourself, as we want to directly combine the result var all = []; var Hierarchy = qx.dom.Hierarchy; for(var i = 0,l = collection.length;i < l;i++){ all.push.apply(all, Hierarchy[method](collection[i])); }; // Remove duplicates var ret = qx.lang.Array.unique(all); // Post reduce result by selector if(selector){ ret = qx.bom.Selector.matches(selector, ret); }; return ret; } }, defer : function(statics){ qxWeb.$attach({ "add" : statics.add, "getChildren" : statics.getChildren, "forEach" : statics.forEach, "getParents" : statics.getParents, "getAncestors" : statics.getAncestors, "getAncestorsUntil" : statics.getAncestorsUntil, "__getAncestors" : statics.__getAncestors, "getClosest" : statics.getClosest, "find" : statics.find, "getContents" : statics.getContents, "is" : statics.is, "eq" : statics.eq, "getFirst" : statics.getFirst, "getLast" : statics.getLast, "has" : statics.has, "getNext" : statics.getNext, "getNextAll" : statics.getNextAll, "getNextUntil" : statics.getNextUntil, "getPrev" : statics.getPrev, "getPrevAll" : statics.getPrevAll, "getPrevUntil" : statics.getPrevUntil, "getSiblings" : statics.getSiblings, "not" : statics.not, "getOffsetParent" : statics.getOffsetParent, "isRendered" : statics.isRendered }); qxWeb.$attachStatic({ "isElement" : statics.isElement, "isNode" : statics.isNode, "isDocument" : statics.isDocument, "getDocument" : statics.getDocument, "getWindow" : statics.getWindow }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2011-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) * Daniel Wagner (danielwagner) ************************************************************************ */ /** * Attribute/Property handling for DOM elements. */ qx.Bootstrap.define("qx.module.Attribute", { statics : { /** * Returns the HTML content of the first item in the collection * @attach {qxWeb} * @return {String|null} HTML content or null if the collection is empty */ getHtml : function(){ if(this[0]){ return qx.bom.element.Attribute.get(this[0], "html"); }; return null; }, /** * Sets the HTML content of each item in the collection * * @attach {qxWeb} * @param html {String} HTML string * @return {qxWeb} The collection for chaining */ setHtml : function(html){ for(var i = 0;i < this.length;i++){ qx.bom.element.Attribute.set(this[i], "html", html); }; return this; }, /** * Sets an HTML attribute on each item in the collection * * @attach {qxWeb} * @param name {String} Attribute name * @param value {var} Attribute value * @return {qxWeb} The collection for chaining */ setAttribute : function(name, value){ for(var i = 0;i < this.length;i++){ qx.bom.element.Attribute.set(this[i], name, value); }; return this; }, /** * Returns the value of the given attribute for the first item in the * collection. * * @attach {qxWeb} * @param name {String} Attribute name * @return {var} Attribute value */ getAttribute : function(name){ if(this[0]){ return qx.bom.element.Attribute.get(this[0], name); }; return null; }, /** * Removes the given attribute from all elements in the collection * * @attach {qxWeb} * @param name {String} Attribute name * @return {qxWeb} The collection for chaining */ removeAttribute : function(name){ for(var i = 0;i < this.length;i++){ qx.bom.element.Attribute.set(this[i], name, null); }; return this; }, /** * Sets multiple attributes for each item in the collection. * * @attach {qxWeb} * @param attributes {Map} A map of attribute name/value pairs * @return {qxWeb} The collection for chaining */ setAttributes : function(attributes){ for(var name in attributes){ this.setAttribute(name, attributes[name]); }; return this; }, /** * Returns the values of multiple attributes for the first item in the collection * * @attach {qxWeb} * @param names {String[]} List of attribute names * @return {Map} Map of attribute name/value pairs */ getAttributes : function(names){ var attributes = { }; for(var i = 0;i < names.length;i++){ attributes[names[i]] = this.getAttribute(names[i]); }; return attributes; }, /** * Removes multiple attributes from each item in the collection. * * @attach {qxWeb} * @param attributes {String[]} List of attribute names * @return {qxWeb} The collection for chaining */ removeAttributes : function(attributes){ for(var i = 0,l = attributes.length;i < l;i++){ this.removeAttribute(attributes[i]); }; return this; }, /** * Sets a property on each item in the collection * * @attach {qxWeb} * @param name {String} Property name * @param value {var} Property value * @return {qxWeb} The collection for chaining */ setProperty : function(name, value){ for(var i = 0;i < this.length;i++){ this[i][name] = value; }; return this; }, /** * Returns the value of the given property for the first item in the * collection * * @attach {qxWeb} * @param name {String} Property name * @return {var} Property value */ getProperty : function(name){ if(this[0]){ return this[0][name]; }; return null; }, /** * Sets multiple properties for each item in the collection. * * @attach {qxWeb} * @param properties {Map} A map of property name/value pairs * @return {qxWeb} The collection for chaining */ setProperties : function(properties){ for(var name in properties){ this.setProperty(name, properties[name]); }; return this; }, /** * Returns the values of multiple properties for the first item in the collection * * @attach {qxWeb} * @param names {String[]} List of property names * @return {Map} Map of property name/value pairs */ getProperties : function(names){ var properties = { }; for(var i = 0;i < names.length;i++){ properties[names[i]] = this.getProperty(names[i]); }; return properties; }, /** * Returns the currently configured value for the first item in the collection. * Works with simple input fields as well as with select boxes or option * elements. Returns an array for select boxes with multi selection. In all * other cases, a string is returned. * * @attach {qxWeb} * @return {String|Array} */ getValue : function(){ if(this[0]){ return qx.bom.Input.getValue(this[0]); }; return null; }, /** * Applies the given value to each element in the collection. * Normally the value is given as a string/number value and applied to the * field content (textfield, textarea) or used to detect whether the field * is checked (checkbox, radiobutton). * Supports array values for selectboxes (multiple selection) and checkboxes * or radiobuttons (for convenience). * Please note: To modify the value attribute of a checkbox or radiobutton * use @link{#set} instead. * * @attach {qxWeb} * @param value {String|Number|Array} The value to apply * @return {qxWeb} The collection for chaining */ setValue : function(value){ for(var i = 0,l = this.length;i < l;i++){ qx.bom.Input.setValue(this[i], value); }; return this; } }, defer : function(statics){ qxWeb.$attach({ "getHtml" : statics.getHtml, "setHtml" : statics.setHtml, "getAttribute" : statics.getAttribute, "setAttribute" : statics.setAttribute, "removeAttribute" : statics.removeAttribute, "getAttributes" : statics.getAttributes, "setAttributes" : statics.setAttributes, "removeAttributes" : statics.removeAttributes, "getProperty" : statics.getProperty, "setProperty" : statics.setProperty, "getProperties" : statics.getProperties, "setProperties" : statics.setProperties, "getValue" : statics.getValue, "setValue" : statics.setValue }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ====================================================================== This class contains code based on the following work: * jQuery http://jquery.com Version 1.3.1 Copyright: 2009 John Resig License: MIT: http://www.opensource.org/licenses/mit-license.php ************************************************************************ */ /* ************************************************************************ #require(qx.lang.Array#contains) ************************************************************************ */ /** * Cross browser abstractions to work with input elements. */ qx.Bootstrap.define("qx.bom.Input", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** {Map} Internal data structures with all supported input types */ __types : { text : 1, textarea : 1, select : 1, checkbox : 1, radio : 1, password : 1, hidden : 1, submit : 1, image : 1, file : 1, search : 1, reset : 1, button : 1 }, /** * Creates an DOM input/textarea/select element. * * Attributes may be given directly with this call. This is critical * for some attributes e.g. name, type, ... in many clients. * * Note: <code>select</code> and <code>textarea</code> elements are created * using the identically named <code>type</code>. * * @param type {String} Any valid type for HTML, <code>select</code> * and <code>textarea</code> * @param attributes {Map} Map of attributes to apply * @param win {Window} Window to create the element for * @return {Element} The created input node */ create : function(type, attributes, win){ { }; // Work on a copy to not modify given attributes map var attributes = attributes ? qx.lang.Object.clone(attributes) : { }; var tag; if(type === "textarea" || type === "select"){ tag = type; } else { tag = "input"; attributes.type = type; }; return qx.dom.Element.create(tag, attributes, win); }, /** * Applies the given value to the element. * * Normally the value is given as a string/number value and applied * to the field content (textfield, textarea) or used to * detect whether the field is checked (checkbox, radiobutton). * * Supports array values for selectboxes (multiple-selection) * and checkboxes or radiobuttons (for convenience). * * Please note: To modify the value attribute of a checkbox or * radiobutton use {@link qx.bom.element.Attribute#set} instead. * * @param element {Element} element to update * @param value {String|Number|Array} the value to apply */ setValue : function(element, value){ var tag = element.nodeName.toLowerCase(); var type = element.type; var Array = qx.lang.Array; var Type = qx.lang.Type; if(typeof value === "number"){ value += ""; }; if((type === "checkbox" || type === "radio")){ if(Type.isArray(value)){ element.checked = Array.contains(value, element.value); } else { element.checked = element.value == value; }; } else if(tag === "select"){ var isArray = Type.isArray(value); var options = element.options; var subel,subval; for(var i = 0,l = options.length;i < l;i++){ subel = options[i]; subval = subel.getAttribute("value"); if(subval == null){ subval = subel.text; }; subel.selected = isArray ? Array.contains(value, subval) : value == subval; }; if(isArray && value.length == 0){ element.selectedIndex = -1; }; } else if((type === "text" || type === "textarea") && (qx.core.Environment.get("engine.name") == "mshtml")){ // These flags are required to detect self-made property-change // events during value modification. They are used by the Input // event handler to filter events. element.$$inValueSet = true; element.value = value; element.$$inValueSet = null; } else { element.value = value; };; }, /** * Returns the currently configured value. * * Works with simple input fields as well as with * select boxes or option elements. * * Returns an array in cases of multi-selection in * select boxes but in all other cases a string. * * @param element {Element} DOM element to query * @return {String|Array} The value of the given element */ getValue : function(element){ var tag = element.nodeName.toLowerCase(); if(tag === "option"){ return (element.attributes.value || { }).specified ? element.value : element.text; }; if(tag === "select"){ var index = element.selectedIndex; // Nothing was selected if(index < 0){ return null; }; var values = []; var options = element.options; var one = element.type == "select-one"; var clazz = qx.bom.Input; var value; // Loop through all the selected options for(var i = one ? index : 0,max = one ? index + 1 : options.length;i < max;i++){ var option = options[i]; if(option.selected){ // Get the specifc value for the option value = clazz.getValue(option); // We don't need an array for one selects if(one){ return value; }; // Multi-Selects return an array values.push(value); }; }; return values; } else { return (element.value || "").replace(/\r/g, ""); }; }, /** * Sets the text wrap behaviour of a text area element. * This property uses the attribute "wrap" respectively * the style property "whiteSpace" * * @signature function(element, wrap) * @param element {Element} DOM element to modify * @param wrap {Boolean} Whether to turn text wrap on or off. */ setWrap : qx.core.Environment.select("engine.name", { "mshtml" : function(element, wrap){ var wrapValue = wrap ? "soft" : "off"; // Explicitly set overflow-y CSS property to auto when wrapped, // allowing the vertical scroll-bar to appear if necessary var styleValue = wrap ? "auto" : ""; element.wrap = wrapValue; element.style.overflowY = styleValue; }, "gecko|webkit" : function(element, wrap){ var wrapValue = wrap ? "soft" : "off"; var styleValue = wrap ? "" : "auto"; element.setAttribute("wrap", wrapValue); element.style.overflow = styleValue; }, "default" : function(element, wrap){ element.style.whiteSpace = wrap ? "normal" : "nowrap"; } }) } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2011-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #ignore(qx.bom.element.AnimationJs) ************************************************************************ */ /** * DOM manipulation module */ qx.Bootstrap.define("qx.module.Manipulating", { statics : { /** * Creates a new collection from the given argument. This can either be an * HTML string, a single DOM element or an array of elements * * @attachStatic{qxWeb} * @param html {String|Element[]} HTML string or DOM element(s) * @return {qxWeb} Collection of elements */ create : function(html){ return qxWeb.$init(qx.bom.Html.clean([html])); }, /** * Clones the items in the current collection and returns them in a new set. * Event listeners can also be cloned. * * @attach{qxWeb} * @param events {Boolean} clone event listeners. Default: <pre>false</pre> * @return {qxWeb} New collection with clones */ clone : function(events){ var clones = []; for(var i = 0;i < this.length;i++){ clones[i] = this[i].cloneNode(true); }; if(events === true && this.copyEventsTo){ this.copyEventsTo(clones); }; return qxWeb(clones); }, /** * Appends content to each element in the current set. Accepts an HTML string, * a single DOM element or an array of elements * * @attach{qxWeb} * @param html {String|Element[]} HTML string or DOM element(s) to append * @return {qxWeb} The collection for chaining */ append : function(html){ var arr = qx.bom.Html.clean([html]); var children = qxWeb.$init(arr); for(var i = 0,l = this.length;i < l;i++){ for(var j = 0,m = children.length;j < m;j++){ if(i == 0){ // first parent: move the target node(s) qx.dom.Element.insertEnd(children[j], this[i]); } else { qx.dom.Element.insertEnd(children.eq(j).clone(true)[0], this[i]); }; }; }; return this; }, /** * Appends all items in the collection to the specified parents. If multiple * parents are given, the items will be moved to the first parent, while * clones of the items will be appended to subsequent parents. * * @attach{qxWeb} * @param parent {String|Element[]} Parent selector expression or list of * parent elements * @return {qxWeb} The collection for chaining */ appendTo : function(parent){ parent = qx.module.Manipulating.__getElementArray(parent); for(var i = 0,l = parent.length;i < l;i++){ for(var j = 0,m = this.length;j < m;j++){ if(i == 0){ // first parent: move the target node(s) qx.dom.Element.insertEnd(this[j], parent[i]); } else { // further parents: clone the target node(s) qx.dom.Element.insertEnd(this.eq(j).clone(true)[0], parent[i]); }; }; }; return this; }, /** * Inserts the current collection before each target item. The collection * items are moved before the first target. For subsequent targets, * clones of the collection items are created and inserted. * * @attach{qxWeb} * @param target {String|Element} Selector expression or DOM element * @return {qxWeb} The collection for chaining */ insertBefore : function(target){ target = qx.module.Manipulating.__getElementArray(target); for(var i = 0,l = target.length;i < l;i++){ for(var j = 0,m = this.length;j < m;j++){ if(i == 0){ // first target: move the target node(s) qx.dom.Element.insertBefore(this[j], target[i]); } else { // further targets: clone the target node(s) qx.dom.Element.insertBefore(this.eq(j).clone(true)[0], target[i]); }; }; }; return this; }, /** * Inserts the current collection after each target item. The collection * items are moved after the first target. For subsequent targets, * clones of the collection items are created and inserted. * * @attach{qxWeb} * @param target {String|Element} Selector expression or DOM element * @return {qxWeb} The collection for chaining */ insertAfter : function(target){ target = qx.module.Manipulating.__getElementArray(target); for(var i = 0,l = target.length;i < l;i++){ for(var j = this.length - 1;j >= 0;j--){ if(i == 0){ // first target: move the target node(s) qx.dom.Element.insertAfter(this[j], target[i]); } else { // further targets: clone the target node(s) qx.dom.Element.insertAfter(this.eq(j).clone(true)[0], target[i]); }; }; }; return this; }, /** * Returns an array from a selector expression or a single element * * @attach{qxWeb} * @param arg {String|Element} Selector expression or DOM element * @return {Element[]} Array of elements * @internal */ __getElementArray : function(arg){ if(!qx.lang.Type.isArray(arg)){ var fromSelector = qxWeb(arg); arg = fromSelector.length > 0 ? fromSelector : [arg]; }; return arg; }, /** * Wraps each element in the collection in a copy of an HTML structure. * Elements will be appended to the deepest nested element in the structure * as determined by a depth-first search. * * @attach{qxWeb} * @param wrapper {var} Selector expression, HTML string, DOM element or * list of DOM elements * @return {qxWeb} The collection for chaining */ wrap : function(wrapper){ var wrapper = qx.module.Manipulating.__getCollectionFromArgument(wrapper); if(wrapper.length == 0 || !qx.dom.Node.isElement(wrapper[0])){ return this; }; for(var i = 0,l = this.length;i < l;i++){ var clonedwrapper = wrapper.eq(0).clone(true); qx.dom.Element.insertAfter(clonedwrapper[0], this[i]); var innermost = qx.module.Manipulating.__getInnermostElement(clonedwrapper[0]); qx.dom.Element.insertEnd(this[i], innermost); }; return this; }, /** * Creates a new collection from the given argument * @param arg {var} Selector expression, HTML string, DOM element or list of * DOM elements * @return {qxWeb} Collection * @internal */ __getCollectionFromArgument : function(arg){ var coll; // Collection/array of DOM elements if(qx.lang.Type.isArray(arg)){ coll = qxWeb(arg); } else { var arr = qx.bom.Html.clean([arg]); if(arr.length > 0 && qx.dom.Node.isElement(arr[0])){ coll = qxWeb(arr); } else { coll = qxWeb(arg); }; }; return coll; }, /** * Returns the innermost element of a DOM tree as determined by a simple * depth-first search. * * @param element {Element} Root element * @return {Element} innermost element * @internal */ __getInnermostElement : function(element){ if(element.childNodes.length == 0){ return element; }; for(var i = 0,l = element.childNodes.length;i < l;i++){ if(element.childNodes[i].nodeType === 1){ return this.__getInnermostElement(element.childNodes[i]); }; }; return element; }, /** * Removes each element in the current collection from the DOM * * @attach{qxWeb} * @return {qxWeb} The collection for chaining */ remove : function(){ for(var i = 0;i < this.length;i++){ qx.dom.Element.remove(this[i]); }; return this; }, /** * Removes all content from the elements in the collection * * @attach{qxWeb} * @return {qxWeb} The collection for chaining */ empty : function(){ for(var i = 0;i < this.length;i++){ this[i].innerHTML = ""; }; return this; }, /** * Inserts content before each element in the collection. This can either * be an HTML string, an array of HTML strings, a single DOM element or an * array of elements. * * @attach{qxWeb} * @param args {String[]|Element[]} HTML string(s) or DOM element(s) * @return {qxWeb} The collection for chaining */ before : function(args){ if(!qx.lang.Type.isArray(args)){ args = [args]; }; var fragment = document.createDocumentFragment(); qx.bom.Html.clean(args, document, fragment); this.forEach(function(item, index){ var kids = qx.lang.Array.cast(fragment.childNodes, Array); for(var i = 0,l = kids.length;i < l;i++){ var child; if(index < this.length - 1){ child = kids[i].cloneNode(true); } else { child = kids[i]; }; item.parentNode.insertBefore(child, item); }; }, this); return this; }, /** * Inserts content after each element in the collection. This can either * be an HTML string, an array of HTML strings, a single DOM element or an * array of elements. * * @attach{qxWeb} * @param args {String[]|Element[]} HTML string(s) or DOM element(s) * @return {qxWeb} The collection for chaining */ after : function(args){ if(!qx.lang.Type.isArray(args)){ args = [args]; }; var fragment = document.createDocumentFragment(); qx.bom.Html.clean(args, document, fragment); this.forEach(function(item, index){ var kids = qx.lang.Array.cast(fragment.childNodes, Array); for(var i = kids.length - 1;i >= 0;i--){ var child; if(index < this.length - 1){ child = kids[i].cloneNode(true); } else { child = kids[i]; }; item.parentNode.insertBefore(child, item.nextSibling); }; }, this); return this; }, /** * Returns the left scroll position of the first element in the collection. * * @attach{qxWeb} * @return {Number} Current left scroll position */ getScrollLeft : function(){ var obj = this[0]; if(!obj){ return null; }; var Node = qx.dom.Node; if(Node.isWindow(obj) || Node.isDocument(obj)){ return qx.bom.Viewport.getScrollLeft(); }; return obj.scrollLeft; }, /** * Returns the top scroll position of the first element in the collection. * * @attach{qxWeb} * @return {Number} Current top scroll position */ getScrollTop : function(){ var obj = this[0]; if(!obj){ return null; }; var Node = qx.dom.Node; if(Node.isWindow(obj) || Node.isDocument(obj)){ return qx.bom.Viewport.getScrollTop(); }; return obj.scrollTop; }, /** Default animation descriptions for animated scrolling **/ _animationDescription : { scrollLeft : { duration : 700, timing : "ease-in", keep : 100, keyFrames : { '0' : { }, '100' : { scrollLeft : 1 } } }, scrollTop : { duration : 700, timing : "ease-in", keep : 100, keyFrames : { '0' : { }, '100' : { scrollTop : 1 } } } }, /** * Performs animated scrolling * * @param property {String} Element property to animate: <code>scrollLeft</code> * or <code>scrollTop</code> * @param value {Number} Final scroll position * @param duration {Number} The animation's duration in ms * @return {q} The collection for chaining. */ __animateScroll : function(property, value, duration){ var desc = qx.lang.Object.clone(qx.module.Manipulating._animationDescription[property], true); desc.keyFrames[100][property] = value; return this.animate(desc, duration); }, /** * Scrolls the elements of the collection to the given coordinate. * * @attach{qxWeb} * @param value {Number} Left scroll position * @param duration {Number?} Optional: Duration in ms for animated scrolling * @return {qxWeb} The collection for chaining */ setScrollLeft : function(value, duration){ var Node = qx.dom.Node; if(duration && qx.bom.element && qx.bom.element.AnimationJs){ qx.module.Manipulating.__animateScroll.bind(this, "scrollLeft", value, duration)(); }; for(var i = 0,l = this.length,obj;i < l;i++){ obj = this[i]; if(Node.isElement(obj)){ if(!(duration && qx.bom.element && qx.bom.element.AnimationJs)){ obj.scrollLeft = value; }; } else if(Node.isWindow(obj)){ obj.scrollTo(value, this.getScrollTop(obj)); } else if(Node.isDocument(obj)){ Node.getWindow(obj).scrollTo(value, this.getScrollTop(obj)); };; }; return this; }, /** * Scrolls the elements of the collection to the given coordinate. * * @attach{qxWeb} * @param value {Number} Top scroll position * @param duration {Number?} Optional: Duration in ms for animated scrolling * @return {qxWeb} The collection for chaining */ setScrollTop : function(value, duration){ var Node = qx.dom.Node; if(duration && qx.bom.element && qx.bom.element.AnimationJs){ qx.module.Manipulating.__animateScroll.bind(this, "scrollTop", value, duration)(); }; for(var i = 0,l = this.length,obj;i < l;i++){ obj = this[i]; if(Node.isElement(obj)){ if(!(duration && qx.bom.element && qx.bom.element.AnimationJs)){ obj.scrollTop = value; }; } else if(Node.isWindow(obj)){ obj.scrollTo(this.getScrollLeft(obj), value); } else if(Node.isDocument(obj)){ Node.getWindow(obj).scrollTo(this.getScrollLeft(obj), value); };; }; return this; }, /** * Focuses the first element in the collection * * @attach{qxWeb} * @return {qxWeb} The collection for chaining */ focus : function(){ try{ this[0].focus(); } catch(ex) { }; return this; }, /** * Blurs each element in the collection * * @attach{qxWeb} * @return {qxWeb} The collection for chaining */ blur : function(){ this.forEach(function(item, index){ try{ item.blur(); } catch(ex) { }; }); return this; } }, defer : function(statics){ qxWeb.$attachStatic({ "create" : statics.create }); qxWeb.$attach({ "append" : statics.append, "appendTo" : statics.appendTo, "remove" : statics.remove, "empty" : statics.empty, "before" : statics.before, "insertBefore" : statics.insertBefore, "after" : statics.after, "insertAfter" : statics.insertAfter, "wrap" : statics.wrap, "clone" : statics.clone, "getScrollLeft" : statics.getScrollLeft, "setScrollLeft" : statics.setScrollLeft, "getScrollTop" : statics.getScrollTop, "setScrollTop" : statics.setScrollTop, "focus" : statics.focus, "blur" : statics.blur }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2009 Sebastian Werner, http://sebastian-werner.net License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) ====================================================================== This class contains code based on the following work: * jQuery http://jquery.com Version 1.3.1 Copyright: 2009 John Resig License: MIT: http://www.opensource.org/licenses/mit-license.php ************************************************************************ */ /* ************************************************************************ #ignore(qxWeb) ************************************************************************ */ /** * This class is mainly a convenience wrapper for DOM elements to * qooxdoo's event system. */ qx.Bootstrap.define("qx.bom.Html", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** * Helper method for XHTML replacement. * * @param all {String} Complete string * @param front {String} Front of the match * @param tag {String} Tag name * @return {String} XHTML corrected tag */ __fixNonDirectlyClosableHelper : function(all, front, tag){ return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ? all : front + "></" + tag + ">"; }, /** {Map} Contains wrap fragments for specific HTML matches */ __convertMap : { opt : [1, "<select multiple='multiple'>", "</select>"], // option or optgroup leg : [1, "<fieldset>", "</fieldset>"], table : [1, "<table>", "</table>"], tr : [2, "<table><tbody>", "</tbody></table>"], td : [3, "<table><tbody><tr>", "</tr></tbody></table>"], col : [2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"], def : qx.core.Environment.select("engine.name", { "mshtml" : [1, "div<div>", "</div>"], "default" : null }) }, /** * Translates a HTML string into an array of elements. * * @param html {String} HTML string * @param context {Document} Context document in which (helper) elements should be created * @return {Array} List of resulting elements */ __convertHtmlString : function(html, context){ var div = context.createElement("div"); // Fix "XHTML"-style tags in all browsers // Replaces tags which are not allowed to be directly closed like // <code>div</code> or <code>p</code>. They are patched to use an // open and close tag instead e.g. <p> => <p></p> html = html.replace(/(<(\w+)[^>]*?)\/>/g, this.__fixNonDirectlyClosableHelper); // Trim whitespace, otherwise indexOf won't work as expected var tags = html.replace(/^\s+/, "").substring(0, 5).toLowerCase(); // Auto-wrap content into required DOM structure var wrap,map = this.__convertMap; if(!tags.indexOf("<opt")){ wrap = map.opt; } else if(!tags.indexOf("<leg")){ wrap = map.leg; } else if(tags.match(/^<(thead|tbody|tfoot|colg|cap)/)){ wrap = map.table; } else if(!tags.indexOf("<tr")){ wrap = map.tr; } else if(!tags.indexOf("<td") || !tags.indexOf("<th")){ wrap = map.td; } else if(!tags.indexOf("<col")){ wrap = map.col; } else { wrap = map.def; };;;;; // Omit string concat when no wrapping is needed if(wrap){ // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + html + wrap[2]; // Move to the right depth var depth = wrap[0]; while(depth--){ div = div.lastChild; }; } else { div.innerHTML = html; }; // Fix IE specific bugs if((qx.core.Environment.get("engine.name") == "mshtml")){ // Remove IE's autoinserted <tbody> from table fragments // String was a <table>, *may* have spurious <tbody> var hasBody = /<tbody/i.test(html); // String was a bare <thead> or <tfoot> var tbody = !tags.indexOf("<table") && !hasBody ? div.firstChild && div.firstChild.childNodes : wrap[1] == "<table>" && !hasBody ? div.childNodes : []; for(var j = tbody.length - 1;j >= 0;--j){ if(tbody[j].tagName.toLowerCase() === "tbody" && !tbody[j].childNodes.length){ tbody[j].parentNode.removeChild(tbody[j]); }; }; // IE completely kills leading whitespace when innerHTML is used if(/^\s/.test(html)){ div.insertBefore(context.createTextNode(html.match(/^\s*/)[0]), div.firstChild); }; }; return qx.lang.Array.fromCollection(div.childNodes); }, /** * Cleans-up the given HTML and append it to a fragment * * When no <code>context</code> is given the global document is used to * create new DOM elements. * * When a <code>fragment</code> is given the nodes are appended to this * fragment except the script tags. These are returned in a separate Array. * * Please note: HTML coming from user input must be validated prior * to passing it to this method. HTML is temporarily inserted to the DOM * using <code>innerHTML</code>. As a consequence, scripts included in * attribute event handlers may be executed. * * @param objs {Element[]|String[]} Array of DOM elements or HTML strings * @param context {Document?document} Context in which the elements should be created * @param fragment {Element?null} Document fragment to appends elements to * @return {Element[]} Array of elements (when a fragment is given it only contains script elements) */ clean : function(objs, context, fragment){ context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if(typeof context.createElement === "undefined"){ context = context.ownerDocument || context[0] && context[0].ownerDocument || document; }; // Fast-Path: // If a single string is passed in and it's a single tag // just do a createElement and skip the rest if(!fragment && objs.length === 1 && typeof objs[0] === "string"){ var match = /^<(\w+)\s*\/?>$/.exec(objs[0]); if(match){ return [context.createElement(match[1])]; }; }; // Interate through items in incoming array var obj,ret = []; for(var i = 0,l = objs.length;i < l;i++){ obj = objs[i]; // Convert HTML string into DOM nodes if(typeof obj === "string"){ obj = this.__convertHtmlString(obj, context); }; // Append or merge depending on type if(obj.nodeType){ ret.push(obj); } else if(obj instanceof qx.type.BaseArray || (typeof qxWeb !== "undefined" && obj instanceof qxWeb)){ ret.push.apply(ret, Array.prototype.slice.call(obj, 0)); } else if(obj.toElement){ ret.push(obj.toElement()); } else { ret.push.apply(ret, obj); };; }; // Append to fragment and filter out scripts... or... if(fragment){ var scripts = [],elem; for(var i = 0;ret[i];i++){ elem = ret[i]; if(elem.nodeType == 1 && elem.tagName.toLowerCase() === "script" && (!elem.type || elem.type.toLowerCase() === "text/javascript")){ // Trying to remove the element from DOM if(elem.parentNode){ elem.parentNode.removeChild(ret[i]); }; // Store in script list scripts.push(elem); } else { if(elem.nodeType === 1){ // Recursively search for scripts and append them to the list of elements to process var scriptList = qx.lang.Array.fromCollection(elem.getElementsByTagName("script")); ret.splice.apply(ret, [i + 1, 0].concat(scriptList)); }; // Finally append element to fragment fragment.appendChild(elem); }; }; return scripts; }; // Otherwise return the array of all elements return ret; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Manipulating) #require(qx.module.Css) #require(qx.module.Attribute) #require(qx.module.Event) #require(qx.module.Environment) #require(qx.module.Polyfill) #require(qx.module.Traversing) ************************************************************************ */ /** * The module supplies a fallback implementation for placeholders, which is * used on input and textarea elements. If the browser supports native placeholders * the API silently ignores all calls. If not, an element will be created for every * given input element and acts as placeholder. Most modern browsers support * placeholders which makes the fallback only relevant for IE < 10 and FF < 4. * * * <a href="http://dev.w3.org/html5/spec/single-page.html#the-placeholder-attribute">HTML Spec</a> * * * <a href="http://caniuse.com/#feat=input-placeholder">Browser Support</a> */ qx.Bootstrap.define("qx.module.Placeholder", { statics : { /** * String holding the property name which holds the placeholder * element for each input. */ PLACEHOLDER_NAME : "$qx_placeholder", /** * Queries for all input and textarea elements on the page and updates * their placeholder. * @attachStatic{qxWeb, placeholder.update} */ update : function(){ // ignore if native placeholder are supported if(!qxWeb.env.get("css.placeholder")){ qxWeb("input[placeholder], textarea[placeholder]").updatePlaceholder(); }; }, /** * Updates the placeholders for input's and textarea's in the collection. * This includes positioning, styles and DOM positioning. * In case the browser supports native placeholders, this methods simply * does nothing. * * @attach {qxWeb} * @return {qxWeb} The collection for chaining */ updatePlaceholder : function(){ // ignore everything if native placeholder are supported if(!qxWeb.env.get("css.placeholder")){ for(var i = 0;i < this.length;i++){ var item = qxWeb(this[i]); // ignore all not fitting items in the collection var placeholder = item.getAttribute("placeholder"); var tagName = item.getProperty("tagName"); if(!placeholder || (tagName != "TEXTAREA" && tagName != "INPUT")){ continue; }; // create the element if necessary var placeholderEl = item.getProperty(qx.module.Placeholder.PLACEHOLDER_NAME); if(!placeholderEl){ placeholderEl = qx.module.Placeholder.__createPlaceholderElement(item); }; // remove and add handling var itemInBody = item.isRendered(); var placeholderElInBody = placeholderEl.isRendered(); if(itemInBody && !placeholderElInBody){ item.before(placeholderEl); } else if(!itemInBody && placeholderElInBody){ placeholderEl.remove(); return this; }; qx.module.Placeholder.__syncStyles(item); }; }; return this; }, /** * Internal helper method to update the styles for a given input element. * @param item {qxWeb} The input element to update. */ __syncStyles : function(item){ var placeholder = item.getAttribute("placeholder"); var placeholderEl = item.getProperty(qx.module.Placeholder.PLACEHOLDER_NAME); var zIndex = item.getStyle("z-index"); var paddingHor = parseInt(item.getStyle("padding-left")) + 2 * parseInt(item.getStyle("padding-right")); var paddingVer = parseInt(item.getStyle("padding-top")) + 2 * parseInt(item.getStyle("padding-bottom")); placeholderEl.setHtml(placeholder).setStyles({ display : item.getValue() == "" ? "inline" : "none", zIndex : zIndex == "auto" ? 1 : zIndex + 1, textAlign : item.getStyle("text-align"), width : (item.getWidth() - paddingHor - 4) + "px", height : (item.getHeight() - paddingVer - 4) + "px", left : item.getOffset().left + "px", top : item.getOffset().top + "px", fontFamily : item.getStyle("font-family"), fontStyle : item.getStyle("font-style"), fontVariant : item.getStyle("font-variant"), fontWeight : item.getStyle("font-weight"), fontSize : item.getStyle("font-size"), paddingTop : (parseInt(item.getStyle("padding-top")) + 2) + "px", paddingRight : (parseInt(item.getStyle("padding-right")) + 2) + "px", paddingBottom : (parseInt(item.getStyle("padding-bottom")) + 2) + "px", paddingLeft : (parseInt(item.getStyle("padding-left")) + 2) + "px" }); }, /** * Creates a placeholder element based on the given input element. * @param item {qxWeb} The input element. * @return {qxWeb} The placeholder element. */ __createPlaceholderElement : function(item){ // create the label with initial styles var placeholderEl = qxWeb.create("<label>").setStyles({ position : "absolute", color : "#989898", overflow : "hidden", pointerEvents : "none" }); // store the label at the input field item.setProperty(qx.module.Placeholder.PLACEHOLDER_NAME, placeholderEl); // update the placeholders visibility on keyUp item.on("keyup", function(item){ var el = item.getProperty(qx.module.Placeholder.PLACEHOLDER_NAME); el.setStyle("display", item.getValue() == "" ? "inline" : "none"); }.bind(this, item)); // for browsers not supporting pointer events if(!qxWeb.env.get("event.pointer")){ placeholderEl.setStyle("cursor", "text").on("click", function(item){ item.focus(); }.bind(this, item)); }; return placeholderEl; } }, defer : function(statics){ qxWeb.$attachStatic({ "placeholder" : { update : statics.update } }); qxWeb.$attach({ "updatePlaceholder" : statics.updatePlaceholder }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * HTML templating module. This is a wrapper for mustache.js which is a * "framework-agnostic way to render logic-free views". * * Here is a basic example how to use it: * <pre class="javascript"> * var template = "Hi, my name is {{name}}!"; * var view = {name: "qooxdoo"}; * q.template.render(template, view); * // return "Hi, my name is qooxdoo!" * </pre> * * For further details, please visit the mustache.js documentation here: * https://github.com/janl/mustache.js/blob/master/README.md */ qx.Bootstrap.define("qx.module.Template", { statics : { /** * Helper method which provides direct access to templates stored as HTML in * the DOM. The DOM node with the given ID will be treated as a template, * parsed and a new DOM node will be returned containing the parsed data. * Keep in mind that templates can only have one root element. * Additionally, you should not put the template into a regular, hidden * DOM element because the template may not be valid HTML due to the containing * mustache tags. We suggest to put it into a script tag with the type * <code>text/template</code>. * * @attachStatic{qxWeb, template.get} * @param id {String} The id of the HTML template in the DOM. * @param view {Object} The object holding the data to render. * @param partials {Object} Object holding parts of a template. * @return {qxWeb} Collection containing a single DOM element with the parsed * template data. */ get : function(id, view, partials){ var el = qx.bom.Template.get(id, view, partials); return qxWeb.$init([el]); }, /** * Original and only template method of mustache.js. For further * documentation, please visit https://github.com/janl/mustache.js * * @attachStatic{qxWeb, template.render} * @param template {String} The String containing the template. * @param view {Object} The object holding the data to render. * @param partials {Object} Object holding parts of a template. * @return {String} The parsed template. */ render : function(template, view, partials){ return qx.bom.Template.render(template, view, partials); } }, defer : function(statics){ qxWeb.$attachStatic({ "template" : { get : statics.get, render : statics.render } }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ====================================================================== This class contains code based on the following work: * Mustache.js version 0.7.0 Code: https://github.com/janl/mustache.js Copyright: (c) 2009 Chris Wanstrath (Ruby) (c) 2010 Jan Lehnardt (JavaScript) License: MIT: http://www.opensource.org/licenses/mit-license.php ---------------------------------------------------------------------- Copyright (c) 2009 Chris Wanstrath (Ruby) Copyright (c) 2010 Jan Lehnardt (JavaScript) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ************************************************************************ */ /* ************************************************************************ #ignore(module) ************************************************************************ */ /** * The is a template class which can be used for HTML templating. In fact, * this is a wrapper for mustache.js which is a "framework-agnostic way to * render logic-free views". * * Here is a basic example how to use it: * Template: * <pre class="javascript"> * var template = "Hi, my name is {{name}}!"; * var view = {name: "qooxdoo"}; * qx.bom.Template.render(template, view); * // return "Hi, my name is qooxdoo!" * </pre> * * For further details, please visit the mustache.js documentation here: * https://github.com/janl/mustache.js/blob/master/README.md * */ qx.Bootstrap.define("qx.bom.Template", { statics : { /** Contains the mustache.js version. */ version : null, /** * Original and only template method of mustache.js. For further * documentation, please visit https://github.com/janl/mustache.js * * @signature function(template, view, partials) * @param template {String} The String containing the template. * @param view {Object} The object holding the data to render. * @param partials {Object} Object holding parts of a template. * @return {String} The parsed template. */ render : null, /** * Helper method which provides you with a direct access to templates * stored as HTML in the DOM. The DOM node with the given ID will be used * as a template, parsed and a new DOM node will be returned containing the * parsed data. Keep in mind to have only one root DOM element in the the * template. * Additionally, you should not put the template into a regular, hidden * DOM element because the template may not be valid HTML due to the containing * mustache tags. We suggest to put it into a script tag with the type * <code>text/template</code>. * * @param id {String} The id of the HTML template in the DOM. * @param view {Object} The object holding the data to render. * @param partials {Object} Object holding parts of a template. * @return {Element} A DOM element holding the parsed template data. */ get : function(id, view, partials){ // get the content stored in the DOM var template = document.getElementById(id); var inner = template.innerHTML; // apply the view inner = this.render(inner, view, partials); // special case for text only conversion if(inner.search(/<|>/) === -1){ return document.createTextNode(inner); }; // create a helper to convert the string into DOM nodes var helper = qx.dom.Element.create("div"); helper.innerHTML = inner; return helper.children[0]; } } }); (function(){ /** * Below is the original mustache.js code. Snapshot date is mentioned in * the head of this file. * @lint ignoreUndefined(module) */ /*! * mustache.js - Logic-less {{mustache}} templates with JavaScript * http://github.com/janl/mustache.js */ /*global define: false*/ var Mustache; /** * @lint ignoreUndefined(module,define) */ (function(exports){ Mustache = exports; }((function(){ var exports = { }; exports.name = "mustache.js"; exports.version = "0.7.0"; exports.tags = ["{{", "}}"]; exports.Scanner = Scanner; exports.Context = Context; exports.Writer = Writer; var whiteRe = /\s*/; var spaceRe = /\s+/; var nonSpaceRe = /\S/; var eqRe = /\s*=/; var curlyRe = /\s*\}/; var tagRe = /#|\^|\/|>|\{|&|=|!/; // Workaround for https://issues.apache.org/jira/browse/COUCHDB-577 // See https://github.com/janl/mustache.js/issues/189 function testRe(re, string){ return RegExp.prototype.test.call(re, string); }; function isWhitespace(string){ return !testRe(nonSpaceRe, string); }; var isArray = Array.isArray || function(obj){ return Object.prototype.toString.call(obj) === "[object Array]"; }; function escapeRe(string){ return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); }; var entityMap = { "&" : "&amp;", "<" : "&lt;", ">" : "&gt;", '"' : '&quot;', "'" : '&#39;', "/" : '&#x2F;' }; function escapeHtml(string){ return String(string).replace(/[&<>"'\/]/g, function(s){ return entityMap[s]; }); }; // Export the escaping function so that the user may override it. // See https://github.com/janl/mustache.js/issues/244 exports.escape = escapeHtml; function Scanner(string){ this.string = string; this.tail = string; this.pos = 0; }; /** * Returns `true` if the tail is empty (end of string). */ Scanner.prototype.eos = function(){ return this.tail === ""; }; /** * Tries to match the given regular expression at the current position. * Returns the matched text if it can match, the empty string otherwise. */ Scanner.prototype.scan = function(re){ var match = this.tail.match(re); if(match && match.index === 0){ this.tail = this.tail.substring(match[0].length); this.pos += match[0].length; return match[0]; }; return ""; }; /** * Skips all text until the given regular expression can be matched. Returns * the skipped string, which is the entire tail if no match can be made. */ Scanner.prototype.scanUntil = function(re){ var match,pos = this.tail.search(re); switch(pos){case -1: match = this.tail; this.pos += this.tail.length; this.tail = ""; break;case 0: match = ""; break;default: match = this.tail.substring(0, pos); this.tail = this.tail.substring(pos); this.pos += pos;}; return match; }; function Context(view, parent){ this.view = view; this.parent = parent; this.clearCache(); }; Context.make = function(view){ return (view instanceof Context) ? view : new Context(view); }; Context.prototype.clearCache = function(){ this._cache = { }; }; Context.prototype.push = function(view){ return new Context(view, this); }; Context.prototype.lookup = function(name){ var value = this._cache[name]; if(!value){ if(name === "."){ value = this.view; } else { var context = this; while(context){ if(name.indexOf(".") > 0){ var names = name.split("."),i = 0; value = context.view; while(value && i < names.length){ value = value[names[i++]]; }; } else { value = context.view[name]; }; if(value != null){ break; }; context = context.parent; }; }; this._cache[name] = value; }; if(typeof value === "function"){ value = value.call(this.view); }; return value; }; function Writer(){ this.clearCache(); }; Writer.prototype.clearCache = function(){ this._cache = { }; this._partialCache = { }; }; Writer.prototype.compile = function(template, tags){ var fn = this._cache[template]; if(!fn){ var tokens = exports.parse(template, tags); fn = this._cache[template] = this.compileTokens(tokens, template); }; return fn; }; Writer.prototype.compilePartial = function(name, template, tags){ var fn = this.compile(template, tags); this._partialCache[name] = fn; return fn; }; Writer.prototype.compileTokens = function(tokens, template){ var fn = compileTokens(tokens); var self = this; return function(view, partials){ if(partials){ if(typeof partials === "function"){ self._loadPartial = partials; } else { for(var name in partials){ self.compilePartial(name, partials[name]); }; }; }; return fn(self, Context.make(view), template); }; }; Writer.prototype.render = function(template, view, partials){ return this.compile(template)(view, partials); }; Writer.prototype._section = function(name, context, text, callback){ var value = context.lookup(name); switch(typeof value){case "object": if(isArray(value)){ var buffer = ""; for(var i = 0,len = value.length;i < len;++i){ buffer += callback(this, context.push(value[i])); }; return buffer; }; return value ? callback(this, context.push(value)) : "";case "function": var self = this; var scopedRender = function(template){ return self.render(template, context); }; return value.call(context.view, text, scopedRender) || "";default: if(value){ return callback(this, context); };}; return ""; }; Writer.prototype._inverted = function(name, context, callback){ var value = context.lookup(name); // Use JavaScript's definition of falsy. Include empty arrays. // See https://github.com/janl/mustache.js/issues/186 if(!value || (isArray(value) && value.length === 0)){ return callback(this, context); }; return ""; }; Writer.prototype._partial = function(name, context){ if(!(name in this._partialCache) && this._loadPartial){ this.compilePartial(name, this._loadPartial(name)); }; var fn = this._partialCache[name]; return fn ? fn(context) : ""; }; Writer.prototype._name = function(name, context){ var value = context.lookup(name); if(typeof value === "function"){ value = value.call(context.view); }; return (value == null) ? "" : String(value); }; Writer.prototype._escaped = function(name, context){ return exports.escape(this._name(name, context)); }; /** * Calculates the bounds of the section represented by the given `token` in * the original template by drilling down into nested sections to find the * last token that is part of that section. Returns an array of [start, end]. */ function sectionBounds(token){ var start = token[3]; var end = start; var tokens; while((tokens = token[4]) && tokens.length){ token = tokens[tokens.length - 1]; end = token[3]; }; return [start, end]; }; /** * Low-level function that compiles the given `tokens` into a function * that accepts three arguments: a Writer, a Context, and the template. */ function compileTokens(tokens){ var subRenders = { }; function subRender(i, tokens, template){ if(!subRenders[i]){ var fn = compileTokens(tokens); subRenders[i] = function(writer, context){ return fn(writer, context, template); }; }; return subRenders[i]; }; return function(writer, context, template){ var buffer = ""; var token,sectionText; for(var i = 0,len = tokens.length;i < len;++i){ token = tokens[i]; switch(token[0]){case "#": sectionText = template.slice.apply(template, sectionBounds(token)); buffer += writer._section(token[1], context, sectionText, subRender(i, token[4], template)); break;case "^": buffer += writer._inverted(token[1], context, subRender(i, token[4], template)); break;case ">": buffer += writer._partial(token[1], context); break;case "&": buffer += writer._name(token[1], context); break;case "name": buffer += writer._escaped(token[1], context); break;case "text": buffer += token[1]; break;}; }; return buffer; }; }; /** * Forms the given array of `tokens` into a nested tree structure where * tokens that represent a section have a fifth item: an array that contains * all tokens in that section. */ function nestTokens(tokens){ var tree = []; var collector = tree; var sections = []; var token,section; for(var i = 0;i < tokens.length;++i){ token = tokens[i]; switch(token[0]){case "#":case "^": token[4] = []; sections.push(token); collector.push(token); collector = token[4]; break;case "/": if(sections.length === 0){ throw new Error("Unopened section: " + token[1]); }; section = sections.pop(); if(section[1] !== token[1]){ throw new Error("Unclosed section: " + section[1]); }; if(sections.length > 0){ collector = sections[sections.length - 1][4]; } else { collector = tree; }; break;default: collector.push(token);}; }; // Make sure there were no open sections when we're done. section = sections.pop(); if(section){ throw new Error("Unclosed section: " + section[1]); }; return tree; }; /** * Combines the values of consecutive text tokens in the given `tokens` array * to a single token. */ function squashTokens(tokens){ var token,lastToken; for(var i = 0;i < tokens.length;++i){ token = tokens[i]; if(lastToken && lastToken[0] === "text" && token[0] === "text"){ lastToken[1] += token[1]; lastToken[3] = token[3]; tokens.splice(i--, 1); } else { lastToken = token; }; }; }; function escapeTags(tags){ if(tags.length !== 2){ throw new Error("Invalid tags: " + tags.join(" ")); }; return [new RegExp(escapeRe(tags[0]) + "\\s*"), new RegExp("\\s*" + escapeRe(tags[1]))]; }; /** * Breaks up the given `template` string into a tree of token objects. If * `tags` is given here it must be an array with two string values: the * opening and closing tags used in the template (e.g. ["<%", "%>"]). Of * course, the default is to use mustaches (i.e. Mustache.tags). */ exports.parse = function(template, tags){ tags = tags || exports.tags; var tagRes = escapeTags(tags); var scanner = new Scanner(template); var tokens = [],// Buffer to hold the tokens spaces = [],// Indices of whitespace tokens on the current line hasTag = false,// Is there a {{tag}} on the current line? nonSpace = false; // Is there a non-space char on the current line? // Strips all whitespace tokens array for the current line // if there was a {{#tag}} on it and otherwise only space. function stripSpace(){ if(hasTag && !nonSpace){ while(spaces.length){ tokens.splice(spaces.pop(), 1); }; } else { spaces = []; }; hasTag = false; nonSpace = false; }; var start,type,value,chr; while(!scanner.eos()){ start = scanner.pos; value = scanner.scanUntil(tagRes[0]); if(value){ for(var i = 0,len = value.length;i < len;++i){ chr = value.charAt(i); if(isWhitespace(chr)){ spaces.push(tokens.length); } else { nonSpace = true; }; tokens.push(["text", chr, start, start + 1]); start += 1; if(chr === "\n"){ stripSpace(); }; }; }; start = scanner.pos; // Match the opening tag. if(!scanner.scan(tagRes[0])){ break; }; hasTag = true; type = scanner.scan(tagRe) || "name"; // Skip any whitespace between tag and value. scanner.scan(whiteRe); // Extract the tag value. if(type === "="){ value = scanner.scanUntil(eqRe); scanner.scan(eqRe); scanner.scanUntil(tagRes[1]); } else if(type === "{"){ var closeRe = new RegExp("\\s*" + escapeRe("}" + tags[1])); value = scanner.scanUntil(closeRe); scanner.scan(curlyRe); scanner.scanUntil(tagRes[1]); type = "&"; } else { value = scanner.scanUntil(tagRes[1]); }; // Match the closing tag. if(!scanner.scan(tagRes[1])){ throw new Error("Unclosed tag at " + scanner.pos); }; tokens.push([type, value, start, scanner.pos]); if(type === "name" || type === "{" || type === "&"){ nonSpace = true; }; // Set the tags for the next time around. if(type === "="){ tags = value.split(spaceRe); tagRes = escapeTags(tags); }; }; squashTokens(tokens); return nestTokens(tokens); }; // The high-level clearCache, compile, compilePartial, and render functions // use this default writer. var _writer = new Writer(); /** * Clears all cached templates and partials in the default writer. */ exports.clearCache = function(){ return _writer.clearCache(); }; /** * Compiles the given `template` to a reusable function using the default * writer. */ exports.compile = function(template, tags){ return _writer.compile(template, tags); }; /** * Compiles the partial with the given `name` and `template` to a reusable * function using the default writer. */ exports.compilePartial = function(name, template, tags){ return _writer.compilePartial(name, template, tags); }; /** * Compiles the given array of tokens (the output of a parse) to a reusable * function using the default writer. */ exports.compileTokens = function(tokens, template){ return _writer.compileTokens(tokens, template); }; /** * Renders the `template` with the given `view` and `partials` using the * default writer. */ exports.render = function(template, view, partials){ return _writer.render(template, view, partials); }; // This is here for backwards compatibility with 0.4.x. exports.to_html = function(template, view, partials, send){ var result = exports.render(template, view, partials); if(typeof send === "function"){ send(result); } else { return result; }; }; return exports; }()))); /** * Above is the original mustache code. */ // EXPOSE qooxdoo variant qx.bom.Template.version = Mustache.version; qx.bom.Template.render = Mustache.render; })(); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Event) ************************************************************************ */ /** * Orientation handler which is responsible for registering and unregistering a * {@link qx.event.handler.OrientationCore} handler for each given element. */ qx.Bootstrap.define("qx.module.event.OrientationHandler", { statics : { /** * List of events that require an orientation handler * @type {Array} */ TYPES : ["orientationchange"], /** * Creates an orientation handler for the given window when an * orientationchange event listener is attached to it * * @param element {Window} DOM Window */ register : function(element){ if(!qx.dom.Node.isWindow(element)){ throw new Error("The 'orientationchange' event is only available on window objects!"); }; if(!element.__orientationHandler){ if(!element.__emitter){ element.__emitter = new qx.event.Emitter(); }; element.__orientationHandler = new qx.event.handler.OrientationCore(element, element.__emitter); }; }, /** * Removes the orientation event handler from the element if there are no more * orientationchange event listeners attached to it * @param element {Element} DOM element */ unregister : function(element){ if(element.__orientationHandler){ if(!element.__emitter){ element.__orientationHandler = null; } else { var hasListener = false; var listeners = element.__emitter.getListeners(); qx.module.event.OrientationHandler.TYPES.forEach(function(type){ if(type in listeners && listeners[type].length > 0){ hasListener = true; }; }); if(!hasListener){ element.__orientationHandler = null; }; }; }; } }, defer : function(statics){ qxWeb.$registerEventHook(statics.TYPES, statics.register, statics.unregister); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Tino Butz (tbtz) * Daniel Wagner (danielwagner) ====================================================================== This class contains code based on the following work: * Unify Project Homepage: http://unify-project.org Copyright: 2009-2010 Deutsche Telekom AG, Germany, http://telekom.com License: MIT: http://www.opensource.org/licenses/mit-license.php ************************************************************************ */ /** * Listens for native orientation change events */ qx.Bootstrap.define("qx.event.handler.OrientationCore", { extend : Object, /** * * @param targetWindow {Window} DOM window object * @param emitter {qx.event.Emitter} Event emitter object */ construct : function(targetWindow, emitter){ this._window = targetWindow || window; this.__emitter = emitter; this._initObserver(); }, members : { __emitter : null, _window : null, _currentOrientation : null, __onNativeWrapper : null, __nativeEventType : null, /* --------------------------------------------------------------------------- OBSERVER INIT --------------------------------------------------------------------------- */ /** * Initializes the native orientation change event listeners. */ _initObserver : function(){ this.__onNativeWrapper = qx.lang.Function.listener(this._onNative, this); // Handle orientation change event for Android devices by the resize event. // See http://stackoverflow.com/questions/1649086/detect-rotation-of-android-phone-in-the-browser-with-javascript // for more information. this.__nativeEventType = qx.bom.Event.supportsEvent(this._window, "orientationchange") ? "orientationchange" : "resize"; qx.bom.Event.addNativeListener(this._window, this.__nativeEventType, this.__onNativeWrapper); }, /* --------------------------------------------------------------------------- OBSERVER STOP --------------------------------------------------------------------------- */ /** * Disconnects the native orientation change event listeners. */ _stopObserver : function(){ qx.bom.Event.removeNativeListener(this._window, this.__nativeEventType, this.__onNativeWrapper); }, /* --------------------------------------------------------------------------- NATIVE EVENT OBSERVERS --------------------------------------------------------------------------- */ /** * Handler for the native orientation change event. * * @signature function(domEvent) * @param domEvent {Event} The touch event from the browser. */ _onNative : function(domEvent){ var orientation = qx.bom.Viewport.getOrientation(); if(this._currentOrientation != orientation){ this._currentOrientation = orientation; var mode = qx.bom.Viewport.isLandscape() ? "landscape" : "portrait"; domEvent._orientation = orientation; domEvent._mode = mode; if(this.__emitter){ this.__emitter.emit("orientationchange", domEvent); }; }; } }, /* ***************************************************************************** DESTRUCTOR ***************************************************************************** */ destruct : function(){ this._stopObserver(); this.__manager = this.__emitter = null; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Tristan Koch (tristankoch) ************************************************************************ */ /* ************************************************************************ #ignore(XDomainRequest) #require(qx.bom.request.Xhr#open) #require(qx.bom.request.Xhr#send) #require(qx.bom.request.Xhr#on) #require(qx.bom.request.Xhr#onreadystatechange) #require(qx.bom.request.Xhr#onload) #require(qx.bom.request.Xhr#onloadend) #require(qx.bom.request.Xhr#onerror) #require(qx.bom.request.Xhr#onabort) #require(qx.bom.request.Xhr#ontimeout) #require(qx.bom.request.Xhr#setRequestHeader) #require(qx.bom.request.Xhr#getAllResponseHeaders) #require(qx.bom.request.Xhr#getRequest) ************************************************************************ */ /** * A wrapper of the XMLHttpRequest host object (or equivalent). The interface is * similar to <a href="http://www.w3.org/TR/XMLHttpRequest/">XmlHttpRequest</a>. * * Hides browser inconsistencies and works around bugs found in popular * implementations. * * <div class="desktop"> * Example: * * <pre class="javascript"> * var req = new qx.bom.request.Xhr(); * req.onload = function() { * // Handle data received * req.responseText; * } * * req.open("GET", url); * req.send(); * </pre> * </div> */ qx.Bootstrap.define("qx.bom.request.Xhr", { construct : function(){ this.__onNativeReadyStateChangeBound = qx.Bootstrap.bind(this.__onNativeReadyStateChange, this); this.__onNativeAbortBound = qx.Bootstrap.bind(this.__onNativeAbort, this); this.__onTimeoutBound = qx.Bootstrap.bind(this.__onTimeout, this); this.__initNativeXhr(); this._emitter = new qx.event.Emitter(); // BUGFIX: IE // IE keeps connections alive unless aborted on unload if(window.attachEvent){ this.__onUnloadBound = qx.Bootstrap.bind(this.__onUnload, this); window.attachEvent("onunload", this.__onUnloadBound); }; }, statics : { UNSENT : 0, OPENED : 1, HEADERS_RECEIVED : 2, LOADING : 3, DONE : 4 }, events : { /** Fired at ready state changes. */ "readystatechange" : "qx.bom.request.Xhr", /** Fired on error. */ "error" : "qx.bom.request.Xhr", /** Fired at loadend. */ "loadend" : "qx.bom.request.Xhr", /** Fired on timeouts. */ "timeout" : "qx.bom.request.Xhr", /** Fired when the request is aborted. */ "abort" : "qx.bom.request.Xhr", /** Fired on successful retrieval. */ "load" : "qx.bom.request.Xhr" }, members : { /* --------------------------------------------------------------------------- PUBLIC --------------------------------------------------------------------------- */ /** * {Number} Ready state. * * States can be: * UNSENT: 0, * OPENED: 1, * HEADERS_RECEIVED: 2, * LOADING: 3, * DONE: 4 */ readyState : 0, /** * {String} The response of the request as text. */ responseText : "", /** * {Object} The response of the request as a Document object. */ responseXML : null, /** * {Number} The HTTP status code. */ status : 0, /** * {String} The HTTP status text. */ statusText : "", /** * {Number} Timeout limit in milliseconds. * * 0 (default) means no timeout. Not supported for synchronous requests. */ timeout : 0, /** * Initializes (prepares) request. * * @lint ignoreUndefined(XDomainRequest) * * @param method {String?"GET"} * The HTTP method to use. * @param url {String} * The URL to which to send the request. * @param async {Boolean?true} * Whether or not to perform the operation asynchronously. * @param user {String?null} * Optional user name to use for authentication purposes. * @param password {String?null} * Optional password to use for authentication purposes. */ open : function(method, url, async, user, password){ this.__checkDisposed(); // Mimick native behavior if(typeof url === "undefined"){ throw new Error("Not enough arguments"); } else if(typeof method === "undefined"){ method = "GET"; }; // Reset flags that may have been set on previous request this.__abort = false; this.__send = false; this.__conditional = false; // Store URL for later checks this.__url = url; if(typeof async == "undefined"){ async = true; }; this.__async = async; // BUGFIX // IE < 9 and FF < 3.5 cannot reuse the native XHR to issue many requests if(!this.__supportsManyRequests() && this.readyState > qx.bom.request.Xhr.UNSENT){ // XmlHttpRequest Level 1 requires open() to abort any pending requests // associated to the object. Since we're dealing with a new object here, // we have to emulate this behavior. Moreover, allow old native XHR to be garbage collected // // Dispose and abort. // this.dispose(); // Replace the underlying native XHR with a new one that can // be used to issue new requests. this.__initNativeXhr(); }; // Restore handler in case it was removed before this.__nativeXhr.onreadystatechange = this.__onNativeReadyStateChangeBound; try{ if(qx.core.Environment.get("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Xhr, "Open native request with method: " + method + ", url: " + url + ", async: " + async); }; this.__nativeXhr.open(method, url, async, user, password); } catch(OpenError) { // Only work around exceptions caused by cross domain request attempts if(!qx.util.Request.isCrossDomain(url)){ // Is same origin throw OpenError; }; if(!this.__async){ this.__openError = OpenError; }; if(this.__async){ // Try again with XDomainRequest // (Success case not handled on purpose) // - IE 9 if(window.XDomainRequest){ this.readyState = 4; this.__nativeXhr = new XDomainRequest(); this.__nativeXhr.onerror = qx.Bootstrap.bind(function(){ this._emit("readystatechange"); this._emit("error"); this._emit("loadend"); }, this); if(qx.core.Environment.get("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Xhr, "Retry open native request with method: " + method + ", url: " + url + ", async: " + async); }; this.__nativeXhr.open(method, url, async, user, password); return; }; // Access denied // - IE 6: -2146828218 // - IE 7: -2147024891 // - Legacy Firefox window.setTimeout(qx.Bootstrap.bind(function(){ if(this.__disposed){ return; }; this.readyState = 4; this._emit("readystatechange"); this._emit("error"); this._emit("loadend"); }, this)); }; }; // BUGFIX: IE < 9 // IE < 9 tends to cache overly agressive. This may result in stale // representations. Force validating freshness of cached representation. if(qx.core.Environment.get("engine.name") === "mshtml" && qx.core.Environment.get("browser.documentmode") < 9 && this.__nativeXhr.readyState > 0){ this.__nativeXhr.setRequestHeader("If-Modified-Since", "-1"); }; // BUGFIX: Firefox // Firefox < 4 fails to trigger onreadystatechange OPENED for sync requests if(qx.core.Environment.get("engine.name") === "gecko" && parseInt(qx.core.Environment.get("engine.version"), 10) < 2 && !this.__async){ // Native XHR is already set to readyState DONE. Fake readyState // and call onreadystatechange manually. this.readyState = qx.bom.request.Xhr.OPENED; this._emit("readystatechange"); }; }, /** * Sets an HTTP request header to be used by the request. * * Note: The request must be initialized before using this method. * * @param key {String} * The name of the header whose value is to be set. * @param value {String} * The value to set as the body of the header. * @return {qx.bom.request.Xhr} Self for chaining. */ setRequestHeader : function(key, value){ this.__checkDisposed(); // Detect conditional requests if(key == "If-Match" || key == "If-Modified-Since" || key == "If-None-Match" || key == "If-Range"){ this.__conditional = true; }; this.__nativeXhr.setRequestHeader(key, value); return this; }, /** * Sends request. * * @param data {String|Document?null} * Optional data to send. * @return {qx.bom.request.Xhr} Self for chaining. */ send : function(data){ this.__checkDisposed(); // BUGFIX: IE & Firefox < 3.5 // For sync requests, some browsers throw error on open() // while it should be on send() // if(!this.__async && this.__openError){ throw this.__openError; }; // BUGFIX: Opera // On network error, Opera stalls at readyState HEADERS_RECEIVED // This violates the spec. See here http://www.w3.org/TR/XMLHttpRequest2/#send // (Section: If there is a network error) // // To fix, assume a default timeout of 10 seconds. Note: The "error" // event will be fired correctly, because the error flag is inferred // from the statusText property. Of course, compared to other // browsers there is an additional call to ontimeout(), but this call // should not harm. // if(qx.core.Environment.get("engine.name") === "opera" && this.timeout === 0){ this.timeout = 10000; }; // Timeout if(this.timeout > 0){ this.__timerId = window.setTimeout(this.__onTimeoutBound, this.timeout); }; // BUGFIX: Firefox 2 // "NS_ERROR_XPC_NOT_ENOUGH_ARGS" when calling send() without arguments data = typeof data == "undefined" ? null : data; // Some browsers may throw an error when sending of async request fails. // This violates the spec which states only sync requests should. try{ if(qx.core.Environment.get("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Xhr, "Send native request"); }; this.__nativeXhr.send(data); } catch(SendError) { if(!this.__async){ throw SendError; }; // BUGFIX // Some browsers throws error when file not found via file:// protocol. // Synthesize readyState changes. if(this._getProtocol() === "file:"){ this.readyState = 2; this.__readyStateChange(); var that = this; window.setTimeout(function(){ if(that.__disposed){ return; }; that.readyState = 3; that.__readyStateChange(); that.readyState = 4; that.__readyStateChange(); }); }; }; // BUGFIX: Firefox // Firefox fails to trigger onreadystatechange DONE for sync requests if(qx.core.Environment.get("engine.name") === "gecko" && !this.__async){ // Properties all set, only missing native readystatechange event this.__onNativeReadyStateChange(); }; // Set send flag this.__send = true; return this; }, /** * Abort request. * * Cancels any network activity. * @return {qx.bom.request.Xhr} Self for chaining. */ abort : function(){ this.__checkDisposed(); this.__abort = true; this.__nativeXhr.abort(); if(this.__nativeXhr){ this.readyState = this.__nativeXhr.readyState; }; return this; }, /** * Helper to emit events and call the callback methods. * @param event {String} The name of the event. */ _emit : function(event){ this["on" + event](); this._emitter.emit(event, this); }, /** * Event handler for XHR event that fires at every state change. * * Replace with custom method to get informed about the communication progress. */ onreadystatechange : function(){ }, /** * Event handler for XHR event "load" that is fired on successful retrieval. * * Note: This handler is called even when the HTTP status indicates an error. * * Replace with custom method to listen to the "load" event. */ onload : function(){ }, /** * Event handler for XHR event "loadend" that is fired on retrieval. * * Note: This handler is called even when a network error (or similar) * occurred. * * Replace with custom method to listen to the "loadend" event. */ onloadend : function(){ }, /** * Event handler for XHR event "error" that is fired on a network error. * * Replace with custom method to listen to the "error" event. */ onerror : function(){ }, /** * Event handler for XHR event "abort" that is fired when request * is aborted. * * Replace with custom method to listen to the "abort" event. */ onabort : function(){ }, /** * Event handler for XHR event "timeout" that is fired when timeout * interval has passed. * * Replace with custom method to listen to the "timeout" event. */ ontimeout : function(){ }, /** * Add an event listener for the given event name. * * @param name {String} The name of the event to listen to. * @param listener {Function} The function to execute when the event is fired * @param ctx {var?} The context of the listener. * @return {qx.bom.request.Xhr} Self for chaining. */ on : function(name, listener, ctx){ this._emitter.on(name, listener, ctx); return this; }, /** * Get a single response header from response. * * @param header {String} * Key of the header to get the value from. * @return {String} * Response header. */ getResponseHeader : function(header){ this.__checkDisposed(); return this.__nativeXhr.getResponseHeader(header); }, /** * Get all response headers from response. * * @return {String} All response headers. */ getAllResponseHeaders : function(){ this.__checkDisposed(); return this.__nativeXhr.getAllResponseHeaders(); }, /** * Get wrapped native XMLHttpRequest (or equivalent). * * Can be XMLHttpRequest or ActiveX. * * @return {Object} XMLHttpRequest or equivalent. */ getRequest : function(){ return this.__nativeXhr; }, /* --------------------------------------------------------------------------- HELPER --------------------------------------------------------------------------- */ /** * Dispose object and wrapped native XHR. * @return {Boolean} <code>true</code> if the object was successfully disposed */ dispose : function(){ if(this.__disposed){ return false; }; window.clearTimeout(this.__timerId); // Remove unload listener in IE. Aborting on unload is no longer required // for this instance. if(window.detachEvent){ window.detachEvent("onunload", this.__onUnloadBound); }; // May fail in IE try{ this.__nativeXhr.onreadystatechange; } catch(PropertiesNotAccessable) { return false; }; // Clear out listeners var noop = function(){ }; this.__nativeXhr.onreadystatechange = noop; this.__nativeXhr.onload = noop; this.__nativeXhr.onerror = noop; // Abort any network activity this.abort(); // Remove reference to native XHR this.__nativeXhr = null; this.__disposed = true; return true; }, /* --------------------------------------------------------------------------- PROTECTED --------------------------------------------------------------------------- */ /** * Create XMLHttpRequest (or equivalent). * * @return {Object} XMLHttpRequest or equivalent. */ _createNativeXhr : function(){ var xhr = qx.core.Environment.get("io.xhr"); if(xhr === "xhr"){ return new XMLHttpRequest(); }; if(xhr == "activex"){ return new window.ActiveXObject("Microsoft.XMLHTTP"); }; qx.Bootstrap.error(this, "No XHR support available."); }, /** * Get protocol of requested URL. * * @return {String} The used protocol. */ _getProtocol : function(){ var url = this.__url; var protocolRe = /^(\w+:)\/\//; // Could be http:// from file:// if(url !== null && url.match){ var match = url.match(protocolRe); if(match && match[1]){ return match[1]; }; }; return window.location.protocol; }, /* --------------------------------------------------------------------------- PRIVATE --------------------------------------------------------------------------- */ /** * {Object} XMLHttpRequest or equivalent. */ __nativeXhr : null, /** * {Boolean} Whether request is async. */ __async : null, /** * {Function} Bound __onNativeReadyStateChange handler. */ __onNativeReadyStateChangeBound : null, /** * {Function} Bound __onNativeAbort handler. */ __onNativeAbortBound : null, /** * {Function} Bound __onUnload handler. */ __onUnloadBound : null, /** * {Function} Bound __onTimeout handler. */ __onTimeoutBound : null, /** * {Boolean} Send flag */ __send : null, /** * {String} Requested URL */ __url : null, /** * {Boolean} Abort flag */ __abort : null, /** * {Boolean} Timeout flag */ __timeout : null, /** * {Boolean} Whether object has been disposed. */ __disposed : null, /** * {Number} ID of timeout timer. */ __timerId : null, /** * {Error} Error thrown on open, if any. */ __openError : null, /** * {Boolean} Conditional get flag */ __conditional : null, /** * Init native XHR. */ __initNativeXhr : function(){ // Create native XHR or equivalent and hold reference this.__nativeXhr = this._createNativeXhr(); // Track native ready state changes this.__nativeXhr.onreadystatechange = this.__onNativeReadyStateChangeBound; // Track native abort, when supported if(this.__nativeXhr.onabort){ this.__nativeXhr.onabort = this.__onNativeAbortBound; }; // Reset flags this.__disposed = this.__send = this.__abort = false; }, /** * Track native abort. * * In case the end user cancels the request by other * means than calling abort(). */ __onNativeAbort : function(){ // When the abort that triggered this method was not a result from // calling abort() if(!this.__abort){ this.abort(); }; }, /** * Handle native onreadystatechange. * * Calls user-defined function onreadystatechange on each * state change and syncs the XHR status properties. */ __onNativeReadyStateChange : function(){ var nxhr = this.__nativeXhr,propertiesReadable = true; if(qx.core.Environment.get("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Xhr, "Received native readyState: " + nxhr.readyState); }; // BUGFIX: IE, Firefox // onreadystatechange() is called twice for readyState OPENED. // // Call onreadystatechange only when readyState has changed. if(this.readyState == nxhr.readyState){ return; }; // Sync current readyState this.readyState = nxhr.readyState; // BUGFIX: IE // Superfluous onreadystatechange DONE when aborting OPENED // without send flag if(this.readyState === qx.bom.request.Xhr.DONE && this.__abort && !this.__send){ return; }; // BUGFIX: IE // IE fires onreadystatechange HEADERS_RECEIVED and LOADING when sync // // According to spec, only onreadystatechange OPENED and DONE should // be fired. if(!this.__async && (nxhr.readyState == 2 || nxhr.readyState == 3)){ return; }; // Default values according to spec. this.status = 0; this.statusText = this.responseText = ""; this.responseXML = null; if(this.readyState >= qx.bom.request.Xhr.HEADERS_RECEIVED){ // In some browsers, XHR properties are not readable // while request is in progress. try{ this.status = nxhr.status; this.statusText = nxhr.statusText; this.responseText = nxhr.responseText; this.responseXML = nxhr.responseXML; } catch(XhrPropertiesNotReadable) { propertiesReadable = false; }; if(propertiesReadable){ this.__normalizeStatus(); this.__normalizeResponseXML(); }; }; this.__readyStateChange(); // BUGFIX: IE // Memory leak in XMLHttpRequest (on-page) if(this.readyState == qx.bom.request.Xhr.DONE){ // Allow garbage collecting of native XHR if(nxhr){ nxhr.onreadystatechange = function(){ }; }; }; }, /** * Handle readystatechange. Called internally when readyState is changed. */ __readyStateChange : function(){ var that = this; // Cancel timeout before invoking handlers because they may throw if(this.readyState === qx.bom.request.Xhr.DONE){ // Request determined DONE. Cancel timeout. window.clearTimeout(this.__timerId); }; // BUGFIX: IE // IE < 8 fires LOADING and DONE on open() - before send() - when from cache if(qx.core.Environment.get("engine.name") == "mshtml" && qx.core.Environment.get("browser.documentmode") < 8){ // Detect premature events when async. LOADING and DONE is // illogical to happen before request was sent. if(this.__async && !this.__send && this.readyState >= qx.bom.request.Xhr.LOADING){ if(this.readyState == qx.bom.request.Xhr.LOADING){ // To early to fire, skip. return; }; if(this.readyState == qx.bom.request.Xhr.DONE){ window.setTimeout(function(){ if(that.__disposed){ return; }; // Replay previously skipped that.readyState = 3; that._emit("readystatechange"); that.readyState = 4; that._emit("readystatechange"); that.__readyStateChangeDone(); }); return; }; }; }; // Always fire "readystatechange" this._emit("readystatechange"); if(this.readyState === qx.bom.request.Xhr.DONE){ this.__readyStateChangeDone(); }; }, /** * Handle readystatechange. Called internally by * {@link #__readyStateChange} when readyState is DONE. */ __readyStateChangeDone : function(){ // Fire "timeout" if timeout flag is set if(this.__timeout){ this._emit("timeout"); // BUGFIX: Opera // Since Opera does not fire "error" on network error, fire additional // "error" on timeout (may well be related to network error) if(qx.core.Environment.get("engine.name") === "opera"){ this._emit("error"); }; this.__timeout = false; } else { if(this.__abort){ this._emit("abort"); } else { if(this.__isNetworkError()){ this._emit("error"); } else { this._emit("load"); }; }; }; // Always fire "onloadend" when DONE this._emit("loadend"); }, /** * Check for network error. * * @return {Boolean} Whether a network error occured. */ __isNetworkError : function(){ var error; // Infer the XHR internal error flag from statusText when not aborted. // See http://www.w3.org/TR/XMLHttpRequest2/#error-flag and // http://www.w3.org/TR/XMLHttpRequest2/#the-statustext-attribute // // With file://, statusText is always falsy. Assume network error when // response is empty. if(this._getProtocol() === "file:"){ error = !this.responseText; } else { error = !this.statusText; }; return error; }, /** * Handle faked timeout. */ __onTimeout : function(){ // Basically, mimick http://www.w3.org/TR/XMLHttpRequest2/#timeout-error var nxhr = this.__nativeXhr; this.readyState = qx.bom.request.Xhr.DONE; // Set timeout flag this.__timeout = true; // No longer consider request. Abort. nxhr.abort(); this.responseText = ""; this.responseXML = null; // Signal readystatechange this.__readyStateChange(); }, /** * Normalize status property across browsers. */ __normalizeStatus : function(){ var isDone = this.readyState === qx.bom.request.Xhr.DONE; // BUGFIX: Most browsers // Most browsers tell status 0 when it should be 200 for local files if(this._getProtocol() === "file:" && this.status === 0 && isDone){ if(!this.__isNetworkError()){ this.status = 200; }; }; // BUGFIX: IE // IE sometimes tells 1223 when it should be 204 if(this.status === 1223){ this.status = 204; }; // BUGFIX: Opera // Opera tells 0 for conditional requests when it should be 304 // // Detect response to conditional request that signals fresh cache. if(qx.core.Environment.get("engine.name") === "opera"){ if(isDone && // Done this.__conditional && // Conditional request !this.__abort && // Not aborted this.status === 0){ this.status = 304; }; }; }, /** * Normalize responseXML property across browsers. */ __normalizeResponseXML : function(){ // BUGFIX: IE // IE does not recognize +xml extension, resulting in empty responseXML. // // Check if Content-Type is +xml, verify missing responseXML then parse // responseText as XML. if(qx.core.Environment.get("engine.name") == "mshtml" && (this.getResponseHeader("Content-Type") || "").match(/[^\/]+\/[^\+]+\+xml/) && this.responseXML && !this.responseXML.documentElement){ var dom = new window.ActiveXObject("Microsoft.XMLDOM"); dom.async = false; dom.validateOnParse = false; dom.loadXML(this.responseText); this.responseXML = dom; }; }, /** * Handler for native unload event. */ __onUnload : function(){ try{ // Abort and dispose if(this){ this.dispose(); }; } catch(e) { }; }, /** * Helper method to determine whether browser supports reusing the * same native XHR to send more requests. * @return {Boolean} <code>true</code> if request object reuse is supported */ __supportsManyRequests : function(){ var name = qx.core.Environment.get("engine.name"); var version = qx.core.Environment.get("browser.version"); return !(name == "mshtml" && version < 9 || name == "gecko" && version < 3.5); }, /** * Throw when already disposed. */ __checkDisposed : function(){ if(this.__disposed){ throw new Error("Already disposed"); }; } }, defer : function(){ qx.core.Environment.add("qx.debug.io", false); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Tristan Koch (tristankoch) ************************************************************************ */ /** * Static helpers for handling requests. */ qx.Bootstrap.define("qx.util.Request", { statics : { /** * Whether URL given points to resource that is cross-domain, * i.e. not of same origin. * * @param url {String} URL. * @return {Boolean} Whether URL is cross domain. */ isCrossDomain : function(url){ var result = qx.util.Uri.parseUri(url),location = window.location; if(!location){ return false; }; var protocol = location.protocol; // URL is relative in the sence that it points to origin host if(!(url.indexOf("//") !== -1)){ return false; }; if(protocol.substr(0, protocol.length - 1) == result.protocol && location.host === result.host && location.port === result.port){ return false; }; return true; }, /** * Determine if given HTTP status is considered successful. * * @param status {Number} HTTP status. * @return {Boolean} Whether status is considered successful. */ isSuccessful : function(status){ return (status >= 200 && status < 300 || status === 304); }, /** * Request body is ignored for HTTP method GET and HEAD. * * See http://www.w3.org/TR/XMLHttpRequest2/#the-send-method. * * @param method {String} The HTTP method. * @return {Boolean} Whether request may contain body. */ methodAllowsRequestBody : function(method){ return !((/^(GET)|(HEAD)$/).test(method)); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Carsten Lergenmueller (carstenl) * Fabian Jakobs (fbjakobs) * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Determines browser-dependent information about the transport layer. * * This class is used by {@link qx.core.Environment} and should not be used * directly. Please check its class comment for details how to use it. * * @internal */ qx.Bootstrap.define("qx.bom.client.Transport", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /** * Returns the maximum number of parallel requests the current browser * supports per host addressed. * * Note that this assumes one connection can support one request at a time * only. Technically, this is not correct when pipelining is enabled (which * it currently is only for IE 8 and Opera). In this case, the number * returned will be too low, as one connection supports multiple pipelined * requests. This is accepted for now because pipelining cannot be * detected from JavaScript and because modern browsers have enough * parallel connections already - it's unlikely an app will require more * than 4 parallel XMLHttpRequests to one server at a time. * * @internal * @return {Integer} Maximum number of parallel requests */ getMaxConcurrentRequestCount : function(){ var maxConcurrentRequestCount; // Parse version numbers. var versionParts = qx.bom.client.Engine.getVersion().split("."); var versionMain = 0; var versionMajor = 0; var versionMinor = 0; // Main number if(versionParts[0]){ versionMain = versionParts[0]; }; // Major number if(versionParts[1]){ versionMajor = versionParts[1]; }; // Minor number if(versionParts[2]){ versionMinor = versionParts[2]; }; // IE 8 gives the max number of connections in a property // see http://msdn.microsoft.com/en-us/library/cc197013(VS.85).aspx if(window.maxConnectionsPerServer){ maxConcurrentRequestCount = window.maxConnectionsPerServer; } else if(qx.bom.client.Engine.getName() == "opera"){ // Opera: 8 total // see http://operawiki.info/HttpProtocol maxConcurrentRequestCount = 8; } else if(qx.bom.client.Engine.getName() == "webkit"){ // Safari: 4 // http://www.stevesouders.com/blog/2008/03/20/roundup-on-parallel-connections/ // Bug #6917: Distinguish Chrome from Safari, Chrome has 6 connections // according to // http://stackoverflow.com/questions/561046/how-many-concurrent-ajax-xmlhttprequest-requests-are-allowed-in-popular-browser maxConcurrentRequestCount = 4; } else if(qx.bom.client.Engine.getName() == "gecko" && ((versionMain > 1) || ((versionMain == 1) && (versionMajor > 9)) || ((versionMain == 1) && (versionMajor == 9) && (versionMinor >= 1)))){ // FF 3.5 (== Gecko 1.9.1): 6 Connections. // see http://gemal.dk/blog/2008/03/18/firefox_3_beta_5_will_have_improved_connection_parallelism/ maxConcurrentRequestCount = 6; } else { // Default is 2, as demanded by RFC 2616 // see http://blogs.msdn.com/ie/archive/2005/04/11/407189.aspx maxConcurrentRequestCount = 2; };;; return maxConcurrentRequestCount; }, /** * Checks whether the app is loaded with SSL enabled which means via https. * * @internal * @return {Boolean} <code>true</code>, if the app runs on https */ getSsl : function(){ return window.location.protocol === "https:"; }, /** * Checks what kind of XMLHttpRequest object the browser supports * for the current protocol, if any. * * The standard XMLHttpRequest is preferred over ActiveX XMLHTTP. * * @internal * @return {String} * <code>"xhr"</code>, if the browser provides standard XMLHttpRequest.<br/> * <code>"activex"</code>, if the browser provides ActiveX XMLHTTP.<br/> * <code>""</code>, if there is not XHR support at all. */ getXmlHttpRequest : function(){ // Standard XHR can be disabled in IE's security settings, // therefore provide ActiveX as fallback. Additionaly, // standard XHR in IE7 is broken for file protocol. var supports = window.ActiveXObject ? (function(){ if(window.location.protocol !== "file:"){ try{ new window.XMLHttpRequest(); return "xhr"; } catch(noXhr) { }; }; try{ new window.ActiveXObject("Microsoft.XMLHTTP"); return "activex"; } catch(noActiveX) { }; })() : (function(){ try{ new window.XMLHttpRequest(); return "xhr"; } catch(noXhr) { }; })(); return supports || ""; } }, defer : function(statics){ qx.core.Environment.add("io.maxrequests", statics.getMaxConcurrentRequestCount); qx.core.Environment.add("io.ssl", statics.getSsl); qx.core.Environment.add("io.xhr", statics.getXmlHttpRequest); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.bom.request.Xhr#open) ************************************************************************ */ /** * This module provides basic IO functionality. It contains three ways to load * data: * * * XMLHttpRequest: {@link #xhr} * * Script tag: {@link #script} * * Script tag using JSONP: {@link #jsonp} */ qx.Bootstrap.define("qx.module.Io", { statics : { /** * Returns a configured XMLHttpRequest object. Using the send method will * finally send the request. * * @param url {String} Mandatory URL to load the data from. * @param settings {Map?} Optional settings map which may contain one of * the following settings: * * * <code>method</code> The method of the request. Default: <pre>GET</pre> * * <code>async</code> flag to mark the request as asynchronous. Default: <pre>true</pre> * * <code>header</code> A map of request headers. * * @attachStatic {qxWeb, io.xhr} * @return {qx.bom.request.Xhr} The request object. */ xhr : function(url, settings){ if(!settings){ settings = { }; }; var xhr = new qx.bom.request.Xhr(); xhr.open(settings.method, url, settings.async); if(settings.header){ var header = settings.header; for(var key in header){ xhr.setRequestHeader(key, header[key]); }; }; return xhr; }, /** * Returns a predefined script tag wrapper which can be used to load data * from cross-domain origins. * * @param url {String} Mandatory URL to load the data from. * @attachStatic {qxWeb, io.script} * @return {qx.bom.request.Script} The request object. */ script : function(url){ var script = new qx.bom.request.Script(); script.open("get", url); return script; }, /** * Returns a predefined script tag wrapper which can be used to load data * from cross-domain origins via JSONP. * * @param url {String} Mandatory URL to load the data from. * @param settings {Map?} Optional settings map which may contain one of * the following settings: * * * <code>callbackName</code>: The name of the callback which will * be called by the loaded script. * * <code>callbackParam</code>: The name of the callback expected by the server * @attachStatic {qxWeb, io.jsonp} * @return {qx.bom.request.Jsonp} The request object. */ jsonp : function(url, settings){ var script = new qx.bom.request.Jsonp(); if(settings && settings.callbackName){ script.setCallbackName(settings.callbackName); }; if(settings && settings.callbackParam){ script.setCallbackParam(settings.callbackParam); }; script.setPrefix("qxWeb.$$"); // needed in case no callback name is given script.open("get", url); return script; } }, defer : function(statics){ qxWeb.$attachStatic({ io : { xhr : statics.xhr, script : statics.script, jsonp : statics.jsonp } }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Tristan Koch (tristankoch) ************************************************************************ */ /** * Script loader with interface similar to * <a href="http://www.w3.org/TR/XMLHttpRequest/">XmlHttpRequest</a>. * * The script loader can be used to load scripts from arbitrary sources. * <span class="desktop"> * For JSONP requests, consider the {@link qx.bom.request.Jsonp} transport * that derives from the script loader. * </span> * * <div class="desktop"> * Example: * * <pre class="javascript"> * var req = new qx.bom.request.Script(); * req.onload = function() { * // Script is loaded and parsed and * // globals set are available * } * * req.open("GET", url); * req.send(); * </pre> * </div> */ /* ************************************************************************ #ignore(qx.core.Environment) #require(qx.bom.request.Script#_success) #require(qx.bom.request.Script#abort) #require(qx.bom.request.Script#dispose) #require(qx.bom.request.Script#getAllResponseHeaders) #require(qx.bom.request.Script#getResponseHeader) #require(qx.bom.request.Script#setDetermineSuccess) #require(qx.bom.request.Script#setRequestHeader) ************************************************************************ */ qx.Bootstrap.define("qx.bom.request.Script", { construct : function(){ this.__initXhrProperties(); this.__onNativeLoadBound = qx.Bootstrap.bind(this._onNativeLoad, this); this.__onNativeErrorBound = qx.Bootstrap.bind(this._onNativeError, this); this.__onTimeoutBound = qx.Bootstrap.bind(this._onTimeout, this); this.__headElement = document.head || document.getElementsByTagName("head")[0] || document.documentElement; this._emitter = new qx.event.Emitter(); // BUGFIX: Browsers not supporting error handler // Set default timeout to capture network errors // // Note: The script is parsed and executed, before a "load" is fired. this.timeout = this.__supportsErrorHandler() ? 0 : 15000; }, events : { /** Fired at ready state changes. */ "readystatechange" : "qx.bom.request.Script", /** Fired on error. */ "error" : "qx.bom.request.Script", /** Fired at loadend. */ "loadend" : "qx.bom.request.Script", /** Fired on timeouts. */ "timeout" : "qx.bom.request.Script", /** Fired when the request is aborted. */ "abort" : "qx.bom.request.Script", /** Fired on successful retrieval. */ "load" : "qx.bom.request.Script" }, members : { /** * {Number} Ready state. * * States can be: * UNSENT: 0, * OPENED: 1, * LOADING: 2, * LOADING: 3, * DONE: 4 * * Contrary to {@link qx.bom.request.Xhr#readyState}, the script transport * does not receive response headers. For compatibility, another LOADING * state is implemented that replaces the HEADERS_RECEIVED state. */ readyState : null, /** * {Number} The status code. * * Note: The script transport cannot determine the HTTP status code. */ status : null, /** * {String} The status text. * * The script transport does not receive response headers. For compatibility, * the statusText property is set to the status casted to string. */ statusText : null, /** * {Number} Timeout limit in milliseconds. * * 0 (default) means no timeout. */ timeout : null, /** * {Function} Function that is executed once the script was loaded. */ __determineSuccess : null, /** * Add an event listener for the given event name. * * @param name {String} The name of the event to listen to. * @param listener {Function} The function to execute when the event is fired * @param ctx {var?} The context of the listener. * @return {qx.bom.request.Script} Self for chaining. */ on : function(name, listener, ctx){ this._emitter.on(name, listener, ctx); return this; }, /** * Initializes (prepares) request. * * @param method {String} * The HTTP method to use. * This parameter exists for compatibility reasons. The script transport * does not support methods other than GET. * @param url {String} * The URL to which to send the request. */ open : function(method, url){ if(this.__disposed){ return; }; // Reset XHR properties that may have been set by previous request this.__initXhrProperties(); this.__abort = null; this.__url = url; if(this.__environmentGet("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Script, "Open native request with " + "url: " + url); }; this._readyStateChange(1); }, /** * Appends a query parameter to URL. * * This method exists for compatibility reasons. The script transport * does not support request headers. However, many services parse query * parameters like request headers. * * Note: The request must be initialized before using this method. * * @param key {String} * The name of the header whose value is to be set. * @param value {String} * The value to set as the body of the header. * @return {qx.bom.request.Script} Self for chaining. */ setRequestHeader : function(key, value){ if(this.__disposed){ return null; }; var param = { }; if(this.readyState !== 1){ throw new Error("Invalid state"); }; param[key] = value; this.__url = qx.util.Uri.appendParamsToUrl(this.__url, param); return this; }, /** * Sends request. * @return {qx.bom.request.Script} Self for chaining. */ send : function(){ if(this.__disposed){ return null; }; var script = this.__createScriptElement(),head = this.__headElement,that = this; if(this.timeout > 0){ this.__timeoutId = window.setTimeout(this.__onTimeoutBound, this.timeout); }; if(this.__environmentGet("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Script, "Send native request"); }; // Attach script to DOM head.insertBefore(script, head.firstChild); // The resource is loaded once the script is in DOM. // Assume HEADERS_RECEIVED and LOADING and dispatch async. window.setTimeout(function(){ that._readyStateChange(2); that._readyStateChange(3); }); return this; }, /** * Aborts request. * @return {qx.bom.request.Script} Self for chaining. */ abort : function(){ if(this.__disposed){ return null; }; this.__abort = true; this.__disposeScriptElement(); this._emit("abort"); return this; }, /** * Helper to emit events and call the callback methods. * @param event {String} The name of the event. */ _emit : function(event){ this["on" + event](); this._emitter.emit(event, this); }, /** * Event handler for an event that fires at every state change. * * Replace with custom method to get informed about the communication progress. */ onreadystatechange : function(){ }, /** * Event handler for XHR event "load" that is fired on successful retrieval. * * Note: This handler is called even when an invalid script is returned. * * Warning: Internet Explorer < 9 receives a false "load" for invalid URLs. * This "load" is fired about 2 seconds after sending the request. To * distinguish from a real "load", consider defining a custom check * function using {@link #setDetermineSuccess} and query the status * property. However, the script loaded needs to have a known impact on * the global namespace. If this does not work for you, you may be able * to set a timeout lower than 2 seconds, depending on script size, * complexity and execution time. * * Replace with custom method to listen to the "load" event. */ onload : function(){ }, /** * Event handler for XHR event "loadend" that is fired on retrieval. * * Note: This handler is called even when a network error (or similar) * occurred. * * Replace with custom method to listen to the "loadend" event. */ onloadend : function(){ }, /** * Event handler for XHR event "error" that is fired on a network error. * * Note: Some browsers do not support the "error" event. * * Replace with custom method to listen to the "error" event. */ onerror : function(){ }, /** * Event handler for XHR event "abort" that is fired when request * is aborted. * * Replace with custom method to listen to the "abort" event. */ onabort : function(){ }, /** * Event handler for XHR event "timeout" that is fired when timeout * interval has passed. * * Replace with custom method to listen to the "timeout" event. */ ontimeout : function(){ }, /** * Get a single response header from response. * * Note: This method exists for compatibility reasons. The script * transport does not receive response headers. * * @param key {String} * Key of the header to get the value from. * @return {String|null} Warning message or <code>null</code> if the request * is disposed */ getResponseHeader : function(key){ if(this.__disposed){ return null; }; if(this.__environmentGet("qx.debug")){ qx.Bootstrap.debug("Response header cannot be determined for " + "requests made with script transport."); }; return "unknown"; }, /** * Get all response headers from response. * * Note: This method exists for compatibility reasons. The script * transport does not receive response headers. * @return {String|null} Warning message or <code>null</code> if the request * is disposed */ getAllResponseHeaders : function(){ if(this.__disposed){ return null; }; if(this.__environmentGet("qx.debug")){ qx.Bootstrap.debug("Response headers cannot be determined for" + "requests made with script transport."); }; return "Unknown response headers"; }, /** * Determine if loaded script has expected impact on global namespace. * * The function is called once the script was loaded and must return a * boolean indicating if the response is to be considered successful. * * @param check {Function} Function executed once the script was loaded. * */ setDetermineSuccess : function(check){ this.__determineSuccess = check; }, /** * Dispose object. */ dispose : function(){ var script = this.__scriptElement; if(!this.__disposed){ // Prevent memory leaks if(script){ script.onload = script.onreadystatechange = null; this.__disposeScriptElement(); }; if(this.__timeoutId){ window.clearTimeout(this.__timeoutId); }; this.__disposed = true; }; }, /* --------------------------------------------------------------------------- PROTECTED --------------------------------------------------------------------------- */ /** * Get URL of request. * * @return {String} URL of request. */ _getUrl : function(){ return this.__url; }, /** * Get script element used for request. * * @return {Element} Script element. */ _getScriptElement : function(){ return this.__scriptElement; }, /** * Handle timeout. */ _onTimeout : function(){ this.__failure(); if(!this.__supportsErrorHandler()){ this._emit("error"); }; this._emit("timeout"); if(!this.__supportsErrorHandler()){ this._emit("loadend"); }; }, /** * Handle native load. */ _onNativeLoad : function(){ var script = this.__scriptElement,determineSuccess = this.__determineSuccess,that = this; // Aborted request must not fire load if(this.__abort){ return; }; // BUGFIX: IE < 9 // When handling "readystatechange" event, skip if readyState // does not signal loaded script if(this.__environmentGet("engine.name") === "mshtml" && this.__environmentGet("browser.documentmode") < 9){ if(!(/loaded|complete/).test(script.readyState)){ return; } else { if(this.__environmentGet("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Script, "Received native readyState: loaded"); }; }; }; if(this.__environmentGet("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Script, "Received native load"); }; // Determine status by calling user-provided check function if(determineSuccess){ // Status set before has higher precedence if(!this.status){ this.status = determineSuccess() ? 200 : 500; }; }; if(this.status === 500){ if(this.__environmentGet("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Script, "Detected error"); }; }; if(this.__timeoutId){ window.clearTimeout(this.__timeoutId); }; window.setTimeout(function(){ that._success(); that._readyStateChange(4); that._emit("load"); that._emit("loadend"); }); }, /** * Handle native error. */ _onNativeError : function(){ this.__failure(); this._emit("error"); this._emit("loadend"); }, /* --------------------------------------------------------------------------- PRIVATE --------------------------------------------------------------------------- */ /** * {Element} Script element */ __scriptElement : null, /** * {Element} Head element */ __headElement : null, /** * {String} URL */ __url : "", /** * {Function} Bound _onNativeLoad handler. */ __onNativeLoadBound : null, /** * {Function} Bound _onNativeError handler. */ __onNativeErrorBound : null, /** * {Function} Bound _onTimeout handler. */ __onTimeoutBound : null, /** * {Number} Timeout timer iD. */ __timeoutId : null, /** * {Boolean} Whether request was aborted. */ __abort : null, /** * {Boolean} Whether request was disposed. */ __disposed : null, /* --------------------------------------------------------------------------- HELPER --------------------------------------------------------------------------- */ /** * Initialize properties. */ __initXhrProperties : function(){ this.readyState = 0; this.status = 0; this.statusText = ""; }, /** * Change readyState. * * @param readyState {Number} The desired readyState */ _readyStateChange : function(readyState){ this.readyState = readyState; this._emit("readystatechange"); }, /** * Handle success. */ _success : function(){ this.__disposeScriptElement(); this.readyState = 4; // By default, load is considered successful if(!this.status){ this.status = 200; }; this.statusText = "" + this.status; }, /** * Handle failure. */ __failure : function(){ this.__disposeScriptElement(); this.readyState = 4; this.status = 0; this.statusText = null; }, /** * Looks up whether browser supports error handler. * * @return {Boolean} Whether browser supports error handler. */ __supportsErrorHandler : function(){ var isLegacyIe = this.__environmentGet("engine.name") === "mshtml" && this.__environmentGet("browser.documentmode") < 9; var isOpera = this.__environmentGet("engine.name") === "opera"; return !(isLegacyIe || isOpera); }, /** * Create and configure script element. * * @return {Element} Configured script element. */ __createScriptElement : function(){ var script = this.__scriptElement = document.createElement("script"); script.src = this.__url; script.onerror = this.__onNativeErrorBound; script.onload = this.__onNativeLoadBound; // BUGFIX: IE < 9 // Legacy IEs do not fire the "load" event for script elements. // Instead, they support the "readystatechange" event if(this.__environmentGet("engine.name") === "mshtml" && this.__environmentGet("browser.documentmode") < 9){ script.onreadystatechange = this.__onNativeLoadBound; }; return script; }, /** * Remove script element from DOM. */ __disposeScriptElement : function(){ var script = this.__scriptElement; if(script && script.parentNode){ this.__headElement.removeChild(script); }; }, /** * Proxy Environment.get to guard against env not being present yet. * * @param key {String} Environment key. * @return {var} Value of the queried environment key * @lint environmentNonLiteralKey(key) */ __environmentGet : function(key){ if(qx && qx.core && qx.core.Environment){ return qx.core.Environment.get(key); } else { if(key === "engine.name"){ return qx.bom.client.Engine.getName(); }; if(key === "browser.documentmode"){ return qx.bom.client.Browser.getDocumentMode(); }; if(key == "qx.debug.io"){ return false; }; throw new Error("Unknown environment key at this phase"); }; } }, defer : function(){ if(qx && qx.core && qx.core.Environment){ qx.core.Environment.add("qx.debug.io", false); }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Tristan Koch (tristankoch) ************************************************************************ */ /* ************************************************************************ #require(qx.bom.request.Script#open) #require(qx.bom.request.Script#on) #require(qx.bom.request.Script#onreadystatechange) #require(qx.bom.request.Script#onload) #require(qx.bom.request.Script#onloadend) #require(qx.bom.request.Script#onerror) #require(qx.bom.request.Script#onabort) #require(qx.bom.request.Script#ontimeout) #require(qx.bom.request.Script#send) ************************************************************************ */ /** * A special script loader handling JSONP responses. Automatically * provides callbacks and populates responseJson property. * * Example: * * <pre class="javascript"> * var req = new qx.bom.request.Jsonp(); * * // Some services have a fixed callback name * // req.setCallbackName("callback"); * * req.onload = function() { * // Handle data received * req.responseJson; * } * * req.open("GET", url); * req.send(); * </pre> */ qx.Bootstrap.define("qx.bom.request.Jsonp", { extend : qx.bom.request.Script, construct : function(){ // Borrow super-class constructor qx.bom.request.Script.apply(this); this.__generateId(); }, members : { /** * {Object} Parsed JSON response. */ responseJson : null, /** * {Number} Identifier of this instance. */ __id : null, /** * {String} Callback parameter. */ __callbackParam : null, /** * {String} Callback name. */ __callbackName : null, /** * {Boolean} Whether callback was called. */ __callbackCalled : null, /** * {Boolean} Whether a custom callback was created automatically. */ __customCallbackCreated : null, /** * {Boolean} Whether request was disposed. */ __disposed : null, /** Prefix used for the internal callback name. */ __prefix : "", /** * Initializes (prepares) request. * * @param method {String} * The HTTP method to use. * This parameter exists for compatibility reasons. The script transport * does not support methods other than GET. * @param url {String} * The URL to which to send the request. */ open : function(method, url){ if(this.__disposed){ return; }; var query = { },callbackParam,callbackName,that = this; // Reset properties that may have been set by previous request this.responseJson = null; this.__callbackCalled = false; callbackParam = this.__callbackParam || "callback"; callbackName = this.__callbackName || this.__prefix + "qx.bom.request.Jsonp[" + this.__id + "].callback"; // Default callback if(!this.__callbackName){ // Store globally available reference to this object this.constructor[this.__id] = this; } else { // Dynamically create globally available callback (if it does not // exist yet) with user defined name. Delegate to this object’s // callback method. if(!window[this.__callbackName]){ this.__customCallbackCreated = true; window[this.__callbackName] = function(data){ that.callback(data); }; } else { if(qx.core.Environment.get("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Jsonp, "Callback " + this.__callbackName + " already exists"); }; }; }; if(qx.core.Environment.get("qx.debug.io")){ qx.Bootstrap.debug(qx.bom.request.Jsonp, "Expecting JavaScript response to call: " + callbackName); }; query[callbackParam] = callbackName; url = qx.util.Uri.appendParamsToUrl(url, query); this.__callBase("open", [method, url]); }, /** * Callback provided for JSONP response to pass data. * * Called internally to populate responseJson property * and indicate successful status. * * Note: If you write a custom callback you’ll need to call * this method in order to notify the request about the data * loaded. Writing a custom callback should not be necessary * in most cases. * * @param data {Object} JSON */ callback : function(data){ if(this.__disposed){ return; }; // Signal callback was called this.__callbackCalled = true; { }; // Set response this.responseJson = data; // Delete global reference to this this.constructor[this.__id] = undefined; this.__deleteCustomCallback(); }, /** * Set callback parameter. * * Some JSONP services expect the callback name to be passed labeled with a * special URL parameter key, e.g. "jsonp" in "?jsonp=myCallback". The * default is "callback". * * @param param {String} Name of the callback parameter. * @return {qx.bom.request.Jsonp} Self reference for chaining. */ setCallbackParam : function(param){ this.__callbackParam = param; return this; }, /** * Set callback name. * * Must be set to the name of the callback function that is called by the * script returned from the JSONP service. By default, the callback name * references this instance’s {@link #callback} method, allowing to connect * multiple JSONP responses to different requests. * * If the JSONP service allows to set custom callback names, it should not * be necessary to change the default. However, some services use a fixed * callback name. This is when setting the callbackName is useful. A * function is created and made available globally under the given name. * The function receives the JSON data and dispatches it to this instance’s * {@link #callback} method. Please note that this function is only created * if it does not exist before. * * @param name {String} Name of the callback function. * @return {qx.bom.request.Jsonp} Self reference for chaining. */ setCallbackName : function(name){ this.__callbackName = name; return this; }, /** * Set the prefix used in front of 'qx.' in case 'qx' is not available * (for qx.Website e.g.) * @internal * @param prefix {String} The prefix to put in front of 'qx' */ setPrefix : function(prefix){ this.__prefix = prefix; }, dispose : function(){ // In case callback was not called this.__deleteCustomCallback(); this.__callBase("dispose"); }, /** * Handle native load. */ _onNativeLoad : function(){ // Indicate erroneous status (500) if callback was not called. // // Why 500? 5xx belongs to the range of server errors. If the callback was // not called, it is assumed the server failed to provide an appropriate // response. Since the exact reason of the error is unknown, the most // generic message ("500 Internal Server Error") is chosen. this.status = this.__callbackCalled ? 200 : 500; this.__callBase("_onNativeLoad"); }, /** * Delete custom callback if dynamically created before. */ __deleteCustomCallback : function(){ if(this.__customCallbackCreated && window[this.__callbackName]){ window[this.__callbackName] = undefined; this.__customCallbackCreated = false; }; }, /** * Call overriden method. * * @param method {String} Name of the overriden method. * @param args {Array} Arguments. */ __callBase : function(method, args){ qx.bom.request.Script.prototype[method].apply(this, args || []); }, /** * Generate ID. */ __generateId : function(){ // Add random digits to date to allow immediately following requests // that may be send at the same time this.__id = (new Date().valueOf()) + ("" + Math.random()).substring(2, 5); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Environment) #require(qx.module.Manipulating) #require(qx.module.Traversing) #require(qx.module.Css) #require(qx.module.Attribute) ************************************************************************ */ /** * Provides a way to block elements so they will no longer receive (native) * events by overlaying them with a div. * For Internet Explorer, an additional Iframe element will be overlayed since * native form controls cannot be blocked otherwise. * * The blocker can also be applied to the entire document, e.g.: * * <pre class="javascript"> * q(document).block(); * </pre> */ qxWeb.define("qx.module.Blocker", { statics : { /** * Attaches a blocker div (and additionally a blocker Iframe for IE) to the * given element. * * @param item {Element|Document} The element to be overlaid with the blocker * @param color {String} The color for the blocker element (any CSS color value) * @param opacity {Number} The CSS opacity value for the blocker * @param zIndex {Number} The zIndex value for the blocker */ __attachBlocker : function(item, color, opacity, zIndex){ var win = qxWeb.getWindow(item); var isDocument = qxWeb.isDocument(item); if(!item.__blocker){ item.__blocker = { div : qxWeb.create("<div/>") }; if((qxWeb.env.get("engine.name") == "mshtml")){ item.__blocker.iframe = qx.module.Blocker.__getIframeElement(win); }; }; qx.module.Blocker.__styleBlocker(item, color, opacity, zIndex, isDocument); item.__blocker.div.appendTo(win.document.body); if(item.__blocker.iframe){ item.__blocker.iframe.appendTo(win.document.body); }; if(isDocument){ qxWeb(win).on("resize", qx.module.Blocker.__onWindowResize); }; }, /** * Styles the blocker element(s) * * @param item {Element|Document} The element to be overlaid with the blocker * @param color {String} The color for the blocker element (any CSS color value) * @param opacity {Number} The CSS opacity value for the blocker * @param zIndex {Number} The zIndex value for the blocker * @param isDocument {Boolean} Whether the item is a document node */ __styleBlocker : function(item, color, opacity, zIndex, isDocument){ var qItem = qxWeb(item); var styles = { "zIndex" : zIndex, "display" : "block", "position" : "absolute", "backgroundColor" : color, "opacity" : opacity, "width" : qItem.getWidth() + "px", "height" : qItem.getHeight() + "px" }; if(isDocument){ styles.top = 0 + "px"; styles.left = 0 + "px"; } else { var pos = qItem.getOffset(); styles.top = pos.top + "px"; styles.left = pos.left + "px"; }; item.__blocker.div.setStyles(styles); if(item.__blocker.iframe){ styles.zIndex = styles.zIndex - 1; styles.backgroundColor = "transparent"; styles.opacity = 0; item.__blocker.iframe.setStyles(styles); }; }, /** * Creates an iframe element used as a blocker in IE * * @param win {Window} The parent window of the item to be blocked * @return {Element} Iframe blocker */ __getIframeElement : function(win){ var iframe = qxWeb.create('<iframe></iframe>'); iframe.setAttributes({ frameBorder : 0, frameSpacing : 0, marginWidth : 0, marginHeight : 0, hspace : 0, vspace : 0, border : 0, allowTransparency : false, src : "javascript:false" }); return iframe; }, /** * Callback for the Window's resize event. Applies the window's new sizes * to the blocker element(s). * * @param ev {Event} resize event */ __onWindowResize : function(ev){ var win = this[0]; var size = { width : this.getWidth() + "px", height : this.getHeight() + "px" }; qxWeb(win.document.__blocker.div).setStyles(size); if(win.document.__blocker.iframe){ qxWeb(win.document.__blocker.iframe).setStyles(size); }; }, /** * Removes the given item's blocker element(s) from the DOM * * @param item {Element} Blocked element * @param index {Number} index of the item in the collection */ __detachBlocker : function(item, index){ if(!item.__blocker){ return; }; item.__blocker.div.remove(); if(item.__blocker.iframe){ item.__blocker.iframe.remove(); }; if(qxWeb.isDocument(item)){ qxWeb(qxWeb.getWindow(item)).off("resize", qx.module.Blocker.__onWindowResize); }; }, /** * Adds an overlay to all items in the collection that intercepts mouse * events. * * @attach {qxWeb} * @param color {String ? transparent} The color for the blocker element (any CSS color value) * @param opacity {Float ? 0} The CSS opacity value for the blocker * @param zIndex {Number ? 10000} The zIndex value for the blocker * @return {qxWeb} The collection for chaining */ block : function(color, opacity, zIndex){ if(!this[0]){ return this; }; color = color || "transparent"; opacity = opacity || 0; zIndex = zIndex || 10000; this.forEach(function(item, index){ qx.module.Blocker.__attachBlocker(item, color, opacity, zIndex); }); return this; }, /** * Removes the blockers from all items in the collection * * @attach {qxWeb} * @return {qxWeb} The collection for chaining */ unblock : function(){ if(!this[0]){ return this; }; this.forEach(qx.module.Blocker.__detachBlocker); return this; } }, defer : function(statics){ qxWeb.$attach({ "block" : statics.block, "unblock" : statics.unblock }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Css) #require(qx.module.Event) ************************************************************************ */ /** * Cross browser animation layer. It uses feature detection to check if CSS * animations are available and ready to use. If not, a JavaScript-based * fallback will be used. */ qx.Bootstrap.define("qx.module.Animation", { events : { /** Fired when an animation starts. */ "animationStart" : undefined, /** Fired when an animation has ended one iteration. */ "animationIteration" : undefined, /** Fired when an animation has ended. */ "animationEnd" : undefined }, statics : { __animationHandles : null, /** * Internal initializer to make sure we always have a plain array * for storing animation handles. * @internal */ $init : function(){ this.__animationHandles = []; }, /** * Returns the stored animation handles. The handles are only * available while an animation is running. * * @internal * @return {Array} An array of animation handles. */ getAnimationHandles : function(){ return this.__animationHandles; }, /** * Animation description used in {@link #fadeOut}. */ _fadeOut : { duration : 700, timing : "ease-out", keep : 100, keyFrames : { '0' : { opacity : 1 }, '100' : { opacity : 0, display : "none" } } }, /** * Animation description used in {@link #fadeIn}. */ _fadeIn : { duration : 700, timing : "ease-in", keep : 100, keyFrames : { '0' : { opacity : 0 }, '100' : { opacity : 1 } } }, /** * Starts the animation with the given description. * The description should be a map, which could look like this: * * <pre class="javascript"> * { * "duration": 1000, * "keep": 100, * "keyFrames": { * 0 : {"opacity": 1, "scale": 1}, * 100 : {"opacity": 0, "scale": 0} * }, * "origin": "50% 50%", * "repeat": 1, * "timing": "ease-out", * "alternate": false, * "delay": 2000 * } * </pre> * * *duration* is the time in milliseconds one animation cycle should take. * * *keep* is the key frame to apply at the end of the animation. (optional) * * *keyFrames* is a map of separate frames. Each frame is defined by a * number which is the percentage value of time in the animation. The value * is a map itself which holds css properties or transforms * (Transforms only for CSS Animations). * * *origin* maps to the transform origin {@link qx.bom.element.Transform#setOrigin} * (Only for CSS animations). * * *repeat* is the amount of time the animation should be run in * sequence. You can also use "infinite". * * *timing* takes one of these predefined values: * <code>ease</code> | <code>linear</code> | <code>ease-in</code> * | <code>ease-out</code> | <code>ease-in-out</code> | * <code>cubic-bezier(&lt;number&gt;, &lt;number&gt;, &lt;number&gt;, &lt;number&gt;)</code> * (cubic-bezier only available for CSS animations) * * *alternate* defines if every other animation should be run in reverse order. * * *delay* is the time in milliseconds the animation should wait before start. * * @attach {qxWeb} * @param desc {Map} The animation's description. * @param duration {Number?} The duration in milliseconds of the animation, * which will override the duration given in the description. * @return {qxWeb} The collection for chaining. */ animate : function(desc, duration){ if(this.__animationHandles.length > 0){ throw new Error("Only one animation at a time."); }; for(var i = 0;i < this.length;i++){ var handle = qx.bom.element.Animation.animate(this[i], desc, duration); var self = this; // only register for the first element if(i == 0){ handle.on("start", function(){ self.emit("animationStart"); }, handle); handle.on("iteration", function(){ self.emit("animationIteration"); }, handle); }; handle.on("end", function(){ var handles = self.__animationHandles; handles.splice(self.indexOf(handle), 1); if(handles.length == 0){ self.emit("animationEnd"); }; }, handle); this.__animationHandles.push(handle); }; return this; }, /** * Starts an animation in reversed order. For further details, take a look at * the {@link #animate} method. * @attach {qxWeb} * @param desc {Map} The animation's description. * @param duration {Number?} The duration in milliseconds of the animation, * which will override the duration given in the description. * @return {qxWeb} The collection for chaining. */ animateReverse : function(desc, duration){ if(this.__animationHandles.length > 0){ throw new Error("Only one animation at a time."); }; for(var i = 0;i < this.length;i++){ var handle = qx.bom.element.Animation.animateReverse(this[i], desc, duration); var self = this; handle.on("end", function(){ var handles = self.__animationHandles; handles.splice(self.indexOf(handle), 1); if(handles.length == 0){ self.emit("animationEnd"); }; }, handle); this.__animationHandles.push(handle); }; return this; }, /** * Manipulates the play state of the animation. * This can be used to continue an animation when paused. * @attach {qxWeb} * @return {qxWeb} The collection for chaining. */ play : function(){ for(var i = 0;i < this.__animationHandles.length;i++){ this.__animationHandles[i].play(); }; return this; }, /** * Manipulates the play state of the animation. * This can be used to pause an animation when running. * @attach {qxWeb} * @return {qxWeb} The collection for chaining. */ pause : function(){ for(var i = 0;i < this.__animationHandles.length;i++){ this.__animationHandles[i].pause(); }; return this; }, /** * Stops a running animation. * @attach {qxWeb} * @return {qxWeb} The collection for chaining. */ stop : function(){ for(var i = 0;i < this.__animationHandles.length;i++){ this.__animationHandles[i].stop(); }; this.__animationHandles = []; return this; }, /** * Returns whether an animation is running or not. * @attach {qxWeb} * @return {Boolean} <code>true</code>, if an animation is running. */ isPlaying : function(){ for(var i = 0;i < this.__animationHandles.length;i++){ if(this.__animationHandles[i].isPlaying()){ return true; }; }; return false; }, /** * Returns whether an animation has ended or not. * @attach {qxWeb} * @return {Boolean} <code>true</code>, if an animation has ended. */ isEnded : function(){ for(var i = 0;i < this.__animationHandles.length;i++){ if(!this.__animationHandles[i].isEnded()){ return false; }; }; return true; }, /** * Fades in all elements in the collection. * @attach {qxWeb} * @param duration {Number?} The duration in milliseconds. * @return {qxWeb} The collection for chaining. */ fadeIn : function(duration){ // remove 'display: none' style this.setStyle("display", ""); return this.animate(qx.module.Animation._fadeIn, duration); }, /** * Fades out all elements in the collection. * @attach {qxWeb} * @param duration {Number?} The duration in milliseconds. * @return {qxWeb} The collection for chaining. */ fadeOut : function(duration){ return this.animate(qx.module.Animation._fadeOut, duration); } }, defer : function(statics){ qxWeb.$attach({ "animate" : statics.animate, "animateReverse" : statics.animateReverse, "fadeIn" : statics.fadeIn, "fadeOut" : statics.fadeOut, "play" : statics.play, "pause" : statics.pause, "stop" : statics.stop, "isEnded" : statics.isEnded, "isPlaying" : statics.isPlaying, "getAnimationHandles" : statics.getAnimationHandles }); qxWeb.$attachInit(statics.$init); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * Wrapper for {@link qx.bom.element.AnimationCss} and * {@link qx.bom.element.AnimationJs}. It offers the pubilc API and decides using * feature checks either to use CSS animations or JS animations. * * If you use this class, the restrictions of the JavaScript animations apply. * This means that you can not use transforms and custom bezier timing functions. */ qx.Bootstrap.define("qx.bom.element.Animation", { statics : { /** * This function takes care of the feature check and starts the animation. * It takes a DOM element to apply the animation to, and a description. * The description should be a map, which could look like this: * * <pre class="javascript"> * { * "duration": 1000, * "keep": 100, * "keyFrames": { * 0 : {"opacity": 1, "scale": 1}, * 100 : {"opacity": 0, "scale": 0} * }, * "origin": "50% 50%", * "repeat": 1, * "timing": "ease-out", * "alternate": false, * "delay" : 2000 * } * </pre> * * *duration* is the time in milliseconds one animation cycle should take. * * *keep* is the key frame to apply at the end of the animation. (optional) * Keep in mind that the keep key is reversed in case you use an reverse * animation or set the alternate key and a even repeat count. * * *keyFrames* is a map of separate frames. Each frame is defined by a * number which is the percentage value of time in the animation. The value * is a map itself which holds css properties or transforms * {@link qx.bom.element.Transform} (Transforms only for CSS Animations). * * *origin* maps to the transform origin {@link qx.bom.element.Transform#setOrigin} * (Only for CSS animations). * * *repeat* is the amount of time the animation should be run in * sequence. You can also use "infinite". * * *timing* takes one of the predefined value: * <code>ease</code> | <code>linear</code> | <code>ease-in</code> * | <code>ease-out</code> | <code>ease-in-out</code> | * <code>cubic-bezier(&lt;number&gt;, &lt;number&gt;, &lt;number&gt;, &lt;number&gt;)</code> * (cubic-bezier only available for CSS animations) * * *alternate* defines if every other animation should be run in reverse order. * * *delay* is the time in milliseconds the animation should wait before start. * * @param el {Element} The element to animate. * @param desc {Map} The animations description. * @param duration {Integer?} The duration in milliseconds of the animation * which will override the duration given in the description. * @return {qx.bom.element.AnimationHandle} AnimationHandle instance to control * the animation. */ animate : function(el, desc, duration){ var onlyCssKeys = qx.bom.element.Animation.__hasOnlyCssKeys(el, desc.keyFrames); if(qx.core.Environment.get("css.animation") && onlyCssKeys){ return qx.bom.element.AnimationCss.animate(el, desc, duration); } else { return qx.bom.element.AnimationJs.animate(el, desc, duration); }; }, /** * Starts an animation in reversed order. For further details, take a look at * the {@link #animate} method. * @param el {Element} The element to animate. * @param desc {Map} The animations description. * @param duration {Integer?} The duration in milliseconds of the animation * which will override the duration given in the description. * @return {qx.bom.element.AnimationHandle} AnimationHandle instance to control * the animation. */ animateReverse : function(el, desc, duration){ var onlyCssKeys = qx.bom.element.Animation.__hasOnlyCssKeys(el, desc.keyFrames); if(qx.core.Environment.get("css.animation") && onlyCssKeys){ return qx.bom.element.AnimationCss.animateReverse(el, desc, duration); } else { return qx.bom.element.AnimationJs.animateReverse(el, desc, duration); }; }, /** * Detection helper which detects if only CSS keys are in * the animations key frames. * @param el {Element} The element to check for the styles. * @param keyFrames {Map} The keyFrames of the animation. * @return {Boolean} <code>true</code> if only css properties are included. */ __hasOnlyCssKeys : function(el, keyFrames){ var keys = []; for(var nr in keyFrames){ var frame = keyFrames[nr]; for(var key in frame){ if(keys.indexOf(key) == -1){ keys.push(key); }; }; }; var transformKeys = ["scale", "rotate", "skew", "translate"]; for(var i = 0;i < keys.length;i++){ var key = qx.lang.String.camelCase(keys[i]); if(!(key in el.style)){ // check for transform keys if(transformKeys.indexOf(keys[i]) != -1){ continue; }; return false; }; }; return true; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.bom.Stylesheet) ************************************************************************ */ /** * Responsible for checking all relevant animation properties. * * Spec: http://www.w3.org/TR/css3-animations/ * * @internal */ qx.Bootstrap.define("qx.bom.client.CssAnimation", { statics : { /** * Main check method which returns an object if CSS animations are * supported. This object contains all necessary keys to work with CSS * animations. * <ul> * <li><code>name</code> The name of the css animation style</li> * <li><code>play-state</code> The name of the play-state style</li> * <li><code>start-event</code> The name of the start event</li> * <li><code>iternation-event</code> The name of the iternation event</li> * <li><code>end-event</code> The name of the end event</li> * <li><code>fill-mode</code> The fill-mode style</li> * <li><code>keyframes</code> The name of the keyframes selector.</li> * </ul> * * @internal * @return {Object|null} The described object or null, if animations are * not supported. */ getSupport : function(){ var name = qx.bom.client.CssAnimation.getName(); if(name != null){ return { "name" : name, "play-state" : qx.bom.client.CssAnimation.getPlayState(), "start-event" : qx.bom.client.CssAnimation.getAnimationStart(), "iteration-event" : qx.bom.client.CssAnimation.getAnimationIteration(), "end-event" : qx.bom.client.CssAnimation.getAnimationEnd(), "fill-mode" : qx.bom.client.CssAnimation.getFillMode(), "keyframes" : qx.bom.client.CssAnimation.getKeyFrames() }; }; return null; }, /** * Checks for the 'animation-fill-mode' CSS style. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getFillMode : function(){ return qx.bom.Style.getPropertyName("AnimationFillMode"); }, /** * Checks for the 'animation-play-state' CSS style. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getPlayState : function(){ return qx.bom.Style.getPropertyName("AnimationPlayState"); }, /** * Checks for the style name used for animations. * @internal * @return {String|null} The name of the style or null, if the style is * not supported. */ getName : function(){ return qx.bom.Style.getPropertyName("animation"); }, /** * Checks for the event name of animation start. * @internal * @return {String} The name of the event. */ getAnimationStart : function(){ var mapping = { "msAnimation" : "MSAnimationStart", "WebkitAnimation" : "webkitAnimationStart", "MozAnimation" : "animationstart", "OAnimation" : "oAnimationStart", "animation" : "animationstart" }; return mapping[this.getName()]; }, /** * Checks for the event name of animation end. * @internal * @return {String} The name of the event. */ getAnimationIteration : function(){ var mapping = { "msAnimation" : "MSAnimationIteration", "WebkitAnimation" : "webkitAnimationIteration", "MozAnimation" : "animationiteration", "OAnimation" : "oAnimationIteration", "animation" : "animationiteration" }; return mapping[this.getName()]; }, /** * Checks for the event name of animation end. * @internal * @return {String} The name of the event. */ getAnimationEnd : function(){ var mapping = { "msAnimation" : "MSAnimationEnd", "WebkitAnimation" : "webkitAnimationEnd", "MozAnimation" : "animationend", "OAnimation" : "oAnimationEnd", "animation" : "animationend" }; return mapping[this.getName()]; }, /** * Checks what selector should be used to add keyframes to stylesheets. * @internal * @return {String|null} The name of the selector or null, if the selector * is not supported. */ getKeyFrames : function(){ var prefixes = qx.bom.Style.VENDOR_PREFIXES; var keyFrames = []; for(var i = 0;i < prefixes.length;i++){ var key = "@" + qx.lang.String.hyphenate(prefixes[i]) + "-keyframes"; // special treatment for IE10 if(key == "@ms-keyframes"){ key = "@-ms-keyframes"; }; keyFrames.push(key); }; keyFrames.unshift("@keyframes"); var sheet = qx.bom.Stylesheet.createElement(); for(var i = 0;i < keyFrames.length;i++){ try{ qx.bom.Stylesheet.addRule(sheet, keyFrames[i] + " name", ""); return keyFrames[i]; } catch(e) { }; }; return null; }, /** * Checks for the requestAnimationFrame method and return the prefixed name. * @internal * @return {String|null} A string the method name or null, if the method * is not supported. */ getRequestAnimationFrame : function(){ var choices = ["requestAnimationFrame", "msRequestAnimationFrame", "webkitRequestAnimationFrame", "mozRequestAnimationFrame", "oRequestAnmiationFrame"]; for(var i = 0;i < choices.length;i++){ if(window[choices[i]] != undefined){ return choices[i]; }; }; return null; } }, defer : function(statics){ qx.core.Environment.add("css.animation", statics.getSupport); qx.core.Environment.add("css.animation.requestframe", statics.getRequestAnimationFrame); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) ************************************************************************ */ /** * This class is responsible for applying CSS3 animations to plain DOM elements. * * The implementation is mostly a cross-browser wrapper for applying the * animations, including transforms. If the browser does not support * CSS animations, but you have set a keep frame, the keep frame will be applied * immediately, thus making the animations optional. * * The API aligns closely to the spec wherever possible. * * http://www.w3.org/TR/css3-animations/ * * {@link qx.bom.element.Animation} is the class, which takes care of the * feature detection for CSS animations and decides which implementation * (CSS or JavaScript) should be used. Most likely, this implementation should * be the one to use. */ qx.Bootstrap.define("qx.bom.element.AnimationCss", { statics : { // initialization __sheet : null, __rulePrefix : "Anni", __id : 0, /** Static map of rules */ __rules : { }, /** The used keys for transforms. */ __transitionKeys : { "scale" : true, "rotate" : true, "skew" : true, "translate" : true }, /** Map of cross browser CSS keys. */ __cssAnimationKeys : qx.core.Environment.get("css.animation"), /** * This is the main function to start the animation in reverse mode. * For further details, take a look at the documentation of the wrapper * {@link qx.bom.element.Animation}. * @param el {Element} The element to animate. * @param desc {Map} Animation description. * @param duration {Integer?} The duration of the animation which will * override the duration given in the description. * @return {qx.bom.element.AnimationHandle} The handle. */ animateReverse : function(el, desc, duration){ return this._animate(el, desc, duration, true); }, /** * This is the main function to start the animation. For further details, * take a look at the documentation of the wrapper * {@link qx.bom.element.Animation}. * @param el {Element} The element to animate. * @param desc {Map} Animation description. * @param duration {Integer?} The duration of the animation which will * override the duration given in the description. * @return {qx.bom.element.AnimationHandle} The handle. */ animate : function(el, desc, duration){ return this._animate(el, desc, duration, false); }, /** * Internal method to start an animation either reverse or not. * {@link qx.bom.element.Animation}. * @param el {Element} The element to animate. * @param desc {Map} Animation description. * @param duration {Integer?} The duration of the animation which will * override the duration given in the description. * @param reverse {Boolean} <code>true</code>, if the animation should be * reversed. * @return {qx.bom.element.AnimationHandle} The handle. */ _animate : function(el, desc, duration, reverse){ this.__normalizeDesc(desc); { }; // reverse the keep property if the animation is reverse as well var keep = desc.keep; if(keep != null && (reverse || (desc.alternate && desc.repeat % 2 == 0))){ keep = 100 - keep; }; if(!this.__sheet){ this.__sheet = qx.bom.Stylesheet.createElement(); }; var keyFrames = desc.keyFrames; if(duration == undefined){ duration = desc.duration; }; // if animations are supported if(this.__cssAnimationKeys != null){ var name = this.__addKeyFrames(keyFrames, reverse); var style = name + " " + duration + "ms " + desc.repeat + " " + desc.timing + " " + (desc.delay ? desc.delay + "ms " : "") + (desc.alternate ? "alternate" : ""); qx.bom.Event.addNativeListener(el, this.__cssAnimationKeys["start-event"], this.__onAnimationStart); qx.bom.Event.addNativeListener(el, this.__cssAnimationKeys["iteration-event"], this.__onAnimationIteration); qx.bom.Event.addNativeListener(el, this.__cssAnimationKeys["end-event"], this.__onAnimationEnd); el.style[qx.lang.String.camelCase(this.__cssAnimationKeys["name"])] = style; // use the fill mode property if available and suitable if(keep && keep == 100 && this.__cssAnimationKeys["fill-mode"]){ el.style[this.__cssAnimationKeys["fill-mode"]] = "forwards"; }; }; var animation = new qx.bom.element.AnimationHandle(); animation.desc = desc; animation.el = el; animation.keep = keep; el.$$animation = animation; // additional transform keys if(desc.origin != null){ qx.bom.element.Transform.setOrigin(el, desc.origin); }; // fallback for browsers not supporting animations if(this.__cssAnimationKeys == null){ window.setTimeout(function(){ qx.bom.element.AnimationCss.__onAnimationEnd({ target : el }); }, 0); }; return animation; }, /** * Handler for the animation start. * @param e {Event} The native event from the browser. */ __onAnimationStart : function(e){ e.target.$$animation.emit("start", e.target); }, /** * Handler for the animation iteration. * @param e {Event} The native event from the browser. */ __onAnimationIteration : function(e){ // It could happen that an animation end event is fired before an // animation iteration appears [BUG #6928] if(e.target != null && e.target.$$animation != null){ e.target.$$animation.emit("iteration", e.target); }; }, /** * Handler for the animation end. * @param e {Event} The native event from the browser. */ __onAnimationEnd : function(e){ var el = e.target; var animation = el.$$animation; // ignore events when already cleaned up if(!animation){ return; }; var desc = animation.desc; if(qx.bom.element.AnimationCss.__cssAnimationKeys != null){ // reset the styling var key = qx.lang.String.camelCase(qx.bom.element.AnimationCss.__cssAnimationKeys["name"]); el.style[key] = ""; qx.bom.Event.removeNativeListener(el, qx.bom.element.AnimationCss.__cssAnimationKeys["name"], qx.bom.element.AnimationCss.__onAnimationEnd); }; if(desc.origin != null){ qx.bom.element.Transform.setOrigin(el, ""); }; qx.bom.element.AnimationCss.__keepFrame(el, desc.keyFrames[animation.keep]); el.$$animation = null; animation.el = null; animation.ended = true; animation.emit("end", el); }, /** * Helper method which takes an element and a key frame description and * applies the properties defined in the given frame to the element. This * method is used to keep the state of the animation. * @param el {Element} The element to apply the frame to. * @param endFrame {Map} The description of the end frame, which is basically * a map containing CSS properties and values including transforms. */ __keepFrame : function(el, endFrame){ // keep the element at this animation step var transforms; for(var style in endFrame){ if(style in qx.bom.element.AnimationCss.__transitionKeys){ if(!transforms){ transforms = { }; }; transforms[style] = endFrame[style]; } else { el.style[qx.lang.String.camelCase(style)] = endFrame[style]; }; }; // transform keeping if(transforms){ qx.bom.element.Transform.transform(el, transforms); }; }, /** * Preprocessing of the description to make sure every necessary key is * set to its default. * @param desc {Map} The description of the animation. */ __normalizeDesc : function(desc){ if(!desc.hasOwnProperty("alternate")){ desc.alternate = false; }; if(!desc.hasOwnProperty("keep")){ desc.keep = null; }; if(!desc.hasOwnProperty("repeat")){ desc.repeat = 1; }; if(!desc.hasOwnProperty("timing")){ desc.timing = "linear"; }; if(!desc.hasOwnProperty("origin")){ desc.origin = null; }; }, /** * Debugging helper to validate the description. * @signature function(desc) * @param desc {Map} The description of the animation. */ __validateDesc : null, /** * Helper to add the given frames to an internal CSS stylesheet. It parses * the description and adds the key frames to the sheet. * @param frames {Map} A map of key frames that describe the animation. * @param reverse {Boolean} <code>true</code>, if the key frames should * be added in reverse order. * @return {String} The generated name of the keyframes rule. */ __addKeyFrames : function(frames, reverse){ var rule = ""; // for each key frame for(var position in frames){ rule += (reverse ? -(position - 100) : position) + "% {"; var frame = frames[position]; var transforms; // each style for(var style in frame){ if(style in this.__transitionKeys){ if(!transforms){ transforms = { }; }; transforms[style] = frame[style]; } else { rule += style + ":" + frame[style] + ";"; }; }; // transform handling if(transforms){ rule += qx.bom.element.Transform.getCss(transforms); }; rule += "} "; }; // cached shorthand if(this.__rules[rule]){ return this.__rules[rule]; }; var name = this.__rulePrefix + this.__id++; var selector = this.__cssAnimationKeys["keyframes"] + " " + name; qx.bom.Stylesheet.addRule(this.__sheet, selector, rule); this.__rules[rule] = name; return name; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #ignore(qx.bom.element.AnimationJs) ************************************************************************ */ /** * This is a simple handle, which will be returned when an animation is * started using the {@link qx.bom.element.Animation#animate} method. It * basically controls the animation. */ qx.Bootstrap.define("qx.bom.element.AnimationHandle", { extend : qx.event.Emitter, construct : function(){ var css = qx.core.Environment.get("css.animation"); this.__playState = css && css["play-state"]; this.__playing = true; }, events : { /** Fired when the animation started via {@link qx.bom.element.Animation}. */ "start" : "Element", /** * Fired when the animation started via {@link qx.bom.element.Animation} has * ended. */ "end" : "Element", /** Fired on every iteration of the animation. */ "iteration" : "Element" }, members : { __playState : null, __playing : false, __ended : false, /** * Accessor of the playing state. * @return {Boolean} <code>true</code>, if the animations is playing. */ isPlaying : function(){ return this.__playing; }, /** * Accessor of the ended state. * @return {Boolean} <code>true</code>, if the animations has ended. */ isEnded : function(){ return this.__ended; }, /** * Accessor of the paused state. * @return {Boolean} <code>true</code>, if the animations is paused. */ isPaused : function(){ return this.el.style[this.__playState] == "paused"; }, /** * Pauses the animation, if running. If not running, it will be ignored. */ pause : function(){ if(this.el){ this.el.style[this.__playState] = "paused"; this.el.$$animation.__playing = false; // in case the animation is based on JS if(this.animationId && qx.bom.element.AnimationJs){ qx.bom.element.AnimationJs.pause(this); }; }; }, /** * Resumes an animation. This does not start the animation once it has ended. * You need to create start a new Animation if you want to restart the animation. */ play : function(){ if(this.el){ this.el.style[this.__playState] = "running"; this.el.$$animation.__playing = true; // in case the animation is based on JS if(this.i != undefined && qx.bom.element.AnimationJs){ qx.bom.element.AnimationJs.play(this); }; }; }, /** * Stops the animation if running. */ stop : function(){ if(this.el && qx.core.Environment.get("css.animation") && !this.animationId){ this.el.style[this.__playState] = ""; this.el.style[qx.core.Environment.get("css.animation").name] = ""; this.el.$$animation.__playing = false; this.el.$$animation.__ended = true; }; // in case the animation is based on JS if(qx.bom.element.AnimationJs){ qx.bom.element.AnimationJs.stop(this); }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #ignore(qx.bom.element.Style) #use(qx.bom.element.AnimationJs#play) ************************************************************************ */ /** * This class offers the same API as the CSS3 animation layer in * {@link qx.bom.element.AnimationCss} but uses JavaScript to fake the behavior. * * {@link qx.bom.element.Animation} is the class, which takes care of the * feature detection for CSS animations and decides which implementation * (CSS or JavaScript) should be used. Most likely, this implementation should * be the one to use. */ qx.Bootstrap.define("qx.bom.element.AnimationJs", { statics : { /** * The maximal time a frame should take. */ __maxStepTime : 30, /** * The supported CSS units. */ __units : ["%", "in", "cm", "mm", "em", "ex", "pt", "pc", "px"], /** * This is the main function to start the animation. For further details, * take a look at the documentation of the wrapper * {@link qx.bom.element.Animation}. * @param el {Element} The element to animate. * @param desc {Map} Animation description. * @param duration {Integer?} The duration of the animation which will * override the duration given in the description. * @return {qx.bom.element.AnimationHandle} The handle. */ animate : function(el, desc, duration){ return this._animate(el, desc, duration, false); }, /** * This is the main function to start the animation in reversed mode. * For further details, take a look at the documentation of the wrapper * {@link qx.bom.element.Animation}. * @param el {Element} The element to animate. * @param desc {Map} Animation description. * @param duration {Integer?} The duration of the animation which will * override the duration given in the description. * @return {qx.bom.element.AnimationHandle} The handle. */ animateReverse : function(el, desc, duration){ return this._animate(el, desc, duration, true); }, /** * Helper to start the animation, either in reversed order or not. * * @param el {Element} The element to animate. * @param desc {Map} Animation description. * @param duration {Integer?} The duration of the animation which will * override the duration given in the description. * @param reverse {Boolean} <code>true</code>, if the animation should be * reversed. * @return {qx.bom.element.AnimationHandle} The handle. */ _animate : function(el, desc, duration, reverse){ // stop if an animation is already running if(el.$$animation){ return el.$$animation; }; desc = qx.lang.Object.clone(desc, true); if(duration == undefined){ duration = desc.duration; }; var keyFrames = desc.keyFrames; var keys = this.__getOrderedKeys(keyFrames); var stepTime = this.__getStepTime(duration, keys); var steps = parseInt(duration / stepTime, 10); this.__normalizeKeyFrames(keyFrames, el); var delta = this.__calculateDelta(steps, stepTime, keys, keyFrames, duration, desc.timing); var handle = new qx.bom.element.AnimationHandle(); if(reverse){ delta.reverse(); handle.reverse = true; }; handle.desc = desc; handle.el = el; handle.delta = delta; handle.stepTime = stepTime; handle.steps = steps; el.$$animation = handle; handle.i = 0; handle.initValues = { }; handle.repeatSteps = this.__applyRepeat(steps, desc.repeat); var delay = desc.delay || 0; var self = this; window.setTimeout(function(){ self.play(handle); }, delay); return handle; }, /** * Try to normalize the keyFrames by adding the default / set values of the * element. * @param keyFrames {Map} The map of key frames. * @param el {Element} The element to animate. */ __normalizeKeyFrames : function(keyFrames, el){ // collect all possible keys and its units var units = { }; for(var percent in keyFrames){ for(var name in keyFrames[percent]){ if(units[name] == undefined){ var item = keyFrames[percent][name]; if(typeof item == "string"){ units[name] = item.substring((parseInt(item, 10) + "").length, item.length); } else { units[name] = ""; }; }; }; }; // add all missing keys for(var percent in keyFrames){ var frame = keyFrames[percent]; for(var name in units){ if(frame[name] == undefined){ if(name in el.style){ // get the computed style if possible if(window.getComputedStyle){ frame[name] = getComputedStyle(el, null)[name]; } else { frame[name] = el.style[name]; }; } else { frame[name] = el[name]; }; // if its a unit we know, set 0 as fallback if(frame[name] === "" && this.__units.indexOf(units[name]) != -1){ frame[name] = "0" + units[name]; }; }; }; }; }, /** * Precalculation of the delta which will be applied during the animation. * The whole deltas will be calculated prior to the animation and stored * in a single array. This method takes care of that calculation. * * @param steps {Integer} The amount of steps to take to the end of the * animation. * @param stepTime {Integer} The amount of milliseconds each step takes. * @param keys {Array} Ordered list of keys in the key frames map. * @param keyFrames {Map} The map of key frames. * @param duration {Integer} Time in milliseconds the animation should take. * @param timing {String} The given timing function. * @return {Array} An array containing the animation deltas. */ __calculateDelta : function(steps, stepTime, keys, keyFrames, duration, timing){ var delta = new Array(steps); var keyIndex = 1; delta[0] = keyFrames[0]; var last = keyFrames[0]; var next = keyFrames[keys[keyIndex]]; // for every step for(var i = 1;i < delta.length;i++){ // switch key frames if we crossed a percent border if(i * stepTime / duration * 100 > keys[keyIndex]){ last = next; keyIndex++; next = keyFrames[keys[keyIndex]]; }; delta[i] = { }; // for every property for(var name in next){ var nItem = next[name] + ""; // color values if(nItem.charAt(0) == "#"){ // get the two values from the frames as RGB arrays var value0 = qx.util.ColorUtil.cssStringToRgb(last[name]); var value1 = qx.util.ColorUtil.cssStringToRgb(nItem); var stepValue = []; // calculate every color chanel for(var j = 0;j < value0.length;j++){ var range = value0[j] - value1[j]; stepValue[j] = parseInt(value0[j] - range * qx.bom.AnimationFrame.calculateTiming(timing, i / steps), 10); }; delta[i][name] = qx.util.ColorUtil.rgbToHexString(stepValue); } else if(!isNaN(parseInt(nItem, 10))){ var unit = nItem.substring((parseInt(nItem, 10) + "").length, nItem.length); var range = parseFloat(nItem) - parseFloat(last[name]); delta[i][name] = (parseFloat(last[name]) + range * qx.bom.AnimationFrame.calculateTiming(timing, i / steps)) + unit; } else { delta[i][name] = last[name] + ""; }; }; }; // make sure the last key frame is right delta[delta.length - 1] = keyFrames[100]; return delta; }, /** * Internal helper for the {@link qx.bom.element.AnimationHandle} to play * the animation. * @internal * @param handle {qx.bom.element.AnimationHandle} The hand which * represents the animation. * @return {qx.bom.element.AnimationHandle} The handle for chaining. */ play : function(handle){ handle.emit("start", handle.el); var id = window.setInterval(function(){ handle.repeatSteps--; var values = handle.delta[handle.i % handle.steps]; // save the init values if(handle.i === 0){ for(var name in values){ if(handle.initValues[name] === undefined){ // animate element property if(handle.el[name] !== undefined){ handle.initValues[name] = handle.el[name]; } else if(qx.bom.element.Style){ handle.initValues[name] = qx.bom.element.Style.get(handle.el, qx.lang.String.camelCase(name)); } else { handle.initValues[name] = handle.el.style[qx.lang.String.camelCase(name)]; }; }; }; }; qx.bom.element.AnimationJs.__applyStyles(handle.el, values); handle.i++; // iteration condition if(handle.i % handle.steps == 0){ handle.emit("iteration", handle.el); if(handle.desc.alternate){ handle.delta.reverse(); }; }; // end condition if(handle.repeatSteps < 0){ qx.bom.element.AnimationJs.stop(handle); }; }, handle.stepTime); handle.animationId = id; return handle; }, /** * Internal helper for the {@link qx.bom.element.AnimationHandle} to pause * the animation. * @internal * @param handle {qx.bom.element.AnimationHandle} The hand which * represents the animation. * @return {qx.bom.element.AnimationHandle} The handle for chaining. */ pause : function(handle){ // stop the interval window.clearInterval(handle.animationId); handle.animationId = null; return handle; }, /** * Internal helper for the {@link qx.bom.element.AnimationHandle} to stop * the animation. * @internal * @param handle {qx.bom.element.AnimationHandle} The hand which * represents the animation. * @return {qx.bom.element.AnimationHandle} The handle for chaining. */ stop : function(handle){ var desc = handle.desc; var el = handle.el; var initValues = handle.initValues; if(handle.animationId){ window.clearInterval(handle.animationId); }; // check if animation is already stopped if(el == undefined){ return handle; }; // if we should keep a frame var keep = desc.keep; if(keep != undefined){ if(handle.reverse || (desc.alternate && desc.repeat && desc.repeat % 2 == 0)){ keep = 100 - keep; }; this.__applyStyles(el, desc.keyFrames[keep]); } else { this.__applyStyles(el, initValues); }; el.$$animation = null; handle.el = null; handle.ended = true; handle.animationId = null; handle.emit("end", el); return handle; }, /** * Takes care of the repeat key of the description. * @param steps {Integer} The number of steps one iteration would take. * @param repeat {Integer|String} It can be either a number how often the * animation should be repeated or the string 'infinite'. * @return {Integer} The number of steps to animate. */ __applyRepeat : function(steps, repeat){ if(repeat == undefined){ return steps; }; if(repeat == "infinite"){ return Number.MAX_VALUE; }; return steps * repeat; }, /** * Central method to apply css styles and element properties. * @param el {Element} The DOM element to apply the styles. * @param styles {Map} A map containing styles and values. */ __applyStyles : function(el, styles){ for(var key in styles){ // ignore undefined values (might be a bad detection) if(styles[key] === undefined){ continue; }; // apply element property value if(key in el){ el[key] = styles[key]; continue; }; var name = qx.lang.String.camelCase(key); if(qx.bom.element.Style){ qx.bom.element.Style.set(el, name, styles[key]); } else { el.style[name] = styles[key]; }; }; }, /** * Dynamic calculation of the steps time considering a max step time. * @param duration {Number} The duration of the animation. * @param keys {Array} An array containing the orderd set of key frame keys. * @return {Integer} The best suited step time. */ __getStepTime : function(duration, keys){ // get min difference var minDiff = 100; for(var i = 0;i < keys.length - 1;i++){ minDiff = Math.min(minDiff, keys[i + 1] - keys[i]); }; var stepTime = duration * minDiff / 100; while(stepTime > this.__maxStepTime){ stepTime = stepTime / 2; }; return Math.round(stepTime); }, /** * Helper which returns the orderd keys of the key frame map. * @param keyFrames {Map} The map of key frames. * @return {Array} An orderd list of kyes. */ __getOrderedKeys : function(keyFrames){ var keys = Object.keys(keyFrames); for(var i = 0;i < keys.length;i++){ keys[i] = parseInt(keys[i], 10); }; keys.sort(function(a, b){ return a - b; }); return keys; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Christian Hagendorn (cs) ************************************************************************ */ /* ************************************************************************ #ignore(qx.theme.*) #ignore(qx.theme) #ignore(qx.Class) ************************************************************************ */ /** * Methods to convert colors between different color spaces. */ qx.Bootstrap.define("qx.util.ColorUtil", { statics : { /** * Regular expressions for color strings */ REGEXP : { hex3 : /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, hex6 : /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, rgb : /^rgb\(\s*([0-9]{1,3}\.{0,1}[0-9]*)\s*,\s*([0-9]{1,3}\.{0,1}[0-9]*)\s*,\s*([0-9]{1,3}\.{0,1}[0-9]*)\s*\)$/, rgba : /^rgba\(\s*([0-9]{1,3}\.{0,1}[0-9]*)\s*,\s*([0-9]{1,3}\.{0,1}[0-9]*)\s*,\s*([0-9]{1,3}\.{0,1}[0-9]*)\s*,\s*([0-9]{1,3}\.{0,1}[0-9]*)\s*\)$/ }, /** * CSS3 system color names. */ SYSTEM : { activeborder : true, activecaption : true, appworkspace : true, background : true, buttonface : true, buttonhighlight : true, buttonshadow : true, buttontext : true, captiontext : true, graytext : true, highlight : true, highlighttext : true, inactiveborder : true, inactivecaption : true, inactivecaptiontext : true, infobackground : true, infotext : true, menu : true, menutext : true, scrollbar : true, threeddarkshadow : true, threedface : true, threedhighlight : true, threedlightshadow : true, threedshadow : true, window : true, windowframe : true, windowtext : true }, /** * Named colors, only the 16 basic colors plus the following ones: * transparent, grey, magenta, orange and brown */ NAMED : { black : [0, 0, 0], silver : [192, 192, 192], gray : [128, 128, 128], white : [255, 255, 255], maroon : [128, 0, 0], red : [255, 0, 0], purple : [128, 0, 128], fuchsia : [255, 0, 255], green : [0, 128, 0], lime : [0, 255, 0], olive : [128, 128, 0], yellow : [255, 255, 0], navy : [0, 0, 128], blue : [0, 0, 255], teal : [0, 128, 128], aqua : [0, 255, 255], // Additional values transparent : [-1, -1, -1], magenta : [255, 0, 255], // alias for fuchsia orange : [255, 165, 0], brown : [165, 42, 42] }, /** * Whether the incoming value is a named color. * * @param value {String} the color value to test * @return {Boolean} true if the color is a named color */ isNamedColor : function(value){ return this.NAMED[value] !== undefined; }, /** * Whether the incoming value is a system color. * * @param value {String} the color value to test * @return {Boolean} true if the color is a system color */ isSystemColor : function(value){ return this.SYSTEM[value] !== undefined; }, /** * Whether the color theme manager is loaded. Generally * part of the GUI of qooxdoo. * * @return {Boolean} <code>true</code> when color theme support is ready. **/ supportsThemes : function(){ if(qx.Class){ return qx.Class.isDefined("qx.theme.manager.Color"); }; return false; }, /** * Whether the incoming value is a themed color. * * @param value {String} the color value to test * @return {Boolean} true if the color is a themed color */ isThemedColor : function(value){ if(!this.supportsThemes()){ return false; }; if(qx.theme && qx.theme.manager && qx.theme.manager.Color){ return qx.theme.manager.Color.getInstance().isDynamic(value); }; return false; }, /** * Try to convert an incoming string to an RGB array. * Supports themed, named and system colors, but also RGB strings, * hex3 and hex6 values. * * @param str {String} any string * @return {Array} returns an array of red, green, blue on a successful transformation * @throws {Error} if the string could not be parsed */ stringToRgb : function(str){ if(this.supportsThemes() && this.isThemedColor(str)){ var str = qx.theme.manager.Color.getInstance().resolveDynamic(str); }; if(this.isNamedColor(str)){ return this.NAMED[str]; } else if(this.isSystemColor(str)){ throw new Error("Could not convert system colors to RGB: " + str); } else if(this.isRgbString(str)){ return this.__rgbStringToRgb(); } else if(this.isHex3String(str)){ return this.__hex3StringToRgb(); } else if(this.isHex6String(str)){ return this.__hex6StringToRgb(); };;;; throw new Error("Could not parse color: " + str); }, /** * Try to convert an incoming string to an RGB array. * Support named colors, RGB strings, hex3 and hex6 values. * * @param str {String} any string * @return {Array} returns an array of red, green, blue on a successful transformation * @throws {Error} if the string could not be parsed */ cssStringToRgb : function(str){ if(this.isNamedColor(str)){ return this.NAMED[str]; } else if(this.isSystemColor(str)){ throw new Error("Could not convert system colors to RGB: " + str); } else if(this.isRgbString(str)){ return this.__rgbStringToRgb(); } else if(this.isRgbaString(str)){ return this.__rgbaStringToRgb(); } else if(this.isHex3String(str)){ return this.__hex3StringToRgb(); } else if(this.isHex6String(str)){ return this.__hex6StringToRgb(); };;;;; throw new Error("Could not parse color: " + str); }, /** * Try to convert an incoming string to an RGB string, which can be used * for all color properties. * Supports themed, named and system colors, but also RGB strings, * hex3 and hex6 values. * * @param str {String} any string * @return {String} a RGB string * @throws {Error} if the string could not be parsed */ stringToRgbString : function(str){ return this.rgbToRgbString(this.stringToRgb(str)); }, /** * Converts a RGB array to an RGB string * * @param rgb {Array} an array with red, green and blue * @return {String} a RGB string */ rgbToRgbString : function(rgb){ return "rgb(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + ")"; }, /** * Converts a RGB array to an hex6 string * * @param rgb {Array} an array with red, green and blue * @return {String} a hex6 string (#xxxxxx) */ rgbToHexString : function(rgb){ return ("#" + qx.lang.String.pad(rgb[0].toString(16).toUpperCase(), 2) + qx.lang.String.pad(rgb[1].toString(16).toUpperCase(), 2) + qx.lang.String.pad(rgb[2].toString(16).toUpperCase(), 2)); }, /** * Detects if a string is a valid qooxdoo color * * @param str {String} any string * @return {Boolean} true when the incoming value is a valid qooxdoo color */ isValidPropertyValue : function(str){ return (this.isThemedColor(str) || this.isNamedColor(str) || this.isHex3String(str) || this.isHex6String(str) || this.isRgbString(str) || this.isRgbaString(str)); }, /** * Detects if a string is a valid CSS color string * * @param str {String} any string * @return {Boolean} true when the incoming value is a valid CSS color string */ isCssString : function(str){ return (this.isSystemColor(str) || this.isNamedColor(str) || this.isHex3String(str) || this.isHex6String(str) || this.isRgbString(str) || this.isRgbaString(str)); }, /** * Detects if a string is a valid hex3 string * * @param str {String} any string * @return {Boolean} true when the incoming value is a valid hex3 string */ isHex3String : function(str){ return this.REGEXP.hex3.test(str); }, /** * Detects if a string is a valid hex6 string * * @param str {String} any string * @return {Boolean} true when the incoming value is a valid hex6 string */ isHex6String : function(str){ return this.REGEXP.hex6.test(str); }, /** * Detects if a string is a valid RGB string * * @param str {String} any string * @return {Boolean} true when the incoming value is a valid RGB string */ isRgbString : function(str){ return this.REGEXP.rgb.test(str); }, /** * Detects if a string is a valid RGBA string * * @param str {String} any string * @return {Boolean} true when the incoming value is a valid RGBA string */ isRgbaString : function(str){ return this.REGEXP.rgba.test(str); }, /** * Converts a regexp object match of a rgb string to an RGB array. * * @return {Array} an array with red, green, blue */ __rgbStringToRgb : function(){ var red = parseInt(RegExp.$1, 10); var green = parseInt(RegExp.$2, 10); var blue = parseInt(RegExp.$3, 10); return [red, green, blue]; }, /** * Converts a regexp object match of a rgba string to an RGB array. * * @return {Array} an array with red, green, blue */ __rgbaStringToRgb : function(){ var red = parseInt(RegExp.$1, 10); var green = parseInt(RegExp.$2, 10); var blue = parseInt(RegExp.$3, 10); return [red, green, blue]; }, /** * Converts a regexp object match of a hex3 string to an RGB array. * * @return {Array} an array with red, green, blue */ __hex3StringToRgb : function(){ var red = parseInt(RegExp.$1, 16) * 17; var green = parseInt(RegExp.$2, 16) * 17; var blue = parseInt(RegExp.$3, 16) * 17; return [red, green, blue]; }, /** * Converts a regexp object match of a hex6 string to an RGB array. * * @return {Array} an array with red, green, blue */ __hex6StringToRgb : function(){ var red = (parseInt(RegExp.$1, 16) * 16) + parseInt(RegExp.$2, 16); var green = (parseInt(RegExp.$3, 16) * 16) + parseInt(RegExp.$4, 16); var blue = (parseInt(RegExp.$5, 16) * 16) + parseInt(RegExp.$6, 16); return [red, green, blue]; }, /** * Converts a hex3 string to an RGB array * * @param value {String} a hex3 (#xxx) string * @return {Array} an array with red, green, blue */ hex3StringToRgb : function(value){ if(this.isHex3String(value)){ return this.__hex3StringToRgb(value); }; throw new Error("Invalid hex3 value: " + value); }, /** * Converts a hex3 (#xxx) string to a hex6 (#xxxxxx) string. * * @param value {String} a hex3 (#xxx) string * @return {String} The hex6 (#xxxxxx) string or the passed value when the * passed value is not an hex3 (#xxx) value. */ hex3StringToHex6String : function(value){ if(this.isHex3String(value)){ return this.rgbToHexString(this.hex3StringToRgb(value)); }; return value; }, /** * Converts a hex6 string to an RGB array * * @param value {String} a hex6 (#xxxxxx) string * @return {Array} an array with red, green, blue */ hex6StringToRgb : function(value){ if(this.isHex6String(value)){ return this.__hex6StringToRgb(value); }; throw new Error("Invalid hex6 value: " + value); }, /** * Converts a hex string to an RGB array * * @param value {String} a hex3 (#xxx) or hex6 (#xxxxxx) string * @return {Array} an array with red, green, blue */ hexStringToRgb : function(value){ if(this.isHex3String(value)){ return this.__hex3StringToRgb(value); }; if(this.isHex6String(value)){ return this.__hex6StringToRgb(value); }; throw new Error("Invalid hex value: " + value); }, /** * Convert RGB colors to HSB * * @param rgb {Number[]} red, blue and green as array * @return {Array} an array with hue, saturation and brightness */ rgbToHsb : function(rgb){ var hue,saturation,brightness; var red = rgb[0]; var green = rgb[1]; var blue = rgb[2]; var cmax = (red > green) ? red : green; if(blue > cmax){ cmax = blue; }; var cmin = (red < green) ? red : green; if(blue < cmin){ cmin = blue; }; brightness = cmax / 255.0; if(cmax != 0){ saturation = (cmax - cmin) / cmax; } else { saturation = 0; }; if(saturation == 0){ hue = 0; } else { var redc = (cmax - red) / (cmax - cmin); var greenc = (cmax - green) / (cmax - cmin); var bluec = (cmax - blue) / (cmax - cmin); if(red == cmax){ hue = bluec - greenc; } else if(green == cmax){ hue = 2.0 + redc - bluec; } else { hue = 4.0 + greenc - redc; }; hue = hue / 6.0; if(hue < 0){ hue = hue + 1.0; }; }; return [Math.round(hue * 360), Math.round(saturation * 100), Math.round(brightness * 100)]; }, /** * Convert HSB colors to RGB * * @param hsb {Number[]} an array with hue, saturation and brightness * @return {Integer[]} an array with red, green, blue */ hsbToRgb : function(hsb){ var i,f,p,q,t; var hue = hsb[0] / 360; var saturation = hsb[1] / 100; var brightness = hsb[2] / 100; if(hue >= 1.0){ hue %= 1.0; }; if(saturation > 1.0){ saturation = 1.0; }; if(brightness > 1.0){ brightness = 1.0; }; var tov = Math.floor(255 * brightness); var rgb = { }; if(saturation == 0.0){ rgb.red = rgb.green = rgb.blue = tov; } else { hue *= 6.0; i = Math.floor(hue); f = hue - i; p = Math.floor(tov * (1.0 - saturation)); q = Math.floor(tov * (1.0 - (saturation * f))); t = Math.floor(tov * (1.0 - (saturation * (1.0 - f)))); switch(i){case 0: rgb.red = tov; rgb.green = t; rgb.blue = p; break;case 1: rgb.red = q; rgb.green = tov; rgb.blue = p; break;case 2: rgb.red = p; rgb.green = tov; rgb.blue = t; break;case 3: rgb.red = p; rgb.green = q; rgb.blue = tov; break;case 4: rgb.red = t; rgb.green = p; rgb.blue = tov; break;case 5: rgb.red = tov; rgb.green = p; rgb.blue = q; break;}; }; return [rgb.red, rgb.green, rgb.blue]; }, /** * Creates a random color. * * @return {String} a valid qooxdoo/CSS rgb color string. */ randomColor : function(){ var r = Math.round(Math.random() * 255); var g = Math.round(Math.random() * 255); var b = Math.round(Math.random() * 255); return this.rgbToRgbString([r, g, b]); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2011 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /** * This is a cross browser wrapper for requestAnimationFrame. For further * information about the feature, take a look at spec: * http://www.w3.org/TR/animation-timing/ * * This class offers two ways of using this feature. First, the plain * API the spec describes. * * Here is a sample usage: * <pre class='javascript'>var start = +(new Date()); * var clb = function(time) { * if (time >= start + duration) { * // ... do some last tasks * } else { * var timePassed = time - start; * // ... calculate the current step and apply it * qx.bom.AnimationFrame.request(clb, this); * } * }; * qx.bom.AnimationFrame.request(clb, this); * </pre> * * Another way of using it is to use it as an instance emitting events. * * Here is a sample usage of that API: * <pre class='javascript'>var frame = new qx.bom.AnimationFrame(); * frame.on("end", function() { * // ... do some last tasks * }, this); * frame.on("frame", function(timePassed) { * // ... calculate the current step and apply it * }, this); * frame.startSequence(duration); * </pre> */ qx.Bootstrap.define("qx.bom.AnimationFrame", { extend : qx.event.Emitter, events : { /** Fired as soon as the animation has ended. */ "end" : undefined, /** Fired on every frame having the passed time as value. */ "frame" : "Number" }, members : { /** * Method used to start a series of animation frames. The series will end as * soon as the given duration is over. * * @param duration {Number} The duration the sequence should take. */ startSequence : function(duration){ var start = +(new Date()); var clb = function(){ var time = +(new Date()); // final call if(time >= start + duration){ this.emit("end"); this.id = null; } else { var timePassed = time - start; this.emit("frame", timePassed); this.id = qx.bom.AnimationFrame.request(clb, this); }; }; this.id = qx.bom.AnimationFrame.request(clb, this); } }, statics : { /** * The default time in ms the timeout fallback implementation uses. */ TIMEOUT : 30, /** * Calculation of the predefined timing functions. Approximation of the real * bezier curves has ben used for easier calculation. This is good and close * enough for the predefined functions like <code>ease</code> or * <code>linear</code>. * * @param func {String} The defined timing function. One of the following values: * <code>"ease-in"</code>, <code>"ease-out"</code>, <code>"linear"</code>, * <code>"ease-in-out"</code>, <code>"ease"</code>. * @param x {Integer} The percent value of the function. * @return {Integer} The calculated value */ calculateTiming : function(func, x){ if(func == "ease-in"){ var a = [3.1223e-7, 0.0757, 1.2646, -0.167, -0.4387, 0.2654]; } else if(func == "ease-out"){ var a = [-7.0198e-8, 1.652, -0.551, -0.0458, 0.1255, -0.1807]; } else if(func == "linear"){ return x; } else if(func == "ease-in-out"){ var a = [2.482e-7, -0.2289, 3.3466, -1.0857, -1.7354, 0.7034]; } else { // default is 'ease' var a = [-0.0021, 0.2472, 9.8054, -21.6869, 17.7611, -5.1226]; };;; // A 6th grade polynomial has been used as approximation of the original // bezier curves described in the transition spec // http://www.w3.org/TR/css3-transitions/#transition-timing-function_tag // (the same is used for animations as well) var y = 0; for(var i = 0;i < a.length;i++){ y += a[i] * Math.pow(x, i); }; return y; }, /** * Request for an animation frame. If the native <code>requestAnimationFrame</code> * method is supported, it will be used. Otherwise, we use timeouts with a * 30ms delay. * @param callback {Function} The callback function which will get the current * time as argument. * @param context {var} The context of the callback. * @return {Number} The id of the request. */ request : function(callback, context){ var req = qx.core.Environment.get("css.animation.requestframe"); var clb = function(){ var time = +(new Date()); callback.call(context, time); }; if(req){ return window[req](clb); } else { return window.setTimeout(clb, qx.bom.AnimationFrame.TIMEOUT); }; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * Abstract class to compute the position of an object on one axis. */ qx.Bootstrap.define("qx.util.placement.AbstractAxis", { extend : Object, statics : { /** * Computes the start of the object on the axis * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param areaSize {Integer} Size of the axis. * @param position {String} Alignment of the object on the target. Valid values are * <ul> * <li><code>edge-start</code> The object is placed before the target</li> * <li><code>edge-end</code> The object is placed after the target</li> * <li><code>align-start</code>The start of the object is aligned with the start of the target</li> * <li><code>align-center</code>The center of the object is aligned with the center of the target</li> * <li><code>align-end</code>The end of the object is aligned with the end of the object</li> * </ul> * @return {Integer} The computed start position of the object. * @abstract */ computeStart : function(size, target, offsets, areaSize, position){ throw new Error("abstract method call!"); }, /** * Computes the start of the object by taking only the attachment and * alignment into account. The object by be not fully visible. * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param position {String} Accepts the same values as the <code> position</code> * argument of {@link #computeStart}. * @return {Integer} The computed start position of the object. */ _moveToEdgeAndAlign : function(size, target, offsets, position){ switch(position){case "edge-start": return target.start - offsets.end - size;case "edge-end": return target.end + offsets.start;case "align-start": return target.start + offsets.start;case "align-center": return target.start + parseInt((target.end - target.start - size) / 2, 10) + offsets.start;case "align-end": return target.end - offsets.end - size;}; }, /** * Whether the object specified by <code>start</code> and <code>size</code> * is completely inside of the axis' range.. * * @param start {Integer} Computed start position of the object * @param size {Integer} Size of the object * @param areaSize {Integer} The size of the axis * @return {Boolean} Whether the object is inside of the axis' range */ _isInRange : function(start, size, areaSize){ return start >= 0 && start + size <= areaSize; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * Places the object directly at the specified position. It is not moved if * parts of the object are outside of the axis' range. */ qx.Bootstrap.define("qx.util.placement.DirectAxis", { statics : { /** * Computes the start of the object by taking only the attachment and * alignment into account. The object by be not fully visible. * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param position {String} Accepts the same values as the <code> position</code> * argument of {@link #computeStart}. * @return {Integer} The computed start position of the object. */ _moveToEdgeAndAlign : qx.util.placement.AbstractAxis._moveToEdgeAndAlign, /** * Computes the start of the object on the axis * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param areaSize {Integer} Size of the axis. * @param position {String} Alignment of the object on the target. Valid values are * <ul> * <li><code>edge-start</code> The object is placed before the target</li> * <li><code>edge-end</code> The object is placed after the target</li> * <li><code>align-start</code>The start of the object is aligned with the start of the target</li> * <li><code>align-center</code>The center of the object is aligned with the center of the target</li> * <li><code>align-end</code>The end of the object is aligned with the end of the object</li> * </ul> * @return {Integer} The computed start position of the object. */ computeStart : function(size, target, offsets, areaSize, position){ return this._moveToEdgeAndAlign(size, target, offsets, position); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * Places the object to the target. If parts of the object are outside of the * range this class places the object at the best "edge", "alignment" * combination so that the overlap between object and range is maximized. */ qx.Bootstrap.define("qx.util.placement.KeepAlignAxis", { statics : { /** * Computes the start of the object by taking only the attachment and * alignment into account. The object by be not fully visible. * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param position {String} Accepts the same values as the <code> position</code> * argument of {@link #computeStart}. * @return {Integer} The computed start position of the object. */ _moveToEdgeAndAlign : qx.util.placement.AbstractAxis._moveToEdgeAndAlign, /** * Whether the object specified by <code>start</code> and <code>size</code> * is completely inside of the axis' range.. * * @param start {Integer} Computed start position of the object * @param size {Integer} Size of the object * @param areaSize {Integer} The size of the axis * @return {Boolean} Whether the object is inside of the axis' range */ _isInRange : qx.util.placement.AbstractAxis._isInRange, /** * Computes the start of the object on the axis * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param areaSize {Integer} Size of the axis. * @param position {String} Alignment of the object on the target. Valid values are * <ul> * <li><code>edge-start</code> The object is placed before the target</li> * <li><code>edge-end</code> The object is placed after the target</li> * <li><code>align-start</code>The start of the object is aligned with the start of the target</li> * <li><code>align-center</code>The center of the object is aligned with the center of the target</li> * <li><code>align-end</code>The end of the object is aligned with the end of the object</li> * </ul> * @return {Integer} The computed start position of the object. */ computeStart : function(size, target, offsets, areaSize, position){ var start = this._moveToEdgeAndAlign(size, target, offsets, position); var range1End,range2Start; if(this._isInRange(start, size, areaSize)){ return start; }; if(position == "edge-start" || position == "edge-end"){ range1End = target.start - offsets.end; range2Start = target.end + offsets.start; } else { range1End = target.end - offsets.end; range2Start = target.start + offsets.start; }; if(range1End > areaSize - range2Start){ start = range1End - size; } else { start = range2Start; }; return start; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) * Christian Hagendorn (chris_schmidt) ************************************************************************ */ /** * Places the object according to the target. If parts of the object are outside * of the axis' range the object's start is adjusted so that the overlap between * the object and the axis is maximized. */ qx.Bootstrap.define("qx.util.placement.BestFitAxis", { statics : { /** * Whether the object specified by <code>start</code> and <code>size</code> * is completely inside of the axis' range.. * * @param start {Integer} Computed start position of the object * @param size {Integer} Size of the object * @param areaSize {Integer} The size of the axis * @return {Boolean} Whether the object is inside of the axis' range */ _isInRange : qx.util.placement.AbstractAxis._isInRange, /** * Computes the start of the object by taking only the attachment and * alignment into account. The object by be not fully visible. * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param position {String} Accepts the same values as the <code> position</code> * argument of {@link #computeStart}. * @return {Integer} The computed start position of the object. */ _moveToEdgeAndAlign : qx.util.placement.AbstractAxis._moveToEdgeAndAlign, /** * Computes the start of the object on the axis * * @param size {Integer} Size of the object to align * @param target {Map} Location of the object to align the object to. This map * should have the keys <code>start</code> and <code>end</code>. * @param offsets {Map} Map with all offsets on each side. * Comes with the keys <code>start</code> and <code>end</code>. * @param areaSize {Integer} Size of the axis. * @param position {String} Alignment of the object on the target. Valid values are * <ul> * <li><code>edge-start</code> The object is placed before the target</li> * <li><code>edge-end</code> The object is placed after the target</li> * <li><code>align-start</code>The start of the object is aligned with the start of the target</li> * <li><code>align-center</code>The center of the object is aligned with the center of the target</li> * <li><code>align-end</code>The end of the object is aligned with the end of the object</li> * </ul> * @return {Integer} The computed start position of the object. */ computeStart : function(size, target, offsets, areaSize, position){ var start = this._moveToEdgeAndAlign(size, target, offsets, position); if(this._isInRange(start, size, areaSize)){ return start; }; if(start < 0){ start = Math.min(0, areaSize - size); }; if(start + size > areaSize){ start = Math.max(0, areaSize - size); }; return start; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.util.placement.KeepAlignAxis#computeStart) #require(qx.util.placement.BestFitAxis#computeStart) #require(qx.util.placement.DirectAxis#computeStart) ************************************************************************ */ /** * The Placement module provides a convenient way to align two elements relative * to each other using various pre-defined algorithms. */ qxWeb.define("qx.module.Placement", { statics : { /** * Moves the first element in the collection, aligning it with the given * target. * * @attach{qxWeb} * @param target {Element} Placement target * @param position {String} Alignment of the object with the target, any of * <code>"top-left"</code>, <code>"top-center"</code>, <code>"top-right"</code>, * <code>"bottom-left"</code>, <code>"bottom-center"</code>, <code>"bottom-right"</code>, * <code>"left-top"</code>, <code>"left-middle"</code>, <code>"left-bottom"</code>, * <code>"right-top"</code>, <code>"right-middle"</code>, <code>"right-bottom"</code> * @param offsets {Map?null} Map with the desired offsets between the two elements. * Must contain the keys <code>left</code>, <code>top</code>, * <code>right</code> and <code>bottom</code> * @param modeX {String?"direct"} Horizontal placement mode. Valid values are: * <ul> * <li><code>direct</code>: place the element directly at the given * location.</li> * <li><code>keep-align</code>: if the element is partially outside of the * visible area, it is moved to the best fitting 'edge' and 'alignment' of * the target. * It is guaranteed the the new position attaches the object to one of the * target edges and that it is aligned with a target edge.</li> * <li><code>best-fit</code>: If the element is partially outside of the visible * area, it is moved into the view port, ignoring any offset and position * values.</li> * </ul> * @param modeY {String?"direct"} Vertical placement mode. Accepts the same values as * the 'modeX' argument. * @return {qxWeb} The collection for chaining */ placeTo : function(target, position, offsets, modeX, modeY){ if(!this[0]){ return null; }; var axes = { x : qx.module.Placement._getAxis(modeX), y : qx.module.Placement._getAxis(modeY) }; var size = { width : this.getWidth(), height : this.getHeight() }; var parent = this.getParents(); var area = { width : parent.getWidth(), height : parent.getHeight() }; var target = qxWeb(target).getOffset(); var offsets = offsets || { top : 0, right : 0, bottom : 0, left : 0 }; var splitted = position.split("-"); var edge = splitted[0]; var align = splitted[1]; var position = { x : qx.module.Placement._getPositionX(edge, align), y : qx.module.Placement._getPositionY(edge, align) }; var newLocation = qx.module.Placement._computePlacement(axes, size, area, target, offsets, position); this.setStyles({ position : "absolute", left : newLocation.left + "px", top : newLocation.top + "px" }); return this; }, /** * Returns the appropriate axis implementation for the given placement * mode * * @param mode {String} Placement mode * @return {Object} Placement axis class */ _getAxis : function(mode){ switch(mode){case "keep-align": return qx.util.placement.KeepAlignAxis;case "best-fit": return qx.util.placement.BestFitAxis;case "direct":default: return qx.util.placement.DirectAxis;}; }, /** * Returns the computed coordinates for the element to be placed * * @param axes {Map} Map with the keys <code>x</code> and <code>y</code>. Values * are the axis implementations * @param size {Map} Map with the keys <code>width</code> and <code>height</code> * containing the size of the placement target * @param area {Map} Map with the keys <code>width</code> and <code>height</code> * containing the size of the two elements' common parent (available space for * placement) * @param target {qxWeb} Collection containing the placement target * @param offsets {Map} Map of offsets (top, right, bottom, left) * @param position {Map} Map with the keys <code>x</code> and <code>y</code>, * containing the type of positioning for each axis * @return {Map} Map with the keys <code>left</code> and <code>top</code> * containing the computed coordinates to which the element should be moved */ _computePlacement : function(axes, size, area, target, offsets, position){ var left = axes.x.computeStart(size.width, { start : target.left, end : target.right }, { start : offsets.left, end : offsets.right }, area.width, position.x); var top = axes.y.computeStart(size.height, { start : target.top, end : target.bottom }, { start : offsets.top, end : offsets.bottom }, area.height, position.y); return { left : left, top : top }; }, /** * Returns the X axis positioning type for the given edge and alignment * values * * @param edge {String} edge value * @param align {String} align value * @return {String} X positioning type */ _getPositionX : function(edge, align){ if(edge == "left"){ return "edge-start"; } else if(edge == "right"){ return "edge-end"; } else if(align == "left"){ return "align-start"; } else if(align == "right"){ return "align-end"; };;; }, /** * Returns the Y axis positioning type for the given edge and alignment * values * * @param edge {String} edge value * @param align {String} align value * @return {String} Y positioning type */ _getPositionY : function(edge, align){ if(edge == "top"){ return "edge-start"; } else if(edge == "bottom"){ return "edge-end"; } else if(align == "top"){ return "align-start"; } else if(align == "bottom"){ return "align-end"; };;; } }, defer : function(statics){ qxWeb.$attach({ "placeTo" : statics.placeTo }); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Event) ************************************************************************ */ /** * Creates a touch event handler that fires high-level events such as "swipe" * based on low-level event sequences on the given element */ qx.Bootstrap.define("qx.module.event.TouchHandler", { statics : { /** * List of events that require a touch handler * @type {Array} */ TYPES : ["tap", "swipe"], /** * Creates a touch handler for the given element when a touch event listener * is attached to it * * @param element {Element} DOM element */ register : function(element){ if(!element.__touchHandler){ if(!element.__emitter){ element.__emitter = new qx.event.Emitter(); }; element.__touchHandler = new qx.event.handler.TouchCore(element, element.__emitter); }; }, /** * Removes the touch event handler from the element if there are no more * touch event listeners attached to it * @param element {Element} DOM element */ unregister : function(element){ if(element.__touchHandler){ if(!element.__emitter){ element.__touchHandler = null; } else { var hasTouchListener = false; var listeners = element.__emitter.getListeners(); qx.module.event.TouchHandler.TYPES.forEach(function(type){ if(type in listeners && listeners[type].length > 0){ hasTouchListener = true; }; }); if(!hasTouchListener){ element.__touchHandler = null; }; }; }; } }, defer : function(statics){ qxWeb.$registerEventHook(statics.TYPES, statics.register, statics.unregister); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (martinwittemann) * Tino Butz (tbtz) * Christian Hagendorn (chris_schmidt) * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #ignore(qx.event.type.Tap) #ignore(qx.event.type.Swipe) #ignore(qx.event.type) #ignore(qx.event) ************************************************************************ */ /** * Listens for native touch events and fires composite events like "tap" and * "swipe" */ qx.Bootstrap.define("qx.event.handler.TouchCore", { extend : Object, statics : { /** {Integer} The maximum distance of a tap. Only if the x or y distance of * the performed tap is less or equal the value of this constant, a tap * event is fired. */ TAP_MAX_DISTANCE : qx.core.Environment.get("os.name") != "android" ? 10 : 40, /** {Map} The direction of a swipe relative to the axis */ SWIPE_DIRECTION : { x : ["left", "right"], y : ["up", "down"] }, /** {Integer} The minimum distance of a swipe. Only if the x or y distance * of the performed swipe is greater as or equal the value of this * constant, a swipe event is fired. */ SWIPE_MIN_DISTANCE : qx.core.Environment.get("os.name") != "android" ? 11 : 41, /** {Integer} The minimum velocity of a swipe. Only if the velocity of the * performed swipe is greater as or equal the value of this constant, a * swipe event is fired. */ SWIPE_MIN_VELOCITY : 0 }, /** * Create a new instance * * @param target {Element} element on which to listen for native touch events * @param emitter {qx.event.Emitter} Event emitter object */ construct : function(target, emitter){ this.__target = target; this.__emitter = emitter; this._initTouchObserver(); }, members : { __target : null, __emitter : null, __onTouchEventWrapper : null, __originalTarget : null, __startPageX : null, __startPageY : null, __startTime : null, __isSingleTouchGesture : null, __onMove : null, /* --------------------------------------------------------------------------- OBSERVER INIT --------------------------------------------------------------------------- */ /** * Initializes the native touch event listeners. */ _initTouchObserver : function(){ this.__onTouchEventWrapper = qx.lang.Function.listener(this._onTouchEvent, this); var Event = qx.bom.Event; Event.addNativeListener(this.__target, "touchstart", this.__onTouchEventWrapper); Event.addNativeListener(this.__target, "touchmove", this.__onTouchEventWrapper); Event.addNativeListener(this.__target, "touchend", this.__onTouchEventWrapper); Event.addNativeListener(this.__target, "touchcancel", this.__onTouchEventWrapper); if(qx.core.Environment.get("event.mspointer")){ Event.addNativeListener(this.__target, "MSPointerDown", this.__onTouchEventWrapper); Event.addNativeListener(this.__target, "MSPointerMove", this.__onTouchEventWrapper); Event.addNativeListener(this.__target, "MSPointerUp", this.__onTouchEventWrapper); Event.addNativeListener(this.__target, "MSPointerCancel", this.__onTouchEventWrapper); }; }, /* --------------------------------------------------------------------------- OBSERVER STOP --------------------------------------------------------------------------- */ /** * Disconnects the native touch event listeners. */ _stopTouchObserver : function(){ var Event = qx.bom.Event; Event.removeNativeListener(this.__target, "touchstart", this.__onTouchEventWrapper); Event.removeNativeListener(this.__target, "touchmove", this.__onTouchEventWrapper); Event.removeNativeListener(this.__target, "touchend", this.__onTouchEventWrapper); Event.removeNativeListener(this.__target, "touchcancel", this.__onTouchEventWrapper); if(qx.core.Environment.get("event.mspointer")){ Event.removeNativeListener(this.__target, "MSPointerDown", this.__onTouchEventWrapper); Event.removeNativeListener(this.__target, "MSPointerMove", this.__onTouchEventWrapper); Event.removeNativeListener(this.__target, "MSPointerUp", this.__onTouchEventWrapper); Event.removeNativeListener(this.__target, "MSPointerCancel", this.__onTouchEventWrapper); }; }, /* --------------------------------------------------------------------------- NATIVE EVENT OBSERVERS --------------------------------------------------------------------------- */ /** * Handler for native touch events. * * @param domEvent {Event} The touch event from the browser. */ _onTouchEvent : function(domEvent){ this._commonTouchEventHandler(domEvent); }, /** * Called by an event handler. * * @param domEvent {Event} DOM event * @param type {String ? null} type of the event */ _commonTouchEventHandler : function(domEvent, type){ var type = type || domEvent.type; if(qx.core.Environment.get("event.mspointer")){ domEvent.changedTouches = [domEvent]; domEvent.targetTouches = [domEvent]; domEvent.touches = [domEvent]; if(type == "MSPointerDown"){ type = "touchstart"; } else if(type == "MSPointerUp"){ type = "touchend"; } else if(type == "MSPointerMove"){ if(this.__onMove == true){ type = "touchmove"; }; } else if(type == "MSPointerCancel"){ type = "touchcancel"; };;; }; if(type == "touchstart"){ this.__originalTarget = this._getTarget(domEvent); }; this._fireEvent(domEvent, type); this.__checkAndFireGesture(domEvent, type); }, /* --------------------------------------------------------------------------- HELPERS --------------------------------------------------------------------------- */ /** * Return the target of the event. * * @param domEvent {Event} DOM event * @return {Element} Event target */ _getTarget : function(domEvent){ var target = qx.bom.Event.getTarget(domEvent); // Text node. Fix Safari Bug, see http://www.quirksmode.org/js/events_properties.html if(qx.core.Environment.get("engine.name") == "webkit"){ if(target && target.nodeType == 3){ target = target.parentNode; }; } else if(qx.core.Environment.get("event.mspointer")){ // Fix for IE10 and pointer-events:none var targetForIE = this.__evaluateTarget(domEvent); if(targetForIE){ target = targetForIE; }; }; return target; }, /** * This method fixes "pointer-events:none" for Internet Explorer 10. * Checks which elements are placed to position x/y and traverses the array * till one element has no "pointer-events:none" inside its style attribute. * @param domEvent {Event} DOM event * @return {Element | null} Event target */ __evaluateTarget : function(domEvent){ if(domEvent && domEvent.touches){ var clientX = domEvent.touches[0].clientX; var clientY = domEvent.touches[0].clientY; }; // Retrieve an array with elements on point X/Y. var hitTargets = document.msElementsFromPoint(clientX, clientY); if(hitTargets){ // Traverse this array for the elements which has no pointer-events:none inside. for(var i = 0;i < hitTargets.length;i++){ var currentTarget = hitTargets[i]; var pointerEvents = qx.bom.element.Style.get(currentTarget, "pointer-events", 3); if(pointerEvents != "none"){ return currentTarget; }; }; }; return null; }, /** * Fire a touch event with the given parameters * * @param domEvent {Event} DOM event * @param type {String ? null} type of the event * @param target {Element ? null} event target */ _fireEvent : function(domEvent, type, target){ if(!target){ target = this._getTarget(domEvent); }; var type = type || domEvent.type; if(target && target.nodeType && this.__emitter){ this.__emitter.emit(type, domEvent); }; }, /** * Checks if a gesture was made and fires the gesture event. * * @param domEvent {Event} DOM event * @param type {String ? null} type of the event * @param target {Element ? null} event target */ __checkAndFireGesture : function(domEvent, type, target){ if(!target){ target = this._getTarget(domEvent); }; var type = type || domEvent.type; if(type == "touchstart"){ this.__gestureStart(domEvent, target); } else if(type == "touchmove"){ this.__gestureChange(domEvent, target); } else if(type == "touchend"){ this.__gestureEnd(domEvent, target); };; }, /** * Helper method for gesture start. * * @param domEvent {Event} DOM event * @param target {Element} event target */ __gestureStart : function(domEvent, target){ var touch = domEvent.changedTouches[0]; this.__onMove = true; this.__startPageX = touch.screenX; this.__startPageY = touch.screenY; this.__startTime = new Date().getTime(); this.__isSingleTouchGesture = domEvent.changedTouches.length === 1; }, /** * Helper method for gesture change. * * @param domEvent {Event} DOM event * @param target {Element} event target */ __gestureChange : function(domEvent, target){ // Abort a single touch gesture when another touch occurs. if(this.__isSingleTouchGesture && domEvent.changedTouches.length > 1){ this.__isSingleTouchGesture = false; }; }, /** * Helper method for gesture end. * * @param domEvent {Event} DOM event * @param target {Element} event target */ __gestureEnd : function(domEvent, target){ this.__onMove = false; if(this.__isSingleTouchGesture){ var touch = domEvent.changedTouches[0]; var deltaCoordinates = { x : touch.screenX - this.__startPageX, y : touch.screenY - this.__startPageY }; var clazz = qx.event.handler.TouchCore; var eventType; if(this.__originalTarget == target && Math.abs(deltaCoordinates.x) <= clazz.TAP_MAX_DISTANCE && Math.abs(deltaCoordinates.y) <= clazz.TAP_MAX_DISTANCE){ if(qx.event && qx.event.type && qx.event.type.Tap){ eventType = qx.event.type.Tap; }; this._fireEvent(domEvent, "tap", target, eventType); } else { var swipe = this.__getSwipeGesture(domEvent, target, deltaCoordinates); if(swipe){ if(qx.event && qx.event.type && qx.event.type.Swipe){ eventType = qx.event.type.Swipe; }; domEvent.swipe = swipe; this._fireEvent(domEvent, "swipe", target, eventType); }; }; }; }, /** * Returns the swipe gesture when the user performed a swipe. * * @param domEvent {Event} DOM event * @param target {Element} event target * @param deltaCoordinates {Map} delta x/y coordinates since the gesture started. * @return {Map} returns the swipe data when the user performed a swipe, null if the gesture was no swipe. */ __getSwipeGesture : function(domEvent, target, deltaCoordinates){ var clazz = qx.event.handler.TouchCore; var duration = new Date().getTime() - this.__startTime; var axis = (Math.abs(deltaCoordinates.x) >= Math.abs(deltaCoordinates.y)) ? "x" : "y"; var distance = deltaCoordinates[axis]; var direction = clazz.SWIPE_DIRECTION[axis][distance < 0 ? 0 : 1]; var velocity = (duration !== 0) ? distance / duration : 0; var swipe = null; if(Math.abs(velocity) >= clazz.SWIPE_MIN_VELOCITY && Math.abs(distance) >= clazz.SWIPE_MIN_DISTANCE){ swipe = { startTime : this.__startTime, duration : duration, axis : axis, direction : direction, distance : distance, velocity : velocity }; }; return swipe; }, /** * Dispose this object */ dispose : function(){ this._stopTouchObserver(); this.__originalTarget = this.__target = this.__emitter = null; } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Event) ************************************************************************ */ /** * Normalization for orientationchange events * Example: * <pre class="javascript"> * q(window).on("orientationchange", function(ev) { * ev.getOrientation(); * ev.isLandscape(); * }); * </pre> */ qx.Bootstrap.define("qx.module.event.Orientation", { statics : { /** * List of event types to be normalized * @type {Array} */ TYPES : ["orientationchange"], /** * List of qx.module.event.Orientation methods to be attached to native * event objects * @type {Array} * @internal */ BIND_METHODS : ["getOrientation", "isLandscape", "isPortrait"], /** * Returns the current orientation of the viewport in degrees. * * All possible values and their meaning: * * * <code>0</code>: "Portrait" * * <code>-90</code>: "Landscape (right, screen turned clockwise)" * * <code>90</code>: "Landscape (left, screen turned counterclockwise)" * * <code>180</code>: "Portrait (upside-down portrait)" * * @return {Number} The current orientation in degrees */ getOrientation : function(){ return this._orientation; }, /** * Whether the viewport orientation is currently in landscape mode. * * @return {Boolean} <code>true</code> when the viewport orientation * is currently in landscape mode. */ isLandscape : function(){ return this._mode == "landscape"; }, /** * Whether the viewport orientation is currently in portrait mode. * * @return {Boolean} <code>true</code> when the viewport orientation * is currently in portrait mode. */ isPortrait : function(){ return this._mode == "portrait"; }, /** * Manipulates the native event object, adding methods if they're not * already present * * @param event {Event} Native event object * @param element {Element} DOM element the listener was attached to * @param type {String} Event type * @return {Event} Normalized event object * @internal */ normalize : function(event, element, type){ if(!event){ return event; }; event._type = type; var bindMethods = qx.module.event.Orientation.BIND_METHODS; for(var i = 0,l = bindMethods.length;i < l;i++){ if(typeof event[bindMethods[i]] != "function"){ event[bindMethods[i]] = qx.module.event.Orientation[bindMethods[i]].bind(event); }; }; return event; } }, defer : function(statics){ qxWeb.$registerEventNormalization(statics.TYPES, statics.normalize); } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Martin Wittemann (wittemann) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Attribute) #require(qx.module.Css) #require(qx.module.Environment) #require(qx.module.Event) #require(qx.module.Manipulating) #require(qx.module.Polyfill) #require(qx.module.Traversing) ************************************************************************ */ /** * Placeholder class which simply defines and includes the core of qxWeb. * The core modules are: * * * {@link qx.module.Attribute} * * {@link qx.module.Css} * * {@link qx.module.Environment} * * {@link qx.module.Event} * * {@link qx.module.Manipulating} * * {@link qx.module.Polyfill} * * {@link qx.module.Traversing} */ qx.Bootstrap.define("qx.module.Core", { }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /* ************************************************************************ #require(qx.module.Event) #require(qx.module.Environment) ************************************************************************ */ /** * Normalization for native keyboard events */ qx.Bootstrap.define("qx.module.event.Keyboard", { statics : { /** * List of event types to be normalized * @type {Array} */ TYPES : ["keydown", "keypress", "keyup"], /** * List qx.module.event.Keyboard methods to be attached to native mouse event * objects * @type {Array} * @internal */ BIND_METHODS : ["getKeyIdentifier"], /** * Identifier of the pressed key. This property is modeled after the <em>KeyboardEvent.keyIdentifier</em> property * of the W3C DOM 3 event specification * (http://www.w3.org/TR/2003/NOTE-DOM-Level-3-Events-20031107/events.html#Events-KeyboardEvent-keyIdentifier). * * Printable keys are represented by an unicode string, non-printable keys * have one of the following values: * * <table> * <tr><th>Backspace</th><td>The Backspace (Back) key.</td></tr> * <tr><th>Tab</th><td>The Horizontal Tabulation (Tab) key.</td></tr> * <tr><th>Space</th><td>The Space (Spacebar) key.</td></tr> * <tr><th>Enter</th><td>The Enter key. Note: This key identifier is also used for the Return (Macintosh numpad) key.</td></tr> * <tr><th>Shift</th><td>The Shift key.</td></tr> * <tr><th>Control</th><td>The Control (Ctrl) key.</td></tr> * <tr><th>Alt</th><td>The Alt (Menu) key.</td></tr> * <tr><th>CapsLock</th><td>The CapsLock key</td></tr> * <tr><th>Meta</th><td>The Meta key. (Apple Meta and Windows key)</td></tr> * <tr><th>Escape</th><td>The Escape (Esc) key.</td></tr> * <tr><th>Left</th><td>The Left Arrow key.</td></tr> * <tr><th>Up</th><td>The Up Arrow key.</td></tr> * <tr><th>Right</th><td>The Right Arrow key.</td></tr> * <tr><th>Down</th><td>The Down Arrow key.</td></tr> * <tr><th>PageUp</th><td>The Page Up key.</td></tr> * <tr><th>PageDown</th><td>The Page Down (Next) key.</td></tr> * <tr><th>End</th><td>The End key.</td></tr> * <tr><th>Home</th><td>The Home key.</td></tr> * <tr><th>Insert</th><td>The Insert (Ins) key. (Does not fire in Opera/Win)</td></tr> * <tr><th>Delete</th><td>The Delete (Del) Key.</td></tr> * <tr><th>F1</th><td>The F1 key.</td></tr> * <tr><th>F2</th><td>The F2 key.</td></tr> * <tr><th>F3</th><td>The F3 key.</td></tr> * <tr><th>F4</th><td>The F4 key.</td></tr> * <tr><th>F5</th><td>The F5 key.</td></tr> * <tr><th>F6</th><td>The F6 key.</td></tr> * <tr><th>F7</th><td>The F7 key.</td></tr> * <tr><th>F8</th><td>The F8 key.</td></tr> * <tr><th>F9</th><td>The F9 key.</td></tr> * <tr><th>F10</th><td>The F10 key.</td></tr> * <tr><th>F11</th><td>The F11 key.</td></tr> * <tr><th>F12</th><td>The F12 key.</td></tr> * <tr><th>NumLock</th><td>The Num Lock key.</td></tr> * <tr><th>PrintScreen</th><td>The Print Screen (PrintScrn, SnapShot) key.</td></tr> * <tr><th>Scroll</th><td>The scroll lock key</td></tr> * <tr><th>Pause</th><td>The pause/break key</td></tr> * <tr><th>Win</th><td>The Windows Logo key</td></tr> * <tr><th>Apps</th><td>The Application key (Windows Context Menu)</td></tr> * </table> * * @return {String} The key identifier */ getKeyIdentifier : function(){ if(this.type == "keypress" && (qxWeb.env.get("engine.name") != "gecko" || this.charCode !== 0)){ return qx.event.util.Keyboard.charCodeToIdentifier(this.charCode || this.keyCode); }; return qx.event.util.Keyboard.keyCodeToIdentifier(this.keyCode); }, /** * Manipulates the native event object, adding methods if they're not * already present * * @param event {Event} Native event object * @param element {Element} DOM element the listener was attached to * @return {Event} Normalized event object * @internal */ normalize : function(event, element){ if(!event){ return event; }; var bindMethods = qx.module.event.Keyboard.BIND_METHODS; for(var i = 0,l = bindMethods.length;i < l;i++){ if(typeof event[bindMethods[i]] != "function"){ event[bindMethods[i]] = qx.module.event.Keyboard[bindMethods[i]].bind(event); }; }; return event; }, /** * IE9 will not fire an "input" event on text input elements if the user changes * the field's value by pressing the Backspace key. We fix this by listening * for the "keyup" event and emitting the missing event if necessary * * @param element {Element} Target element */ registerInputFix : function(element){ if(element.type === "text" || element.type === "password" || element.type === "textarea"){ if(!element.__inputFix){ element.__inputFix = qxWeb(element).on("keyup", qx.module.event.Keyboard._inputFix); }; }; }, /** * Removes the IE9 input event fix * @param element {Element} target element */ unregisterInputFix : function(element){ if(element.__inputFix && !qxWeb(element).hasListener("input")){ qxWeb(element).off("keyup", qx.module.event.Keyboard._inputFix); element.__inputFix = null; }; }, /** * IE9 fix: Emits an "input" event if a text input element's value was changed * using the Backspace key * @param ev {Event} Keyup event */ _inputFix : function(ev){ if(ev.getKeyIdentifier() !== "Backspace"){ return; }; var target = ev.getTarget(); var newValue = qxWeb(target).getValue(); if(!target.__oldInputValue || target.__oldInputValue !== newValue){ target.__oldInputValue = newValue; ev.type = ev._type = "input"; target.__emitter.emit("input", ev); }; } }, defer : function(statics){ qxWeb.$registerEventNormalization(qx.module.event.Keyboard.TYPES, statics.normalize); if(qxWeb.env.get("engine.name") === "mshtml" && qxWeb.env.get("browser.documentmode") === 9){ qxWeb.$registerEventHook("input", statics.registerInputFix, statics.unregisterInputFix); }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) * Fabian Jakobs (fjakobs) ************************************************************************ */ /** * Utilities for working with character codes and key identifiers */ qx.Bootstrap.define("qx.event.util.Keyboard", { statics : { /* --------------------------------------------------------------------------- KEY MAPS --------------------------------------------------------------------------- */ /** * {Map} maps the charcodes of special printable keys to key identifiers * * @lint ignoreReferenceField(specialCharCodeMap) */ specialCharCodeMap : { '8' : "Backspace", // The Backspace (Back) key. '9' : "Tab", // The Horizontal Tabulation (Tab) key. // Note: This key identifier is also used for the // Return (Macintosh numpad) key. '13' : "Enter", // The Enter key. '27' : "Escape", // The Escape (Esc) key. '32' : "Space" }, /** * {Map} maps the keycodes of the numpad keys to the right charcodes * * @lint ignoreReferenceField(numpadToCharCode) */ numpadToCharCode : { '96' : "0".charCodeAt(0), '97' : "1".charCodeAt(0), '98' : "2".charCodeAt(0), '99' : "3".charCodeAt(0), '100' : "4".charCodeAt(0), '101' : "5".charCodeAt(0), '102' : "6".charCodeAt(0), '103' : "7".charCodeAt(0), '104' : "8".charCodeAt(0), '105' : "9".charCodeAt(0), '106' : "*".charCodeAt(0), '107' : "+".charCodeAt(0), '109' : "-".charCodeAt(0), '110' : ",".charCodeAt(0), '111' : "/".charCodeAt(0) }, /** * {Map} maps the keycodes of non printable keys to key identifiers * * @lint ignoreReferenceField(keyCodeToIdentifierMap) */ keyCodeToIdentifierMap : { '16' : "Shift", // The Shift key. '17' : "Control", // The Control (Ctrl) key. '18' : "Alt", // The Alt (Menu) key. '20' : "CapsLock", // The CapsLock key '224' : "Meta", // The Meta key. (Apple Meta and Windows key) '37' : "Left", // The Left Arrow key. '38' : "Up", // The Up Arrow key. '39' : "Right", // The Right Arrow key. '40' : "Down", // The Down Arrow key. '33' : "PageUp", // The Page Up key. '34' : "PageDown", // The Page Down (Next) key. '35' : "End", // The End key. '36' : "Home", // The Home key. '45' : "Insert", // The Insert (Ins) key. (Does not fire in Opera/Win) '46' : "Delete", // The Delete (Del) Key. '112' : "F1", // The F1 key. '113' : "F2", // The F2 key. '114' : "F3", // The F3 key. '115' : "F4", // The F4 key. '116' : "F5", // The F5 key. '117' : "F6", // The F6 key. '118' : "F7", // The F7 key. '119' : "F8", // The F8 key. '120' : "F9", // The F9 key. '121' : "F10", // The F10 key. '122' : "F11", // The F11 key. '123' : "F12", // The F12 key. '144' : "NumLock", // The Num Lock key. '44' : "PrintScreen", // The Print Screen (PrintScrn, SnapShot) key. '145' : "Scroll", // The scroll lock key '19' : "Pause", // The pause/break key // The left Windows Logo key or left cmd key '91' : qx.core.Environment.get("os.name") == "osx" ? "cmd" : "Win", '92' : "Win", // The right Windows Logo key or left cmd key // The Application key (Windows Context Menu) or right cmd key '93' : qx.core.Environment.get("os.name") == "osx" ? "cmd" : "Apps" }, /** char code for capital A */ charCodeA : "A".charCodeAt(0), /** char code for capital Z */ charCodeZ : "Z".charCodeAt(0), /** char code for 0 */ charCode0 : "0".charCodeAt(0), /** char code for 9 */ charCode9 : "9".charCodeAt(0), /** * converts a keyboard code to the corresponding identifier * * @param keyCode {Integer} key code * @return {String} key identifier */ keyCodeToIdentifier : function(keyCode){ if(this.isIdentifiableKeyCode(keyCode)){ var numPadKeyCode = this.numpadToCharCode[keyCode]; if(numPadKeyCode){ return String.fromCharCode(numPadKeyCode); }; return (this.keyCodeToIdentifierMap[keyCode] || this.specialCharCodeMap[keyCode] || String.fromCharCode(keyCode)); } else { return "Unidentified"; }; }, /** * converts a character code to the corresponding identifier * * @param charCode {String} character code * @return {String} key identifier */ charCodeToIdentifier : function(charCode){ return this.specialCharCodeMap[charCode] || String.fromCharCode(charCode).toUpperCase(); }, /** * Check whether the keycode can be reliably detected in keyup/keydown events * * @param keyCode {String} key code to check. * @return {Boolean} Whether the keycode can be reliably detected in keyup/keydown events. */ isIdentifiableKeyCode : function(keyCode){ // A-Z (TODO: is this lower or uppercase?) if(keyCode >= this.charCodeA && keyCode <= this.charCodeZ){ return true; }; // 0-9 if(keyCode >= this.charCode0 && keyCode <= this.charCode9){ return true; }; // Enter, Space, Tab, Backspace if(this.specialCharCodeMap[keyCode]){ return true; }; // Numpad if(this.numpadToCharCode[keyCode]){ return true; }; // non printable keys if(this.isNonPrintableKeyCode(keyCode)){ return true; }; return false; }, /** * Checks whether the keyCode represents a non printable key * * @param keyCode {String} key code to check. * @return {Boolean} Whether the keyCode represents a non printable key. */ isNonPrintableKeyCode : function(keyCode){ return this.keyCodeToIdentifierMap[keyCode] ? true : false; }, /** * Checks whether a given string is a valid keyIdentifier * * @param keyIdentifier {String} The key identifier. * @return {Boolean} whether the given string is a valid keyIdentifier */ isValidKeyIdentifier : function(keyIdentifier){ if(this.identifierToKeyCodeMap[keyIdentifier]){ return true; }; if(keyIdentifier.length != 1){ return false; }; if(keyIdentifier >= "0" && keyIdentifier <= "9"){ return true; }; if(keyIdentifier >= "A" && keyIdentifier <= "Z"){ return true; }; switch(keyIdentifier){case "+":case "-":case "*":case "/": return true;default: return false;}; }, /** * Checks whether a given string is a printable keyIdentifier. * * @param keyIdentifier {String} The key identifier. * @return {Boolean} whether the given string is a printable keyIdentifier. */ isPrintableKeyIdentifier : function(keyIdentifier){ if(keyIdentifier === "Space"){ return true; } else { return this.identifierToKeyCodeMap[keyIdentifier] ? false : true; }; } }, defer : function(statics, members){ // construct inverse of keyCodeToIdentifierMap if(!statics.identifierToKeyCodeMap){ statics.identifierToKeyCodeMap = { }; for(var key in statics.keyCodeToIdentifierMap){ statics.identifierToKeyCodeMap[statics.keyCodeToIdentifierMap[key]] = parseInt(key, 10); }; for(var key in statics.specialCharCodeMap){ statics.identifierToKeyCodeMap[statics.specialCharCodeMap[key]] = parseInt(key, 10); }; }; } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ************************************************************************ */ /** * A wrapper for Cookie handling. */ qx.Bootstrap.define("qx.bom.Cookie", { /* ***************************************************************************** STATICS ***************************************************************************** */ statics : { /* --------------------------------------------------------------------------- USER APPLICATION METHODS --------------------------------------------------------------------------- */ /** * Returns the string value of a cookie. * * @param key {String} The key for the saved string value. * @return {null | String} Returns the saved string value, if the cookie * contains a value for the key, <code>null</code> otherwise. */ get : function(key){ var start = document.cookie.indexOf(key + "="); var len = start + key.length + 1; if((!start) && (key != document.cookie.substring(0, key.length))){ return null; }; if(start == -1){ return null; }; var end = document.cookie.indexOf(";", len); if(end == -1){ end = document.cookie.length; }; return unescape(document.cookie.substring(len, end)); }, /** * Sets the string value of a cookie. * * @param key {String} The key for the string value. * @param value {String} The string value. * @param expires {Number?null} The expires in days starting from now, * or <code>null</code> if the cookie should deleted after browser close. * @param path {String?null} Path value. * @param domain {String?null} Domain value. * @param secure {Boolean?null} Secure flag. */ set : function(key, value, expires, path, domain, secure){ // Generate cookie var cookie = [key, "=", escape(value)]; if(expires){ var today = new Date(); today.setTime(today.getTime()); cookie.push(";expires=", new Date(today.getTime() + (expires * 1000 * 60 * 60 * 24)).toGMTString()); }; if(path){ cookie.push(";path=", path); }; if(domain){ cookie.push(";domain=", domain); }; if(secure){ cookie.push(";secure"); }; // Store cookie document.cookie = cookie.join(""); }, /** * Deletes the string value of a cookie. * * @param key {String} The key for the string value. * @param path {String?null} Path value. * @param domain {String?null} Domain value. */ del : function(key, path, domain){ if(!qx.bom.Cookie.get(key)){ return; }; // Generate cookie var cookie = [key, "="]; if(path){ cookie.push(";path=", path); }; if(domain){ cookie.push(";domain=", domain); }; cookie.push(";expires=Thu, 01-Jan-1970 00:00:01 GMT"); // Store cookie document.cookie = cookie.join(""); } } }); /* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2012 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Daniel Wagner (danielwagner) ************************************************************************ */ /** * Cookie handling module */ qx.Bootstrap.define("qx.module.Cookie", { statics : { /** * Returns the string value of a cookie. * * @attachStatic {qxWeb, cookie.get} * @param key {String} The key for the saved string value. * @return {String|null} Returns the saved string value if the cookie * contains a value for the key, otherwise <code>null</code> * @signature function(key) */ get : qx.bom.Cookie.get, /** * Sets the string value of a cookie. * * @attachStatic {qxWeb, cookie.set} * @param key {String} The key for the string value. * @param value {String} The string value. * @param expires {Number?null} Expires directive value in days starting from now, * or <code>null</code> if the cookie should be deleted when the browser * is closed. * @param path {String?null} Path value. * @param domain {String?null} Domain value. * @param secure {Boolean?null} Secure flag. * @signature function(key, value, expires, path, domain, secure) */ set : qx.bom.Cookie.set, /** * Deletes the string value of a cookie. * * @attachStatic {qxWeb, cookie.del} * @param key {String} The key for the string value. * @param path {String?null} Path value. * @param domain {String?null} Domain value. * @signature function(key, path, domain) */ del : qx.bom.Cookie.del }, defer : function(statics){ qxWeb.$attachStatic({ "cookie" : { get : statics.get, set : statics.set, del : statics.del } }); } }); var exp = envinfo["qx.export"]; if (exp) { for (var name in exp) { var c = exp[name].split("."); var root = window; for (var i=0; i < c.length; i++) { root = root[c[i]]; }; window[name] = root; } } window["qx"] = undefined; try { delete window.qx; } catch(e) {} })();
src/components/OpenGraph/index.js
ndlib/usurper
import React from 'react' import PropTypes from 'prop-types' import { Helmet } from 'react-helmet' import DefaultImage from 'static/images/search.banner.jpg' const OpenGraph = (props) => { const url = props.url || window.location.href const type = props.type || 'article' const title = props.title || document.title || 'Hesburgh Library' const description = props.description || 'Hesburgh Library - University of Notre Dame' let image = DefaultImage if (props.image && props.image.fields && props.image.fields.file) { image = 'https:' + props.image.fields.file.url } return ( <Helmet> <meta name='twitter:card' content='summary_large_image' /> <meta name='twitter:site' content='@NDLibraries' /> <meta name='twitter:title' content={title} /> <meta name='twitter:description' content={description} /> <meta name='twitter:image' content={image} /> <meta property='og:url' content={url} /> <meta property='og:type' content={type} /> <meta property='og:title' content={title} /> <meta property='og:description' content={description} /> <meta property='og:image' content={image} /> </Helmet> ) } OpenGraph.propTypes = { url: PropTypes.string, type: PropTypes.string, title: PropTypes.string, description: PropTypes.string, image: PropTypes.oneOfType([PropTypes.string, PropTypes.object, PropTypes.bool]), } export default OpenGraph
components/calendar/index.js
dotKom/glowing-fortnight
import React from 'react'; import Calendar from './calendar'; const CalendarContainer = ({ events, error = null }) => { return ( <section id="calendar" className="component"> <h1> Program. <a href="https://online.ntnu.no/splash/events.ics">iCalendar</a> </h1> <Calendar events={events} error={error} /> </section> ); }; export default CalendarContainer;
ajax/libs/vega-lite/2.0.0-beta.9/vega-lite.js
sufuf3/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.vl = 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){ var json = typeof JSON !== 'undefined' ? JSON : require('jsonify'); module.exports = function (obj, opts) { if (!opts) opts = {}; if (typeof opts === 'function') opts = { cmp: opts }; var space = opts.space || ''; if (typeof space === 'number') space = Array(space+1).join(' '); var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false; var replacer = opts.replacer || function(key, value) { return value; }; var cmp = opts.cmp && (function (f) { return function (node) { return function (a, b) { var aobj = { key: a, value: node[a] }; var bobj = { key: b, value: node[b] }; return f(aobj, bobj); }; }; })(opts.cmp); var seen = []; return (function stringify (parent, key, node, level) { var indent = space ? ('\n' + new Array(level + 1).join(space)) : ''; var colonSeparator = space ? ': ' : ':'; if (node && node.toJSON && typeof node.toJSON === 'function') { node = node.toJSON(); } node = replacer.call(parent, key, node); if (node === undefined) { return; } if (typeof node !== 'object' || node === null) { return json.stringify(node); } if (isArray(node)) { var out = []; for (var i = 0; i < node.length; i++) { var item = stringify(node, i, node[i], level+1) || json.stringify(null); out.push(indent + space + item); } return '[' + out.join(',') + indent + ']'; } else { if (seen.indexOf(node) !== -1) { if (cycles) return json.stringify('__cycle__'); throw new TypeError('Converting circular structure to JSON'); } else seen.push(node); var keys = objectKeys(node).sort(cmp && cmp(node)); var out = []; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = stringify(node, key, node[key], level+1); if(!value) continue; var keyValue = json.stringify(key) + colonSeparator + value; ; out.push(indent + space + keyValue); } seen.splice(seen.indexOf(node), 1); return '{' + out.join(',') + indent + '}'; } })({ '': obj }, '', obj, 0); }; var isArray = Array.isArray || function (x) { return {}.toString.call(x) === '[object Array]'; }; var objectKeys = Object.keys || function (obj) { var has = Object.prototype.hasOwnProperty || function () { return true }; var keys = []; for (var key in obj) { if (has.call(obj, key)) keys.push(key); } return keys; }; },{"jsonify":2}],2:[function(require,module,exports){ exports.parse = require('./lib/parse'); exports.stringify = require('./lib/stringify'); },{"./lib/parse":3,"./lib/stringify":4}],3:[function(require,module,exports){ var at, // The index of the current character ch, // The current character escapee = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' }, text, error = function (m) { // Call error when something is wrong. throw { name: 'SyntaxError', message: m, at: at, text: text }; }, next = function (c) { // If a c parameter is provided, verify that it matches the current character. if (c && c !== ch) { error("Expected '" + c + "' instead of '" + ch + "'"); } // Get the next character. When there are no more characters, // return the empty string. ch = text.charAt(at); at += 1; return ch; }, number = function () { // Parse a number value. var number, string = ''; if (ch === '-') { string = '-'; next('-'); } while (ch >= '0' && ch <= '9') { string += ch; next(); } if (ch === '.') { string += '.'; while (next() && ch >= '0' && ch <= '9') { string += ch; } } if (ch === 'e' || ch === 'E') { string += ch; next(); if (ch === '-' || ch === '+') { string += ch; next(); } while (ch >= '0' && ch <= '9') { string += ch; next(); } } number = +string; if (!isFinite(number)) { error("Bad number"); } else { return number; } }, string = function () { // Parse a string value. var hex, i, string = '', uffff; // When parsing for string values, we must look for " and \ characters. if (ch === '"') { while (next()) { if (ch === '"') { next(); return string; } else if (ch === '\\') { next(); if (ch === 'u') { uffff = 0; for (i = 0; i < 4; i += 1) { hex = parseInt(next(), 16); if (!isFinite(hex)) { break; } uffff = uffff * 16 + hex; } string += String.fromCharCode(uffff); } else if (typeof escapee[ch] === 'string') { string += escapee[ch]; } else { break; } } else { string += ch; } } } error("Bad string"); }, white = function () { // Skip whitespace. while (ch && ch <= ' ') { next(); } }, word = function () { // true, false, or null. switch (ch) { case 't': next('t'); next('r'); next('u'); next('e'); return true; case 'f': next('f'); next('a'); next('l'); next('s'); next('e'); return false; case 'n': next('n'); next('u'); next('l'); next('l'); return null; } error("Unexpected '" + ch + "'"); }, value, // Place holder for the value function. array = function () { // Parse an array value. var array = []; if (ch === '[') { next('['); white(); if (ch === ']') { next(']'); return array; // empty array } while (ch) { array.push(value()); white(); if (ch === ']') { next(']'); return array; } next(','); white(); } } error("Bad array"); }, object = function () { // Parse an object value. var key, object = {}; if (ch === '{') { next('{'); white(); if (ch === '}') { next('}'); return object; // empty object } while (ch) { key = string(); white(); next(':'); if (Object.hasOwnProperty.call(object, key)) { error('Duplicate key "' + key + '"'); } object[key] = value(); white(); if (ch === '}') { next('}'); return object; } next(','); white(); } } error("Bad object"); }; value = function () { // Parse a JSON value. It could be an object, an array, a string, a number, // or a word. white(); switch (ch) { case '{': return object(); case '[': return array(); case '"': return string(); case '-': return number(); default: return ch >= '0' && ch <= '9' ? number() : word(); } }; // Return the json_parse function. It will have access to all of the above // functions and variables. module.exports = function (source, reviver) { var result; text = source; at = 0; ch = ' '; result = value(); white(); if (ch) { error("Syntax error"); } // If there is a reviver function, we recursively walk the new structure, // passing each name/value pair to the reviver function for possible // transformation, starting with a temporary root object that holds the result // in an empty key. If there is not a reviver function, we simply return the // result. return typeof reviver === 'function' ? (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); }({'': result}, '')) : result; }; },{}],4:[function(require,module,exports){ var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); case 'object': if (!value) return 'null'; gap += indent; partial = []; // Array.isArray if (Object.prototype.toString.apply(value) === '[object Array]') { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and // wrap them in brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be // stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } module.exports = function (value, replacer, space) { var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } } // If the space parameter is a string, it will be used as the indent string. else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; },{}],5:[function(require,module,exports){ (function (global){ /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global global, define, System, Reflect, Promise */ var __extends; var __assign; var __rest; var __decorate; var __param; var __metadata; var __awaiter; var __generator; var __exportStar; var __values; var __read; var __spread; var __await; var __asyncGenerator; var __asyncDelegator; var __asyncValues; (function (factory) { var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; if (typeof define === "function" && define.amd) { define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); } else if (typeof module === "object" && typeof module.exports === "object") { factory(createExporter(root, createExporter(module.exports))); } else { factory(createExporter(root)); } function createExporter(exports, previous) { return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; } }) (function (exporter) { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; __extends = function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; __assign = Object.assign || function (t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; __rest = function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]]; return t; }; __decorate = function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; __param = function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; __metadata = function (metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); }; __awaiter = function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; __generator = function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [0, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; __exportStar = function (m, exports) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; }; __values = function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; }; __read = function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; __spread = function () { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; }; __await = function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }; __asyncGenerator = function (thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; __asyncDelegator = function (o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } }; __asyncValues = function (o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); }; exporter("__extends", __extends); exporter("__assign", __assign); exporter("__rest", __rest); exporter("__decorate", __decorate); exporter("__param", __param); exporter("__metadata", __metadata); exporter("__awaiter", __awaiter); exporter("__generator", __generator); exporter("__exportStar", __exportStar); exporter("__values", __values); exporter("__read", __read); exporter("__spread", __spread); exporter("__await", __await); exporter("__asyncGenerator", __asyncGenerator); exporter("__asyncDelegator", __asyncDelegator); exporter("__asyncValues", __asyncValues); }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],6:[function(require,module,exports){ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.vega = global.vega || {}))); }(this, (function (exports) { 'use strict'; /** * Parse an event selector string. * Returns an array of event stream definitions. */ var eventSelector = function(selector, source, marks) { DEFAULT_SOURCE = source || VIEW; MARKS = marks || DEFAULT_MARKS; return parseMerge(selector.trim()).map(parseSelector); }; var VIEW = 'view'; var LBRACK = '['; var RBRACK = ']'; var LBRACE = '{'; var RBRACE = '}'; var COLON = ':'; var COMMA = ','; var NAME = '@'; var GT = '>'; var ILLEGAL = /[[\]{}]/; var DEFAULT_SOURCE; var MARKS; var DEFAULT_MARKS = { '*': 1, arc: 1, area: 1, group: 1, image: 1, line: 1, path: 1, rect: 1, rule: 1, shape: 1, symbol: 1, text: 1, trail: 1 }; function isMarkType(type) { return MARKS.hasOwnProperty(type); } function find(s, i, endChar, pushChar, popChar) { var count = 0, n = s.length, c; for (; i<n; ++i) { c = s[i]; if (!count && c === endChar) return i; else if (popChar && popChar.indexOf(c) >= 0) --count; else if (pushChar && pushChar.indexOf(c) >= 0) ++count; } return i; } function parseMerge(s) { var output = [], start = 0, n = s.length, i = 0; while (i < n) { i = find(s, i, COMMA, LBRACK + LBRACE, RBRACK + RBRACE); output.push(s.substring(start, i).trim()); start = ++i; } if (output.length === 0) { throw 'Empty event selector: ' + s; } return output; } function parseSelector(s) { return s[0] === '[' ? parseBetween(s) : parseStream(s); } function parseBetween(s) { var n = s.length, i = 1, b, stream; i = find(s, i, RBRACK, LBRACK, RBRACK); if (i === n) { throw 'Empty between selector: ' + s; } b = parseMerge(s.substring(1, i)); if (b.length !== 2) { throw 'Between selector must have two elements: ' + s; } s = s.slice(i + 1).trim(); if (s[0] !== GT) { throw 'Expected \'>\' after between selector: ' + s; } b = b.map(parseSelector); stream = parseSelector(s.slice(1).trim()); if (stream.between) { return { between: b, stream: stream }; } else { stream.between = b; } return stream; } function parseStream(s) { var stream = {source: DEFAULT_SOURCE}, source = [], throttle = [0, 0], markname = 0, start = 0, n = s.length, i = 0, j, filter; // extract throttle from end if (s[n-1] === RBRACE) { i = s.lastIndexOf(LBRACE); if (i >= 0) { try { throttle = parseThrottle(s.substring(i+1, n-1)); } catch (e) { throw 'Invalid throttle specification: ' + s; } s = s.slice(0, i).trim(); n = s.length; } else throw 'Unmatched right brace: ' + s; i = 0; } if (!n) throw s; // set name flag based on first char if (s[0] === NAME) markname = ++i; // extract first part of multi-part stream selector j = find(s, i, COLON); if (j < n) { source.push(s.substring(start, j).trim()); start = i = ++j; } // extract remaining part of stream selector i = find(s, i, LBRACK); if (i === n) { source.push(s.substring(start, n).trim()); } else { source.push(s.substring(start, i).trim()); filter = []; start = ++i; if (start === n) throw 'Unmatched left bracket: ' + s; } // extract filters while (i < n) { i = find(s, i, RBRACK); if (i === n) throw 'Unmatched left bracket: ' + s; filter.push(s.substring(start, i).trim()); if (i < n-1 && s[++i] !== LBRACK) throw 'Expected left bracket: ' + s; start = ++i; } // marshall event stream specification if (!(n = source.length) || ILLEGAL.test(source[n-1])) { throw 'Invalid event selector: ' + s; } if (n > 1) { stream.type = source[1]; if (markname) { stream.markname = source[0].slice(1); } else if (isMarkType(source[0])) { stream.marktype = source[0]; } else { stream.source = source[0]; } } else { stream.type = source[0]; } if (stream.type.slice(-1) === '!') { stream.consume = true; stream.type = stream.type.slice(0, -1); } if (filter != null) stream.filter = filter; if (throttle[0]) stream.throttle = throttle[0]; if (throttle[1]) stream.debounce = throttle[1]; return stream; } function parseThrottle(s) { var a = s.split(COMMA); if (!s.length || a.length > 2) throw s; return a.map(function(_) { var x = +_; if (x !== x) throw s; return x; }); } exports.selector = eventSelector; Object.defineProperty(exports, '__esModule', { value: true }); }))); },{}],7:[function(require,module,exports){ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.vega = global.vega || {}))); }(this, (function (exports) { 'use strict'; var accessor = function(fn, fields, name) { fn.fields = fields || []; fn.fname = name; return fn; }; function accessorName(fn) { return fn == null ? null : fn.fname; } function accessorFields(fn) { return fn == null ? null : fn.fields; } var error = function(message) { throw Error(message); }; var splitAccessPath = function(p) { var path = [], q = null, b = 0, n = p.length, s = '', i, j, c; p = p + ''; function push() { path.push(s + p.substring(i, j)); s = ''; i = j + 1; } for (i=j=0; j<n; ++j) { c = p[j]; if (c === '\\') { s += p.substring(i, j); i = ++j; } else if (c === q) { push(); q = null; b = -1; } else if (q) { continue; } else if (i === b && c === '"') { i = j + 1; q = c; } else if (i === b && c === "'") { i = j + 1; q = c; } else if (c === '.' && !b) { if (j > i) { push(); } else { i = j + 1; } } else if (c === '[') { if (j > i) push(); b = i = j + 1; } else if (c === ']') { if (!b) error('Access path missing open bracket: ' + p); if (b > 0) push(); b = 0; i = j + 1; } } if (b) error('Access path missing closing bracket: ' + p); if (q) error('Access path missing closing quote: ' + p); if (j > i) { j++; push(); } return path; }; var isArray = Array.isArray; var isObject = function(_) { return _ === Object(_); }; var isString = function(_) { return typeof _ === 'string'; }; function $(x) { return isArray(x) ? '[' + x.map($) + ']' : isObject(x) || isString(x) ? // Output valid JSON and JS source strings. // See http://timelessrepo.com/json-isnt-a-javascript-subset JSON.stringify(x).replace('\u2028','\\u2028').replace('\u2029', '\\u2029') : x; } var field = function(field, name) { var path = splitAccessPath(field), code = 'return _[' + path.map($).join('][') + '];'; return accessor( Function('_', code), [(field = path.length===1 ? path[0] : field)], name || field ); }; var empty = []; var id = field('id'); var identity = accessor(function(_) { return _; }, empty, 'identity'); var zero = accessor(function() { return 0; }, empty, 'zero'); var one = accessor(function() { return 1; }, empty, 'one'); var truthy = accessor(function() { return true; }, empty, 'true'); var falsy = accessor(function() { return false; }, empty, 'false'); function log(method, level, input) { var args = [level].concat([].slice.call(input)); console[method].apply(console, args); // eslint-disable-line no-console } var None = 0; var Error$1 = 1; var Warn = 2; var Info = 3; var Debug = 4; var logger = function(_) { var level = _ || None; return { level: function(_) { if (arguments.length) { level = +_; return this; } else { return level; } }, error: function() { if (level >= Error$1) log('error', 'ERROR', arguments); return this; }, warn: function() { if (level >= Warn) log('warn', 'WARN', arguments); return this; }, info: function() { if (level >= Info) log('log', 'INFO', arguments); return this; }, debug: function() { if (level >= Debug) log('log', 'DEBUG', arguments); return this; } } }; var array = function(_) { return _ != null ? (isArray(_) ? _ : [_]) : []; }; var compare = function(fields, orders) { var idx = [], cmp = (fields = array(fields)).map(function(f, i) { if (f == null) { return null; } else { idx.push(i); return splitAccessPath(f).map($).join(']['); } }), n = idx.length - 1, ord = array(orders), code = 'var u,v;return ', i, j, f, u, v, d, lt, gt; if (n < 0) return null; for (j=0; j<=n; ++j) { i = idx[j]; f = cmp[i]; u = '(u=a['+f+'])'; v = '(v=b['+f+'])'; d = '((v=v instanceof Date?+v:v),(u=u instanceof Date?+u:u))'; if (ord[i] !== 'descending') { gt = 1; lt = -1; } else { gt = -1; lt = 1; } code += '(' + u+'<'+v+'||u==null)&&v!=null?' + lt + ':(u>v||v==null)&&u!=null?' + gt + ':'+d+'!==u&&v===v?' + lt + ':v!==v&&u===u?' + gt + (i < n ? ':' : ':0'); } return accessor( Function('a', 'b', code + ';'), fields.filter(function(_) { return _ != null; }) ); }; var isFunction = function(_) { return typeof _ === 'function'; }; var constant = function(_) { return isFunction(_) ? _ : function() { return _; }; }; var debounce = function(delay, handler) { var tid, evt; function callback() { handler(evt); tid = evt = null; } return function(e) { evt = e; if (tid) clearTimeout(tid); tid = setTimeout(callback, delay); }; }; var extend = function(_) { for (var x, k, i=1, len=arguments.length; i<len; ++i) { x = arguments[i]; for (k in x) { _[k] = x[k]; } } return _; }; var extentIndex = function(array, f) { var i = -1, n = array.length, a, b, c, u, v; if (f == null) { while (++i < n) { b = array[i]; if (b != null && b >= b) { a = c = b; break; } } u = v = i; while (++i < n) { b = array[i]; if (b != null) { if (a > b) { a = b; u = i; } if (c < b) { c = b; v = i; } } } } else { while (++i < n) { b = f(array[i], i, array); if (b != null && b >= b) { a = c = b; break; } } u = v = i; while (++i < n) { b = f(array[i], i, array); if (b != null) { if (a > b) { a = b; u = i; } if (c < b) { c = b; v = i; } } } } return [u, v]; }; var NULL = {}; var fastmap = function(input) { var obj = {}, map, test; function has(key) { return obj.hasOwnProperty(key) && obj[key] !== NULL; } map = { size: 0, empty: 0, object: obj, has: has, get: function(key) { return has(key) ? obj[key] : undefined; }, set: function(key, value) { if (!has(key)) { ++map.size; if (obj[key] === NULL) --map.empty; } obj[key] = value; return this; }, delete: function(key) { if (has(key)) { --map.size; ++map.empty; obj[key] = NULL; } return this; }, clear: function() { map.size = map.empty = 0; map.object = obj = {}; }, test: function(_) { if (arguments.length) { test = _; return map; } else { return test; } }, clean: function() { var next = {}, size = 0, key, value; for (key in obj) { value = obj[key]; if (value !== NULL && (!test || !test(value))) { next[key] = value; ++size; } } map.size = size; map.empty = 0; map.object = (obj = next); } }; if (input) Object.keys(input).forEach(function(key) { map.set(key, input[key]); }); return map; }; var inherits = function(child, parent) { var proto = (child.prototype = Object.create(parent.prototype)); proto.constructor = child; return proto; }; var isBoolean = function(_) { return typeof _ === 'boolean'; }; var isDate = function(_) { return Object.prototype.toString.call(_) === '[object Date]'; }; var isNumber = function(_) { return typeof _ === 'number'; }; var isRegExp = function(_) { return Object.prototype.toString.call(_) === '[object RegExp]'; }; var key = function(fields) { fields = fields ? array(fields) : fields; var fn = !(fields && fields.length) ? function() { return ''; } : Function('_', 'return \'\'+' + fields.map(function(f) { return '_[' + splitAccessPath(f).map($).join('][') + ']'; }).join('+\'|\'+') + ';'); return accessor(fn, fields, 'key'); }; var merge = function(compare, array0, array1, output) { var n0 = array0.length, n1 = array1.length; if (!n1) return array0; if (!n0) return array1; var merged = output || new array0.constructor(n0 + n1), i0 = 0, i1 = 0, i = 0; for (; i0<n0 && i1<n1; ++i) { merged[i] = compare(array0[i0], array1[i1]) > 0 ? array1[i1++] : array0[i0++]; } for (; i0<n0; ++i0, ++i) { merged[i] = array0[i0]; } for (; i1<n1; ++i1, ++i) { merged[i] = array1[i1]; } return merged; }; var repeat = function(str, reps) { var s = ''; while (--reps >= 0) s += str; return s; }; var pad = function(str, length, padchar, align) { var c = padchar || ' ', s = str + '', n = length - s.length; return n <= 0 ? s : align === 'left' ? repeat(c, n) + s : align === 'center' ? repeat(c, ~~(n/2)) + s + repeat(c, Math.ceil(n/2)) : s + repeat(c, n); }; var peek = function(array) { return array[array.length - 1]; }; var toBoolean = function(_) { return _ == null || _ === '' ? null : !_ || _ === 'false' || _ === '0' ? false : !!_; }; function defaultParser(_) { return isNumber(_) ? _ : isDate(_) ? _ : Date.parse(_); } var toDate = function(_, parser) { parser = parser || defaultParser; return _ == null || _ === '' ? null : parser(_); }; var toNumber = function(_) { return _ == null || _ === '' ? null : +_; }; var toString = function(_) { return _ == null || _ === '' ? null : _ + ''; }; var toSet = function(_) { for (var s={}, i=0, n=_.length; i<n; ++i) s[_[i]] = 1; return s; }; var truncate = function(str, length, align, ellipsis) { var e = ellipsis != null ? ellipsis : '\u2026', s = str + '', n = s.length, l = Math.max(0, length - e.length); return n <= length ? s : align === 'left' ? e + s.slice(n - l) : align === 'center' ? s.slice(0, Math.ceil(l/2)) + e + s.slice(n - ~~(l/2)) : s.slice(0, l) + e; }; var visitArray = function(array, filter, visitor) { if (array) { var i = 0, n = array.length, t; if (filter) { for (; i<n; ++i) { if (t = filter(array[i])) visitor(t, i, array); } } else { array.forEach(visitor); } } }; exports.accessor = accessor; exports.accessorName = accessorName; exports.accessorFields = accessorFields; exports.id = id; exports.identity = identity; exports.zero = zero; exports.one = one; exports.truthy = truthy; exports.falsy = falsy; exports.logger = logger; exports.None = None; exports.Error = Error$1; exports.Warn = Warn; exports.Info = Info; exports.Debug = Debug; exports.array = array; exports.compare = compare; exports.constant = constant; exports.debounce = debounce; exports.error = error; exports.extend = extend; exports.extentIndex = extentIndex; exports.fastmap = fastmap; exports.field = field; exports.inherits = inherits; exports.isArray = isArray; exports.isBoolean = isBoolean; exports.isDate = isDate; exports.isFunction = isFunction; exports.isNumber = isNumber; exports.isObject = isObject; exports.isRegExp = isRegExp; exports.isString = isString; exports.key = key; exports.merge = merge; exports.pad = pad; exports.peek = peek; exports.repeat = repeat; exports.splitAccessPath = splitAccessPath; exports.stringValue = $; exports.toBoolean = toBoolean; exports.toDate = toDate; exports.toNumber = toNumber; exports.toString = toString; exports.toSet = toSet; exports.truncate = truncate; exports.visitArray = visitArray; Object.defineProperty(exports, '__esModule', { value: true }); }))); },{}],8:[function(require,module,exports){ module.exports={ "name": "vega-lite", "author": "Jeffrey Heer, Dominik Moritz, Kanit \"Ham\" Wongsuphasawat", "version": "2.0.0-beta.9", "collaborators": [ "Kanit Wongsuphasawat <kanitw@gmail.com> (http://kanitw.yellowpigz.com)", "Dominik Moritz <domoritz@cs.washington.edu> (https://www.domoritz.de)", "Jeffrey Heer <jheer@uw.edu> (http://jheer.org)" ], "homepage": "https://vega.github.io/vega-lite/", "description": "Vega-lite provides a higher-level grammar for visual analysis, comparable to ggplot or Tableau, that generates complete Vega specifications.", "main": "build/src/index.js", "types": "typings/vega-lite.d.ts", "bin": { "vl2png": "./bin/vl2png", "vl2svg": "./bin/vl2svg", "vl2vg": "./bin/vl2vg" }, "directories": { "test": "test" }, "scripts": { "pretsc": "mkdir -p build && rm -rf build/*/** && cp package.json build/", "tsc": "tsc", "prebuild": "mkdir -p build/site build/examples/images build/test-gallery", "build": "npm run build:only", "build:only": "npm run tsc && cp package.json build && browserify src/index.ts -p tsify -d -s vl | exorcist build/vega-lite.js.map > build/vega-lite.js", "postbuild": "node node_modules/uglify-js/bin/uglifyjs build/vega-lite.js -cm --source-map content=build/vega-lite.js.map,filename=build/vega-lite.min.js.map -o build/vega-lite.min.js && npm run schema", "build:examples": "npm run build && npm run build:examples-only", "build:examples-only": "./scripts/build-examples.sh && rm -rf examples/specs/normalized/* && scripts/build-normalized-examples", "build:examples-quick": "npm run build:only && npm run build:examples-only", "build:images": "npm run data && scripts/generate-images.sh", "build:toc": "bundle exec jekyll build -q && scripts/generate-toc", "build:site": "browserify site/static/main.ts -p [tsify -p site] -d | exorcist build/site/main.js.map > build/site/main.js", "build:versions": "scripts/update-version.sh", "build:test-gallery": "browserify test-gallery/main.ts -p [tsify -p test-gallery] -d > build/test-gallery/main.js", "check:examples": "scripts/check-examples.sh", "check:schema": "scripts/check-schema.sh", "clean": "rm -rf build && rm -f vega-lite.* & find -E src test site examples -regex '.*\\.(js|js.map|d.ts|vg.json)' -delete & rm -rf data", "data": "rsync -r node_modules/vega-datasets/data/* data", "link": "npm link && npm link vega-lite", "deploy": "scripts/deploy.sh", "deploy:gh": "scripts/deploy-gh.sh", "deploy:schema": "scripts/deploy-schema.sh", "prestart": "npm run data && npm run build && scripts/index-examples", "start": "nodemon -x 'npm run build:test-gallery' & browser-sync start --server --files 'build/test-gallery/main.js' --index 'test-gallery/index.html'", "poststart": "rm examples/all-examples.json", "preschema": "npm run prebuild", "schema": "typescript-to-json-schema --path tsconfig.json --type TopLevelExtendedSpec > build/vega-lite-schema.json && npm run renameschema && cp build/vega-lite-schema.json _data/", "renameschema": "scripts/rename-schema.sh", "presite": "npm run build && npm run data && npm run build:site && npm run build:toc && npm run build:versions", "site": "bundle exec jekyll serve", "lint": "tslint --project tsconfig.json -c tslint.json --type-check", "test": "npm run tsc && npm run test:only && npm run lint", "posttest": "npm run schema && npm run data && npm run mocha:examples", "test:nocompile": "npm run test:only && npm run lint && npm run mocha:examples", "test:only": "nyc --reporter=html --reporter=text-summary npm run mocha:test", "test:debug": "npm run tsc && mocha --recursive --debug-brk --inspect build/test", "test:debug-examples": "npm run tsc && npm run schema && mocha --recursive --debug-brk --inspect build/examples", "mocha:test": "mocha --require source-map-support/register --reporter dot --recursive build/test", "mocha:examples": "mocha --require source-map-support/register --reporter dot --recursive build/examples", "codecov": "nyc report --reporter=json && codecov -f coverage/*.json", "watch:build": "watchify src/index.ts -p tsify -v -d -s vl -o 'exorcist build/vega-lite.js.map > build/vega-lite.js'", "watch:tsc": "npm run tsc -- -w", "watch:test": "nodemon -x 'npm test'", "watch": "nodemon -x 'npm run build && npm run test:nocompile' # already ran schema in build" }, "repository": { "type": "git", "url": "https://github.com/vega/vega-lite.git" }, "license": "BSD-3-Clause", "bugs": { "url": "https://github.com/vega/vega-lite/issues" }, "devDependencies": { "@types/chai": "^4.0.1", "@types/d3": "^4.9.0", "@types/highlight.js": "^9.1.9", "@types/json-stable-stringify": "^1.0.31", "@types/mocha": "^2.2.41", "@types/node": "^8.0.11", "ajv": "5.2.2", "browser-sync": "^2.18.12", "browserify": "^14.4.0", "browserify-shim": "^3.8.14", "chai": "^4.1.0", "cheerio": "^1.0.0-rc.2", "codecov": "^2.2.0", "d3": "^4.9.1", "exorcist": "^0.4.0", "highlight.js": "^9.12.0", "mocha": "^3.4.2", "nodemon": "^1.11.0", "nyc": "^11.0.3", "source-map-support": "^0.4.15", "tsify": "^3.0.1", "tslint": "5.4.3", "tslint-eslint-rules": "^4.1.1", "typescript": "^2.4.1", "typescript-to-json-schema": "vega/typescript-to-json-schema#v0.7.0", "uglify-js": "^3.0.24", "vega": "^3.0.0-rc2", "vega-datasets": "vega/vega-datasets#gh-pages", "vega-embed": "^3.0.0-beta.19", "vega-tooltip": "^0.4.2", "watchify": "^3.9.0", "yaml-front-matter": "^3.4.0" }, "dependencies": { "json-stable-stringify": "^1.0.1", "tslib": "^1.7.1", "vega-event-selector": "^2.0.0", "vega-util": "^1.4.1", "yargs": "^8.0.2" } } },{}],9:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require("./util"); exports.AGGREGATE_OPS = [ 'values', 'count', 'valid', 'missing', 'distinct', 'sum', 'mean', 'average', 'variance', 'variancep', 'stdev', 'stdevp', 'median', 'q1', 'q3', 'ci0', 'ci1', 'modeskew', 'min', 'max', 'argmin', 'argmax', ]; exports.AGGREGATE_OP_INDEX = util_1.toSet(exports.AGGREGATE_OPS); exports.COUNTING_OPS = ['count', 'valid', 'missing', 'distinct']; function isCountingAggregateOp(aggregate) { return aggregate && util_1.contains(exports.COUNTING_OPS, aggregate); } exports.isCountingAggregateOp = isCountingAggregateOp; /** Additive-based aggregation operations. These can be applied to stack. */ exports.SUM_OPS = [ 'count', 'sum', 'distinct', 'valid', 'missing' ]; /** * Aggregation operators that always produce values within the range [domainMin, domainMax]. */ exports.SHARED_DOMAIN_OPS = [ 'mean', 'average', 'median', 'q1', 'q3', 'min', 'max', ]; exports.SHARED_DOMAIN_OP_INDEX = util_1.toSet(exports.SHARED_DOMAIN_OPS); },{"./util":107}],10:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AXIS_PROPERTIES = [ 'domain', 'format', 'grid', 'labelPadding', 'labels', 'labelOverlap', 'maxExtent', 'minExtent', 'offset', 'orient', 'position', 'tickCount', 'tickExtra', 'ticks', 'tickSize', 'title', 'titlePadding', 'values', 'zindex' ]; exports.VG_AXIS_PROPERTIES = [].concat(exports.AXIS_PROPERTIES, ['gridScale']); },{}],11:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var channel_1 = require("./channel"); var util_1 = require("./util"); function binToString(bin) { if (util_1.isBoolean(bin)) { return 'bin'; } return 'bin' + util_1.keys(bin).map(function (p) { return "_" + p + "_" + bin[p]; }).join(''); } exports.binToString = binToString; function autoMaxBins(channel) { switch (channel) { case channel_1.ROW: case channel_1.COLUMN: case channel_1.SIZE: case channel_1.COLOR: case channel_1.OPACITY: // Facets and Size shouldn't have too many bins // We choose 6 like shape to simplify the rule case channel_1.SHAPE: return 6; // Vega's "shape" has 6 distinct values default: return 10; } } exports.autoMaxBins = autoMaxBins; },{"./channel":12,"./util":107}],12:[function(require,module,exports){ "use strict"; /* * Constants and utilities for encoding channels (Visual variables) * such as 'x', 'y', 'color'. */ Object.defineProperty(exports, "__esModule", { value: true }); var scale_1 = require("./scale"); var util_1 = require("./util"); var Channel; (function (Channel) { // Facet Channel.ROW = 'row'; Channel.COLUMN = 'column'; // Position Channel.X = 'x'; Channel.Y = 'y'; Channel.X2 = 'x2'; Channel.Y2 = 'y2'; // Mark property with scale Channel.COLOR = 'color'; Channel.SHAPE = 'shape'; Channel.SIZE = 'size'; Channel.OPACITY = 'opacity'; // Non-scale channel Channel.TEXT = 'text'; Channel.ORDER = 'order'; Channel.DETAIL = 'detail'; Channel.TOOLTIP = 'tooltip'; })(Channel = exports.Channel || (exports.Channel = {})); exports.X = Channel.X; exports.Y = Channel.Y; exports.X2 = Channel.X2; exports.Y2 = Channel.Y2; exports.ROW = Channel.ROW; exports.COLUMN = Channel.COLUMN; exports.SHAPE = Channel.SHAPE; exports.SIZE = Channel.SIZE; exports.COLOR = Channel.COLOR; exports.TEXT = Channel.TEXT; exports.DETAIL = Channel.DETAIL; exports.ORDER = Channel.ORDER; exports.OPACITY = Channel.OPACITY; exports.TOOLTIP = Channel.TOOLTIP; exports.CHANNELS = [exports.X, exports.Y, exports.X2, exports.Y2, exports.ROW, exports.COLUMN, exports.SIZE, exports.SHAPE, exports.COLOR, exports.ORDER, exports.OPACITY, exports.TEXT, exports.DETAIL, exports.TOOLTIP]; var CHANNEL_INDEX = util_1.toSet(exports.CHANNELS); /** * Channels cannot have an array of channelDef. * model.fieldDef, getFieldDef only work for these channels. * * (The only two channels that can have an array of channelDefs are "detail" and "order". * Since there can be multiple fieldDefs for detail and order, getFieldDef/model.fieldDef * are not applicable for them. Similarly, selection projecttion won't work with "detail" and "order".) */ exports.SINGLE_DEF_CHANNELS = [exports.X, exports.Y, exports.X2, exports.Y2, exports.ROW, exports.COLUMN, exports.SIZE, exports.SHAPE, exports.COLOR, exports.OPACITY, exports.TEXT, exports.TOOLTIP]; function isChannel(str) { return !!CHANNEL_INDEX[str]; } exports.isChannel = isChannel; // CHANNELS without COLUMN, ROW exports.UNIT_CHANNELS = [exports.X, exports.Y, exports.X2, exports.Y2, exports.SIZE, exports.SHAPE, exports.COLOR, exports.ORDER, exports.OPACITY, exports.TEXT, exports.DETAIL, exports.TOOLTIP]; /** List of channels with scales */ exports.SCALE_CHANNELS = [exports.X, exports.Y, exports.SIZE, exports.SHAPE, exports.COLOR, exports.OPACITY]; var SCALE_CHANNEL_INDEX = util_1.toSet(exports.SCALE_CHANNELS); function isScaleChannel(channel) { return !!SCALE_CHANNEL_INDEX[channel]; } exports.isScaleChannel = isScaleChannel; // UNIT_CHANNELS without X, Y, X2, Y2; exports.NONSPATIAL_CHANNELS = [exports.SIZE, exports.SHAPE, exports.COLOR, exports.ORDER, exports.OPACITY, exports.TEXT, exports.DETAIL, exports.TOOLTIP]; // X and Y; exports.SPATIAL_SCALE_CHANNELS = [exports.X, exports.Y]; // SCALE_CHANNELS without X, Y; exports.NONSPATIAL_SCALE_CHANNELS = [exports.SIZE, exports.SHAPE, exports.COLOR, exports.OPACITY]; exports.LEVEL_OF_DETAIL_CHANNELS = util_1.without(exports.NONSPATIAL_CHANNELS, ['order']); /** Channels that can serve as groupings for stacked charts. */ exports.STACK_BY_CHANNELS = [exports.COLOR, exports.DETAIL, exports.ORDER, exports.OPACITY, exports.SIZE]; /** * Return whether a channel supports a particular mark type. * @param channel channel name * @param mark the mark type * @return whether the mark supports the channel */ function supportMark(channel, mark) { return mark in getSupportedMark(channel); } exports.supportMark = supportMark; /** * Return a dictionary showing whether a channel supports mark type. * @param channel * @return A dictionary mapping mark types to boolean values. */ function getSupportedMark(channel) { switch (channel) { case exports.X: case exports.Y: case exports.COLOR: case exports.DETAIL: case exports.TOOLTIP: case exports.ORDER: // TODO: revise (order might not support rect, which is not stackable?) case exports.OPACITY: case exports.ROW: case exports.COLUMN: return { point: true, tick: true, rule: true, circle: true, square: true, bar: true, rect: true, line: true, area: true, text: true }; case exports.X2: case exports.Y2: return { rule: true, bar: true, rect: true, area: true }; case exports.SIZE: return { point: true, tick: true, rule: true, circle: true, square: true, bar: true, text: true, line: true }; case exports.SHAPE: return { point: true }; case exports.TEXT: return { text: true }; } } exports.getSupportedMark = getSupportedMark; function hasScale(channel) { return !util_1.contains([exports.DETAIL, exports.TEXT, exports.ORDER, exports.TOOLTIP], channel); } exports.hasScale = hasScale; // Position does not work with ordinal (lookup) scale and sequential (which is only for color) var POSITION_SCALE_TYPE_INDEX = util_1.toSet(util_1.without(scale_1.SCALE_TYPES, ['ordinal', 'sequential'])); function supportScaleType(channel, scaleType) { switch (channel) { case exports.ROW: case exports.COLUMN: return scaleType === 'band'; // row / column currently supports band only case exports.X: case exports.Y: case exports.SIZE: // TODO: size and opacity can support ordinal with more modification case exports.OPACITY: // Although it generally doesn't make sense to use band with size and opacity, // it can also work since we use band: 0.5 to get midpoint. return scaleType in POSITION_SCALE_TYPE_INDEX; case exports.COLOR: return scaleType !== 'band'; // band does not make sense with color case exports.SHAPE: return scaleType === 'ordinal'; // shape = lookup only } /* istanbul ignore next: it should never reach here */ return false; } exports.supportScaleType = supportScaleType; function rangeType(channel) { switch (channel) { case exports.X: case exports.Y: case exports.SIZE: case exports.OPACITY: // X2 and Y2 use X and Y scales, so they similarly have continuous range. case exports.X2: case exports.Y2: return 'continuous'; case exports.ROW: case exports.COLUMN: case exports.SHAPE: // TEXT and TOOLTIP have no scale but have discrete output case exports.TEXT: case exports.TOOLTIP: return 'discrete'; // Color can be either continuous or discrete, depending on scale type. case exports.COLOR: return 'flexible'; // No scale, no range type. case exports.DETAIL: case exports.ORDER: return undefined; } /* istanbul ignore next: should never reach here. */ throw new Error('getSupportedRole not implemented for ' + channel); } exports.rangeType = rangeType; },{"./scale":98,"./util":107}],13:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var mainAxisReducer = getAxisReducer('main'); var gridAxisReducer = getAxisReducer('grid'); function getAxisReducer(axisType) { return function (axes, axis) { if (axis[axisType]) { // Need to cast here so it's not longer partial type. axes.push(axis[axisType].combine()); } return axes; }; } function assembleAxes(axisComponents) { return [].concat(axisComponents.x ? [].concat(axisComponents.x.reduce(mainAxisReducer, []), axisComponents.x.reduce(gridAxisReducer, [])) : [], axisComponents.y ? [].concat(axisComponents.y.reduce(mainAxisReducer, []), axisComponents.y.reduce(gridAxisReducer, [])) : []); } exports.assembleAxes = assembleAxes; },{}],14:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var split_1 = require("../split"); var AxisComponentPart = (function (_super) { tslib_1.__extends(AxisComponentPart, _super); function AxisComponentPart() { return _super !== null && _super.apply(this, arguments) || this; } return AxisComponentPart; }(split_1.Split)); exports.AxisComponentPart = AxisComponentPart; },{"../split":80,"tslib":5}],15:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var channel_1 = require("../../channel"); var scale_1 = require("../../scale"); var type_1 = require("../../type"); var util_1 = require("../../util"); var common_1 = require("../common"); function labels(model, channel, specifiedLabelsSpec, def) { var fieldDef = model.fieldDef(channel) || (channel === 'x' ? model.fieldDef('x2') : channel === 'y' ? model.fieldDef('y2') : undefined); var axis = model.axis(channel); var config = model.config; var labelsSpec = {}; // Text if (fieldDef.type === type_1.TEMPORAL) { var isUTCScale = model.getScaleComponent(channel).get('type') === scale_1.ScaleType.UTC; labelsSpec.text = { signal: common_1.timeFormatExpression('datum.value', fieldDef.timeUnit, axis.format, config.axis.shortTimeLabels, config.timeFormat, isUTCScale) }; } // Label Angle var angle = labelAngle(axis, channel, fieldDef); if (angle) { labelsSpec.angle = { value: angle }; } if (labelsSpec.angle && channel === 'x') { var align = labelAlign(angle, def.get('orient')); if (align) { labelsSpec.align = { value: align }; } // Auto set baseline if x is rotated by 90, or -90 if (util_1.contains([90, 270], angle)) { labelsSpec.baseline = { value: 'middle' }; } } labelsSpec = tslib_1.__assign({}, labelsSpec, specifiedLabelsSpec); return util_1.keys(labelsSpec).length === 0 ? undefined : labelsSpec; } exports.labels = labels; function labelAngle(axis, channel, fieldDef) { if (axis.labelAngle !== undefined) { // Make angle within [0,360) return ((axis.labelAngle % 360) + 360) % 360; } else { // auto rotate for X if (channel === channel_1.X && (util_1.contains([type_1.NOMINAL, type_1.ORDINAL], fieldDef.type) || !!fieldDef.bin || fieldDef.type === type_1.TEMPORAL)) { return 270; } } return undefined; } exports.labelAngle = labelAngle; function labelAlign(angle, orient) { if (angle && angle > 0) { if (angle > 180) { return orient === 'top' ? 'left' : 'right'; } else if (angle < 180) { return orient === 'top' ? 'right' : 'left'; } } return undefined; } exports.labelAlign = labelAlign; },{"../../channel":12,"../../scale":98,"../../type":106,"../../util":107,"../common":18,"tslib":5}],16:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var axis_1 = require("../../axis"); var channel_1 = require("../../channel"); var util_1 = require("../../util"); var common_1 = require("../common"); var resolve_1 = require("../resolve"); var split_1 = require("../split"); var component_1 = require("./component"); var encode = require("./encode"); var rules = require("./rules"); var AXIS_PARTS = ['domain', 'grid', 'labels', 'ticks', 'title']; function parseUnitAxis(model) { return channel_1.SPATIAL_SCALE_CHANNELS.reduce(function (axis, channel) { if (model.axis(channel)) { var axisComponent = {}; // TODO: support multiple axis var main = parseMainAxis(channel, model); if (main && isVisibleAxis(main)) { axisComponent.main = main; } var grid = parseGridAxis(channel, model); if (grid && isVisibleAxis(grid)) { axisComponent.grid = grid; } axis[channel] = [axisComponent]; } return axis; }, {}); } exports.parseUnitAxis = parseUnitAxis; var OPPOSITE_ORIENT = { bottom: 'top', top: 'bottom', left: 'right', right: 'left' }; function parseLayerAxis(model) { var _a = model.component, axes = _a.axes, resolve = _a.resolve; var axisCount = { top: 0, bottom: 0, right: 0, left: 0 }; var _loop_1 = function (child) { child.parseAxisAndHeader(); util_1.keys(child.component.axes).forEach(function (channel) { var channelResolve = model.component.resolve[channel]; channelResolve.axis = resolve_1.parseGuideResolve(model.component.resolve, channel); if (channelResolve.axis === 'shared') { // If the resolve says shared (and has not been overridden) // We will try to merge and see if there is a conflict axes[channel] = mergeAxisComponents(axes[channel], child.component.axes[channel]); if (!axes[channel]) { // If merge returns nothing, there is a conflict so we cannot make the axis shared. // Thus, mark axis as independent and remove the axis component. channelResolve.axis = 'independent'; delete axes[channel]; } } }); }; for (var _i = 0, _b = model.children; _i < _b.length; _i++) { var child = _b[_i]; _loop_1(child); } // Move axes to layer's axis component and merge shared axes ['x', 'y'].forEach(function (channel) { for (var _i = 0, _a = model.children; _i < _a.length; _i++) { var child = _a[_i]; if (!child.component.axes[channel]) { // skip if the child does not have a particular axis return; } if (resolve[channel].axis === 'independent') { // If axes are independent, concat the axisComponent array. axes[channel] = (axes[channel] || []).concat(child.component.axes[channel]); // Automatically adjust orient child.component.axes[channel].forEach(function (axisComponent) { var _a = axisComponent.main.getWithExplicit('orient'), orient = _a.value, explicit = _a.explicit; if (axisCount[orient] > 0 && !explicit) { // Change axis orient if the number do not match var oppositeOrient = OPPOSITE_ORIENT[orient]; if (axisCount[orient] > axisCount[oppositeOrient]) { axisComponent.main.set('orient', oppositeOrient, false); } } axisCount[orient]++; // TODO(https://github.com/vega/vega-lite/issues/2634): automaticaly add extra offset? }); } // After merging, make sure to remove axes from child delete child.component.axes[channel]; } }); } exports.parseLayerAxis = parseLayerAxis; function mergeAxisComponents(mergedAxisCmpts, childAxisCmpts) { if (mergedAxisCmpts) { if (mergedAxisCmpts.length !== childAxisCmpts.length) { return undefined; // Cannot merge axis component with different number of axes. } var length_1 = mergedAxisCmpts.length; for (var i = 0; i < length_1; i++) { var mergedMain = mergedAxisCmpts[i].main; var childMain = childAxisCmpts[i].main; if ((!!mergedMain) !== (!!childMain)) { return undefined; } else if (mergedMain && childMain) { var mergedOrient = mergedMain.getWithExplicit('orient'); var childOrient = childMain.getWithExplicit('orient'); if (mergedOrient.explicit && childOrient.explicit && mergedOrient.value !== childOrient.value) { // TODO: throw warning if resolve is explicit (We don't have info about explicit/implicit resolve yet.) // Cannot merge due to inconsistent orient return undefined; } else { mergedAxisCmpts[i].main = mergeAxisComponentPart(mergedMain, childMain); } } var mergedGrid = mergedAxisCmpts[i].grid; var childGrid = childAxisCmpts[i].grid; if ((!!mergedGrid) !== (!!childGrid)) { return undefined; } else if (mergedGrid && childGrid) { mergedAxisCmpts[i].grid = mergeAxisComponentPart(mergedGrid, childGrid); } } } else { // For first one, return a copy of the child return childAxisCmpts.map(function (axisComponent) { return (tslib_1.__assign({}, (axisComponent.main ? { main: axisComponent.main.clone() } : {}), (axisComponent.grid ? { grid: axisComponent.grid.clone() } : {}))); }); } return mergedAxisCmpts; } function mergeAxisComponentPart(merged, child) { var _loop_2 = function (prop) { var mergedValueWithExplicit = split_1.mergeValuesWithExplicit(merged.getWithExplicit(prop), child.getWithExplicit(prop), prop, 'axis', // Tie breaker function function (v1, v2) { switch (prop) { case 'title': return common_1.titleMerger(v1, v2); case 'gridScale': return { explicit: v1.explicit, value: v1.value || v2.value }; } return split_1.defaultTieBreaker(v1, v2, prop, 'axis'); }); merged.setWithExplicit(prop, mergedValueWithExplicit); }; for (var _i = 0, VG_AXIS_PROPERTIES_1 = axis_1.VG_AXIS_PROPERTIES; _i < VG_AXIS_PROPERTIES_1.length; _i++) { var prop = VG_AXIS_PROPERTIES_1[_i]; _loop_2(prop); } return merged; } function isFalseOrNull(v) { return v === false || v === null; } /** * Return if an axis is visible (shows at least one part of the axis). */ function isVisibleAxis(axis) { return util_1.some(AXIS_PARTS, function (part) { return hasAxisPart(axis, part); }); } function hasAxisPart(axis, part) { // FIXME(https://github.com/vega/vega-lite/issues/2552) this method can be wrong if users use a Vega theme. if (part === 'axis') { return true; } if (part === 'grid' || part === 'title') { return !!axis.get(part); } // Other parts are enabled by default, so they should not be false or null. return !isFalseOrNull(axis.get(part)); } /** * Make an inner axis for showing grid for shared axis. */ function parseGridAxis(channel, model) { // FIXME: support adding ticks for grid axis that are inner axes of faceted plots. return parseAxis(channel, model, true); } exports.parseGridAxis = parseGridAxis; function parseMainAxis(channel, model) { return parseAxis(channel, model, false); } exports.parseMainAxis = parseMainAxis; function parseAxis(channel, model, isGridAxis) { var axis = model.axis(channel); var axisComponent = new component_1.AxisComponentPart({}, { scale: model.scaleName(channel) } // implicit ); // 1.2. Add properties axis_1.AXIS_PROPERTIES.forEach(function (property) { var value = getSpecifiedOrDefaultValue(property, axis, channel, model, isGridAxis); if (value !== undefined) { var explicit = property === 'values' ? !!axis.values : value === axis[property]; axisComponent.set(property, value, explicit); } }); // Special case for gridScale since gridScale is not a Vega-Lite Axis property. var gridScale = rules.gridScale(model, channel, isGridAxis); if (gridScale !== undefined) { axisComponent.set('gridScale', gridScale, false); } // 2) Add guide encode definition groups var axisEncoding = axis.encoding || {}; var axisEncode = AXIS_PARTS.reduce(function (e, part) { if (!hasAxisPart(axisComponent, part)) { // No need to create encode for a disabled part. return e; } var value = part === 'labels' ? encode.labels(model, channel, axisEncoding.labels || {}, axisComponent) : axisEncoding[part] || {}; if (value !== undefined && util_1.keys(value).length > 0) { e[part] = { update: value }; } return e; }, {}); // FIXME: By having encode as one property, we won't have fine grained encode merging. if (util_1.keys(axisEncode).length > 0) { axisComponent.set('encode', axisEncode, !!axis.encoding || !!axis.labelAngle); } return axisComponent; } function getSpecifiedOrDefaultValue(property, specifiedAxis, channel, model, isGridAxis) { var fieldDef = model.fieldDef(channel); switch (property) { case 'labels': return isGridAxis ? false : specifiedAxis.labels; case 'labelOverlap': var scaleType = model.component.scales[channel].get('type'); return rules.labelOverlap(fieldDef, specifiedAxis, channel, isGridAxis, scaleType); case 'domain': return rules.domain(property, specifiedAxis, isGridAxis, channel); case 'ticks': return rules.ticks(property, specifiedAxis, isGridAxis, channel); case 'format': return rules.format(specifiedAxis, fieldDef, model.config); case 'grid': return rules.grid(model, channel, isGridAxis); // FIXME: refactor this case 'orient': return rules.orient(specifiedAxis, channel); case 'tickCount': return rules.tickCount(specifiedAxis, channel, fieldDef); // TODO: scaleType case 'title': return rules.title(specifiedAxis, fieldDef, model.config, isGridAxis); case 'values': return rules.values(specifiedAxis, model, fieldDef); case 'zindex': return rules.zindex(specifiedAxis, isGridAxis); } // Otherwise, return specified property. return specifiedAxis[property]; } },{"../../axis":10,"../../channel":12,"../../util":107,"../common":18,"../resolve":60,"../split":80,"./component":14,"./encode":15,"./rules":17,"tslib":5}],17:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var bin_1 = require("../../bin"); var channel_1 = require("../../channel"); var datetime_1 = require("../../datetime"); var fielddef_1 = require("../../fielddef"); var log = require("../../log"); var util_1 = require("../../util"); var common_1 = require("../common"); var encode_1 = require("./encode"); function format(specifiedAxis, fieldDef, config) { return common_1.numberFormat(fieldDef, specifiedAxis.format, config); } exports.format = format; // TODO: we need to refactor this method after we take care of config refactoring /** * Default rules for whether to show a grid should be shown for a channel. * If `grid` is unspecified, the default value is `true` for ordinal scales that are not binned */ function gridShow(model, channel) { var grid = model.axis(channel).grid; if (grid !== undefined) { return grid; } return !model.hasDiscreteDomain(channel) && !model.fieldDef(channel).bin; } exports.gridShow = gridShow; function grid(model, channel, isGridAxis) { if (!isGridAxis) { return undefined; } return gridShow(model, channel); } exports.grid = grid; function gridScale(model, channel, isGridAxis) { if (isGridAxis) { var gridChannel = channel === 'x' ? 'y' : 'x'; if (model.getScaleComponent(gridChannel)) { return model.scaleName(gridChannel); } } return undefined; } exports.gridScale = gridScale; function orient(specifiedAxis, channel) { var orient = specifiedAxis.orient; if (orient) { return orient; } switch (channel) { case channel_1.COLUMN: // FIXME test and decide return 'top'; case channel_1.X: return 'bottom'; case channel_1.ROW: case channel_1.Y: return 'left'; } /* istanbul ignore next: This should never happen. */ throw new Error(log.message.INVALID_CHANNEL_FOR_AXIS); } exports.orient = orient; function tickCount(specifiedAxis, channel, fieldDef) { var count = specifiedAxis.tickCount; if (count !== undefined) { return count; } // FIXME depends on scale type too if (channel === channel_1.X && !fieldDef.bin) { // Vega's default tickCount often lead to a lot of label occlusion on X without 90 degree rotation return 5; } return undefined; } exports.tickCount = tickCount; function title(specifiedAxis, fieldDef, config, isGridAxis) { if (isGridAxis) { return undefined; } if (specifiedAxis.title === '') { return undefined; } if (specifiedAxis.title !== undefined) { return specifiedAxis.title; } // if not defined, automatically determine axis title from field def var fieldTitle = fielddef_1.title(fieldDef, config); var maxLength = specifiedAxis.titleMaxLength; return maxLength ? util_1.truncate(fieldTitle, maxLength) : fieldTitle; } exports.title = title; function values(specifiedAxis, model, fieldDef) { var vals = specifiedAxis.values; if (specifiedAxis.values && datetime_1.isDateTime(vals[0])) { return vals.map(function (dt) { // normalize = true as end user won't put 0 = January return { signal: datetime_1.dateTimeExpr(dt, true) }; }); } if (!vals && fieldDef.bin) { var signal = model.getName(bin_1.binToString(fieldDef.bin) + "_" + fieldDef.field + "_bins"); return { signal: "sequence(" + signal + ".start, " + signal + ".stop + " + signal + ".step, " + signal + ".step)" }; } return vals; } exports.values = values; function zindex(specifiedAxis, isGridAxis) { var z = specifiedAxis.zindex; if (z !== undefined) { return z; } if (isGridAxis) { // if grid is true, need to put layer on the back so that grid is behind marks return 0; } return 1; // otherwise return undefined and use Vega's default. } exports.zindex = zindex; function domainAndTicks(property, specifiedAxis, isGridAxis, channel) { if (isGridAxis || channel === channel_1.ROW || channel === channel_1.COLUMN) { return false; } return specifiedAxis[property]; } exports.domainAndTicks = domainAndTicks; function labelOverlap(fieldDef, specifiedAxis, channel, isGridAxis, scaleType) { if (!isGridAxis && channel === 'x' && !encode_1.labelAngle(specifiedAxis, channel, fieldDef)) { if (scaleType === 'log') { return 'greedy'; } return true; } return undefined; } exports.labelOverlap = labelOverlap; exports.domain = domainAndTicks; exports.ticks = domainAndTicks; },{"../../bin":11,"../../channel":12,"../../datetime":87,"../../fielddef":90,"../../log":95,"../../util":107,"../common":18,"./encode":15}],18:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var fielddef_1 = require("../fielddef"); var log = require("../log"); var scale_1 = require("../scale"); var spec_1 = require("../spec"); var timeunit_1 = require("../timeunit"); var type_1 = require("../type"); var util_1 = require("../util"); var concat_1 = require("./concat"); var facet_1 = require("./facet"); var layer_1 = require("./layer"); var repeat_1 = require("./repeat"); var unit_1 = require("./unit"); function buildModel(spec, parent, parentGivenName, unitSize, repeater, config) { if (spec_1.isFacetSpec(spec)) { return new facet_1.FacetModel(spec, parent, parentGivenName, repeater, config); } if (spec_1.isLayerSpec(spec)) { return new layer_1.LayerModel(spec, parent, parentGivenName, unitSize, repeater, config); } if (spec_1.isUnitSpec(spec)) { return new unit_1.UnitModel(spec, parent, parentGivenName, unitSize, repeater, config); } if (spec_1.isRepeatSpec(spec)) { return new repeat_1.RepeatModel(spec, parent, parentGivenName, repeater, config); } if (spec_1.isConcatSpec(spec)) { return new concat_1.ConcatModel(spec, parent, parentGivenName, repeater, config); } throw new Error(log.message.INVALID_SPEC); } exports.buildModel = buildModel; function applyConfig(e, config, // TODO(#1842): consolidate MarkConfig | TextConfig? propsList) { for (var _i = 0, propsList_1 = propsList; _i < propsList_1.length; _i++) { var property = propsList_1[_i]; var value = config[property]; if (value !== undefined) { e[property] = { value: value }; } } return e; } exports.applyConfig = applyConfig; function applyMarkConfig(e, model, propsList) { for (var _i = 0, propsList_2 = propsList; _i < propsList_2.length; _i++) { var property = propsList_2[_i]; var value = getMarkConfig(property, model.markDef, model.config); if (value !== undefined) { e[property] = { value: value }; } } return e; } exports.applyMarkConfig = applyMarkConfig; /** * Return value mark specific config property if exists. * Otherwise, return general mark specific config. */ function getMarkConfig(prop, mark, config) { if (mark.role) { var roleSpecificConfig = config[mark.role]; if (roleSpecificConfig && roleSpecificConfig[prop] !== undefined) { return roleSpecificConfig[prop]; } } else { var markSpecificConfig = config[mark.type]; if (markSpecificConfig[prop] !== undefined) { return markSpecificConfig[prop]; } } return config.mark[prop]; } exports.getMarkConfig = getMarkConfig; function formatSignalRef(fieldDef, specifiedFormat, expr, config, useBinRange) { if (fieldDef.type === 'quantitative') { var format = numberFormat(fieldDef, specifiedFormat, config); if (fieldDef.bin) { if (useBinRange) { // For bin range, no need to apply format as the formula that creates range already include format return { signal: fielddef_1.field(fieldDef, { expr: expr, binSuffix: 'range' }) }; } else { return { signal: formatExpr(fielddef_1.field(fieldDef, { expr: expr, binSuffix: 'start' }), format) + " + '-' + " + formatExpr(fielddef_1.field(fieldDef, { expr: expr, binSuffix: 'end' }), format) }; } } else { return { signal: "" + formatExpr(fielddef_1.field(fieldDef, { expr: expr }), format) }; } } else if (fieldDef.type === 'temporal') { var isUTCScale = fielddef_1.isScaleFieldDef(fieldDef) && fieldDef['scale'] && fieldDef['scale'].type === scale_1.ScaleType.UTC; return { signal: timeFormatExpression(fielddef_1.field(fieldDef, { expr: expr }), fieldDef.timeUnit, specifiedFormat, config.text.shortTimeLabels, config.timeFormat, isUTCScale) }; } else { return { signal: fielddef_1.field(fieldDef, { expr: expr }) }; } } exports.formatSignalRef = formatSignalRef; /** * Returns number format for a fieldDef * * @param format explicitly specified format */ function numberFormat(fieldDef, specifiedFormat, config) { if (fieldDef.type === type_1.QUANTITATIVE) { // add number format for quantitative type only // Specified format in axis/legend has higher precedence than fieldDef.format if (specifiedFormat) { return specifiedFormat; } // TODO: need to make this work correctly for numeric ordinal / nominal type return config.numberFormat; } return undefined; } exports.numberFormat = numberFormat; function formatExpr(field, format) { return "format(" + field + ", '" + (format || '') + "')"; } function numberFormatExpr(field, specifiedFormat, config) { return formatExpr(field, specifiedFormat || config.numberFormat); } exports.numberFormatExpr = numberFormatExpr; /** * Returns the time expression used for axis/legend labels or text mark for a temporal field */ function timeFormatExpression(field, timeUnit, format, shortTimeLabels, timeFormatConfig, isUTCScale) { if (!timeUnit || format) { // If there is not time unit, or if user explicitly specify format for axis/legend/text. var _format = format || timeFormatConfig; // only use config.timeFormat if there is no timeUnit. if (isUTCScale) { return "utcFormat(" + field + ", '" + _format + "')"; } else { return "timeFormat(" + field + ", '" + _format + "')"; } } else { return timeunit_1.formatExpression(timeUnit, field, shortTimeLabels, isUTCScale); } } exports.timeFormatExpression = timeFormatExpression; /** * Return Vega sort parameters (tuple of field and order). */ function sortParams(orderDef) { return (util_1.isArray(orderDef) ? orderDef : [orderDef]).reduce(function (s, orderChannelDef) { s.field.push(fielddef_1.field(orderChannelDef, { binSuffix: 'start' })); s.order.push(orderChannelDef.sort || 'ascending'); return s; }, { field: [], order: [] }); } exports.sortParams = sortParams; function titleMerger(v1, v2) { return { explicit: v1.explicit, value: v1.value === v2.value ? v1.value : v1.value + ', ' + v2.value // join title with comma if different }; } exports.titleMerger = titleMerger; },{"../fielddef":90,"../log":95,"../scale":98,"../spec":101,"../timeunit":103,"../type":106,"../util":107,"./concat":20,"./facet":36,"./layer":37,"./repeat":59,"./unit":81}],19:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); /** * Module for compiling Vega-lite spec into Vega spec. */ var config_1 = require("../config"); var log = require("../log"); var spec_1 = require("../spec"); var toplevelprops_1 = require("../toplevelprops"); var common_1 = require("./common"); var layer_1 = require("./layer"); var unit_1 = require("./unit"); function compile(inputSpec, logger) { if (logger) { // set the singleton logger to the provided logger log.set(logger); } try { // 1. initialize config var config = config_1.initConfig(inputSpec.config); // 2. Convert input spec into a normal form // (Decompose all extended unit specs into composition of unit spec.) var spec = spec_1.normalize(inputSpec, config); // 3. Instantiate the model with default config var model = common_1.buildModel(spec, null, '', undefined, undefined, config); // 4. Parse each part of the model to produce components that will be assembled later // We traverse the whole tree to parse once for each type of components // (e.g., data, layout, mark, scale). // Please see inside model.parse() for order for compilation. model.parse(); // 5. Assemble a Vega Spec from the parsed components in 3. return assemble(model, getTopLevelProperties(inputSpec, config)); } finally { // Reset the singleton logger if a logger is provided if (logger) { log.reset(); } } } exports.compile = compile; function getTopLevelProperties(topLevelSpec, config) { return tslib_1.__assign({}, toplevelprops_1.extractTopLevelProperties(config), toplevelprops_1.extractTopLevelProperties(topLevelSpec)); } function assemble(model, topLevelProperties) { // TODO: change type to become VgSpec // Config with Vega-Lite only config removed. var vgConfig = model.config ? config_1.stripConfig(model.config) : undefined; // autoResize has to be put under autosize var autoResize = topLevelProperties.autoResize, topLevelProps = tslib_1.__rest(topLevelProperties, ["autoResize"]); var encode = model.assembleParentGroupProperties(); if (encode) { delete encode.width; delete encode.height; } var output = tslib_1.__assign({ $schema: 'https://vega.github.io/schema/vega/v3.0.json' }, (model.description ? { description: model.description } : {}), { // By using Vega layout, we don't support custom autosize autosize: topLevelProperties.autoResize ? { type: 'pad', resize: true } : 'pad' }, topLevelProps, (encode ? { encode: { update: encode } } : {}), { data: [].concat(model.assembleSelectionData([]), model.assembleData()) }, model.assembleGroup([].concat( // TODO(https://github.com/vega/vega-lite/issues/2198): // Merge the top-level's width/height signal with the top-level model // so we can remove this special casing based on model.name ((model.name && ((model instanceof layer_1.LayerModel) || (model instanceof unit_1.UnitModel))) ? [ // If model has name, its calculated width and height will not be named width and height, need to map it to the global width and height signals. { name: 'width', update: model.getName('width') }, { name: 'height', update: model.getName('height') } ] : []), model.assembleLayoutSignals(), model.assembleSelectionTopLevelSignals([]))), (vgConfig ? { config: vgConfig } : {})); return { spec: output // TODO: add warning / errors here }; } },{"../config":85,"../log":95,"../spec":101,"../toplevelprops":104,"./common":18,"./layer":37,"./unit":81,"tslib":5}],20:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var spec_1 = require("../spec"); var util_1 = require("../util"); var common_1 = require("./common"); var assemble_1 = require("./data/assemble"); var parse_1 = require("./data/parse"); var assemble_2 = require("./layout/assemble"); var parse_2 = require("./layout/parse"); var parse_3 = require("./legend/parse"); var model_1 = require("./model"); var ConcatModel = (function (_super) { tslib_1.__extends(ConcatModel, _super); function ConcatModel(spec, parent, parentGivenName, repeater, config) { var _this = _super.call(this, spec, parent, parentGivenName, config, spec.resolve) || this; _this.isVConcat = spec_1.isVConcatSpec(spec); _this.children = (spec_1.isVConcatSpec(spec) ? spec.vconcat : spec.hconcat).map(function (child, i) { return common_1.buildModel(child, _this, _this.getName('concat_' + i), undefined, repeater, config); }); return _this; } ConcatModel.prototype.parseData = function () { this.component.data = parse_1.parseData(this); this.children.forEach(function (child) { child.parseData(); }); }; ConcatModel.prototype.parseLayoutSize = function () { parse_2.parseConcatLayoutSize(this); }; ConcatModel.prototype.parseSelection = function () { var _this = this; // Merge selections up the hierarchy so that they may be referenced // across unit specs. Persist their definitions within each child // to assemble signals which remain within output Vega unit groups. this.component.selection = {}; var _loop_1 = function (child) { child.parseSelection(); util_1.keys(child.component.selection).forEach(function (key) { _this.component.selection[key] = child.component.selection[key]; }); }; for (var _i = 0, _a = this.children; _i < _a.length; _i++) { var child = _a[_i]; _loop_1(child); } }; ConcatModel.prototype.parseMarkGroup = function () { for (var _i = 0, _a = this.children; _i < _a.length; _i++) { var child = _a[_i]; child.parseMarkGroup(); } }; ConcatModel.prototype.parseAxisAndHeader = function () { for (var _i = 0, _a = this.children; _i < _a.length; _i++) { var child = _a[_i]; child.parseAxisAndHeader(); } // TODO(#2415): support shared axes }; ConcatModel.prototype.parseAxisGroup = function () { return null; }; ConcatModel.prototype.parseLegend = function () { parse_3.parseNonUnitLegend(this); }; ConcatModel.prototype.assembleData = function () { if (!this.parent) { // only assemble data in the root return assemble_1.assembleData(this.component.data); } return []; }; ConcatModel.prototype.assembleParentGroupProperties = function () { return null; }; ConcatModel.prototype.assembleSelectionTopLevelSignals = function (signals) { return this.children.reduce(function (sg, child) { return child.assembleSelectionTopLevelSignals(sg); }, signals); }; ConcatModel.prototype.assembleSelectionSignals = function () { this.children.forEach(function (child) { return child.assembleSelectionSignals(); }); return []; }; ConcatModel.prototype.assembleLayoutSignals = function () { return this.children.reduce(function (signals, child) { return signals.concat(child.assembleLayoutSignals()); }, assemble_2.assembleLayoutSignals(this)); }; ConcatModel.prototype.assembleSelectionData = function (data) { return this.children.reduce(function (db, child) { return child.assembleSelectionData(db); }, []); }; ConcatModel.prototype.assembleLayout = function () { // TODO: allow customization return tslib_1.__assign({ padding: { row: 10, column: 10 }, offset: 10 }, (this.isVConcat ? { columns: 1 } : {}), { bounds: 'full', align: 'all' }); }; ConcatModel.prototype.assembleMarks = function () { // only children have marks return this.children.map(function (child) { var encodeEntry = child.assembleParentGroupProperties(); return tslib_1.__assign({ type: 'group', name: child.getName('group') }, (encodeEntry ? { encode: { update: encodeEntry } } : {}), child.assembleGroup()); }); }; return ConcatModel; }(model_1.Model)); exports.ConcatModel = ConcatModel; },{"../spec":101,"../util":107,"./common":18,"./data/assemble":22,"./data/parse":30,"./layout/assemble":38,"./layout/parse":40,"./legend/parse":44,"./model":58,"tslib":5}],21:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var channel_1 = require("../../channel"); var fielddef_1 = require("../../fielddef"); var log = require("../../log"); var type_1 = require("../../type"); var util_1 = require("../../util"); var dataflow_1 = require("./dataflow"); function addDimension(dims, fieldDef) { if (fieldDef.bin) { dims[fielddef_1.field(fieldDef, { binSuffix: 'start' })] = true; dims[fielddef_1.field(fieldDef, { binSuffix: 'end' })] = true; // We need the range only when the user explicitly forces a binned field to be ordinal (range used in axis and legend labels). // We could check whether the axis or legend exists but that seems overkill. In axes and legends, we check hasDiscreteDomain(scaleType). if (fieldDef.type === type_1.ORDINAL) { dims[fielddef_1.field(fieldDef, { binSuffix: 'range' })] = true; } } else { dims[fielddef_1.field(fieldDef)] = true; } return dims; } function mergeMeasures(parentMeasures, childMeasures) { for (var f in childMeasures) { if (childMeasures.hasOwnProperty(f)) { // when we merge a measure, we either have to add an aggregation operator or even a new field var ops = childMeasures[f]; for (var op in ops) { if (ops.hasOwnProperty(op)) { if (f in parentMeasures) { // add operator to existing measure field parentMeasures[f][op] = ops[op]; } else { parentMeasures[f] = { op: ops[op] }; } } } } } } var AggregateNode = (function (_super) { tslib_1.__extends(AggregateNode, _super); /** * @param dimensions string set for dimensions * @param measures dictionary mapping field name => dict of aggregation functions and names to use */ function AggregateNode(dimensions, measures) { var _this = _super.call(this) || this; _this.dimensions = dimensions; _this.measures = measures; return _this; } AggregateNode.prototype.clone = function () { return new AggregateNode(util_1.extend({}, this.dimensions), util_1.duplicate(this.measures)); }; AggregateNode.makeFromEncoding = function (model) { var isAggregate = false; model.forEachFieldDef(function (fd) { if (fd.aggregate) { isAggregate = true; } }); var meas = {}; var dims = {}; if (!isAggregate) { // no need to create this node if the model has no aggregation return null; } model.forEachFieldDef(function (fieldDef, channel) { if (fieldDef.aggregate) { if (fieldDef.aggregate === 'count') { meas['*'] = meas['*'] || {}; meas['*']['count'] = fielddef_1.field(fieldDef, { aggregate: 'count' }); } else { meas[fieldDef.field] = meas[fieldDef.field] || {}; meas[fieldDef.field][fieldDef.aggregate] = fielddef_1.field(fieldDef); // For scale channel with domain === 'unaggregated', add min/max so we can use their union as unaggregated domain if (channel_1.isScaleChannel(channel) && model.scaleDomain(channel) === 'unaggregated') { meas[fieldDef.field]['min'] = fielddef_1.field(fieldDef, { aggregate: 'min' }); meas[fieldDef.field]['max'] = fielddef_1.field(fieldDef, { aggregate: 'max' }); } } } else { addDimension(dims, fieldDef); } }); if ((util_1.keys(dims).length + util_1.keys(meas).length) === 0) { return null; } return new AggregateNode(dims, meas); }; AggregateNode.makeFromTransform = function (model, t) { var dims = {}; var meas = {}; for (var _i = 0, _a = t.summarize; _i < _a.length; _i++) { var s = _a[_i]; if (s.aggregate) { if (s.aggregate === 'count') { meas['*'] = meas['*'] || {}; meas['*']['count'] = s.as || fielddef_1.field(s); } else { meas[s.field] = meas[s.field] || {}; meas[s.field][s.aggregate] = s.as || fielddef_1.field(s); } } } for (var _b = 0, _c = t.groupby; _b < _c.length; _b++) { var s = _c[_b]; dims[s] = true; } if ((util_1.keys(dims).length + util_1.keys(meas).length) === 0) { return null; } return new AggregateNode(dims, meas); }; AggregateNode.prototype.merge = function (other) { if (!util_1.differ(this.dimensions, other.dimensions)) { mergeMeasures(this.measures, other.measures); other.remove(); } else { log.debug('different dimensions, cannot merge'); } }; AggregateNode.prototype.addDimensions = function (fields) { var _this = this; fields.forEach(function (f) { return _this.dimensions[f] = true; }); }; AggregateNode.prototype.dependentFields = function () { var out = {}; util_1.keys(this.dimensions).forEach(function (f) { return out[f] = true; }); util_1.keys(this.measures).forEach(function (m) { return out[m] = true; }); return out; }; AggregateNode.prototype.producedFields = function () { var _this = this; var out = {}; util_1.keys(this.measures).forEach(function (field) { util_1.keys(_this.measures[field]).forEach(function (op) { out[op + "_" + field] = true; }); }); return out; }; AggregateNode.prototype.assemble = function () { var _this = this; var ops = []; var fields = []; var as = []; util_1.keys(this.measures).forEach(function (field) { util_1.keys(_this.measures[field]).forEach(function (op) { as.push(_this.measures[field][op]); ops.push(op); fields.push(field); }); }); var result = { type: 'aggregate', groupby: util_1.keys(this.dimensions), ops: ops, fields: fields, as: as }; return result; }; return AggregateNode; }(dataflow_1.DataFlowNode)); exports.AggregateNode = AggregateNode; },{"../../channel":12,"../../fielddef":90,"../../log":95,"../../type":106,"../../util":107,"./dataflow":24,"tslib":5}],22:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var data_1 = require("../../data"); var util_1 = require("../../util"); var aggregate_1 = require("./aggregate"); var bin_1 = require("./bin"); var dataflow_1 = require("./dataflow"); var facet_1 = require("./facet"); var formatparse_1 = require("./formatparse"); var nonpositivefilter_1 = require("./nonpositivefilter"); var nullfilter_1 = require("./nullfilter"); var optimizers_1 = require("./optimizers"); var optimizers = require("./optimizers"); var pathorder_1 = require("./pathorder"); var source_1 = require("./source"); var stack_1 = require("./stack"); var timeunit_1 = require("./timeunit"); var transforms_1 = require("./transforms"); exports.FACET_SCALE_PREFIX = 'scale_'; /** * Start optimization path from the root. Useful for removing nodes. */ function removeUnnecessaryNodes(node) { // remove empty non positive filter if (node instanceof nonpositivefilter_1.NonPositiveFilterNode && util_1.every(util_1.vals(node.filter), function (b) { return b === false; })) { node.remove(); } // remove empty null filter nodes if (node instanceof nullfilter_1.NullFilterNode && util_1.every(util_1.vals(node.filteredFields), function (f) { return f === null; })) { node.remove(); } // remove output nodes that are not required if (node instanceof dataflow_1.OutputNode && !node.isRequired()) { node.remove(); } node.children.forEach(removeUnnecessaryNodes); } /** * Clones the subtree and ignores output nodes except for the leafs, which are renamed. */ function cloneSubtree(facet) { function clone(node) { if (!(node instanceof pathorder_1.OrderNode)) { var copy_1 = node.clone(); if (copy_1 instanceof dataflow_1.OutputNode) { var newName = exports.FACET_SCALE_PREFIX + facet.model.getName(copy_1.getSource()); copy_1.setSource(newName); facet.model.component.data.outputNodes[newName] = copy_1; } else if (copy_1 instanceof aggregate_1.AggregateNode || copy_1 instanceof stack_1.StackNode) { copy_1.addDimensions(facet.fields); } util_1.flatten(node.children.map(clone)).forEach(function (n) { return n.parent = copy_1; }); return [copy_1]; } return util_1.flatten(node.children.map(clone)); } return clone; } /** * Move facet nodes down to the next fork or output node. Also pull the main output with the facet node. * After moving down the facet node, make a copy of the subtree and make it a child of the main output. */ function moveFacetDown(node) { if (node instanceof facet_1.FacetNode) { if (node.numChildren() === 1 && !(node.children[0] instanceof dataflow_1.OutputNode)) { // move down until we hit a fork or output node var child = node.children[0]; if (child instanceof aggregate_1.AggregateNode || child instanceof stack_1.StackNode) { child.addDimensions(node.fields); } child.swapWithParent(); moveFacetDown(node); } else { // move main to facet moveMainDownToFacet(node.model.component.data.main); // replicate the subtree and place it before the facet's main node var copy = util_1.flatten(node.children.map(cloneSubtree(node))); copy.forEach(function (c) { return c.parent = node.model.component.data.main; }); } } else { node.children.forEach(moveFacetDown); } } function moveMainDownToFacet(node) { if (node instanceof dataflow_1.OutputNode && node.type === data_1.MAIN) { if (node.numChildren() === 1) { var child = node.children[0]; if (!(child instanceof facet_1.FacetNode)) { child.swapWithParent(); moveMainDownToFacet(node); } } } } /** * Return all leaf nodes. */ function getLeaves(roots) { var leaves = []; function append(node) { if (node.numChildren() === 0) { leaves.push(node); } else { node.children.forEach(append); } } roots.forEach(append); return leaves; } /** * Print debug information for dataflow tree. */ function debug(node) { console.log("" + node.constructor.name + (node.debugName ? " (" + node.debugName + ")" : '') + " -> " + (node.children.map(function (c) { return "" + c.constructor.name + (c.debugName ? " (" + c.debugName + ")" : ''); }))); console.log(node); node.children.forEach(debug); } function makeWalkTree(data) { // to name datasources var datasetIndex = 0; /** * Recursively walk down the tree. */ function walkTree(node, dataSource) { if (node instanceof source_1.SourceNode) { // If the source is a named data source or a data source with values, we need // to put it in a different data source. Otherwise, Vega may override the data. if (!data_1.isUrlData(node.data)) { data.push(dataSource); var newData = { name: null, source: dataSource.name, transform: [] }; dataSource = newData; } } if (node instanceof formatparse_1.ParseNode) { if (node.parent instanceof source_1.SourceNode && !dataSource.source) { // If node's parent is a root source and the data source does not refer to another data source, use normal format parse dataSource.format = tslib_1.__assign({}, dataSource.format || {}, { parse: node.assembleFormatParse() }); } else { // Otherwise use Vega expression to parse dataSource.transform = dataSource.transform.concat(node.assembleTransforms()); } } if (node instanceof facet_1.FacetNode) { if (!dataSource.name) { dataSource.name = "data_" + datasetIndex++; } if (!dataSource.source || dataSource.transform.length > 0) { data.push(dataSource); node.data = dataSource.name; } else { node.data = dataSource.source; } node.assemble().forEach(function (d) { return data.push(d); }); // break here because the rest of the tree has to be taken care of by the facet. return; } if (node instanceof transforms_1.FilterNode || node instanceof nullfilter_1.NullFilterNode || node instanceof transforms_1.CalculateNode || node instanceof aggregate_1.AggregateNode || node instanceof pathorder_1.OrderNode || node instanceof transforms_1.LookupNode) { dataSource.transform.push(node.assemble()); } if (node instanceof nonpositivefilter_1.NonPositiveFilterNode || node instanceof bin_1.BinNode || node instanceof timeunit_1.TimeUnitNode || node instanceof stack_1.StackNode) { dataSource.transform = dataSource.transform.concat(node.assemble()); } if (node instanceof aggregate_1.AggregateNode) { if (!dataSource.name) { dataSource.name = "data_" + datasetIndex++; } } if (node instanceof dataflow_1.OutputNode) { if (dataSource.source && dataSource.transform.length === 0) { node.setSource(dataSource.source); } else if (node.parent instanceof dataflow_1.OutputNode) { // Note that an output node may be required but we still do not assemble a // separate data source for it. node.setSource(dataSource.name); } else { if (!dataSource.name) { dataSource.name = "data_" + datasetIndex++; } // Here we set the name of the datasource we generated. From now on // other assemblers can use it. node.setSource(dataSource.name); // if this node has more than one child, we will add a datasource automatically if (node.numChildren() === 1) { data.push(dataSource); var newData = { name: null, source: dataSource.name, transform: [] }; dataSource = newData; } } } switch (node.numChildren()) { case 0: // done if (node instanceof dataflow_1.OutputNode && (!dataSource.source || dataSource.transform.length > 0)) { // do not push empty datasources that are simply references data.push(dataSource); } break; case 1: walkTree(node.children[0], dataSource); break; default: if (!dataSource.name) { dataSource.name = "data_" + datasetIndex++; } var source_2 = dataSource.name; if (!dataSource.source || dataSource.transform.length > 0) { data.push(dataSource); } else { source_2 = dataSource.source; } node.children.forEach(function (child) { var newData = { name: null, source: source_2, transform: [] }; walkTree(child, newData); }); break; } } return walkTree; } /** * Assemble data sources that are derived from faceted data. */ function assembleFacetData(root) { var data = []; var walkTree = makeWalkTree(data); root.children.forEach(function (child) { return walkTree(child, { source: root.name, name: null, transform: [] }); }); return data; } exports.assembleFacetData = assembleFacetData; /** * Create Vega Data array from a given compiled model and append all of them to the given array * * @param model * @param data array * @return modified data array */ function assembleData(dataCompomponent) { var roots = util_1.vals(dataCompomponent.sources); var data = []; roots.forEach(removeUnnecessaryNodes); // remove source nodes that don't have any children because they also don't have output nodes roots = roots.filter(function (r) { return r.numChildren() > 0; }); getLeaves(roots).forEach(optimizers_1.iterateFromLeaves(optimizers.removeUnusedSubtrees)); roots = roots.filter(function (r) { return r.numChildren() > 0; }); getLeaves(roots).forEach(optimizers_1.iterateFromLeaves(optimizers.moveParseUp)); getLeaves(roots).forEach(optimizers.removeDuplicateTimeUnits); roots.forEach(moveFacetDown); // roots.forEach(debug); var walkTree = makeWalkTree(data); var sourceIndex = 0; roots.forEach(function (root) { // assign a name if the source does not have a name yet if (!root.hasName()) { root.dataName = "source_" + sourceIndex++; } var newData = root.assemble(); walkTree(root, newData); }); // remove empty transform arrays for cleaner output data.forEach(function (d) { if (d.transform.length === 0) { delete d.transform; } }); // move sources without transforms (the ones that are potentially used in lookups) to the beginning data.sort(function (a, b) { return (a.transform || []).length === 0 ? -1 : ((b.transform || []).length === 0 ? 1 : 0); }); // now fix the from references in lookup transforms for (var _i = 0, data_2 = data; _i < data_2.length; _i++) { var d = data_2[_i]; for (var _a = 0, _b = d.transform || []; _a < _b.length; _a++) { var t = _b[_a]; if (t.type === 'lookup') { t.from = dataCompomponent.outputNodes[t.from].getSource(); } } } return data; } exports.assembleData = assembleData; },{"../../data":86,"../../util":107,"./aggregate":21,"./bin":23,"./dataflow":24,"./facet":25,"./formatparse":26,"./nonpositivefilter":27,"./nullfilter":28,"./optimizers":29,"./pathorder":31,"./source":32,"./stack":33,"./timeunit":34,"./transforms":35,"tslib":5}],23:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var bin_1 = require("../../bin"); var fielddef_1 = require("../../fielddef"); var util_1 = require("../../util"); var common_1 = require("../common"); var unit_1 = require("../unit"); var dataflow_1 = require("./dataflow"); function rangeFormula(model, fieldDef, channel, config) { var discreteDomain = model.hasDiscreteDomain(channel); if (discreteDomain) { // read format from axis or legend, if there is no format then use config.numberFormat var guide = (model instanceof unit_1.UnitModel) ? (model.axis(channel) || model.legend(channel) || {}) : {}; var startField = fielddef_1.field(fieldDef, { expr: 'datum', binSuffix: 'start' }); var endField = fielddef_1.field(fieldDef, { expr: 'datum', binSuffix: 'end' }); return { formulaAs: fielddef_1.field(fieldDef, { binSuffix: 'range' }), formula: common_1.numberFormatExpr(startField, guide.format, config) + " + \" - \" + " + common_1.numberFormatExpr(endField, guide.format, config) }; } return {}; } function binKey(bin, field) { return bin_1.binToString(bin) + "_" + field; } function createBinComponent(bin, t, model, key) { return { bin: bin, field: t.field, as: [fielddef_1.field(t, { binSuffix: 'start' }), fielddef_1.field(t, { binSuffix: 'end' })], signal: model.getName(key + "_bins"), extentSignal: model.getName(key + '_extent') }; } var BinNode = (function (_super) { tslib_1.__extends(BinNode, _super); function BinNode(bins) { var _this = _super.call(this) || this; _this.bins = bins; return _this; } BinNode.prototype.clone = function () { return new BinNode(util_1.duplicate(this.bins)); }; BinNode.makeBinFromEncoding = function (model) { var bins = model.reduceFieldDef(function (binComponent, fieldDef, channel) { var fieldDefBin = fieldDef.bin; if (fieldDefBin) { var bin = fielddef_1.normalizeBin(fieldDefBin, undefined) || {}; var key = binKey(bin, fieldDef.field); if (!(key in binComponent)) { binComponent[key] = createBinComponent(bin, fieldDef, model, key); } binComponent[key] = tslib_1.__assign({}, binComponent[key], rangeFormula(model, fieldDef, channel, model.config)); } return binComponent; }, {}); if (util_1.keys(bins).length === 0) { return null; } return new BinNode(bins); }; BinNode.makeFromTransform = function (model, t) { var bins = {}; var bin = fielddef_1.normalizeBin(t.bin, undefined) || {}; var key = binKey(bin, t.field); return new BinNode((_a = {}, _a[key] = createBinComponent(bin, t, model, key), _a)); var _a; }; BinNode.prototype.merge = function (other) { this.bins = util_1.extend(other.bins); other.remove(); }; BinNode.prototype.producedFields = function () { var out = {}; util_1.vals(this.bins).forEach(function (c) { c.as.forEach(function (f) { return out[f] = true; }); }); return out; }; BinNode.prototype.dependentFields = function () { var out = {}; util_1.vals(this.bins).forEach(function (c) { out[c.field] = true; }); return out; }; BinNode.prototype.assemble = function () { return util_1.flatten(util_1.vals(this.bins).map(function (bin) { var transform = []; var binTrans = tslib_1.__assign({ type: 'bin', field: bin.field, as: bin.as, signal: bin.signal }, bin.bin); if (!bin.bin.extent) { transform.push({ type: 'extent', field: bin.field, signal: bin.extentSignal }); binTrans.extent = { signal: bin.extentSignal }; } transform.push(binTrans); if (bin.formula) { transform.push({ type: 'formula', expr: bin.formula, as: bin.formulaAs }); } return transform; })); }; return BinNode; }(dataflow_1.DataFlowNode)); exports.BinNode = BinNode; },{"../../bin":11,"../../fielddef":90,"../../util":107,"../common":18,"../unit":81,"./dataflow":24,"tslib":5}],24:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); /** * A node in the dataflow tree. */ var DataFlowNode = (function () { function DataFlowNode(debugName) { this.debugName = debugName; this._children = []; this._parent = null; } /** * Clone this node with a deep copy but don't clone links to children or parents. */ DataFlowNode.prototype.clone = function () { throw new Error('Cannot clone node'); }; /** * Set of fields that are being created by this node. */ DataFlowNode.prototype.producedFields = function () { return {}; }; DataFlowNode.prototype.dependentFields = function () { return {}; }; Object.defineProperty(DataFlowNode.prototype, "parent", { get: function () { return this._parent; }, /** * Set the parent of the node and also add this not to the parent's children. */ set: function (parent) { this._parent = parent; parent.addChild(this); }, enumerable: true, configurable: true }); Object.defineProperty(DataFlowNode.prototype, "children", { get: function () { return this._children; }, enumerable: true, configurable: true }); DataFlowNode.prototype.numChildren = function () { return this._children.length; }; DataFlowNode.prototype.addChild = function (child) { this._children.push(child); }; DataFlowNode.prototype.removeChild = function (oldChild) { this._children.splice(this._children.indexOf(oldChild), 1); }; /** * Remove node from the dataflow. */ DataFlowNode.prototype.remove = function () { for (var _i = 0, _a = this._children; _i < _a.length; _i++) { var child = _a[_i]; child.parent = this._parent; } this._parent.removeChild(this); }; /** * Insert another node as a parent of this node. */ DataFlowNode.prototype.insertAsParentOf = function (other) { var parent = other.parent; parent.removeChild(this); this.parent = parent; other.parent = this; }; DataFlowNode.prototype.swapWithParent = function () { var parent = this._parent; var newParent = parent.parent; // reconnect the children for (var _i = 0, _a = this._children; _i < _a.length; _i++) { var child = _a[_i]; child.parent = parent; } // remove old links this._children = []; // equivalent to removing every child link one by one parent.removeChild(this); parent.parent.removeChild(parent); // swap two nodes this.parent = newParent; parent.parent = this; }; return DataFlowNode; }()); exports.DataFlowNode = DataFlowNode; var OutputNode = (function (_super) { tslib_1.__extends(OutputNode, _super); /** * @param source The name of the source. Will change in assemble. * @param type The type of the output node. * @param refCounts A global ref counter map. */ function OutputNode(source, type, refCounts) { var _this = _super.call(this, source) || this; _this.type = type; _this.refCounts = refCounts; _this._source = _this._name = source; if (_this.refCounts && !(_this._name in _this.refCounts)) { _this.refCounts[_this._name] = 0; } return _this; } OutputNode.prototype.clone = function () { var cloneObj = new this.constructor; cloneObj.debugName = 'clone_' + this.debugName; cloneObj._source = this._source; cloneObj.type = this.type; cloneObj.refCounts = this.refCounts; return cloneObj; }; /** * Request the datasource name and increase the ref counter. * * During the parsing phase, this will return the simple name such as 'main' or 'raw'. * It is crucial to request the name from an output node to mark it as a required node. * If nobody ever requests the name, this datasource will not be instantiated in the assemble phase. * * In the assemble phase, this will return the correct name. */ OutputNode.prototype.getSource = function () { this.refCounts[this._name]++; return this._source; }; OutputNode.prototype.isRequired = function () { return !!this.refCounts[this._name]; }; OutputNode.prototype.setSource = function (source) { this._source = source; }; return OutputNode; }(DataFlowNode)); exports.OutputNode = OutputNode; },{"tslib":5}],25:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var channel_1 = require("../../channel"); var dataflow_1 = require("./dataflow"); /** * A node that helps us track what fields we are faceting by. */ var FacetNode = (function (_super) { tslib_1.__extends(FacetNode, _super); /** * @param model The facet model. * @param name The name that this facet source will have. * @param data The source data for this facet data. */ function FacetNode(model, name, data) { var _this = _super.call(this) || this; _this.model = model; _this.name = name; _this.data = data; if (model.facet.column) { _this.columnField = model.field(channel_1.COLUMN); _this.columnName = model.getName('column'); } if (model.facet.row) { _this.rowField = model.field(channel_1.ROW); _this.rowName = model.getName('row'); } return _this; } Object.defineProperty(FacetNode.prototype, "fields", { get: function () { var fields = []; if (this.columnField) { fields.push(this.columnField); } if (this.rowField) { fields.push(this.rowField); } return fields; }, enumerable: true, configurable: true }); /** * The name to reference this source is its name. */ FacetNode.prototype.getSource = function () { return this.name; }; FacetNode.prototype.assemble = function () { var data = []; if (this.columnName) { data.push({ name: this.columnName, source: this.data, transform: [{ type: 'aggregate', groupby: [this.columnField] }] }); // Column needs another data source to calculate cardinality as input to layout data.push({ name: this.columnName + '_layout', source: this.columnName, transform: [{ type: 'aggregate', ops: ['distinct'], fields: [this.columnField] }] }); } if (this.rowName) { data.push({ name: this.rowName, source: this.data, transform: [{ type: 'aggregate', groupby: [this.rowField] }] }); } return data; }; return FacetNode; }(dataflow_1.DataFlowNode)); exports.FacetNode = FacetNode; },{"../../channel":12,"./dataflow":24,"tslib":5}],26:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var aggregate_1 = require("../../aggregate"); var log = require("../../log"); var transform_1 = require("../../transform"); var type_1 = require("../../type"); var util_1 = require("../../util"); var model_1 = require("../model"); var dataflow_1 = require("./dataflow"); function parseExpression(field, parse) { var f = "datum[" + util_1.stringValue(field) + "]"; if (parse === 'number') { return "toNumber(" + f + ")"; } else if (parse === 'boolean') { return "toBoolean(" + f + ")"; } else if (parse === 'string') { return "toString(" + f + ")"; } else if (parse === 'date') { return "toDate(" + f + ")"; } else if (parse.indexOf('date:') === 0) { var specifier = parse.slice(5, parse.length); return "timeParse(" + f + "," + specifier + ")"; } else if (parse.indexOf('utc:') === 0) { var specifier = parse.slice(4, parse.length); return "utcParse(" + f + "," + specifier + ")"; } else { log.warn(log.message.unrecognizedParse(parse)); return null; } } var ParseNode = (function (_super) { tslib_1.__extends(ParseNode, _super); function ParseNode(parse) { var _this = _super.call(this) || this; _this._parse = {}; _this._parse = parse; return _this; } ParseNode.prototype.clone = function () { return new ParseNode(util_1.duplicate(this.parse)); }; ParseNode.make = function (model) { var parse = {}; var calcFieldMap = model.transforms.filter(transform_1.isCalculate).reduce(function (fieldMap, formula) { fieldMap[formula.as] = true; return fieldMap; }, {}); if (model instanceof model_1.ModelWithField) { // Parse encoded fields model.forEachFieldDef(function (fieldDef) { if (fieldDef.type === type_1.TEMPORAL) { parse[fieldDef.field] = 'date'; } else if (fieldDef.type === type_1.QUANTITATIVE) { if (calcFieldMap[fieldDef.field] || aggregate_1.isCountingAggregateOp(fieldDef.aggregate)) { return; } parse[fieldDef.field] = 'number'; } }); } // Custom parse should override inferred parse var data = model.data; if (data && data.format && data.format.parse) { var p_1 = data.format.parse; util_1.keys(p_1).forEach(function (field) { parse[field] = p_1[field]; }); } // We should not parse what has already been parsed in a parent var modelParse = model.component.data.ancestorParse; util_1.keys(modelParse).forEach(function (field) { if (parse[field] !== modelParse[field]) { log.warn(log.message.differentParse(field, parse[field], modelParse[field])); } else { delete parse[field]; } }); if (util_1.keys(parse).length === 0) { return null; } return new ParseNode(parse); }; Object.defineProperty(ParseNode.prototype, "parse", { get: function () { return this._parse; }, enumerable: true, configurable: true }); ParseNode.prototype.merge = function (other) { this._parse = util_1.extend(this._parse, other.parse); other.remove(); }; ParseNode.prototype.assembleFormatParse = function () { return this._parse; }; // format parse depends and produces all fields in its parse ParseNode.prototype.producedFields = function () { return util_1.toSet(util_1.keys(this.parse)); }; ParseNode.prototype.dependentFields = function () { return util_1.toSet(util_1.keys(this.parse)); }; ParseNode.prototype.assembleTransforms = function () { var _this = this; return util_1.keys(this._parse).map(function (field) { var expr = parseExpression(field, _this._parse[field]); if (!expr) { return null; } var formula = { type: 'formula', expr: expr, as: field }; return formula; }).filter(function (t) { return t !== null; }); }; return ParseNode; }(dataflow_1.DataFlowNode)); exports.ParseNode = ParseNode; },{"../../aggregate":9,"../../log":95,"../../transform":105,"../../type":106,"../../util":107,"../model":58,"./dataflow":24,"tslib":5}],27:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var channel_1 = require("../../channel"); var scale_1 = require("../../scale"); var util_1 = require("../../util"); var dataflow_1 = require("./dataflow"); var NonPositiveFilterNode = (function (_super) { tslib_1.__extends(NonPositiveFilterNode, _super); function NonPositiveFilterNode(filter) { var _this = _super.call(this) || this; _this._filter = filter; return _this; } NonPositiveFilterNode.prototype.clone = function () { return new NonPositiveFilterNode(util_1.extend({}, this._filter)); }; NonPositiveFilterNode.make = function (model) { var filter = channel_1.SCALE_CHANNELS.reduce(function (nonPositiveComponent, channel) { var scale = model.getScaleComponent(channel); if (!scale || !model.field(channel)) { // don't set anything return nonPositiveComponent; } nonPositiveComponent[model.field(channel)] = scale.get('type') === scale_1.ScaleType.LOG; return nonPositiveComponent; }, {}); if (!util_1.keys(filter).length) { return null; } return new NonPositiveFilterNode(filter); }; Object.defineProperty(NonPositiveFilterNode.prototype, "filter", { get: function () { return this._filter; }, enumerable: true, configurable: true }); NonPositiveFilterNode.prototype.assemble = function () { var _this = this; return util_1.keys(this._filter).filter(function (field) { // Only filter fields (keys) with value = true return _this._filter[field]; }).map(function (field) { return { type: 'filter', expr: "datum[" + util_1.stringValue(field) + "] > 0" }; }); }; return NonPositiveFilterNode; }(dataflow_1.DataFlowNode)); exports.NonPositiveFilterNode = NonPositiveFilterNode; },{"../../channel":12,"../../scale":98,"../../util":107,"./dataflow":24,"tslib":5}],28:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var channel_1 = require("../../channel"); var scale_1 = require("../../scale"); var type_1 = require("../../type"); var util_1 = require("../../util"); var dataflow_1 = require("./dataflow"); var NullFilterNode = (function (_super) { tslib_1.__extends(NullFilterNode, _super); function NullFilterNode(fields) { var _this = _super.call(this) || this; _this._filteredFields = fields; return _this; } NullFilterNode.prototype.clone = function () { return new NullFilterNode(util_1.duplicate(this._filteredFields)); }; NullFilterNode.make = function (model) { var fields = model.reduceFieldDef(function (aggregator, fieldDef, channel) { if (model.config.invalidValues === 'filter' && !fieldDef.aggregate && fieldDef.field) { // Vega's aggregate operator already handle invalid values, so we only have to consider non-aggregate field here. var scaleComponent = channel_1.isScaleChannel(channel) && model.getScaleComponent(channel); if (scaleComponent) { var scaleType = scaleComponent.get('type'); // only automatically filter null for continuous domain since discrete domain scales can handle invalid values. if (scale_1.hasContinuousDomain(scaleType)) { aggregator[fieldDef.field] = fieldDef; } } } return aggregator; }, {}); if (util_1.keys(fields).length === 0) { return null; } return new NullFilterNode(fields); }; Object.defineProperty(NullFilterNode.prototype, "filteredFields", { get: function () { return this._filteredFields; }, enumerable: true, configurable: true }); NullFilterNode.prototype.merge = function (other) { var _this = this; var t = util_1.keys(this._filteredFields).map(function (k) { return k + ' ' + util_1.hash(_this._filteredFields[k]); }); var o = util_1.keys(other.filteredFields).map(function (k) { return k + ' ' + util_1.hash(other.filteredFields[k]); }); if (!util_1.differArray(t, o)) { this._filteredFields = util_1.extend(this._filteredFields, other._filteredFields); other.remove(); } }; NullFilterNode.prototype.assemble = function () { var _this = this; var filters = util_1.keys(this._filteredFields).reduce(function (_filters, field) { var fieldDef = _this._filteredFields[field]; if (fieldDef !== null) { _filters.push("datum[" + util_1.stringValue(fieldDef.field) + "] !== null"); if (util_1.contains([type_1.QUANTITATIVE, type_1.TEMPORAL], fieldDef.type)) { // TODO(https://github.com/vega/vega-lite/issues/1436): // We can be even smarter and add NaN filter for N,O that are numbers // based on the `parse` property once we have it. _filters.push("!isNaN(datum[" + util_1.stringValue(fieldDef.field) + "])"); } } return _filters; }, []); return filters.length > 0 ? { type: 'filter', expr: filters.join(' && ') } : null; }; return NullFilterNode; }(dataflow_1.DataFlowNode)); exports.NullFilterNode = NullFilterNode; },{"../../channel":12,"../../scale":98,"../../type":106,"../../util":107,"./dataflow":24,"tslib":5}],29:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var util_1 = require("../../util"); var dataflow_1 = require("./dataflow"); var formatparse_1 = require("./formatparse"); var source_1 = require("./source"); var timeunit_1 = require("./timeunit"); /** * Start optimization path at the leaves. Useful for merging up or removing things. * * If the callback returns true, the recursion continues. */ function iterateFromLeaves(f) { function optimizeNextFromLeaves(node) { if (node instanceof source_1.SourceNode) { return; } var next = node.parent; if (f(node)) { optimizeNextFromLeaves(next); } } return optimizeNextFromLeaves; } exports.iterateFromLeaves = iterateFromLeaves; /** * Move parse nodes up to forks. */ function moveParseUp(node) { var parent = node.parent; // move parse up by merging or swapping if (node instanceof formatparse_1.ParseNode) { if (parent instanceof source_1.SourceNode) { return false; } if (parent.numChildren() > 1) { // don't move parse further up but continue with parent. return true; } if (parent instanceof formatparse_1.ParseNode) { parent.merge(node); } else { // don't swap with nodes that produce something that the parse node depends on (e.g. lookup) if (util_1.hasIntersection(parent.producedFields(), node.dependentFields())) { return true; } node.swapWithParent(); } } return true; } exports.moveParseUp = moveParseUp; /** * Repeatedly remove leaf nodes that are not output nodes. * The reason is that we don't need subtrees that don't have any output nodes. */ function removeUnusedSubtrees(node) { var parent = node.parent; if (node instanceof dataflow_1.OutputNode || node.numChildren() > 0) { // no need to continue with parent because it is output node or will have children (there was a fork) return false; } else { node.remove(); } return true; } exports.removeUnusedSubtrees = removeUnusedSubtrees; /** * Removes duplicate time unit nodes (as determined by the name of the * output field) that may be generated due to selections projected over * time units. */ function removeDuplicateTimeUnits(leaf) { var fields = {}; return iterateFromLeaves(function (node) { if (node instanceof timeunit_1.TimeUnitNode) { var pfields = node.producedFields(); var dupe = util_1.keys(pfields).every(function (k) { return !!fields[k]; }); if (dupe) { node.remove(); } else { fields = tslib_1.__assign({}, fields, pfields); } } return true; })(leaf); } exports.removeDuplicateTimeUnits = removeDuplicateTimeUnits; },{"../../util":107,"./dataflow":24,"./formatparse":26,"./source":32,"./timeunit":34,"tslib":5}],30:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var data_1 = require("../../data"); var facet_1 = require("../facet"); var layer_1 = require("../layer"); var model_1 = require("../model"); var unit_1 = require("../unit"); var aggregate_1 = require("./aggregate"); var bin_1 = require("./bin"); var dataflow_1 = require("./dataflow"); var facet_2 = require("./facet"); var formatparse_1 = require("./formatparse"); var nonpositivefilter_1 = require("./nonpositivefilter"); var nullfilter_1 = require("./nullfilter"); var pathorder_1 = require("./pathorder"); var source_1 = require("./source"); var stack_1 = require("./stack"); var timeunit_1 = require("./timeunit"); var transforms_1 = require("./transforms"); function parseRoot(model, sources) { if (model.data || !model.parent) { // if the model defines a data source or is the root, create a source node var source = new source_1.SourceNode(model.data); var hash = source.hash(); if (hash in sources) { // use a reference if we already have a source return sources[hash]; } else { // otherwise add a new one sources[hash] = source; return source; } } else { // If we don't have a source defined (overriding parent's data), use the parent's facet root or main. return model.parent.component.data.facetRoot ? model.parent.component.data.facetRoot : model.parent.component.data.main; } } /* Description of the dataflow (http://asciiflow.com/): +--------+ | Source | +---+----+ | v Transforms (Filter, Calculate, ...) | v FormatParse | v Null Filter | v Binning | v Timeunit | v +--+--+ | Raw | +-----+ | v Aggregate | v Stack | v >0 Filter | v Path Order | v +----------+ | Main | +----------+ | v +-------+ | Facet |----> "column", "column-layout", and "row" +-------+ | v ...Child data... */ function parseData(model) { var root = parseRoot(model, model.component.data.sources); var outputNodes = model.component.data.outputNodes; var outputNodeRefCounts = model.component.data.outputNodeRefCounts; // the current head of the tree that we are appending to var head = root; // HACK: This is equivalent for merging bin extent for union scale. // FIXME(https://github.com/vega/vega-lite/issues/2270): Correctly merge extent / bin node for shared bin scale var parentIsLayer = model.parent && (model.parent instanceof layer_1.LayerModel); if (model instanceof model_1.ModelWithField) { if (parentIsLayer) { var bin = bin_1.BinNode.makeBinFromEncoding(model); if (bin) { bin.parent = head; head = bin; } } } if (model.transforms.length > 0) { var _a = transforms_1.parseTransformArray(model), first = _a.first, last = _a.last; first.parent = head; head = last; } var parse = formatparse_1.ParseNode.make(model); if (parse) { parse.parent = head; head = parse; } if (model instanceof model_1.ModelWithField) { var nullFilter = nullfilter_1.NullFilterNode.make(model); if (nullFilter) { nullFilter.parent = head; head = nullFilter; } if (!parentIsLayer) { var bin = bin_1.BinNode.makeBinFromEncoding(model); if (bin) { bin.parent = head; head = bin; } } var tu = timeunit_1.TimeUnitNode.makeFromEncoding(model); if (tu) { tu.parent = head; head = tu; } } // add an output node pre aggregation var rawName = model.getName(data_1.RAW); var raw = new dataflow_1.OutputNode(rawName, data_1.RAW, outputNodeRefCounts); outputNodes[rawName] = raw; raw.parent = head; head = raw; if (model instanceof unit_1.UnitModel) { var agg = aggregate_1.AggregateNode.makeFromEncoding(model); if (agg) { agg.parent = head; head = agg; } var stack = stack_1.StackNode.make(model); if (stack) { stack.parent = head; head = stack; } var nonPosFilter = nonpositivefilter_1.NonPositiveFilterNode.make(model); if (nonPosFilter) { nonPosFilter.parent = head; head = nonPosFilter; } } if (model instanceof unit_1.UnitModel) { var order = pathorder_1.OrderNode.make(model); if (order) { order.parent = head; head = order; } } // output node for marks var mainName = model.getName(data_1.MAIN); var main = new dataflow_1.OutputNode(mainName, data_1.MAIN, outputNodeRefCounts); outputNodes[mainName] = main; main.parent = head; head = main; // add facet marker var facetRoot = null; if (model instanceof facet_1.FacetModel) { var facetName = model.getName('facet'); facetRoot = new facet_2.FacetNode(model, facetName, main.getSource()); outputNodes[facetName] = facetRoot; facetRoot.parent = head; head = facetRoot; } // add the format parse from this model so that children don't parse the same field again var ancestorParse = tslib_1.__assign({}, model.component.data.ancestorParse, (parse ? parse.parse : {})); return tslib_1.__assign({}, model.component.data, { outputNodes: outputNodes, outputNodeRefCounts: outputNodeRefCounts, main: main, facetRoot: facetRoot, ancestorParse: ancestorParse }); } exports.parseData = parseData; },{"../../data":86,"../facet":36,"../layer":37,"../model":58,"../unit":81,"./aggregate":21,"./bin":23,"./dataflow":24,"./facet":25,"./formatparse":26,"./nonpositivefilter":27,"./nullfilter":28,"./pathorder":31,"./source":32,"./stack":33,"./timeunit":34,"./transforms":35,"tslib":5}],31:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var encoding_1 = require("../../encoding"); var fielddef_1 = require("../../fielddef"); var sort_1 = require("../../sort"); var util_1 = require("../../util"); var common_1 = require("../common"); var dataflow_1 = require("./dataflow"); var OrderNode = (function (_super) { tslib_1.__extends(OrderNode, _super); function OrderNode(sort) { var _this = _super.call(this) || this; _this.sort = sort; return _this; } OrderNode.prototype.clone = function () { return new OrderNode(util_1.duplicate(this.sort)); }; OrderNode.make = function (model) { var sort = null; if (util_1.contains(['line', 'area'], model.mark())) { if (model.mark() === 'line' && model.channelHasField('order')) { // For only line, sort by the order field if it is specified. sort = common_1.sortParams(model.encoding.order); } else { // For both line and area, we sort values based on dimension by default var dimensionChannel = model.markDef.orient === 'horizontal' ? 'y' : 'x'; var s = model.sort(dimensionChannel); var sortField = sort_1.isSortField(s) ? fielddef_1.field({ // FIXME: this op might not already exist? // FIXME: what if dimensionChannel (x or y) contains custom domain? aggregate: encoding_1.isAggregate(model.encoding) ? s.op : undefined, field: s.field }) : model.field(dimensionChannel, { binSuffix: 'start' }); sort = { field: sortField, order: 'descending' }; } } else { return null; } return new OrderNode(sort); }; OrderNode.prototype.assemble = function () { return { type: 'collect', sort: this.sort }; }; return OrderNode; }(dataflow_1.DataFlowNode)); exports.OrderNode = OrderNode; },{"../../encoding":88,"../../fielddef":90,"../../sort":100,"../../util":107,"../common":18,"./dataflow":24,"tslib":5}],32:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var data_1 = require("../../data"); var util_1 = require("../../util"); var dataflow_1 = require("./dataflow"); var SourceNode = (function (_super) { tslib_1.__extends(SourceNode, _super); function SourceNode(data) { var _this = _super.call(this) || this; data = data || { name: 'source' }; if (data_1.isInlineData(data)) { _this._data = { values: data.values }; } else if (data_1.isUrlData(data)) { // Extract extension from URL using snippet from // http://stackoverflow.com/questions/680929/how-to-extract-extension-from-filename-string-in-javascript var defaultExtension = /(?:\.([^.]+))?$/.exec(data.url)[1]; if (!util_1.contains(['json', 'csv', 'tsv', 'topojson'], defaultExtension)) { defaultExtension = 'json'; } var dataFormat = data.format || {}; // For backward compatibility for former `data.formatType` property var formatType = dataFormat.type || data['formatType']; var property = dataFormat.property, feature = dataFormat.feature, mesh = dataFormat.mesh; var format = tslib_1.__assign({ type: formatType ? formatType : defaultExtension }, (property ? { property: property } : {}), (feature ? { feature: feature } : {}), (mesh ? { mesh: mesh } : {})); _this._data = { url: data.url, format: format }; } else if (data_1.isNamedData(data)) { _this._name = data.name; _this._data = {}; } return _this; } Object.defineProperty(SourceNode.prototype, "data", { get: function () { return this._data; }, enumerable: true, configurable: true }); SourceNode.prototype.hasName = function () { return !!this._name; }; Object.defineProperty(SourceNode.prototype, "dataName", { get: function () { return this._name; }, set: function (name) { this._name = name; }, enumerable: true, configurable: true }); Object.defineProperty(SourceNode.prototype, "parent", { set: function (parent) { throw new Error('Source nodes have to be roots.'); }, enumerable: true, configurable: true }); SourceNode.prototype.remove = function () { throw new Error('Source nodes are roots and cannot be removed.'); }; /** * Return a unique identifir for this data source. */ SourceNode.prototype.hash = function () { if (data_1.isInlineData(this._data)) { return util_1.hash(this._data); } else if (data_1.isUrlData(this._data)) { return this._data.url + " " + util_1.hash(this._data.format); } else { return this._name; } }; SourceNode.prototype.assemble = function () { return tslib_1.__assign({ name: this._name }, this._data, { transform: [] }); }; return SourceNode; }(dataflow_1.DataFlowNode)); exports.SourceNode = SourceNode; },{"../../data":86,"../../util":107,"./dataflow":24,"tslib":5}],33:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var vega_util_1 = require("vega-util"); var channel_1 = require("../../channel"); var fielddef_1 = require("../../fielddef"); var scale_1 = require("../../scale"); var util_1 = require("../../util"); var common_1 = require("../common"); var dataflow_1 = require("./dataflow"); function getStackByFields(model) { return model.stack.stackBy.reduce(function (fields, by) { var channel = by.channel; var fieldDef = by.fieldDef; var scale = channel_1.isScaleChannel(channel) ? model.getScaleComponent(channel) : undefined; var _field = fielddef_1.field(fieldDef, { binSuffix: scale && scale_1.hasDiscreteDomain(scale.get('type')) ? 'range' : 'start' }); if (_field) { fields.push(_field); } return fields; }, []); } var StackNode = (function (_super) { tslib_1.__extends(StackNode, _super); function StackNode(stack) { var _this = _super.call(this) || this; _this._stack = stack; return _this; } StackNode.prototype.clone = function () { return new StackNode(util_1.duplicate(this._stack)); }; StackNode.make = function (model) { var stackProperties = model.stack; if (!stackProperties) { return null; } var groupby = []; if (stackProperties.groupbyChannel) { var groupbyFieldDef = model.fieldDef(stackProperties.groupbyChannel); if (groupbyFieldDef.bin) { // For Bin, we need to add both start and end to ensure that both get imputed // and included in the stack output (https://github.com/vega/vega-lite/issues/1805). groupby.push(model.field(stackProperties.groupbyChannel, { binSuffix: 'start' })); groupby.push(model.field(stackProperties.groupbyChannel, { binSuffix: 'end' })); } else { groupby.push(model.field(stackProperties.groupbyChannel)); } } var stackby = getStackByFields(model); var orderDef = model.encoding.order; var sort; if (orderDef) { sort = common_1.sortParams(orderDef); } else { // default = descending by stackFields // FIXME is the default here correct for binned fields? sort = stackby.reduce(function (s, field) { s.field.push(field); s.order.push('descending'); return s; }, { field: [], order: [] }); } return new StackNode({ groupby: groupby, field: model.field(stackProperties.fieldChannel), stackby: stackby, sort: sort, offset: stackProperties.offset, impute: util_1.contains(['area', 'line'], model.mark()), }); }; Object.defineProperty(StackNode.prototype, "stack", { get: function () { return this._stack; }, enumerable: true, configurable: true }); StackNode.prototype.addDimensions = function (fields) { this._stack.groupby = this._stack.groupby.concat(fields); }; StackNode.prototype.dependentFields = function () { var out = {}; out[this._stack.field] = true; this._stack.groupby.forEach(function (f) { return out[f] = true; }); var field = this._stack.sort.field; vega_util_1.isArray(field) ? field.forEach(function (f) { return out[f] = true; }) : out[field] = true; return out; }; StackNode.prototype.producedFields = function () { var out = {}; out[this._stack.field + '_start'] = true; out[this._stack.field + '_end'] = true; return out; }; StackNode.prototype.assemble = function () { var transform = []; var stack = this._stack; // Impute if (stack.impute) { var order = stack.groupby.length === 1 ? stack.groupby[0] : 'key_' + stack.groupby.join('_'); // Impute only takes a single key so we might have to create one if (stack.groupby.length > 1) { transform.push({ type: 'formula', expr: stack.groupby.map(function (f) { return "datum[" + util_1.stringValue(f) + "]"; }).join(" + '_' + "), as: order }); } transform.push({ type: 'impute', field: stack.field, groupby: stack.stackby, key: order, method: 'value', value: 0 }); } // Stack transform.push({ type: 'stack', groupby: stack.groupby, field: stack.field, sort: stack.sort, as: [ stack.field + '_start', stack.field + '_end' ], offset: stack.offset }); return transform; }; return StackNode; }(dataflow_1.DataFlowNode)); exports.StackNode = StackNode; },{"../../channel":12,"../../fielddef":90,"../../scale":98,"../../util":107,"../common":18,"./dataflow":24,"tslib":5,"vega-util":7}],34:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var fielddef_1 = require("../../fielddef"); var timeunit_1 = require("../../timeunit"); var type_1 = require("../../type"); var util_1 = require("../../util"); var dataflow_1 = require("./dataflow"); var TimeUnitNode = (function (_super) { tslib_1.__extends(TimeUnitNode, _super); function TimeUnitNode(formula) { var _this = _super.call(this) || this; _this.formula = formula; return _this; } TimeUnitNode.prototype.clone = function () { return new TimeUnitNode(util_1.duplicate(this.formula)); }; TimeUnitNode.makeFromEncoding = function (model) { var formula = model.reduceFieldDef(function (timeUnitComponent, fieldDef) { if (fieldDef.type === type_1.TEMPORAL && fieldDef.timeUnit) { var f = fielddef_1.field(fieldDef); timeUnitComponent[f] = { as: f, timeUnit: fieldDef.timeUnit, field: fieldDef.field }; } return timeUnitComponent; }, {}); if (util_1.keys(formula).length === 0) { return null; } return new TimeUnitNode(formula); }; TimeUnitNode.makeFromTransform = function (model, t) { return new TimeUnitNode((_a = {}, _a[t.field] = { as: t.as, timeUnit: t.timeUnit, field: t.field }, _a)); var _a; }; TimeUnitNode.prototype.merge = function (other) { this.formula = util_1.extend(this.formula, other.formula); other.remove(); }; TimeUnitNode.prototype.producedFields = function () { var out = {}; util_1.vals(this.formula).forEach(function (f) { out[f.as] = true; }); return out; }; TimeUnitNode.prototype.dependentFields = function () { var out = {}; util_1.vals(this.formula).forEach(function (f) { out[f.field] = true; }); return out; }; TimeUnitNode.prototype.assemble = function () { return util_1.vals(this.formula).map(function (c) { return { type: 'formula', as: c.as, expr: timeunit_1.fieldExpr(c.timeUnit, c.field) }; }); }; return TimeUnitNode; }(dataflow_1.DataFlowNode)); exports.TimeUnitNode = TimeUnitNode; },{"../../fielddef":90,"../../timeunit":103,"../../type":106,"../../util":107,"./dataflow":24,"tslib":5}],35:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var vega_util_1 = require("vega-util"); var datetime_1 = require("../../datetime"); var filter_1 = require("../../filter"); var log = require("../../log"); var transform_1 = require("../../transform"); var util_1 = require("../../util"); var aggregate_1 = require("./aggregate"); var bin_1 = require("./bin"); var dataflow_1 = require("./dataflow"); var formatparse_1 = require("./formatparse"); var source_1 = require("./source"); var timeunit_1 = require("./timeunit"); var FilterNode = (function (_super) { tslib_1.__extends(FilterNode, _super); function FilterNode(model, filter) { var _this = _super.call(this) || this; _this.model = model; _this.filter = filter; _this.expr = filter_1.expression(_this.model, _this.filter, _this); return _this; } FilterNode.prototype.clone = function () { return new FilterNode(this.model, util_1.duplicate(this.filter)); }; FilterNode.prototype.assemble = function () { return { type: 'filter', expr: this.expr }; }; return FilterNode; }(dataflow_1.DataFlowNode)); exports.FilterNode = FilterNode; /** * We don't know what a calculate node depends on so we should never move it beyond anything that produces fields. */ var CalculateNode = (function (_super) { tslib_1.__extends(CalculateNode, _super); function CalculateNode(transform) { var _this = _super.call(this) || this; _this.transform = transform; return _this; } CalculateNode.prototype.clone = function () { return new CalculateNode(util_1.duplicate(this.transform)); }; CalculateNode.prototype.producedFields = function () { var out = {}; out[this.transform.as] = true; return out; }; CalculateNode.prototype.assemble = function () { return { type: 'formula', expr: this.transform.calculate, as: this.transform.as }; }; return CalculateNode; }(dataflow_1.DataFlowNode)); exports.CalculateNode = CalculateNode; var LookupNode = (function (_super) { tslib_1.__extends(LookupNode, _super); function LookupNode(transform, secondary) { var _this = _super.call(this) || this; _this.transform = transform; _this.secondary = secondary; return _this; } LookupNode.make = function (model, transform, counter) { var sources = model.component.data.sources; var s = new source_1.SourceNode(transform.from.data); var fromSource = sources[s.hash()]; if (!fromSource) { sources[s.hash()] = s; fromSource = s; } var fromOutputName = model.getName("lookup_" + counter); var fromOutputNode = new dataflow_1.OutputNode(fromOutputName, 'lookup', model.component.data.outputNodeRefCounts); fromOutputNode.parent = fromSource; model.component.data.outputNodes[fromOutputName] = fromOutputNode; return new LookupNode(transform, fromOutputNode.getSource()); }; LookupNode.prototype.producedFields = function () { return util_1.toSet(this.transform.from.fields || ((this.transform.as instanceof Array) ? this.transform.as : [this.transform.as])); }; LookupNode.prototype.assemble = function () { var foreign; if (this.transform.from.fields) { // lookup a few fields and add create a flat output foreign = tslib_1.__assign({ values: this.transform.from.fields }, this.transform.as ? { as: ((this.transform.as instanceof Array) ? this.transform.as : [this.transform.as]) } : {}); } else { // lookup full record and nest it var asName = this.transform.as; if (!vega_util_1.isString(asName)) { log.warn(log.message.NO_FIELDS_NEEDS_AS); asName = '_lookup'; } foreign = { as: [asName] }; } return tslib_1.__assign({ type: 'lookup', from: this.secondary, key: this.transform.from.key, fields: [this.transform.lookup] }, foreign, (this.transform.default ? { default: this.transform.default } : {})); }; return LookupNode; }(dataflow_1.DataFlowNode)); exports.LookupNode = LookupNode; /** * Parses a transforms array into a chain of connected dataflow nodes. */ function parseTransformArray(model) { var first = null; var node; var previous; var lookupCounter = 0; function insert(newNode) { if (!first) { // A parent may be inserted during node construction // (e.g., selection FilterNodes may add a TimeUnitNode). first = newNode.parent || newNode; } else if (newNode.parent) { previous.insertAsParentOf(newNode); } else { newNode.parent = previous; } previous = newNode; } model.transforms.forEach(function (t) { if (transform_1.isCalculate(t)) { node = new CalculateNode(t); } else if (transform_1.isFilter(t)) { // Automatically add a parse node for filters with filter objects var parse = {}; var filter = t.filter; var val = null; // For EqualFilter, just use the equal property. // For RangeFilter and OneOfFilter, all array members should have // the same type, so we only use the first one. if (filter_1.isEqualFilter(filter)) { val = filter.equal; } else if (filter_1.isRangeFilter(filter)) { val = filter.range[0]; } else if (filter_1.isOneOfFilter(filter)) { val = (filter.oneOf || filter['in'])[0]; } // else -- for filter expression, we can't infer anything if (val) { if (datetime_1.isDateTime(val)) { parse[filter['field']] = 'date'; } else if (vega_util_1.isNumber(val)) { parse[filter['field']] = 'number'; } else if (vega_util_1.isString(val)) { parse[filter['field']] = 'string'; } } if (util_1.keys(parse).length > 0) { var parseNode = new formatparse_1.ParseNode(parse); insert(parseNode); } node = new FilterNode(model, t.filter); } else if (transform_1.isBin(t)) { node = bin_1.BinNode.makeFromTransform(model, t); } else if (transform_1.isTimeUnit(t)) { node = timeunit_1.TimeUnitNode.makeFromTransform(model, t); } else if (transform_1.isSummarize(t)) { node = aggregate_1.AggregateNode.makeFromTransform(model, t); } else if (transform_1.isLookup(t)) { node = LookupNode.make(model, t, lookupCounter++); } else { log.warn(log.message.invalidTransformIgnored(t)); return; } insert(node); }); var last = node; return { first: first, last: last }; } exports.parseTransformArray = parseTransformArray; },{"../../datetime":87,"../../filter":91,"../../log":95,"../../transform":105,"../../util":107,"./aggregate":21,"./bin":23,"./dataflow":24,"./formatparse":26,"./source":32,"./timeunit":34,"tslib":5,"vega-util":7}],36:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var channel_1 = require("../channel"); var encoding_1 = require("../encoding"); var fielddef_1 = require("../fielddef"); var log = require("../log"); var mark_1 = require("../mark"); var util_1 = require("../util"); var common_1 = require("./common"); var assemble_1 = require("./data/assemble"); var parse_1 = require("./data/parse"); var header_1 = require("./layout/header"); var parse_2 = require("./layout/parse"); var parse_3 = require("./legend/parse"); var model_1 = require("./model"); var repeat_1 = require("./repeat"); var resolve_1 = require("./resolve"); var FacetModel = (function (_super) { tslib_1.__extends(FacetModel, _super); function FacetModel(spec, parent, parentGivenName, repeater, config) { var _this = _super.call(this, spec, parent, parentGivenName, config, spec.resolve) || this; _this.child = common_1.buildModel(spec.spec, _this, _this.getName('child'), undefined, repeater, config); _this.children = [_this.child]; var facet = repeat_1.replaceRepeaterInFacet(spec.facet, repeater); _this.facet = _this.initFacet(facet); return _this; } FacetModel.prototype.initFacet = function (facet) { // clone to prevent side effect to the original spec return encoding_1.reduce(facet, function (normalizedFacet, fieldDef, channel) { if (!util_1.contains([channel_1.ROW, channel_1.COLUMN], channel)) { // Drop unsupported channel log.warn(log.message.incompatibleChannel(channel, 'facet')); return normalizedFacet; } if (fieldDef.field === undefined) { log.warn(log.message.emptyFieldDef(fieldDef, channel)); return normalizedFacet; } // Convert type to full, lowercase type, or augment the fieldDef with a default type if missing. normalizedFacet[channel] = fielddef_1.normalize(fieldDef, channel); return normalizedFacet; }, {}); }; FacetModel.prototype.channelHasField = function (channel) { return !!this.facet[channel]; }; FacetModel.prototype.hasDiscreteDomain = function (channel) { return true; }; FacetModel.prototype.fieldDef = function (channel) { return this.facet[channel]; }; FacetModel.prototype.parseData = function () { this.component.data = parse_1.parseData(this); this.child.parseData(); }; FacetModel.prototype.parseLayoutSize = function () { parse_2.parseChildrenLayoutSize(this); }; FacetModel.prototype.parseSelection = function () { // As a facet has a single child, the selection components are the same. // The child maintains its selections to assemble signals, which remain // within its unit. this.child.parseSelection(); this.component.selection = this.child.component.selection; }; FacetModel.prototype.parseMarkGroup = function () { this.child.parseMarkGroup(); // if we facet by two dimensions, we need to add a cross operator to the aggregation // so that we create all groups var hasRow = this.channelHasField(channel_1.ROW); var hasColumn = this.channelHasField(channel_1.COLUMN); this.component.mark = [{ name: this.getName('cell'), type: 'group', from: { facet: tslib_1.__assign({ name: this.component.data.facetRoot.name, data: this.component.data.facetRoot.data, groupby: [].concat(hasRow ? [this.field(channel_1.ROW)] : [], hasColumn ? [this.field(channel_1.COLUMN)] : []) }, (hasRow && hasColumn ? { aggregate: { cross: true } } : {})) }, sort: { field: [].concat(hasRow ? [this.field(channel_1.ROW, { expr: 'datum' })] : [], hasColumn ? [this.field(channel_1.COLUMN, { expr: 'datum' })] : []), order: [].concat(hasRow ? [(this.facet.row.header && this.facet.row.header.sort) || 'ascending'] : [], hasColumn ? [(this.facet.column.header && this.facet.column.header.sort) || 'ascending'] : []) }, encode: { update: getFacetGroupProperties(this) } }]; }; FacetModel.prototype.parseAxisAndHeader = function () { this.child.parseAxisAndHeader(); this.parseHeader('column'); this.parseHeader('row'); this.mergeChildAxis('x'); this.mergeChildAxis('y'); }; FacetModel.prototype.parseHeader = function (channel) { if (this.channelHasField(channel)) { var fieldDef = this.facet[channel]; var header = fieldDef.header || {}; var title = header.title !== undefined ? header.title : fielddef_1.title(fieldDef, this.config); if (this.child.component.layoutHeaders[channel].title) { // merge title with child to produce "Title / Subtitle / Sub-subtitle" title += ' / ' + this.child.component.layoutHeaders[channel].title; this.child.component.layoutHeaders[channel].title = null; } this.component.layoutHeaders[channel] = { title: title, facetFieldDef: fieldDef, // TODO: support adding label to footer as well header: [this.makeHeaderComponent(channel, true)] }; } }; FacetModel.prototype.makeHeaderComponent = function (channel, labels) { var sizeChannel = channel === 'row' ? 'height' : 'width'; return { labels: labels, sizeSignal: this.child.getSizeSignalRef(sizeChannel), axes: [] }; }; FacetModel.prototype.mergeChildAxis = function (channel) { var child = this.child; if (child.component.axes[channel]) { var _a = this.component, layoutHeaders = _a.layoutHeaders, resolve = _a.resolve; var channelResolve = resolve[channel]; channelResolve.axis = resolve_1.parseGuideResolve(resolve, channel); if (channelResolve.axis === 'shared') { // For shared axis, move the axes to facet's header or footer var headerChannel = channel === 'x' ? 'column' : 'row'; var layoutHeader = layoutHeaders[headerChannel]; for (var _i = 0, _b = child.component.axes[channel]; _i < _b.length; _i++) { var axisComponent = _b[_i]; var mainAxis = axisComponent.main; var headerType = header_1.getHeaderType(mainAxis.get('orient')); layoutHeader[headerType] = layoutHeader[headerType] || [this.makeHeaderComponent(headerChannel, false)]; // LayoutHeader no longer keep track of property precedence, thus let's combine. layoutHeader[headerType][0].axes.push(mainAxis.combine()); delete axisComponent.main; } } else { // Otherwise do nothing for independent axes } } }; FacetModel.prototype.parseLegend = function () { parse_3.parseNonUnitLegend(this); }; FacetModel.prototype.assembleData = function () { if (!this.parent) { // only assemble data in the root return assemble_1.assembleData(this.component.data); } return []; }; FacetModel.prototype.assembleParentGroupProperties = function () { return null; }; FacetModel.prototype.assembleSelectionTopLevelSignals = function (signals) { return this.child.assembleSelectionTopLevelSignals(signals); }; FacetModel.prototype.assembleSelectionSignals = function () { this.child.assembleSelectionSignals(); return []; }; FacetModel.prototype.assembleSelectionData = function (data) { return this.child.assembleSelectionData(data); }; FacetModel.prototype.assembleLayout = function () { var columns = this.channelHasField('column') ? { signal: this.columnDistinctSignal() } : 1; // TODO: determine default align based on shared / independent scales return { padding: { row: 10, column: 10 }, // TODO: support offset for rowHeader/rowFooter/rowTitle/columnHeader/columnFooter/columnTitle offset: 10, columns: columns, bounds: 'full' }; }; FacetModel.prototype.assembleLayoutSignals = function () { // FIXME(https://github.com/vega/vega-lite/issues/1193): this can be incorrect if we have independent scales. return this.child.assembleLayoutSignals(); }; FacetModel.prototype.columnDistinctSignal = function () { // In facetNode.assemble(), the name is always this.getName('column') + '_layout'. var facetLayoutDataName = this.getName('column') + '_layout'; var columnDistinct = this.field('column', { prefix: 'distinct' }); return "data('" + facetLayoutDataName + "')[0][" + util_1.stringValue(columnDistinct) + "]"; }; FacetModel.prototype.assembleMarks = function () { var facetRoot = this.component.data.facetRoot; var data = assemble_1.assembleFacetData(facetRoot); var mark = this.component.mark[0]; // correct the name of the faceted data source mark.from.facet = tslib_1.__assign({}, mark.from.facet, { name: facetRoot.name, data: facetRoot.data }); var marks = [tslib_1.__assign({}, (data.length > 0 ? { data: data } : {}), mark, this.child.assembleGroup())]; return marks; }; FacetModel.prototype.getMapping = function () { return this.facet; }; return FacetModel; }(model_1.ModelWithField)); exports.FacetModel = FacetModel; function getFacetGroupProperties(model) { var encodeEntry = model.child.assembleParentGroupProperties(); return tslib_1.__assign({}, (encodeEntry ? encodeEntry : {}), common_1.applyConfig({}, model.config.facet.cell, mark_1.FILL_STROKE_CONFIG.concat(['clip']))); } },{"../channel":12,"../encoding":88,"../fielddef":90,"../log":95,"../mark":97,"../util":107,"./common":18,"./data/assemble":22,"./data/parse":30,"./layout/header":39,"./layout/parse":40,"./legend/parse":44,"./model":58,"./repeat":59,"./resolve":60,"tslib":5}],37:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var log = require("../log"); var mark_1 = require("../mark"); var spec_1 = require("../spec"); var util_1 = require("../util"); var parse_1 = require("./axis/parse"); var common_1 = require("./common"); var assemble_1 = require("./data/assemble"); var parse_2 = require("./data/parse"); var assemble_2 = require("./layout/assemble"); var parse_3 = require("./layout/parse"); var parse_4 = require("./legend/parse"); var model_1 = require("./model"); var selection_1 = require("./selection/selection"); var unit_1 = require("./unit"); var LayerModel = (function (_super) { tslib_1.__extends(LayerModel, _super); function LayerModel(spec, parent, parentGivenName, parentGivenSize, repeater, config) { var _this = _super.call(this, spec, parent, parentGivenName, config, spec.resolve) || this; var layoutSize = tslib_1.__assign({}, parentGivenSize, (spec.width ? { width: spec.width } : {}), (spec.height ? { height: spec.height } : {})); _this.initSize(layoutSize); _this.children = spec.layer.map(function (layer, i) { if (spec_1.isLayerSpec(layer)) { return new LayerModel(layer, _this, _this.getName('layer_' + i), layoutSize, repeater, config); } if (spec_1.isUnitSpec(layer)) { return new unit_1.UnitModel(layer, _this, _this.getName('layer_' + i), layoutSize, repeater, config); } throw new Error(log.message.INVALID_SPEC); }); return _this; } LayerModel.prototype.parseData = function () { this.component.data = parse_2.parseData(this); for (var _i = 0, _a = this.children; _i < _a.length; _i++) { var child = _a[_i]; child.parseData(); } }; LayerModel.prototype.parseLayoutSize = function () { parse_3.parseLayerLayoutSize(this); }; LayerModel.prototype.parseSelection = function () { var _this = this; // Merge selections up the hierarchy so that they may be referenced // across unit specs. Persist their definitions within each child // to assemble signals which remain within output Vega unit groups. this.component.selection = {}; var _loop_1 = function (child) { child.parseSelection(); util_1.keys(child.component.selection).forEach(function (key) { _this.component.selection[key] = child.component.selection[key]; }); }; for (var _i = 0, _a = this.children; _i < _a.length; _i++) { var child = _a[_i]; _loop_1(child); } }; LayerModel.prototype.parseMarkGroup = function () { for (var _i = 0, _a = this.children; _i < _a.length; _i++) { var child = _a[_i]; child.parseMarkGroup(); } }; LayerModel.prototype.parseAxisAndHeader = function () { parse_1.parseLayerAxis(this); }; LayerModel.prototype.parseLegend = function () { parse_4.parseNonUnitLegend(this); }; LayerModel.prototype.assembleParentGroupProperties = function () { return tslib_1.__assign({ width: this.getSizeSignalRef('width'), height: this.getSizeSignalRef('height') }, common_1.applyConfig({}, this.config.cell, mark_1.FILL_STROKE_CONFIG.concat(['clip']))); }; LayerModel.prototype.assembleSelectionTopLevelSignals = function (signals) { return this.children.reduce(function (sg, child) { return child.assembleSelectionTopLevelSignals(sg); }, signals); }; // TODO: Support same named selections across children. LayerModel.prototype.assembleSelectionSignals = function () { return this.children.reduce(function (signals, child) { return signals.concat(child.assembleSelectionSignals()); }, []); }; LayerModel.prototype.assembleLayoutSignals = function () { return this.children.reduce(function (signals, child) { return signals.concat(child.assembleLayoutSignals()); }, assemble_2.assembleLayoutSignals(this)); }; LayerModel.prototype.assembleSelectionData = function (data) { return this.children.reduce(function (db, child) { return child.assembleSelectionData(db); }, []); }; LayerModel.prototype.assembleData = function () { if (!this.parent) { // only assemble data in the root return assemble_1.assembleData(this.component.data); } return []; }; LayerModel.prototype.assembleScales = function () { // combine with scales from children return this.children.reduce(function (scales, c) { return scales.concat(c.assembleScales()); }, _super.prototype.assembleScales.call(this)); }; LayerModel.prototype.assembleLayout = function () { return null; }; LayerModel.prototype.assembleMarks = function () { return selection_1.assembleLayerSelectionMarks(this, util_1.flatten(this.children.map(function (child) { return child.assembleMarks(); }))); }; return LayerModel; }(model_1.Model)); exports.LayerModel = LayerModel; },{"../log":95,"../mark":97,"../spec":101,"../util":107,"./axis/parse":16,"./common":18,"./data/assemble":22,"./data/parse":30,"./layout/assemble":38,"./layout/parse":40,"./legend/parse":44,"./model":58,"./selection/selection":70,"./unit":81,"tslib":5}],38:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var scale_1 = require("../../scale"); var vega_schema_1 = require("../../vega.schema"); function assembleLayoutSignals(model) { var signals = []; var width = sizeExpr(model, 'width'); if (width !== undefined) { signals.push({ name: model.getName('width'), update: width }); } var height = sizeExpr(model, 'height'); if (height !== undefined) { signals.push({ name: model.getName('height'), update: height }); } return signals; } exports.assembleLayoutSignals = assembleLayoutSignals; function sizeExpr(model, sizeType) { var channel = sizeType === 'width' ? 'x' : 'y'; var size = model.component.layoutSize.get(sizeType); if (size === 'merged') { return undefined; } else if (size === 'range-step') { var scaleComponent = model.getScaleComponent(channel); if (scaleComponent) { var type = scaleComponent.get('type'); var range = scaleComponent.get('range'); if (scale_1.hasDiscreteDomain(type) && vega_schema_1.isVgRangeStep(range)) { var scaleName = model.scaleName(channel); var cardinality = "domain('" + scaleName + "').length"; var padding = scaleComponent.get('padding'); var paddingOuter = scaleComponent.get('paddingOuter'); paddingOuter = paddingOuter !== undefined ? paddingOuter : padding; var paddingInner = scaleComponent.get('paddingInner'); paddingInner = type === 'band' ? // only band has real paddingInner (paddingInner !== undefined ? paddingInner : padding) : // For point, as calculated in https://github.com/vega/vega-scale/blob/master/src/band.js#L128, // it's equivalent to have paddingInner = 1 since there is only n-1 steps between n points. 1; return "bandspace(" + cardinality + ", " + paddingInner + ", " + paddingOuter + ") * " + range.step; } } /* istanbul ignore next: Condition should not happen -- only for warning in development. */ throw new Error('layout size is range step although there is no rangeStep.'); } return size ? "" + size : undefined; } exports.sizeExpr = sizeExpr; },{"../../scale":98,"../../vega.schema":109}],39:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var fielddef_1 = require("../../fielddef"); var common_1 = require("../common"); exports.HEADER_CHANNELS = ['row', 'column']; exports.HEADER_TYPES = ['header', 'footer']; function getHeaderType(orient) { if (orient === 'top' || orient === 'left') { return 'header'; } return 'footer'; } exports.getHeaderType = getHeaderType; function getTitleGroup(model, channel) { var sizeChannel = channel === 'row' ? 'height' : 'width'; var title = model.component.layoutHeaders[channel].title; var positionChannel = channel === 'row' ? 'y' : 'x'; var align = channel === 'row' ? 'right' : 'center'; var textOrient = channel === 'row' ? 'vertical' : undefined; return { name: model.getName(channel + "_title"), role: channel + "-title", type: 'group', marks: [{ type: 'text', role: channel + "-title-text", encode: { update: tslib_1.__assign((_a = {}, _a[positionChannel] = { signal: "0.5 * " + sizeChannel }, _a.align = { value: align }, _a.text = { value: title }, _a.fill = { value: 'black' }, _a.fontWeight = { value: 'bold' }, _a), (textOrient === 'vertical' ? { angle: { value: 270 } } : {})) } }] }; var _a; } exports.getTitleGroup = getTitleGroup; function getHeaderGroup(model, channel, headerType, layoutHeader, header) { if (header) { var title = null; if (layoutHeader.facetFieldDef && header.labels) { var facetFieldDef = layoutHeader.facetFieldDef; var format = facetFieldDef.header ? facetFieldDef.header.format : undefined; title = { text: common_1.formatSignalRef(facetFieldDef, format, 'parent', model.config, true), offset: 10, orient: channel === 'row' ? 'left' : 'top', encode: { update: tslib_1.__assign({ fontWeight: { value: 'normal' }, angle: { value: 0 }, fontSize: { value: 10 } }, (channel === 'row' ? { align: { value: 'right' }, baseline: { value: 'middle' } } : {})) } }; } var axes = header.axes; var hasAxes = axes && axes.length > 0; if (title || hasAxes) { var sizeChannel = channel === 'row' ? 'height' : 'width'; return tslib_1.__assign({ name: model.getName(channel + "_" + headerType), type: 'group', role: channel + "-" + headerType }, (layoutHeader.facetFieldDef ? { from: { data: model.getName(channel) }, sort: { field: fielddef_1.field(layoutHeader.facetFieldDef, { expr: 'datum' }), order: (layoutHeader.facetFieldDef.header && layoutHeader.facetFieldDef.header.sort) || 'ascending' } } : {}), (title ? { title: title } : {}), { encode: { update: (_a = {}, _a[sizeChannel] = header.sizeSignal, _a) } }, (hasAxes ? { axes: axes } : {})); } } return null; var _a; } exports.getHeaderGroup = getHeaderGroup; },{"../../fielddef":90,"../common":18,"tslib":5}],40:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var scale_1 = require("../../scale"); var vega_schema_1 = require("../../vega.schema"); var split_1 = require("../split"); function parseLayerLayoutSize(model) { parseChildrenLayoutSize(model); var layoutSizeCmpt = model.component.layoutSize; layoutSizeCmpt.setWithExplicit('width', parseNonUnitLayoutSizeForChannel(model, 'width')); layoutSizeCmpt.setWithExplicit('height', parseNonUnitLayoutSizeForChannel(model, 'height')); } exports.parseLayerLayoutSize = parseLayerLayoutSize; exports.parseRepeatLayoutSize = parseLayerLayoutSize; function parseConcatLayoutSize(model) { parseChildrenLayoutSize(model); var layoutSizeCmpt = model.component.layoutSize; var sizeTypeToMerge = model.isVConcat ? 'width' : 'height'; layoutSizeCmpt.setWithExplicit(sizeTypeToMerge, parseNonUnitLayoutSizeForChannel(model, sizeTypeToMerge)); } exports.parseConcatLayoutSize = parseConcatLayoutSize; function parseChildrenLayoutSize(model) { for (var _i = 0, _a = model.children; _i < _a.length; _i++) { var child = _a[_i]; child.parseLayoutSize(); } } exports.parseChildrenLayoutSize = parseChildrenLayoutSize; function parseNonUnitLayoutSizeForChannel(model, sizeType) { var channel = sizeType === 'width' ? 'x' : 'y'; var resolve = model.component.resolve; var mergedSize; // Try to merge layout size for (var _i = 0, _a = model.children; _i < _a.length; _i++) { var child = _a[_i]; var childSize = child.component.layoutSize.getWithExplicit(sizeType); var scaleResolve = resolve[channel] ? resolve[channel].scale : undefined; if (scaleResolve === 'independent' && childSize.value === 'range-step') { // Do not merge independent scales with range-step as their size depends // on the scale domains, which can be different between scales. mergedSize = undefined; break; } if (mergedSize) { if (scaleResolve === 'independent' && mergedSize.value !== childSize.value) { // For independent scale, only merge if all the sizes are the same. // If the values are different, abandon the merge! mergedSize = undefined; break; } mergedSize = split_1.mergeValuesWithExplicit(mergedSize, childSize, sizeType, '', split_1.defaultTieBreaker); } else { mergedSize = childSize; } } if (mergedSize) { // If merged, rename size and set size of all children. for (var _b = 0, _c = model.children; _b < _c.length; _b++) { var child = _c[_b]; model.renameLayoutSize(child.getSizeSignalRef(sizeType).signal, model.getSizeSignalRef(sizeType).signal); child.component.layoutSize.set(sizeType, 'merged', false); } return mergedSize; } else { // Otherwise, there is no merged size. return { explicit: false, value: undefined }; } } function parseUnitLayoutSize(model) { var layoutSizeComponent = model.component.layoutSize; if (!layoutSizeComponent.explicit.width) { var width = defaultUnitSize(model, 'width'); layoutSizeComponent.set('width', width, false); } if (!layoutSizeComponent.explicit.height) { var height = defaultUnitSize(model, 'height'); layoutSizeComponent.set('height', height, false); } } exports.parseUnitLayoutSize = parseUnitLayoutSize; function defaultUnitSize(model, sizeType) { var channel = sizeType === 'width' ? 'x' : 'y'; var config = model.config; var scaleComponent = model.getScaleComponent(channel); if (scaleComponent) { var scaleType = scaleComponent.get('type'); var range = scaleComponent.get('range'); if (scale_1.hasDiscreteDomain(scaleType) && vega_schema_1.isVgRangeStep(range)) { // For discrete domain with range.step, use dynamic width/height return 'range-step'; } else { // FIXME(https://github.com/vega/vega-lite/issues/1975): revise config.cell name // Otherwise, read this from cell config return config.cell[sizeType]; } } else { // No scale - set default size if (sizeType === 'width' && model.mark() === 'text') { // width for text mark without x-field is a bit wider than typical range step return config.scale.textXRangeStep; } // Set width/height equal to rangeStep config or if rangeStep is null, use value from default scale config. return config.scale.rangeStep || scale_1.defaultScaleConfig.rangeStep; } } },{"../../scale":98,"../../vega.schema":109,"../split":80}],41:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var stringify = require("json-stable-stringify"); var util_1 = require("../../util"); var parse_1 = require("./parse"); function assembleLegends(model) { var legendComponentIndex = model.component.legends; var legendByDomain = {}; util_1.keys(legendComponentIndex).forEach(function (channel) { var scaleComponent = model.getScaleComponent(channel); var domainHash = stringify(scaleComponent.get('domain')); if (legendByDomain[domainHash]) { for (var _i = 0, _a = legendByDomain[domainHash]; _i < _a.length; _i++) { var mergedLegendComponent = _a[_i]; var merged = parse_1.mergeLegendComponent(mergedLegendComponent, legendComponentIndex[channel]); if (!merged) { // If cannot merge, need to add this legend separately legendByDomain[domainHash].push(legendComponentIndex[channel]); } } } else { legendByDomain[domainHash] = [legendComponentIndex[channel].clone()]; } }); return util_1.flatten(util_1.vals(legendByDomain)).map(function (legendCmpt) { return legendCmpt.combine(); }); } exports.assembleLegends = assembleLegends; },{"../../util":107,"./parse":44,"json-stable-stringify":1}],42:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var split_1 = require("../split"); var LegendComponent = (function (_super) { tslib_1.__extends(LegendComponent, _super); function LegendComponent() { return _super !== null && _super.apply(this, arguments) || this; } return LegendComponent; }(split_1.Split)); exports.LegendComponent = LegendComponent; },{"../split":80,"tslib":5}],43:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var channel_1 = require("../../channel"); var fielddef_1 = require("../../fielddef"); var mark_1 = require("../../mark"); var scale_1 = require("../../scale"); var type_1 = require("../../type"); var util_1 = require("../../util"); var common_1 = require("../common"); var mixins = require("../mark/mixins"); function symbols(fieldDef, symbolsSpec, model, channel) { var symbols = {}; var mark = model.mark(); switch (mark) { case mark_1.BAR: case mark_1.TICK: case mark_1.TEXT: symbols.shape = { value: 'square' }; break; case mark_1.CIRCLE: case mark_1.SQUARE: symbols.shape = { value: mark }; break; case mark_1.POINT: case mark_1.LINE: case mark_1.AREA: // use default circle break; } var cfg = model.config; var filled = model.markDef.filled; var config = channel === channel_1.COLOR ? /* For color's legend, do not set fill (when filled) or stroke (when unfilled) property from config because the legend's `fill` or `stroke` scale should have precedence */ util_1.without(mark_1.FILL_STROKE_CONFIG, [filled ? 'fill' : 'stroke', 'strokeDash', 'strokeDashOffset']) : /* For other legend, no need to omit. */ mark_1.FILL_STROKE_CONFIG; config = util_1.without(config, ['strokeDash', 'strokeDashOffset']); common_1.applyMarkConfig(symbols, model, config); if (channel !== channel_1.COLOR) { var colorMixins = mixins.color(model); // If there are field for fill or stroke, remove them as we already apply channels. if (colorMixins.fill && colorMixins.fill['field']) { delete colorMixins.fill; } if (colorMixins.stroke && colorMixins.stroke['field']) { delete colorMixins.stroke; } util_1.extend(symbols, colorMixins); } if (channel !== channel_1.SHAPE) { var shapeDef = model.encoding.shape; if (fielddef_1.isValueDef(shapeDef)) { symbols.shape = { value: shapeDef.value }; } } symbols = util_1.extend(symbols, symbolsSpec || {}); return util_1.keys(symbols).length > 0 ? symbols : undefined; } exports.symbols = symbols; function labels(fieldDef, labelsSpec, model, channel) { var legend = model.legend(channel); var config = model.config; var labels = {}; if (fieldDef.type === type_1.TEMPORAL) { var isUTCScale = model.getScaleComponent(channel).get('type') === scale_1.ScaleType.UTC; labelsSpec = util_1.extend({ text: { signal: common_1.timeFormatExpression('datum.value', fieldDef.timeUnit, legend.format, config.legend.shortTimeLabels, config.timeFormat, isUTCScale) } }, labelsSpec || {}); } labels = util_1.extend(labels, labelsSpec || {}); return util_1.keys(labels).length > 0 ? labels : undefined; } exports.labels = labels; },{"../../channel":12,"../../fielddef":90,"../../mark":97,"../../scale":98,"../../type":106,"../../util":107,"../common":18,"../mark/mixins":51}],44:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var channel_1 = require("../../channel"); var legend_1 = require("../../legend"); var util_1 = require("../../util"); var common_1 = require("../common"); var resolve_1 = require("../resolve"); var split_1 = require("../split"); var split_2 = require("../split"); var component_1 = require("./component"); var encode = require("./encode"); var rules = require("./rules"); function parseUnitLegend(model) { return [channel_1.COLOR, channel_1.SIZE, channel_1.SHAPE, channel_1.OPACITY].reduce(function (legendComponent, channel) { if (model.legend(channel)) { legendComponent[channel] = parseLegendForChannel(model, channel); } return legendComponent; }, {}); } exports.parseUnitLegend = parseUnitLegend; function getLegendDefWithScale(model, channel) { // For binned field with continuous scale, use a special scale so we can overrride the mark props and labels switch (channel) { case channel_1.COLOR: var scale = model.scaleName(channel_1.COLOR); return model.markDef.filled ? { fill: scale } : { stroke: scale }; case channel_1.SIZE: return { size: model.scaleName(channel_1.SIZE) }; case channel_1.SHAPE: return { shape: model.scaleName(channel_1.SHAPE) }; case channel_1.OPACITY: return { opacity: model.scaleName(channel_1.OPACITY) }; } return null; } function parseLegendForChannel(model, channel) { var fieldDef = model.fieldDef(channel); var legend = model.legend(channel); var legendCmpt = new component_1.LegendComponent({}, getLegendDefWithScale(model, channel)); legend_1.LEGEND_PROPERTIES.forEach(function (property) { var value = getSpecifiedOrDefaultValue(property, legend, channel, model); if (value !== undefined) { var explicit = property === 'values' ? !!legend.values : value === legend[property]; legendCmpt.set(property, value, explicit); } }); // 2) Add mark property definition groups var legendEncoding = legend.encoding || {}; var legendEncode = ['labels', 'legend', 'title', 'symbols'].reduce(function (e, part) { var value = encode[part] ? encode[part](fieldDef, legendEncoding[part], model, channel) : legendEncoding[part]; // no rule -- just default values if (value !== undefined && util_1.keys(value).length > 0) { e[part] = { update: value }; } return e; }, {}); if (util_1.keys(legendEncode).length > 0) { legendCmpt.set('encode', legendEncode, !!legend.encoding); } return legendCmpt; } exports.parseLegendForChannel = parseLegendForChannel; function getSpecifiedOrDefaultValue(property, specifiedLegend, channel, model) { var fieldDef = model.fieldDef(channel); switch (property) { case 'format': return common_1.numberFormat(fieldDef, specifiedLegend.format, model.config); case 'title': return rules.title(specifiedLegend, fieldDef, model.config); case 'values': return rules.values(specifiedLegend); case 'type': return rules.type(specifiedLegend, fieldDef.type, channel, model.getScaleComponent(channel).get('type')); } // Otherwise, return specified property. return specifiedLegend[property]; } function parseNonUnitLegend(model) { var _a = model.component, legends = _a.legends, resolve = _a.resolve; var _loop_1 = function (child) { child.parseLegend(); util_1.keys(child.component.legends).forEach(function (channel) { var channelResolve = model.component.resolve[channel]; channelResolve.legend = resolve_1.parseGuideResolve(model.component.resolve, channel); if (channelResolve.legend === 'shared') { // If the resolve says shared (and has not been overridden) // We will try to merge and see if there is a conflict legends[channel] = mergeLegendComponent(legends[channel], child.component.legends[channel]); if (!legends[channel]) { // If merge returns nothing, there is a conflict so we cannot make the legend shared. // Thus, mark legend as independent and remove the legend component. channelResolve.legend = 'independent'; delete legends[channel]; } } }); }; for (var _i = 0, _b = model.children; _i < _b.length; _i++) { var child = _b[_i]; _loop_1(child); } util_1.keys(legends).forEach(function (channel) { for (var _i = 0, _a = model.children; _i < _a.length; _i++) { var child = _a[_i]; if (!child.component.legends[channel]) { // skip if the child does not have a particular legend return; } if (resolve[channel].legend === 'shared') { // After merging shared legend, make sure to remove legend from child delete child.component.legends[channel]; } } }); } exports.parseNonUnitLegend = parseNonUnitLegend; function mergeLegendComponent(mergedLegend, childLegend) { if (!mergedLegend) { return childLegend.clone(); } var mergedOrient = mergedLegend.getWithExplicit('orient'); var childOrient = childLegend.getWithExplicit('orient'); if (mergedOrient.explicit && childOrient.explicit && mergedOrient.value !== childOrient.value) { // TODO: throw warning if resolve is explicit (We don't have info about explicit/implicit resolve yet.) // Cannot merge due to inconsistent orient return undefined; } var _loop_2 = function (prop) { var mergedValueWithExplicit = split_2.mergeValuesWithExplicit(mergedLegend.getWithExplicit(prop), childLegend.getWithExplicit(prop), prop, 'legend', // Tie breaker function function (v1, v2) { switch (prop) { case 'title': return common_1.titleMerger(v1, v2); case 'type': // There are only two types. If we have different types, then prefer symbol over gradient. return split_1.makeImplicit('symbol'); } return split_2.defaultTieBreaker(v1, v2, prop, 'legend'); }); mergedLegend.setWithExplicit(prop, mergedValueWithExplicit); }; // Otherwise, let's merge for (var _i = 0, VG_LEGEND_PROPERTIES_1 = legend_1.VG_LEGEND_PROPERTIES; _i < VG_LEGEND_PROPERTIES_1.length; _i++) { var prop = VG_LEGEND_PROPERTIES_1[_i]; _loop_2(prop); } return mergedLegend; } exports.mergeLegendComponent = mergeLegendComponent; },{"../../channel":12,"../../legend":94,"../../util":107,"../common":18,"../resolve":60,"../split":80,"./component":42,"./encode":43,"./rules":45}],45:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var channel_1 = require("../../channel"); var datetime_1 = require("../../datetime"); var fielddef_1 = require("../../fielddef"); var scale_1 = require("../../scale"); var util_1 = require("../../util"); function title(legend, fieldDef, config) { if (legend.title !== undefined) { return legend.title; } return fielddef_1.title(fieldDef, config); } exports.title = title; function values(legend) { var vals = legend.values; if (vals && datetime_1.isDateTime(vals[0])) { return vals.map(function (dt) { // normalize = true as end user won't put 0 = January return { signal: datetime_1.dateTimeExpr(dt, true) }; }); } return vals; } exports.values = values; function type(legend, type, channel, scaleType) { if (legend.type) { return legend.type; } if (channel === channel_1.COLOR && ((type === 'quantitative' && !scale_1.isBinScale(scaleType)) || (type === 'temporal' && util_1.contains(['time', 'utc'], scaleType)))) { return 'gradient'; } return undefined; } exports.type = type; },{"../../channel":12,"../../datetime":87,"../../fielddef":90,"../../scale":98,"../../util":107}],46:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var mixins = require("./mixins"); exports.area = { vgMark: 'area', defaultRole: undefined, encodeEntry: function (model) { return tslib_1.__assign({}, mixins.pointPosition('x', model, 'zeroOrMin'), mixins.pointPosition('y', model, 'zeroOrMin'), mixins.pointPosition2(model, 'zeroOrMin'), mixins.color(model), mixins.text(model, 'tooltip'), mixins.nonPosition('opacity', model), mixins.markDefProperties(model.markDef, ['orient', 'interpolate', 'tension'])); } }; },{"./mixins":51,"tslib":5}],47:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var channel_1 = require("../../channel"); var fielddef_1 = require("../../fielddef"); var log = require("../../log"); var scale_1 = require("../../scale"); var vega_schema_1 = require("../../vega.schema"); var mixins = require("./mixins"); var ref = require("./valueref"); exports.bar = { vgMark: 'rect', defaultRole: 'bar', encodeEntry: function (model) { var stack = model.stack; return tslib_1.__assign({}, x(model, stack), y(model, stack), mixins.color(model), mixins.text(model, 'tooltip'), mixins.nonPosition('opacity', model)); } }; function x(model, stack) { var config = model.config, width = model.width; var orient = model.markDef.orient; var sizeDef = model.encoding.size; var xDef = model.encoding.x; var xScaleName = model.scaleName(channel_1.X); var xScale = model.getScaleComponent(channel_1.X); // x, x2, and width -- we must specify two of these in all conditions if (orient === 'horizontal') { return tslib_1.__assign({}, mixins.pointPosition('x', model, 'zeroOrMin'), mixins.pointPosition2(model, 'zeroOrMin')); } else { if (fielddef_1.isFieldDef(xDef)) { if (xDef.bin && !sizeDef) { return mixins.binnedPosition(xDef, 'x', model.scaleName('x'), config.bar.binSpacing); } else { var xScaleType = xScale.get('type'); if (xScaleType === scale_1.ScaleType.BAND) { return mixins.bandPosition(xDef, 'x', model); } } } // sized bin, normal point-ordinal axis, quantitative x-axis, or no x return mixins.centeredBandPosition('x', model, tslib_1.__assign({}, ref.midX(width, config)), defaultSizeRef(xScaleName, xScale, config)); } } function y(model, stack) { var config = model.config, encoding = model.encoding, height = model.height; var orient = model.markDef.orient; var sizeDef = encoding.size; var yDef = encoding.y; var yScaleName = model.scaleName(channel_1.Y); var yScale = model.getScaleComponent(channel_1.Y); // y, y2 & height -- we must specify two of these in all conditions if (orient === 'vertical') { return tslib_1.__assign({}, mixins.pointPosition('y', model, 'zeroOrMin'), mixins.pointPosition2(model, 'zeroOrMin')); } else { if (fielddef_1.isFieldDef(yDef)) { var yScaleType = yScale.get('type'); if (yDef.bin && !sizeDef) { return mixins.binnedPosition(yDef, 'y', model.scaleName('y'), config.bar.binSpacing); } else if (yScaleType === scale_1.ScaleType.BAND) { return mixins.bandPosition(yDef, 'y', model); } } return mixins.centeredBandPosition('y', model, ref.midY(height, config), defaultSizeRef(yScaleName, yScale, config)); } } function defaultSizeRef(scaleName, scale, config) { if (config.bar.discreteBandSize) { return { value: config.bar.discreteBandSize }; } if (scale) { var scaleType = scale.get('type'); if (scaleType === scale_1.ScaleType.POINT) { var scaleRange = scale.get('range'); if (vega_schema_1.isVgRangeStep(scaleRange)) { return { value: scaleRange.step - 1 }; } log.warn(log.message.BAR_WITH_POINT_SCALE_AND_RANGESTEP_NULL); } else if (scaleType === scale_1.ScaleType.BAND) { return ref.band(scaleName); } else { return { value: config.bar.continuousBandSize }; } } if (config.scale.rangeStep && config.scale.rangeStep !== null) { return { value: config.scale.rangeStep - 1 }; } // TODO: this should depends on cell's width / height? return { value: 20 }; } },{"../../channel":12,"../../fielddef":90,"../../log":95,"../../scale":98,"../../vega.schema":109,"./mixins":51,"./valueref":57,"tslib":5}],48:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var encoding_1 = require("../../encoding"); var fielddef_1 = require("../../fielddef"); var log = require("../../log"); var mark_1 = require("../../mark"); var scale_1 = require("../../scale"); var type_1 = require("../../type"); var util_1 = require("../../util"); var common_1 = require("../common"); function normalizeMarkDef(markDef, encoding, scales, config) { var specifiedOrient = markDef.orient || common_1.getMarkConfig('orient', markDef, config); markDef.orient = orient(markDef.type, encoding, scales, specifiedOrient); if (specifiedOrient !== undefined && specifiedOrient !== markDef.orient) { log.warn(log.message.orientOverridden(markDef.orient, specifiedOrient)); } var specifiedFilled = markDef.filled; if (specifiedFilled === undefined) { markDef.filled = filled(markDef, config); } } exports.normalizeMarkDef = normalizeMarkDef; /** * Initialize encoding's value with some special default values */ function initEncoding(mark, encoding, stacked, config) { var opacityConfig = common_1.getMarkConfig('opacity', mark, config); if (!encoding.opacity && opacityConfig === undefined) { var opacity = defaultOpacity(mark.type, encoding, stacked); if (opacity !== undefined) { encoding.opacity = { value: opacity }; } } return encoding; } exports.initEncoding = initEncoding; function defaultOpacity(mark, encoding, stacked) { if (util_1.contains([mark_1.POINT, mark_1.TICK, mark_1.CIRCLE, mark_1.SQUARE], mark)) { // point-based marks if (!encoding_1.isAggregate(encoding)) { return 0.7; } } return undefined; } function filled(markDef, config) { var filledConfig = common_1.getMarkConfig('filled', markDef, config); var mark = markDef.type; return filledConfig !== undefined ? filledConfig : mark !== mark_1.POINT && mark !== mark_1.LINE && mark !== mark_1.RULE; } function orient(mark, encoding, scales, specifiedOrient) { switch (mark) { case mark_1.POINT: case mark_1.CIRCLE: case mark_1.SQUARE: case mark_1.TEXT: case mark_1.RECT: // orient is meaningless for these marks. return undefined; } var yIsRange = encoding.y && encoding.y2; var xIsRange = encoding.x && encoding.x2; switch (mark) { case mark_1.TICK: var xScaleType = scales.x ? scales.x.get('type') : null; var yScaleType = scales.y ? scales.y.get('type') : null; // Tick is opposite to bar, line, area and never have ranged mark. if (!scale_1.hasDiscreteDomain(xScaleType) && (!encoding.y || scale_1.hasDiscreteDomain(yScaleType) || (fielddef_1.isFieldDef(encoding.y) && encoding.y.bin))) { return 'vertical'; } // y:Q or Ambiguous case, return horizontal return 'horizontal'; case mark_1.RULE: case mark_1.BAR: case mark_1.AREA: // If there are range for both x and y, y (vertical) has higher precedence. if (yIsRange) { return 'vertical'; } else if (xIsRange) { return 'horizontal'; } else if (mark === mark_1.RULE) { if (encoding.x && !encoding.y) { return 'vertical'; } else if (encoding.y && !encoding.x) { return 'horizontal'; } } /* tslint:disable */ case mark_1.LINE:// intentional fall through /* tslint:enable */ var xIsContinuous = fielddef_1.isFieldDef(encoding.x) && fielddef_1.isContinuous(encoding.x); var yIsContinuous = fielddef_1.isFieldDef(encoding.y) && fielddef_1.isContinuous(encoding.y); if (xIsContinuous && !yIsContinuous) { return 'horizontal'; } else if (!xIsContinuous && yIsContinuous) { return 'vertical'; } else if (xIsContinuous && yIsContinuous) { var xDef = encoding.x; // we can cast here since they are surely fieldDef var yDef = encoding.y; var xIsTemporal = xDef.type === type_1.TEMPORAL; var yIsTemporal = yDef.type === type_1.TEMPORAL; // temporal without timeUnit is considered continuous, but better serves as dimension if (xIsTemporal && !yIsTemporal) { return 'vertical'; } else if (!xIsTemporal && yIsTemporal) { return 'horizontal'; } if (!xDef.aggregate && yDef.aggregate) { return 'vertical'; } else if (xDef.aggregate && !yDef.aggregate) { return 'horizontal'; } if (specifiedOrient) { // When ambiguous, use user specified one. return specifiedOrient; } if (!(mark === mark_1.LINE && encoding.order)) { // Except for connected scatterplot, we should log warning for unclear orientation of QxQ plots. log.warn(log.message.unclearOrientContinuous(mark)); } return 'vertical'; } else { // For Discrete x Discrete case, return undefined. log.warn(log.message.unclearOrientDiscreteOrEmpty(mark)); return undefined; } } return 'vertical'; } },{"../../encoding":88,"../../fielddef":90,"../../log":95,"../../mark":97,"../../scale":98,"../../type":106,"../../util":107,"../common":18}],49:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var mixins = require("./mixins"); exports.line = { vgMark: 'line', defaultRole: undefined, encodeEntry: function (model) { return tslib_1.__assign({}, mixins.pointPosition('x', model, 'zeroOrMin'), mixins.pointPosition('y', model, 'zeroOrMin'), mixins.color(model), mixins.text(model, 'tooltip'), mixins.nonPosition('opacity', model), mixins.nonPosition('size', model, { vgChannel: 'strokeWidth' // VL's line size is strokeWidth }), mixins.markDefProperties(model.markDef, ['interpolate', 'tension'])); } }; },{"./mixins":51,"tslib":5}],50:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var vega_util_1 = require("vega-util"); var channel_1 = require("../../channel"); var channel_2 = require("../../channel"); var data_1 = require("../../data"); var fielddef_1 = require("../../fielddef"); var mark_1 = require("../../mark"); var scale_1 = require("../../scale"); var util_1 = require("../../util"); var unit_1 = require("../unit"); var area_1 = require("./area"); var bar_1 = require("./bar"); var init_1 = require("./init"); var line_1 = require("./line"); var point_1 = require("./point"); var rect_1 = require("./rect"); var rule_1 = require("./rule"); var text_1 = require("./text"); var tick_1 = require("./tick"); var markCompiler = { area: area_1.area, bar: bar_1.bar, line: line_1.line, point: point_1.point, text: text_1.text, tick: tick_1.tick, rect: rect_1.rect, rule: rule_1.rule, circle: point_1.circle, square: point_1.square }; function parseMarkDef(model) { if (model instanceof unit_1.UnitModel) { init_1.normalizeMarkDef(model.markDef, model.encoding, model.component.scales, model.config); } else { for (var _i = 0, _a = model.children; _i < _a.length; _i++) { var child = _a[_i]; parseMarkDef(child); } } } exports.parseMarkDef = parseMarkDef; function parseMarkGroup(model) { if (util_1.contains([mark_1.LINE, mark_1.AREA], model.mark())) { return parsePathMark(model); } else { return parseNonPathMark(model); } } exports.parseMarkGroup = parseMarkGroup; var FACETED_PATH_PREFIX = 'faceted_path_'; function parsePathMark(model) { var mark = model.mark(); // FIXME: replace this with more general case for composition var details = detailFields(model); var role = model.markDef.role || markCompiler[mark].defaultRole; var pathMarks = [ tslib_1.__assign({ name: model.getName('marks'), type: markCompiler[mark].vgMark }, (clip(model)), (role ? { role: role } : {}), { // If has subfacet for line/area group, need to use faceted data from below. // FIXME: support sorting path order (in connected scatterplot) from: { data: (details.length > 0 ? FACETED_PATH_PREFIX : '') + model.requestDataName(data_1.MAIN) }, encode: { update: markCompiler[mark].encodeEntry(model) } }) ]; if (details.length > 0) { // TODO: for non-stacked plot, map order to zindex. (Maybe rename order for layer to zindex?) return [{ name: model.getName('pathgroup'), type: 'group', from: { facet: { name: FACETED_PATH_PREFIX + model.requestDataName(data_1.MAIN), data: model.requestDataName(data_1.MAIN), groupby: details, } }, encode: { update: { width: { field: { group: 'width' } }, height: { field: { group: 'height' } } } }, marks: pathMarks }]; } else { return pathMarks; } } function parseNonPathMark(model) { var mark = model.mark(); var role = model.markDef.role || markCompiler[mark].defaultRole; var marks = []; // TODO: vgMarks // TODO: for non-stacked plot, map order to zindex. (Maybe rename order for layer to zindex?) marks.push(tslib_1.__assign({ name: model.getName('marks'), type: markCompiler[mark].vgMark }, (clip(model)), (role ? { role: role } : {}), { from: { data: model.requestDataName(data_1.MAIN) }, encode: { update: markCompiler[mark].encodeEntry(model) } })); return marks; } /** * Returns list of detail (group-by) fields * that the model's spec contains. */ function detailFields(model) { return channel_2.LEVEL_OF_DETAIL_CHANNELS.reduce(function (details, channel) { var encoding = model.encoding; if (channel === 'detail' || channel === 'order') { var channelDef = encoding[channel]; if (channelDef) { (vega_util_1.isArray(channelDef) ? channelDef : [channelDef]).forEach(function (fieldDef) { if (!fieldDef.aggregate) { details.push(fielddef_1.field(fieldDef, { binSuffix: 'start' })); } }); } } else { var fieldDef = fielddef_1.getFieldDef(encoding[channel]); if (fieldDef && !fieldDef.aggregate) { details.push(fielddef_1.field(fieldDef, { binSuffix: 'start' })); } } return details; }, []); } function clip(model) { var xScaleDomain = model.scaleDomain(channel_1.X); var yScaleDomain = model.scaleDomain(channel_1.Y); return (xScaleDomain && scale_1.isSelectionDomain(xScaleDomain)) || (yScaleDomain && scale_1.isSelectionDomain(yScaleDomain)) ? { clip: true } : {}; } },{"../../channel":12,"../../data":86,"../../fielddef":90,"../../mark":97,"../../scale":98,"../../util":107,"../unit":81,"./area":46,"./bar":47,"./init":48,"./line":49,"./point":52,"./rect":53,"./rule":54,"./text":55,"./tick":56,"tslib":5,"vega-util":7}],51:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var fielddef_1 = require("../../fielddef"); var log = require("../../log"); var util = require("../../util"); var common_1 = require("../common"); var selection_1 = require("../selection/selection"); var ref = require("./valueref"); function color(model) { var config = model.config; var filled = model.markDef.filled; var e = nonPosition('color', model, { vgChannel: filled ? 'fill' : 'stroke', defaultValue: common_1.getMarkConfig('color', model.markDef, config) }); // If there is no fill, always fill symbols // with transparent fills https://github.com/vega/vega-lite/issues/1316 if (!e.fill && util.contains(['bar', 'point', 'circle', 'square'], model.mark())) { e.fill = { value: 'transparent' }; } return e; } exports.color = color; function markDefProperties(mark, props) { return props.reduce(function (m, prop) { if (mark[prop]) { m[prop] = { value: mark[prop] }; } return m; }, {}); } exports.markDefProperties = markDefProperties; function valueIfDefined(prop, value) { if (value !== undefined) { return _a = {}, _a[prop] = { value: value }, _a; } return undefined; var _a; } exports.valueIfDefined = valueIfDefined; /** * Return mixins for non-positional channels with scales. (Text doesn't have scale.) */ function nonPosition(channel, model, opt) { // TODO: refactor how we refer to scale as discussed in https://github.com/vega/vega-lite/pull/1613 if (opt === void 0) { opt = {}; } var defaultValue = opt.defaultValue, vgChannel = opt.vgChannel; var defaultRef = opt.defaultRef || (defaultValue !== undefined ? { value: defaultValue } : undefined); var channelDef = model.encoding[channel]; return wrapCondition(model, channelDef, vgChannel || channel, function (cDef) { return ref.midPoint(channel, cDef, model.scaleName(channel), model.getScaleComponent(channel), defaultRef); }); } exports.nonPosition = nonPosition; /** * Return a mixin that include a Vega production rule for a Vega-Lite conditional channel definition. * or a simple mixin if channel def has no condition. */ function wrapCondition(model, channelDef, vgChannel, refFn) { var condition = channelDef && channelDef.condition; var valueRef = refFn(channelDef); if (condition) { var conditionValueRef = refFn(condition); return _a = {}, _a[vgChannel] = [ tslib_1.__assign({ test: selection_1.predicate(model, condition.selection) }, conditionValueRef) ].concat((valueRef !== undefined ? [valueRef] : [])), _a; } else { return valueRef !== undefined ? (_b = {}, _b[vgChannel] = valueRef, _b) : {}; } var _a, _b; } function text(model, channel) { if (channel === void 0) { channel = 'text'; } var channelDef = model.encoding[channel]; return wrapCondition(model, channelDef, channel, function (cDef) { return ref.text(cDef, model.config); }); } exports.text = text; function bandPosition(fieldDef, channel, model) { var scaleName = model.scaleName(channel); var sizeChannel = channel === 'x' ? 'width' : 'height'; if (model.encoding.size) { var orient = model.markDef.orient; if (orient) { var centeredBandPositionMixins = (_a = {}, // Use xc/yc and place the mark at the middle of the band // This way we never have to deal with size's condition for x/y position. _a[channel + 'c'] = ref.fieldRef(fieldDef, scaleName, {}, { band: 0.5 }), _a); if (fielddef_1.getFieldDef(model.encoding.size)) { log.warn(log.message.cannotUseSizeFieldWithBandSize(channel)); // TODO: apply size to band and set scale range to some values between 0-1. // return { // ...centeredBandPositionMixins, // ...bandSize('size', model, {vgChannel: sizeChannel}) // }; } else if (fielddef_1.isValueDef(model.encoding.size)) { return tslib_1.__assign({}, centeredBandPositionMixins, nonPosition('size', model, { vgChannel: sizeChannel })); } } else { log.warn(log.message.cannotApplySizeToNonOrientedMark(model.markDef.type)); } } return _b = {}, _b[channel] = ref.fieldRef(fieldDef, scaleName, {}), _b[sizeChannel] = ref.band(scaleName), _b; var _a, _b; } exports.bandPosition = bandPosition; function centeredBandPosition(channel, model, defaultPosRef, defaultSizeRef) { var centerChannel = channel === 'x' ? 'xc' : 'yc'; var sizeChannel = channel === 'x' ? 'width' : 'height'; return tslib_1.__assign({}, pointPosition(channel, model, defaultPosRef, centerChannel), nonPosition('size', model, { defaultRef: defaultSizeRef, vgChannel: sizeChannel })); } exports.centeredBandPosition = centeredBandPosition; function binnedPosition(fieldDef, channel, scaleName, spacing) { if (channel === 'x') { return { x2: ref.bin(fieldDef, scaleName, 'start', spacing), x: ref.bin(fieldDef, scaleName, 'end') }; } else { return { y2: ref.bin(fieldDef, scaleName, 'start'), y: ref.bin(fieldDef, scaleName, 'end', spacing) }; } } exports.binnedPosition = binnedPosition; /** * Return mixins for point (non-band) position channels. */ function pointPosition(channel, model, defaultRef, vgChannel) { // TODO: refactor how refer to scale as discussed in https://github.com/vega/vega-lite/pull/1613 var encoding = model.encoding, stack = model.stack; var valueRef = ref.stackable(channel, encoding[channel], model.scaleName(channel), model.getScaleComponent(channel), stack, defaultRef); return _a = {}, _a[vgChannel || channel] = valueRef, _a; var _a; } exports.pointPosition = pointPosition; /** * Return mixins for x2, y2. * If channel is not specified, return one channel based on orientation. */ function pointPosition2(model, defaultRef, channel) { var encoding = model.encoding, markDef = model.markDef, stack = model.stack; channel = channel || (markDef.orient === 'horizontal' ? 'x2' : 'y2'); var baseChannel = channel === 'x2' ? 'x' : 'y'; var valueRef = ref.stackable2(channel, encoding[baseChannel], encoding[channel], model.scaleName(baseChannel), model.getScaleComponent(baseChannel), stack, defaultRef); return _a = {}, _a[channel] = valueRef, _a; var _a; } exports.pointPosition2 = pointPosition2; },{"../../fielddef":90,"../../log":95,"../../util":107,"../common":18,"../selection/selection":70,"./valueref":57,"tslib":5}],52:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var common_1 = require("../common"); var mixins = require("./mixins"); var ref = require("./valueref"); function encodeEntry(model, fixedShape) { var config = model.config, width = model.width, height = model.height; return tslib_1.__assign({}, mixins.pointPosition('x', model, ref.midX(width, config)), mixins.pointPosition('y', model, ref.midY(height, config)), mixins.color(model), mixins.text(model, 'tooltip'), mixins.nonPosition('size', model), shapeMixins(model, config, fixedShape), mixins.nonPosition('opacity', model)); } function shapeMixins(model, config, fixedShape) { if (fixedShape) { return { shape: { value: fixedShape } }; } return mixins.nonPosition('shape', model, { defaultValue: common_1.getMarkConfig('shape', model.markDef, config) }); } exports.shapeMixins = shapeMixins; exports.point = { vgMark: 'symbol', defaultRole: 'point', encodeEntry: function (model) { return encodeEntry(model); } }; exports.circle = { vgMark: 'symbol', defaultRole: 'circle', encodeEntry: function (model) { return encodeEntry(model, 'circle'); } }; exports.square = { vgMark: 'symbol', defaultRole: 'square', encodeEntry: function (model) { return encodeEntry(model, 'square'); } }; },{"../common":18,"./mixins":51,"./valueref":57,"tslib":5}],53:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var channel_1 = require("../../channel"); var fielddef_1 = require("../../fielddef"); var log = require("../../log"); var mark_1 = require("../../mark"); var scale_1 = require("../../scale"); var mixins = require("./mixins"); exports.rect = { vgMark: 'rect', defaultRole: undefined, encodeEntry: function (model) { return tslib_1.__assign({}, x(model), y(model), mixins.color(model), mixins.text(model, 'tooltip'), mixins.nonPosition('opacity', model)); } }; function x(model) { var xDef = model.encoding.x; var x2Def = model.encoding.x2; var xScale = model.getScaleComponent(channel_1.X); var xScaleType = xScale ? xScale.get('type') : undefined; if (fielddef_1.isFieldDef(xDef) && xDef.bin && !x2Def) { return mixins.binnedPosition(xDef, 'x', model.scaleName('x'), 0); } else if (fielddef_1.isFieldDef(xDef) && xScale && scale_1.hasDiscreteDomain(xScaleType)) { /* istanbul ignore else */ if (xScaleType === scale_1.ScaleType.BAND) { return mixins.bandPosition(xDef, 'x', model); } else { // We don't support rect mark with point/ordinal scale throw new Error(log.message.scaleTypeNotWorkWithMark(mark_1.RECT, xScaleType)); } } else { return tslib_1.__assign({}, mixins.pointPosition('x', model, 'zeroOrMax'), mixins.pointPosition2(model, 'zeroOrMin', 'x2')); } } function y(model) { var yDef = model.encoding.y; var y2Def = model.encoding.y2; var yScale = model.getScaleComponent(channel_1.Y); var yScaleType = yScale ? yScale.get('type') : undefined; if (fielddef_1.isFieldDef(yDef) && yDef.bin && !y2Def) { return mixins.binnedPosition(yDef, 'y', model.scaleName('y'), 0); } else if (fielddef_1.isFieldDef(yDef) && yScale && scale_1.hasDiscreteDomain(yScaleType)) { /* istanbul ignore else */ if (yScaleType === scale_1.ScaleType.BAND) { return mixins.bandPosition(yDef, 'y', model); } else { // We don't support rect mark with point/ordinal scale throw new Error(log.message.scaleTypeNotWorkWithMark(mark_1.RECT, yScaleType)); } } else { return tslib_1.__assign({}, mixins.pointPosition('y', model, 'zeroOrMax'), mixins.pointPosition2(model, 'zeroOrMin', 'y2')); } } },{"../../channel":12,"../../fielddef":90,"../../log":95,"../../mark":97,"../../scale":98,"./mixins":51,"tslib":5}],54:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var mixins = require("./mixins"); var ref = require("./valueref"); exports.rule = { vgMark: 'rule', defaultRole: undefined, encodeEntry: function (model) { var config = model.config, markDef = model.markDef, width = model.width, height = model.height; var orient = markDef.orient; return tslib_1.__assign({}, mixins.pointPosition('x', model, orient === 'horizontal' ? 'zeroOrMin' : ref.midX(width, config)), mixins.pointPosition('y', model, orient === 'vertical' ? 'zeroOrMin' : ref.midY(height, config)), mixins.pointPosition2(model, 'zeroOrMax'), mixins.color(model), mixins.text(model, 'tooltip'), mixins.nonPosition('opacity', model), mixins.nonPosition('size', model, { vgChannel: 'strokeWidth' // VL's rule size is strokeWidth })); } }; },{"./mixins":51,"./valueref":57,"tslib":5}],55:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var channel_1 = require("../../channel"); var encoding_1 = require("../../encoding"); var fielddef_1 = require("../../fielddef"); var type_1 = require("../../type"); var common_1 = require("../common"); var mixins = require("./mixins"); var ref = require("./valueref"); exports.text = { vgMark: 'text', defaultRole: undefined, encodeEntry: function (model) { var config = model.config, encoding = model.encoding, height = model.height; var textDef = encoding.text; return tslib_1.__assign({}, mixins.pointPosition('x', model, xDefault(config, textDef)), mixins.pointPosition('y', model, ref.midY(height, config)), mixins.text(model), mixins.color(model), mixins.text(model, 'tooltip'), mixins.nonPosition('opacity', model), mixins.nonPosition('size', model, { vgChannel: 'fontSize' // VL's text size is fontSize }), mixins.valueIfDefined('align', align(model.markDef, encoding, config))); } }; function xDefault(config, textDef) { if (fielddef_1.isFieldDef(textDef) && textDef.type === type_1.QUANTITATIVE) { return { field: { group: 'width' }, offset: -5 }; } // TODO: allow this to fit (Be consistent with ref.midX()) return { value: config.scale.textXRangeStep / 2 }; } function align(markDef, encoding, config) { var alignConfig = common_1.getMarkConfig('align', markDef, config); if (alignConfig === undefined) { return encoding_1.channelHasField(encoding, channel_1.X) ? 'center' : 'right'; } // If there is a config, Vega-parser will process this already. return undefined; } },{"../../channel":12,"../../encoding":88,"../../fielddef":90,"../../type":106,"../common":18,"./mixins":51,"./valueref":57,"tslib":5}],56:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var vega_schema_1 = require("../../vega.schema"); var mixins = require("./mixins"); var ref = require("./valueref"); exports.tick = { vgMark: 'rect', defaultRole: 'tick', encodeEntry: function (model) { var config = model.config, markDef = model.markDef, width = model.width, height = model.height; var orient = markDef.orient; var vgSizeChannel = orient === 'horizontal' ? 'width' : 'height'; var vgThicknessChannel = orient === 'horizontal' ? 'height' : 'width'; return tslib_1.__assign({}, mixins.pointPosition('x', model, ref.midX(width, config), 'xc'), mixins.pointPosition('y', model, ref.midY(height, config), 'yc'), mixins.nonPosition('size', model, { defaultValue: defaultSize(model), vgChannel: vgSizeChannel }), (_a = {}, _a[vgThicknessChannel] = { value: config.tick.thickness }, _a), mixins.color(model), mixins.nonPosition('opacity', model)); var _a; } }; function defaultSize(model) { var config = model.config; var orient = model.markDef.orient; var scale = model.getScaleComponent(orient === 'horizontal' ? 'x' : 'y'); if (config.tick.bandSize !== undefined) { return config.tick.bandSize; } else { var scaleRange = scale ? scale.get('range') : undefined; var rangeStep = scaleRange && vega_schema_1.isVgRangeStep(scaleRange) ? scaleRange.step : config.scale.rangeStep; if (typeof rangeStep !== 'number') { // FIXME consolidate this log throw new Error('Function does not handle non-numeric rangeStep'); } return rangeStep / 1.5; } } },{"../../vega.schema":109,"./mixins":51,"./valueref":57,"tslib":5}],57:[function(require,module,exports){ "use strict"; /** * Utility files for producing Vega ValueRef for marks */ Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var vega_util_1 = require("vega-util"); var channel_1 = require("../../channel"); var fielddef_1 = require("../../fielddef"); var scale_1 = require("../../scale"); var util_1 = require("../../util"); var vega_schema_1 = require("../../vega.schema"); var common_1 = require("../common"); // TODO: we need to find a way to refactor these so that scaleName is a part of scale // but that's complicated. For now, this is a huge step moving forward. /** * @return Vega ValueRef for stackable x or y */ function stackable(channel, channelDef, scaleName, scale, stack, defaultRef) { if (fielddef_1.isFieldDef(channelDef) && stack && channel === stack.fieldChannel) { // x or y use stack_end so that stacked line's point mark use stack_end too. return fieldRef(channelDef, scaleName, { suffix: 'end' }); } return midPoint(channel, channelDef, scaleName, scale, defaultRef); } exports.stackable = stackable; /** * @return Vega ValueRef for stackable x2 or y2 */ function stackable2(channel, aFieldDef, a2fieldDef, scaleName, scale, stack, defaultRef) { if (fielddef_1.isFieldDef(aFieldDef) && stack && // If fieldChannel is X and channel is X2 (or Y and Y2) channel.charAt(0) === stack.fieldChannel.charAt(0)) { return fieldRef(aFieldDef, scaleName, { suffix: 'start' }); } return midPoint(channel, a2fieldDef, scaleName, scale, defaultRef); } exports.stackable2 = stackable2; /** * Value Ref for binned fields */ function bin(fieldDef, scaleName, side, offset) { return fieldRef(fieldDef, scaleName, { binSuffix: side }, offset ? { offset: offset } : {}); } exports.bin = bin; function fieldRef(fieldDef, scaleName, opt, mixins) { var ref = { scale: scaleName, field: fielddef_1.field(fieldDef, opt), }; if (mixins) { return tslib_1.__assign({}, ref, mixins); } return ref; } exports.fieldRef = fieldRef; function band(scaleName, band) { if (band === void 0) { band = true; } return { scale: scaleName, band: band }; } exports.band = band; /** * Signal that returns the middle of a bin. Should only be used with x and y. */ function binMidSignal(fieldDef, scaleName) { return { signal: "(" + ("scale(\"" + scaleName + "\", " + fielddef_1.field(fieldDef, { binSuffix: 'start', expr: 'datum' }) + ")") + " + " + ("scale(\"" + scaleName + "\", " + fielddef_1.field(fieldDef, { binSuffix: 'end', expr: 'datum' }) + ")") + ")/2" }; } /** * @returns {VgValueRef} Value Ref for xc / yc or mid point for other channels. */ function midPoint(channel, channelDef, scaleName, scale, defaultRef) { // TODO: datum support if (channelDef) { /* istanbul ignore else */ if (fielddef_1.isFieldDef(channelDef)) { if (channelDef.bin) { // Use middle only for x an y to place marks in the center between start and end of the bin range. // We do not use the mid point for other channels (e.g. size) so that properties of legends and marks match. if (util_1.contains(['x', 'y'], channel)) { return binMidSignal(channelDef, scaleName); } return fieldRef(channelDef, scaleName, { binSuffix: 'start' }); } var scaleType = scale.get('type'); if (scale_1.hasDiscreteDomain(scaleType)) { if (scaleType === 'band') { // For band, to get mid point, need to offset by half of the band return fieldRef(channelDef, scaleName, { binSuffix: 'range' }, { band: 0.5 }); } return fieldRef(channelDef, scaleName, { binSuffix: 'range' }); } else { return fieldRef(channelDef, scaleName, {}); // no need for bin suffix } } else if (fielddef_1.isValueDef(channelDef)) { return { value: channelDef.value }; } else { throw new Error('FieldDef without field or value.'); // FIXME add this to log.message } } if (defaultRef === 'zeroOrMin') { /* istanbul ignore else */ if (channel === channel_1.X || channel === channel_1.X2) { return zeroOrMinX(scaleName, scale); } else if (channel === channel_1.Y || channel === channel_1.Y2) { return zeroOrMinY(scaleName, scale); } else { throw new Error("Unsupported channel " + channel + " for base function"); // FIXME add this to log.message } } else if (defaultRef === 'zeroOrMax') { /* istanbul ignore else */ if (channel === channel_1.X || channel === channel_1.X2) { return zeroOrMaxX(scaleName, scale); } else if (channel === channel_1.Y || channel === channel_1.Y2) { return zeroOrMaxY(scaleName, scale); } else { throw new Error("Unsupported channel " + channel + " for base function"); // FIXME add this to log.message } } return defaultRef; } exports.midPoint = midPoint; function text(textDef, config) { // text if (textDef) { if (fielddef_1.isFieldDef(textDef)) { return common_1.formatSignalRef(textDef, textDef.format, 'datum', config); } else if (fielddef_1.isValueDef(textDef)) { return { value: textDef.value }; } } return undefined; } exports.text = text; function midX(width, config) { if (vega_util_1.isNumber(width)) { return { value: width / 2 }; } else if (vega_schema_1.isVgSignalRef(width)) { return tslib_1.__assign({}, width, { mult: 0.5 }); } return { value: config.scale.rangeStep / 2 }; } exports.midX = midX; function midY(height, config) { if (vega_util_1.isNumber(height)) { return { value: height / 2 }; } else if (vega_schema_1.isVgSignalRef(height)) { return tslib_1.__assign({}, height, { mult: 0.5 }); } return { value: config.scale.rangeStep / 2 }; } exports.midY = midY; function zeroOrMinX(scaleName, scale) { if (scaleName) { // Log / Time / UTC scale do not support zero if (!util_1.contains([scale_1.ScaleType.LOG, scale_1.ScaleType.TIME, scale_1.ScaleType.UTC], scale.get('type')) && scale.get('zero') !== false) { return { scale: scaleName, value: 0 }; } } // Put the mark on the x-axis return { value: 0 }; } /** * @returns {VgValueRef} base value if scale exists and return max value if scale does not exist */ function zeroOrMaxX(scaleName, scale) { if (scaleName) { // Log / Time / UTC scale do not support zero if (!util_1.contains([scale_1.ScaleType.LOG, scale_1.ScaleType.TIME, scale_1.ScaleType.UTC], scale.get('type')) && scale.get('zero') !== false) { return { scale: scaleName, value: 0 }; } } return { field: { group: 'width' } }; } function zeroOrMinY(scaleName, scale) { if (scaleName) { // Log / Time / UTC scale do not support zero if (!util_1.contains([scale_1.ScaleType.LOG, scale_1.ScaleType.TIME, scale_1.ScaleType.UTC], scale.get('type')) && scale.get('zero') !== false) { return { scale: scaleName, value: 0 }; } } // Put the mark on the y-axis return { field: { group: 'height' } }; } /** * @returns {VgValueRef} base value if scale exists and return max value if scale does not exist */ function zeroOrMaxY(scaleName, scale) { if (scaleName) { // Log / Time / UTC scale do not support zero if (!util_1.contains([scale_1.ScaleType.LOG, scale_1.ScaleType.TIME, scale_1.ScaleType.UTC], scale.get('type')) && scale.get('zero') !== false) { return { scale: scaleName, value: 0 }; } } // Put the mark on the y-axis return { value: 0 }; } },{"../../channel":12,"../../fielddef":90,"../../scale":98,"../../util":107,"../../vega.schema":109,"../common":18,"tslib":5,"vega-util":7}],58:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var vega_util_1 = require("vega-util"); var channel_1 = require("../channel"); var encoding_1 = require("../encoding"); var fielddef_1 = require("../fielddef"); var log = require("../log"); var util_1 = require("../util"); var assemble_1 = require("./axis/assemble"); var header_1 = require("./layout/header"); var assemble_2 = require("./legend/assemble"); var mark_1 = require("./mark/mark"); var assemble_3 = require("./scale/assemble"); var parse_1 = require("./scale/parse"); var split_1 = require("./split"); var unit_1 = require("./unit"); var NameMap = (function () { function NameMap() { this.nameMap = {}; } NameMap.prototype.rename = function (oldName, newName) { this.nameMap[oldName] = newName; }; NameMap.prototype.has = function (name) { return this.nameMap[name] !== undefined; }; NameMap.prototype.get = function (name) { // If the name appears in the _nameMap, we need to read its new name. // We have to loop over the dict just in case the new name also gets renamed. while (this.nameMap[name]) { name = this.nameMap[name]; } return name; }; return NameMap; }()); exports.NameMap = NameMap; var Model = (function () { function Model(spec, parent, parentGivenName, config, resolve) { var _this = this; this.children = []; /** * Corrects the data references in marks after assemble. */ this.correctDataNames = function (mark) { // TODO: make this correct // for normal data references if (mark.from && mark.from.data) { mark.from.data = _this.lookupDataSource(mark.from.data); } // for access to facet data if (mark.from && mark.from.facet && mark.from.facet.data) { mark.from.facet.data = _this.lookupDataSource(mark.from.facet.data); } return mark; }; this.parent = parent; this.config = config; // If name is not provided, always use parent's givenName to avoid name conflicts. this.name = spec.name || parentGivenName; // Shared name maps this.scaleNameMap = parent ? parent.scaleNameMap : new NameMap(); this.layoutSizeNameMap = parent ? parent.layoutSizeNameMap : new NameMap(); this.data = spec.data; this.description = spec.description; this.transforms = spec.transform || []; this.component = { data: { sources: parent ? parent.component.data.sources : {}, outputNodes: parent ? parent.component.data.outputNodes : {}, outputNodeRefCounts: parent ? parent.component.data.outputNodeRefCounts : {}, ancestorParse: parent ? tslib_1.__assign({}, parent.component.data.ancestorParse) : {} }, layoutSize: new split_1.Split(), layoutHeaders: { row: {}, column: {} }, mark: null, resolve: resolve || {}, selection: null, scales: null, axes: {}, legends: {}, }; } Object.defineProperty(Model.prototype, "width", { get: function () { return this.getLayoutSize('width'); }, enumerable: true, configurable: true }); Object.defineProperty(Model.prototype, "height", { get: function () { return this.getLayoutSize('height'); }, enumerable: true, configurable: true }); Model.prototype.getLayoutSize = function (sizeType) { /* istanbul ignore else: Condition should not happen -- only for warning in development. */ var size = this.component.layoutSize.get(sizeType); if (size !== undefined) { if (vega_util_1.isNumber(size)) { return size; } return this.getSizeSignalRef(sizeType); } throw new Error("calling model." + sizeType + " before parseLayoutSize()"); }; Model.prototype.initSize = function (size) { var width = size.width, height = size.height; if (width) { this.component.layoutSize.set('width', width, true); } if (height) { this.component.layoutSize.set('height', height, true); } }; Model.prototype.parse = function () { this.parseScale(); this.parseMarkDef(); this.parseLayoutSize(); // depends on scale this.parseSelection(); this.parseData(); // (pathorder) depends on markDef; selection filters depend on parsed selections. this.parseAxisAndHeader(); // depends on scale this.parseLegend(); // depends on scale, markDef this.parseMarkGroup(); // depends on data name, scale, layoutSize, axisGroup, and children's scale, axis, legend and mark. }; Model.prototype.parseScale = function () { parse_1.parseScale(this); }; Model.prototype.parseMarkDef = function () { mark_1.parseMarkDef(this); }; Model.prototype.assembleScales = function () { return assemble_3.assembleScale(this); }; Model.prototype.assembleHeaderMarks = function () { var layoutHeaders = this.component.layoutHeaders; var headerMarks = []; for (var _i = 0, HEADER_CHANNELS_1 = header_1.HEADER_CHANNELS; _i < HEADER_CHANNELS_1.length; _i++) { var channel = HEADER_CHANNELS_1[_i]; if (layoutHeaders[channel].title) { headerMarks.push(header_1.getTitleGroup(this, channel)); } } for (var _a = 0, HEADER_CHANNELS_2 = header_1.HEADER_CHANNELS; _a < HEADER_CHANNELS_2.length; _a++) { var channel = HEADER_CHANNELS_2[_a]; var layoutHeader = layoutHeaders[channel]; for (var _b = 0, HEADER_TYPES_1 = header_1.HEADER_TYPES; _b < HEADER_TYPES_1.length; _b++) { var headerType = HEADER_TYPES_1[_b]; if (layoutHeader[headerType]) { for (var _c = 0, _d = layoutHeader[headerType]; _c < _d.length; _c++) { var header = _d[_c]; var headerGroup = header_1.getHeaderGroup(this, channel, headerType, layoutHeader, header); if (headerGroup) { headerMarks.push(headerGroup); } } } } } return headerMarks; }; Model.prototype.assembleAxes = function () { return assemble_1.assembleAxes(this.component.axes); }; Model.prototype.assembleLegends = function () { return assemble_2.assembleLegends(this); }; Model.prototype.assembleGroup = function (signals) { if (signals === void 0) { signals = []; } var group = {}; signals = signals.concat(this.assembleSelectionSignals()); if (signals.length > 0) { group.signals = signals; } var layout = this.assembleLayout(); if (layout) { group.layout = layout; } group.marks = [].concat(this.assembleHeaderMarks(), this.assembleMarks()); var scales = this.assembleScales(); if (scales.length > 0) { group.scales = scales; } var axes = this.assembleAxes(); if (axes.length > 0) { group.axes = axes; } var legends = this.assembleLegends(); if (legends.length > 0) { group.legends = legends; } return group; }; Model.prototype.hasDescendantWithFieldOnChannel = function (channel) { for (var _i = 0, _a = this.children; _i < _a.length; _i++) { var child = _a[_i]; if (child instanceof unit_1.UnitModel) { if (child.channelHasField(channel)) { return true; } } else { if (child.hasDescendantWithFieldOnChannel(channel)) { return true; } } } return false; }; Model.prototype.getName = function (text) { return util_1.varName((this.name ? this.name + '_' : '') + text); }; /** * Request a data source name for the given data source type and mark that data source as required. This method should be called in parse, so that all used data source can be correctly instantiated in assembleData(). */ Model.prototype.requestDataName = function (name) { var fullName = this.getName(name); // Increase ref count. This is critical because otherwise we won't create a data source. // We also increase the ref counts on OutputNode.getSource() calls. var refCounts = this.component.data.outputNodeRefCounts; refCounts[fullName] = (refCounts[fullName] || 0) + 1; return fullName; }; Model.prototype.getSizeSignalRef = function (sizeType) { return { signal: this.layoutSizeNameMap.get(this.getName(sizeType)) }; }; /** * Lookup the name of the datasource for an output node. You probably want to call this in assemble. */ Model.prototype.lookupDataSource = function (name) { var node = this.component.data.outputNodes[name]; if (!node) { // Name not found in map so let's just return what we got. // This can happen if we already have the correct name. return name; } return node.getSource(); }; Model.prototype.renameLayoutSize = function (oldName, newName) { this.layoutSizeNameMap.rename(oldName, newName); }; Model.prototype.channelSizeName = function (channel) { return this.sizeName(channel === channel_1.X || channel === channel_1.COLUMN ? 'width' : 'height'); }; Model.prototype.sizeName = function (size) { return this.layoutSizeNameMap.get(this.getName(size)); }; Model.prototype.renameScale = function (oldName, newName) { this.scaleNameMap.rename(oldName, newName); }; /** * @return scale name for a given channel after the scale has been parsed and named. */ Model.prototype.scaleName = function (originalScaleName, parse) { if (parse) { // During the parse phase always return a value // No need to refer to rename map because a scale can't be renamed // before it has the original name. return this.getName(originalScaleName); } // If there is a scale for the channel, it should either // be in the scale component or exist in the name map if ( // If there is a scale for the channel, there should be a local scale component for it channel_1.isChannel(originalScaleName) && channel_1.isScaleChannel(originalScaleName) && this.component.scales[originalScaleName] || // in the scale name map (the the scale get merged by its parent) this.scaleNameMap.has(this.getName(originalScaleName))) { return this.scaleNameMap.get(this.getName(originalScaleName)); } return undefined; }; /** * Traverse a model's hierarchy to get the scale component for a particular channel. */ Model.prototype.getScaleComponent = function (channel) { /* istanbul ignore next: This is warning for debugging test */ if (!this.component.scales) { throw new Error('getScaleComponent cannot be called before parseScale(). Make sure you have called parseScale or use parseUnitModelWithScale().'); } var localScaleComponent = this.component.scales[channel]; if (localScaleComponent && !localScaleComponent.merged) { return localScaleComponent; } return (this.parent ? this.parent.getScaleComponent(channel) : undefined); }; /** * Traverse a model's hierarchy to get a particular selection component. */ Model.prototype.getSelectionComponent = function (varName, origName) { var sel = this.component.selection[varName]; if (!sel && this.parent) { sel = this.parent.getSelectionComponent(varName, origName); } if (!sel) { throw new Error(log.message.selectionNotFound(origName)); } return sel; }; return Model; }()); exports.Model = Model; /** Abstract class for UnitModel and FacetModel. Both of which can contain fieldDefs as a part of its own specification. */ var ModelWithField = (function (_super) { tslib_1.__extends(ModelWithField, _super); function ModelWithField() { return _super !== null && _super.apply(this, arguments) || this; } /** Get "field" reference for vega */ ModelWithField.prototype.field = function (channel, opt) { if (opt === void 0) { opt = {}; } var fieldDef = this.fieldDef(channel); if (fieldDef.bin) { opt = util_1.extend({ binSuffix: this.hasDiscreteDomain(channel) ? 'range' : 'start' }, opt); } return fielddef_1.field(fieldDef, opt); }; ModelWithField.prototype.reduceFieldDef = function (f, init, t) { return encoding_1.reduce(this.getMapping(), function (acc, cd, c) { var fieldDef = fielddef_1.getFieldDef(cd); if (fieldDef) { return f(acc, fieldDef, c); } return acc; }, init, t); }; ModelWithField.prototype.forEachFieldDef = function (f, t) { encoding_1.forEach(this.getMapping(), function (cd, c) { var fieldDef = fielddef_1.getFieldDef(cd); if (fieldDef) { f(fieldDef, c); } }, t); }; return ModelWithField; }(Model)); exports.ModelWithField = ModelWithField; },{"../channel":12,"../encoding":88,"../fielddef":90,"../log":95,"../util":107,"./axis/assemble":13,"./layout/header":39,"./legend/assemble":41,"./mark/mark":50,"./scale/assemble":61,"./scale/parse":64,"./split":80,"./unit":81,"tslib":5,"vega-util":7}],59:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var vega_util_1 = require("vega-util"); var fielddef_1 = require("../fielddef"); var log = require("../log"); var util_1 = require("../util"); var common_1 = require("./common"); var assemble_1 = require("./data/assemble"); var parse_1 = require("./data/parse"); var assemble_2 = require("./layout/assemble"); var parse_2 = require("./layout/parse"); var parse_3 = require("./legend/parse"); var model_1 = require("./model"); function replaceRepeaterInFacet(facet, repeater) { return replaceRepeater(facet, repeater); } exports.replaceRepeaterInFacet = replaceRepeaterInFacet; function replaceRepeaterInEncoding(encoding, repeater) { return replaceRepeater(encoding, repeater); } exports.replaceRepeaterInEncoding = replaceRepeaterInEncoding; /** * Replace repeater values in a field def with the concrete field name. */ function replaceRepeaterInFieldDef(fieldDef, repeater) { var field = fieldDef.field; if (fielddef_1.isRepeatRef(field)) { if (field.repeat in repeater) { return tslib_1.__assign({}, fieldDef, { field: repeater[field.repeat] }); } else { log.warn(log.message.noSuchRepeatedValue(field.repeat)); return null; } } else { // field is not a repeat ref so we can just return the field def return fieldDef; } } function replaceRepeater(mapping, repeater) { var out = {}; for (var channel in mapping) { if (mapping.hasOwnProperty(channel)) { var fieldDef = mapping[channel]; if (vega_util_1.isArray(fieldDef)) { out[channel] = fieldDef.map(function (fd) { return replaceRepeaterInFieldDef(fd, repeater); }) .filter(function (fd) { return fd !== null; }); } else { var fd = replaceRepeaterInFieldDef(fieldDef, repeater); if (fd !== null) { out[channel] = fd; } } } } return out; } var RepeatModel = (function (_super) { tslib_1.__extends(RepeatModel, _super); function RepeatModel(spec, parent, parentGivenName, repeatValues, config) { var _this = _super.call(this, spec, parent, parentGivenName, config, spec.resolve) || this; _this.repeat = spec.repeat; _this.children = _this._initChildren(spec, _this.repeat, repeatValues, config); return _this; } RepeatModel.prototype._initChildren = function (spec, repeat, repeater, config) { var children = []; var row = repeat.row || [repeater ? repeater.row : null]; var column = repeat.column || [repeater ? repeater.column : null]; // cross product for (var _i = 0, row_1 = row; _i < row_1.length; _i++) { var rowField = row_1[_i]; for (var _a = 0, column_1 = column; _a < column_1.length; _a++) { var columnField = column_1[_a]; var name_1 = (rowField ? '_' + rowField : '') + (columnField ? '_' + columnField : ''); var childRepeat = { row: rowField, column: columnField }; children.push(common_1.buildModel(spec.spec, this, this.getName('child' + name_1), undefined, childRepeat, config)); } } return children; }; RepeatModel.prototype.parseData = function () { this.component.data = parse_1.parseData(this); this.children.forEach(function (child) { child.parseData(); }); }; RepeatModel.prototype.parseLayoutSize = function () { parse_2.parseRepeatLayoutSize(this); }; RepeatModel.prototype.parseSelection = function () { var _this = this; // Merge selections up the hierarchy so that they may be referenced // across unit specs. Persist their definitions within each child // to assemble signals which remain within output Vega unit groups. this.component.selection = {}; var _loop_1 = function (child) { child.parseSelection(); util_1.keys(child.component.selection).forEach(function (key) { _this.component.selection[key] = child.component.selection[key]; }); }; for (var _i = 0, _a = this.children; _i < _a.length; _i++) { var child = _a[_i]; _loop_1(child); } }; RepeatModel.prototype.parseMarkGroup = function () { for (var _i = 0, _a = this.children; _i < _a.length; _i++) { var child = _a[_i]; child.parseMarkGroup(); } }; RepeatModel.prototype.parseAxisAndHeader = function () { for (var _i = 0, _a = this.children; _i < _a.length; _i++) { var child = _a[_i]; child.parseAxisAndHeader(); } // TODO(#2415): support shared axes }; RepeatModel.prototype.parseLegend = function () { parse_3.parseNonUnitLegend(this); }; RepeatModel.prototype.assembleData = function () { if (!this.parent) { // only assemble data in the root return assemble_1.assembleData(this.component.data); } return []; }; RepeatModel.prototype.assembleParentGroupProperties = function () { return null; }; RepeatModel.prototype.assembleSelectionTopLevelSignals = function (signals) { return this.children.reduce(function (sg, child) { return child.assembleSelectionTopLevelSignals(sg); }, signals); }; RepeatModel.prototype.assembleSelectionSignals = function () { this.children.forEach(function (child) { return child.assembleSelectionSignals(); }); return []; }; RepeatModel.prototype.assembleLayoutSignals = function () { return this.children.reduce(function (signals, child) { return signals.concat(child.assembleLayoutSignals()); }, assemble_2.assembleLayoutSignals(this)); }; RepeatModel.prototype.assembleSelectionData = function (data) { return this.children.reduce(function (db, child) { return child.assembleSelectionData(db); }, []); }; RepeatModel.prototype.assembleLayout = function () { // TODO: allow customization return { padding: { row: 10, column: 10 }, offset: 10, columns: this.repeat && this.repeat.column ? this.repeat.column.length : 1, bounds: 'full', align: 'all' }; }; RepeatModel.prototype.assembleMarks = function () { // only children have marks return this.children.map(function (child) { var encodeEntry = child.assembleParentGroupProperties(); return tslib_1.__assign({ type: 'group', name: child.getName('group') }, (encodeEntry ? { encode: { update: encodeEntry } } : {}), child.assembleGroup()); }); }; return RepeatModel; }(model_1.Model)); exports.RepeatModel = RepeatModel; },{"../fielddef":90,"../log":95,"../util":107,"./common":18,"./data/assemble":22,"./data/parse":30,"./layout/assemble":38,"./layout/parse":40,"./legend/parse":44,"./model":58,"tslib":5,"vega-util":7}],60:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var channel_1 = require("../channel"); var log = require("../log"); var util_1 = require("../util"); var concat_1 = require("./concat"); var facet_1 = require("./facet"); var layer_1 = require("./layer"); var repeat_1 = require("./repeat"); function defaultScaleResolve(channel, model) { if (model instanceof layer_1.LayerModel || model instanceof facet_1.FacetModel) { return 'shared'; } else if (model instanceof concat_1.ConcatModel || model instanceof repeat_1.RepeatModel) { return util_1.contains(channel_1.SPATIAL_SCALE_CHANNELS, channel) ? 'independent' : 'shared'; } /* istanbul ignore next: should never reach here. */ throw new Error('invalid model type for resolve'); } exports.defaultScaleResolve = defaultScaleResolve; function parseGuideResolve(resolve, channel) { var channelResolve = resolve[channel]; var guide = util_1.contains(channel_1.SPATIAL_SCALE_CHANNELS, channel) ? 'axis' : 'legend'; if (channelResolve.scale === 'independent') { if (channelResolve[guide] === 'shared') { log.warn(log.message.independentScaleMeansIndependentGuide(channel)); } return 'independent'; } return channelResolve[guide] || 'shared'; } exports.parseGuideResolve = parseGuideResolve; },{"../channel":12,"../log":95,"../util":107,"./concat":20,"./facet":36,"./layer":37,"./repeat":59}],61:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var vega_util_1 = require("vega-util"); var util_1 = require("../../util"); var vega_schema_1 = require("../../vega.schema"); var selection_1 = require("../selection/selection"); function assembleScale(model) { return util_1.vals(model.component.scales).reduce(function (scales, scaleComponent) { if (scaleComponent.merged) { // Skipped merged scales return scales; } // We need to cast here as combine returns Partial<VgScale> by default. var scale = scaleComponent.combine(['name', 'type', 'domain', 'domainRaw', 'range']); var domainRaw = scaleComponent.get('domainRaw'); // As scale parsing occurs before selection parsing, a temporary signal // is used for domainRaw. Here, we detect if this temporary signal // is set, and replace it with the correct domainRaw signal. // For more information, see isRawSelectionDomain in selection.ts. if (domainRaw && selection_1.isRawSelectionDomain(domainRaw)) { scale.domainRaw = selection_1.selectionScaleDomain(model, domainRaw); } // Correct references to data as the original domain's data was determined // in parseScale, which happens before parseData. Thus the original data // reference can be incorrect. var domain = scaleComponent.get('domain'); if (vega_schema_1.isDataRefDomain(domain) || vega_schema_1.isFieldRefUnionDomain(domain)) { domain.data = model.lookupDataSource(domain.data); scales.push(scale); } else if (vega_schema_1.isDataRefUnionedDomain(domain)) { domain.fields = domain.fields.map(function (f) { return tslib_1.__assign({}, f, { data: model.lookupDataSource(f.data) }); }); scales.push(scale); } else if (vega_schema_1.isSignalRefDomain(domain) || vega_util_1.isArray(domain)) { scales.push(scale); } else { throw new Error('invalid scale domain'); } return scales; }, []); } exports.assembleScale = assembleScale; },{"../../util":107,"../../vega.schema":109,"../selection/selection":70,"tslib":5,"vega-util":7}],62:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var split_1 = require("../split"); var ScaleComponent = (function (_super) { tslib_1.__extends(ScaleComponent, _super); function ScaleComponent(name, typeWithExplicit) { var _this = _super.call(this, {}, // no initial explicit property { name: name } // name as initial implicit property ) || this; _this.merged = false; _this.setWithExplicit('type', typeWithExplicit); return _this; } return ScaleComponent; }(split_1.Split)); exports.ScaleComponent = ScaleComponent; },{"../split":80,"tslib":5}],63:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var aggregate_1 = require("../../aggregate"); var bin_1 = require("../../bin"); var channel_1 = require("../../channel"); var data_1 = require("../../data"); var datetime_1 = require("../../datetime"); var log = require("../../log"); var scale_1 = require("../../scale"); var sort_1 = require("../../sort"); var util = require("../../util"); var util_1 = require("../../util"); var vega_schema_1 = require("../../vega.schema"); var assemble_1 = require("../data/assemble"); var facet_1 = require("../facet"); var selection_1 = require("../selection/selection"); var unit_1 = require("../unit"); function parseScaleDomain(model) { if (model instanceof unit_1.UnitModel) { parseUnitScaleDomain(model); } else { parseNonUnitScaleDomain(model); } } exports.parseScaleDomain = parseScaleDomain; function parseUnitScaleDomain(model) { var scales = model.specifiedScales; var localScaleComponents = model.component.scales; util_1.keys(localScaleComponents).forEach(function (channel) { var specifiedScale = scales[channel]; var specifiedDomain = specifiedScale ? specifiedScale.domain : undefined; var hasSpecifiedDomain = specifiedDomain && !scale_1.isSelectionDomain(specifiedDomain); var domain = parseDomainForChannel(model, channel); var localScaleCmpt = localScaleComponents[channel]; localScaleCmpt.set('domain', domain, hasSpecifiedDomain); if (scale_1.isSelectionDomain(specifiedDomain)) { // As scale parsing occurs before selection parsing, we use a temporary // signal here and append the scale.domain definition. This is replaced // with the correct domainRaw signal during scale assembly. // For more information, see isRawSelectionDomain in selection.ts. // FIXME: replace this with a special property in the scaleComponent localScaleCmpt.set('domainRaw', { signal: selection_1.SELECTION_DOMAIN + JSON.stringify(specifiedDomain) }, true); } }); } function parseNonUnitScaleDomain(model) { for (var _i = 0, _a = model.children; _i < _a.length; _i++) { var child = _a[_i]; parseScaleDomain(child); } var localScaleComponents = model.component.scales; util_1.keys(localScaleComponents).forEach(function (channel) { // FIXME: Arvind -- Please revise logic for merging selectionDomain / domainRaw var domain; for (var _i = 0, _a = model.children; _i < _a.length; _i++) { var child = _a[_i]; var childComponent = child.component.scales[channel]; if (childComponent) { var childDomain = childComponent.get('domain'); if (domain === undefined) { domain = childDomain; } else { domain = unionDomains(domain, childDomain); } } } if (model instanceof facet_1.FacetModel) { // Replace the scale domain with data output from a cloned subtree after the facet. if (vega_schema_1.isDataRefDomain(domain) || vega_schema_1.isFieldRefUnionDomain(domain)) { domain.data = assemble_1.FACET_SCALE_PREFIX + model.getName(domain.data); } else if (vega_schema_1.isDataRefUnionedDomain(domain)) { domain.fields = domain.fields.map(function (f) { return tslib_1.__assign({}, f, { data: assemble_1.FACET_SCALE_PREFIX + model.getName(f.data) }); }); } } localScaleComponents[channel].set('domain', domain, true); }); } /** * Remove unaggregated domain if it is not applicable * Add unaggregated domain if domain is not specified and config.scale.useUnaggregatedDomain is true. */ function normalizeUnaggregatedDomain(domain, fieldDef, scaleType, scaleConfig) { if (domain === 'unaggregated') { var _a = canUseUnaggregatedDomain(fieldDef, scaleType), valid = _a.valid, reason = _a.reason; if (!valid) { log.warn(reason); return undefined; } } else if (domain === undefined && scaleConfig.useUnaggregatedDomain) { // Apply config if domain is not specified. var valid = canUseUnaggregatedDomain(fieldDef, scaleType).valid; if (valid) { return 'unaggregated'; } } return domain; } // FIXME: Domoritz -- please change this to return VgDomain[] and union one at the end in assemble function parseDomainForChannel(model, channel) { var scaleType = model.getScaleComponent(channel).get('type'); var domain = normalizeUnaggregatedDomain(model.scaleDomain(channel), model.fieldDef(channel), scaleType, model.config.scale); if (domain !== model.scaleDomain(channel)) { model.specifiedScales[channel] = tslib_1.__assign({}, model.specifiedScales[channel], { domain: domain }); } // If channel is either X or Y then union them with X2 & Y2 if they exist if (channel === 'x' && model.channelHasField('x2')) { if (model.channelHasField('x')) { return unionDomains(parseSingleChannelDomain(scaleType, domain, model, 'x'), parseSingleChannelDomain(scaleType, domain, model, 'x2')); } else { return parseSingleChannelDomain(scaleType, domain, model, 'x2'); } } else if (channel === 'y' && model.channelHasField('y2')) { if (model.channelHasField('y')) { return unionDomains(parseSingleChannelDomain(scaleType, domain, model, 'y'), parseSingleChannelDomain(scaleType, domain, model, 'y2')); } else { return parseSingleChannelDomain(scaleType, domain, model, 'y2'); } } return parseSingleChannelDomain(scaleType, domain, model, channel); } exports.parseDomainForChannel = parseDomainForChannel; function parseSingleChannelDomain(scaleType, domain, model, channel) { var fieldDef = model.fieldDef(channel); if (domain && domain !== 'unaggregated' && !scale_1.isSelectionDomain(domain)) { if (fieldDef.bin) { log.warn(log.message.conflictedDomain(channel)); } else { if (datetime_1.isDateTime(domain[0])) { return domain.map(function (dt) { return { signal: datetime_1.dateTimeExpr(dt, true) }; }); } return domain; } } var stack = model.stack; if (stack && channel === stack.fieldChannel) { if (stack.offset === 'normalize') { return [0, 1]; } return { data: model.requestDataName(data_1.MAIN), fields: [ model.field(channel, { suffix: 'start' }), model.field(channel, { suffix: 'end' }) ] }; } var sort = channel_1.isScaleChannel(channel) ? domainSort(model, channel, scaleType) : undefined; if (domain === 'unaggregated') { return { data: model.requestDataName(data_1.MAIN), fields: [ model.field(channel, { aggregate: 'min' }), model.field(channel, { aggregate: 'max' }) ] }; } else if (fieldDef.bin) { if (scale_1.isBinScale(scaleType)) { var signal = model.getName(bin_1.binToString(fieldDef.bin) + "_" + fieldDef.field + "_bins"); return { signal: "sequence(" + signal + ".start, " + signal + ".stop + " + signal + ".step, " + signal + ".step)" }; } if (scale_1.hasDiscreteDomain(scaleType)) { // ordinal bin scale takes domain from bin_range, ordered by bin_start // This is useful for both axis-based scale (x/y) and legend-based scale (other channels). return { data: model.requestDataName(data_1.MAIN), field: model.field(channel, { binSuffix: 'range' }), sort: { field: model.field(channel, { binSuffix: 'start' }), op: 'min' // min or max doesn't matter since same _range would have the same _start } }; } else { if (channel === 'x' || channel === 'y') { // X/Y position have to include start and end for non-ordinal scale return { data: model.requestDataName(data_1.MAIN), fields: [ model.field(channel, { binSuffix: 'start' }), model.field(channel, { binSuffix: 'end' }) ] }; } else { // TODO: use bin_mid return { data: model.requestDataName(data_1.MAIN), field: model.field(channel, { binSuffix: 'start' }) }; } } } else if (sort) { return { // If sort by aggregation of a specified sort field, we need to use RAW table, // so we can aggregate values for the scale independently from the main aggregation. data: util.isBoolean(sort) ? model.requestDataName(data_1.MAIN) : model.requestDataName(data_1.RAW), field: model.field(channel), sort: sort }; } else { return { data: model.requestDataName(data_1.MAIN), field: model.field(channel) }; } } function domainSort(model, channel, scaleType) { if (!scale_1.hasDiscreteDomain(scaleType)) { return undefined; } var sort = model.sort(channel); // Sorted based on an aggregate calculation over a specified sort field (only for ordinal scale) if (sort_1.isSortField(sort)) { return sort; } if (sort === 'descending') { return { op: 'min', field: model.field(channel), order: 'descending' }; } if (util.contains(['ascending', undefined /* default =ascending*/], sort)) { return true; } // sort === 'none' return undefined; } exports.domainSort = domainSort; /** * Determine if a scale can use unaggregated domain. * @return {Boolean} Returns true if all of the following conditons applies: * 1. `scale.domain` is `unaggregated` * 2. Aggregation function is not `count` or `sum` * 3. The scale is quantitative or time scale. */ function canUseUnaggregatedDomain(fieldDef, scaleType) { if (!fieldDef.aggregate) { return { valid: false, reason: log.message.unaggregateDomainHasNoEffectForRawField(fieldDef) }; } if (!aggregate_1.SHARED_DOMAIN_OP_INDEX[fieldDef.aggregate]) { return { valid: false, reason: log.message.unaggregateDomainWithNonSharedDomainOp(fieldDef.aggregate) }; } if (fieldDef.type === 'quantitative') { if (scaleType === 'log') { return { valid: false, reason: log.message.unaggregatedDomainWithLogScale(fieldDef) }; } } return { valid: true }; } exports.canUseUnaggregatedDomain = canUseUnaggregatedDomain; /** * Convert the domain to an array of data refs or an array of values. Also, throw * away sorting information since we always sort the domain when we union two domains. */ function normalizeDomain(domain) { if (util.isArray(domain)) { return [domain]; } else if (vega_schema_1.isSignalRefDomain(domain)) { return [domain]; } else if (vega_schema_1.isDataRefDomain(domain)) { delete domain.sort; return [domain]; } else if (vega_schema_1.isFieldRefUnionDomain(domain)) { return domain.fields.map(function (d) { return { data: domain.data, field: d }; }); } else if (vega_schema_1.isDataRefUnionedDomain(domain)) { return domain.fields; } /* istanbul ignore next: This should never happen. */ throw new Error(log.message.INVAID_DOMAIN); } /** * Union two data domains. A unioned domain is always sorted. */ function unionDomains(domain1, domain2) { var normalizedDomain1 = normalizeDomain(domain1); var normalizedDomain2 = normalizeDomain(domain2); var domains = normalizedDomain1.concat(normalizedDomain2); domains = util.unique(domains, util.hash); if (domains.length > 1) { var allData = domains.map(function (d) { if (vega_schema_1.isDataRefDomain(d)) { return d.data; } return null; }); if (util.unique(allData, function (x) { return x; }).length === 1 && allData[0] !== null) { // create a union domain of different fields with a single data source var domain = { data: allData[0], fields: domains.map(function (d) { return d.field; }) }; return domain; } return { fields: domains, sort: true }; } else { return domains[0]; } } exports.unionDomains = unionDomains; },{"../../aggregate":9,"../../bin":11,"../../channel":12,"../../data":86,"../../datetime":87,"../../log":95,"../../scale":98,"../../sort":100,"../../util":107,"../../vega.schema":109,"../data/assemble":22,"../facet":36,"../selection/selection":70,"../unit":81,"tslib":5}],64:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var channel_1 = require("../../channel"); var fielddef_1 = require("../../fielddef"); var scale_1 = require("../../scale"); var util_1 = require("../../util"); var resolve_1 = require("../resolve"); var split_1 = require("../split"); var unit_1 = require("../unit"); var component_1 = require("./component"); var domain_1 = require("./domain"); var properties_1 = require("./properties"); var range_1 = require("./range"); var type_1 = require("./type"); function parseScale(model) { parseScaleCore(model); domain_1.parseScaleDomain(model); for (var _i = 0, NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTIES_1 = scale_1.NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTIES; _i < NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTIES_1.length; _i++) { var prop = NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTIES_1[_i]; properties_1.parseScaleProperty(model, prop); } // range depends on zero range_1.parseScaleRange(model); } exports.parseScale = parseScale; function parseScaleCore(model) { if (model instanceof unit_1.UnitModel) { model.component.scales = parseUnitScaleCore(model); } else { model.component.scales = parseNonUnitScaleCore(model); } } exports.parseScaleCore = parseScaleCore; /** * Parse scales for all channels of a model. */ function parseUnitScaleCore(model) { var encoding = model.encoding, config = model.config; var mark = model.mark(); return channel_1.SCALE_CHANNELS.reduce(function (scaleComponents, channel) { var fieldDef; var specifiedScale = {}; var channelDef = encoding[channel]; if (fielddef_1.isFieldDef(channelDef)) { fieldDef = channelDef; specifiedScale = channelDef.scale || {}; } else if (fielddef_1.isConditionalDef(channelDef) && fielddef_1.isFieldDef(channelDef.condition)) { fieldDef = channelDef.condition; specifiedScale = channelDef.condition.scale || {}; } else if (channel === 'x') { fieldDef = fielddef_1.getFieldDef(encoding.x2); } else if (channel === 'y') { fieldDef = fielddef_1.getFieldDef(encoding.y2); } if (fieldDef) { var specifiedScaleType = specifiedScale.type; var sType = type_1.scaleType(specifiedScale.type, channel, fieldDef, mark, specifiedScale.rangeStep, config.scale); scaleComponents[channel] = new component_1.ScaleComponent(model.scaleName(channel + '', true), { value: sType, explicit: specifiedScaleType === sType }); } return scaleComponents; }, {}); } var scaleTypeTieBreaker = split_1.tieBreakByComparing(function (st1, st2) { return (scale_1.scaleTypePrecedence(st1) - scale_1.scaleTypePrecedence(st2)); }); function parseNonUnitScaleCore(model) { var scaleComponents = model.component.scales = {}; var scaleTypeWithExplicitIndex = {}; var resolve = model.component.resolve; var _loop_1 = function (child) { parseScaleCore(child); // Instead of always merging right away -- check if it is compatible to merge first! util_1.keys(child.component.scales).forEach(function (channel) { // if resolve is undefined, set default first resolve[channel] = resolve[channel] || {}; resolve[channel].scale = resolve[channel].scale || resolve_1.defaultScaleResolve(channel, model); if (model.component.resolve[channel].scale === 'shared') { var scaleType_1 = scaleTypeWithExplicitIndex[channel]; var childScaleType = child.component.scales[channel].getWithExplicit('type'); if (scaleType_1) { if (scale_1.scaleCompatible(scaleType_1.value, childScaleType.value)) { // merge scale component if type are compatible scaleTypeWithExplicitIndex[channel] = split_1.mergeValuesWithExplicit(scaleType_1, childScaleType, 'type', 'scale', scaleTypeTieBreaker); } else { // Otherwise, update conflicting channel to be independent model.component.resolve[channel].scale = 'independent'; // Remove from the index so they don't get merged delete scaleTypeWithExplicitIndex[channel]; } } else { scaleTypeWithExplicitIndex[channel] = childScaleType; } } }); }; // Parse each child scale and determine if a particular channel can be merged. for (var _i = 0, _a = model.children; _i < _a.length; _i++) { var child = _a[_i]; _loop_1(child); } // Merge each channel listed in the index util_1.keys(scaleTypeWithExplicitIndex).forEach(function (channel) { // Create new merged scale component var name = model.scaleName(channel, true); var typeWithExplicit = scaleTypeWithExplicitIndex[channel]; var modelScale = scaleComponents[channel] = new component_1.ScaleComponent(name, typeWithExplicit); // rename each child and mark them as merged for (var _i = 0, _a = model.children; _i < _a.length; _i++) { var child = _a[_i]; var childScale = child.component.scales[channel]; if (childScale) { child.renameScale(childScale.get('name'), name); childScale.merged = true; } } }); return scaleComponents; } },{"../../channel":12,"../../fielddef":90,"../../scale":98,"../../util":107,"../resolve":60,"../split":80,"../unit":81,"./component":62,"./domain":63,"./properties":65,"./range":66,"./type":67}],65:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var channel_1 = require("../../channel"); var log = require("../../log"); var scale_1 = require("../../scale"); var timeunit_1 = require("../../timeunit"); var util = require("../../util"); var util_1 = require("../../util"); var split_1 = require("../split"); var unit_1 = require("../unit"); var range_1 = require("./range"); function parseScaleProperty(model, property) { if (model instanceof unit_1.UnitModel) { parseUnitScaleProperty(model, property); } else { parseNonUnitScaleProperty(model, property); } } exports.parseScaleProperty = parseScaleProperty; function parseUnitScaleProperty(model, property) { var localScaleComponents = model.component.scales; util_1.keys(localScaleComponents).forEach(function (channel) { var specifiedScale = model.specifiedScales[channel]; var localScaleCmpt = localScaleComponents[channel]; var mergedScaleCmpt = model.getScaleComponent(channel); var fieldDef = model.fieldDef(channel); var config = model.config; var specifiedValue = specifiedScale[property]; var sType = mergedScaleCmpt.get('type'); var supportedByScaleType = scale_1.scaleTypeSupportProperty(sType, property); var channelIncompatability = scale_1.channelScalePropertyIncompatability(channel, property); if (specifiedValue !== undefined) { // If there is a specified value, check if it is compatible with scale type and channel if (!supportedByScaleType) { log.warn(log.message.scalePropertyNotWorkWithScaleType(sType, property, channel)); } else if (channelIncompatability) { log.warn(channelIncompatability); } } if (supportedByScaleType && channelIncompatability === undefined) { if (specifiedValue !== undefined) { // copyKeyFromObject ensure type safety localScaleCmpt.copyKeyFromObject(property, specifiedScale); } else { var value = getDefaultValue(property, specifiedScale, mergedScaleCmpt, channel, fieldDef, config.scale); if (value !== undefined) { localScaleCmpt.set(property, value, false); } } } }); } function getDefaultValue(property, scale, scaleCmpt, channel, fieldDef, scaleConfig) { // If we have default rule-base, determine default value first switch (property) { case 'nice': return nice(scaleCmpt.get('type'), channel, fieldDef); case 'padding': return padding(channel, scaleCmpt.get('type'), scaleConfig); case 'paddingInner': return paddingInner(scaleCmpt.get('padding'), channel, scaleConfig); case 'paddingOuter': return paddingOuter(scaleCmpt.get('padding'), channel, scaleCmpt.get('type'), scaleCmpt.get('paddingInner'), scaleConfig); case 'round': return round(channel, scaleConfig); case 'zero': return zero(channel, fieldDef, !!scale.domain); } // Otherwise, use scale config return scaleConfig[property]; } function parseNonUnitScaleProperty(model, property) { var localScaleComponents = model.component.scales; for (var _i = 0, _a = model.children; _i < _a.length; _i++) { var child = _a[_i]; if (property === 'range') { range_1.parseScaleRange(child); } else { parseScaleProperty(child, property); } } util_1.keys(localScaleComponents).forEach(function (channel) { var valueWithExplicit; for (var _i = 0, _a = model.children; _i < _a.length; _i++) { var child = _a[_i]; var childComponent = child.component.scales[channel]; if (childComponent) { var childValueWithExplicit = childComponent.getWithExplicit(property); valueWithExplicit = split_1.mergeValuesWithExplicit(valueWithExplicit, childValueWithExplicit, property, 'scale', split_1.tieBreakByComparing(function (v1, v2) { switch (property) { case 'range': // For range step, prefer larger step if (v1.step && v2.step) { return v1.step - v2.step; } return 0; } return 0; })); } } localScaleComponents[channel].setWithExplicit(property, valueWithExplicit); }); } exports.parseNonUnitScaleProperty = parseNonUnitScaleProperty; function nice(scaleType, channel, fieldDef) { if (util.contains([scale_1.ScaleType.TIME, scale_1.ScaleType.UTC], scaleType)) { return timeunit_1.smallestUnit(fieldDef.timeUnit); } if (fieldDef.bin) { return undefined; } return util.contains([channel_1.X, channel_1.Y], channel); // return true for quantitative X/Y unless binned } exports.nice = nice; function padding(channel, scaleType, scaleConfig) { if (util.contains([channel_1.X, channel_1.Y], channel)) { if (scaleType === scale_1.ScaleType.POINT) { return scaleConfig.pointPadding; } } return undefined; } exports.padding = padding; function paddingInner(padding, channel, scaleConfig) { if (padding !== undefined) { // If user has already manually specified "padding", no need to add default paddingInner. return undefined; } if (util.contains([channel_1.X, channel_1.Y], channel)) { // Padding is only set for X and Y by default. // Basically it doesn't make sense to add padding for color and size. // paddingOuter would only be called if it's a band scale, just return the default for bandScale. return scaleConfig.bandPaddingInner; } return undefined; } exports.paddingInner = paddingInner; function paddingOuter(padding, channel, scaleType, paddingInner, scaleConfig) { if (padding !== undefined) { // If user has already manually specified "padding", no need to add default paddingOuter. return undefined; } if (util.contains([channel_1.X, channel_1.Y], channel)) { // Padding is only set for X and Y by default. // Basically it doesn't make sense to add padding for color and size. if (scaleType === scale_1.ScaleType.BAND) { if (scaleConfig.bandPaddingOuter !== undefined) { return scaleConfig.bandPaddingOuter; } /* By default, paddingOuter is paddingInner / 2. The reason is that size (width/height) = step * (cardinality - paddingInner + 2 * paddingOuter). and we want the width/height to be integer by default. Note that step (by default) and cardinality are integers.) */ return paddingInner / 2; } } return undefined; } exports.paddingOuter = paddingOuter; function round(channel, scaleConfig) { if (util.contains(['x', 'y'], channel)) { return scaleConfig.round; } return undefined; } exports.round = round; function zero(channel, fieldDef, hasCustomDomain) { // By default, return true only for the following cases: // 1) using quantitative field with size // While this can be either ratio or interval fields, our assumption is that // ratio are more common. if (channel === 'size' && fieldDef.type === 'quantitative') { return true; } // 2) non-binned, quantitative x-scale or y-scale if no custom domain is provided. // (For binning, we should not include zero by default because binning are calculated without zero. // Similar, if users explicitly provide a domain range, we should not augment zero as that will be unexpected.) if (!hasCustomDomain && !fieldDef.bin && util.contains([channel_1.X, channel_1.Y], channel)) { return true; } return false; } exports.zero = zero; },{"../../channel":12,"../../log":95,"../../scale":98,"../../timeunit":103,"../../util":107,"../split":80,"../unit":81,"./range":66}],66:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var vega_util_1 = require("vega-util"); var channel_1 = require("../../channel"); var log = require("../../log"); var scale_1 = require("../../scale"); var util = require("../../util"); var vega_schema_1 = require("../../vega.schema"); var split_1 = require("../split"); var unit_1 = require("../unit"); var properties_1 = require("./properties"); exports.RANGE_PROPERTIES = ['range', 'rangeStep', 'scheme']; function parseScaleRange(model) { if (model instanceof unit_1.UnitModel) { parseUnitScaleRange(model); } else { properties_1.parseNonUnitScaleProperty(model, 'range'); } } exports.parseScaleRange = parseScaleRange; function parseUnitScaleRange(model) { var localScaleComponents = model.component.scales; // use SCALE_CHANNELS instead of scales[channel] to ensure that x, y come first! channel_1.SCALE_CHANNELS.forEach(function (channel) { var localScaleCmpt = localScaleComponents[channel]; if (!localScaleCmpt) { return; } var specifiedScale = model.specifiedScales[channel]; var fieldDef = model.fieldDef(channel); // Read if there is a specified width/height var specifiedSize = channel === 'x' ? model.component.layoutSize.get('width') : channel === 'y' ? model.component.layoutSize.get('height') : undefined; var xyRangeSteps = getXYRangeStep(model); var rangeWithExplicit = parseRangeForChannel(channel, localScaleCmpt.get('type'), fieldDef.type, specifiedScale, model.config, localScaleCmpt.get('zero'), model.mark(), specifiedSize, xyRangeSteps); localScaleCmpt.setWithExplicit('range', rangeWithExplicit); }); } function getXYRangeStep(model) { var xyRangeSteps = []; var xScale = model.getScaleComponent('x'); var xRange = xScale && xScale.get('range'); if (xRange && vega_schema_1.isVgRangeStep(xRange)) { xyRangeSteps.push(xRange.step); } var yScale = model.getScaleComponent('y'); var yRange = yScale && yScale.get('range'); if (yRange && vega_schema_1.isVgRangeStep(yRange)) { xyRangeSteps.push(yRange.step); } return xyRangeSteps; } /** * Return mixins that includes one of the range properties (range, rangeStep, scheme). */ function parseRangeForChannel(channel, scaleType, type, specifiedScale, config, zero, mark, specifiedSize, xyRangeSteps) { var specifiedRangeStepIsNull = false; // Check if any of the range properties is specified. // If so, check if it is compatible and make sure that we only output one of the properties for (var _i = 0, RANGE_PROPERTIES_1 = exports.RANGE_PROPERTIES; _i < RANGE_PROPERTIES_1.length; _i++) { var property = RANGE_PROPERTIES_1[_i]; if (specifiedScale[property] !== undefined) { var supportedByScaleType = scale_1.scaleTypeSupportProperty(scaleType, property); var channelIncompatability = scale_1.channelScalePropertyIncompatability(channel, property); if (!supportedByScaleType) { log.warn(log.message.scalePropertyNotWorkWithScaleType(scaleType, property, channel)); } else if (channelIncompatability) { log.warn(channelIncompatability); } else { switch (property) { case 'range': return split_1.makeImplicit(specifiedScale[property]); case 'scheme': return split_1.makeImplicit(parseScheme(specifiedScale[property])); case 'rangeStep': if (specifiedSize === undefined) { var rangeStep = specifiedScale[property]; if (rangeStep !== null) { return split_1.makeImplicit({ step: rangeStep }); } else { specifiedRangeStepIsNull = true; } } else { // If top-level size is specified, we ignore specified rangeStep. log.warn(log.message.rangeStepDropped(channel)); } } } } } return { explicit: false, value: defaultRange(channel, scaleType, type, config, zero, mark, specifiedSize, xyRangeSteps, specifiedRangeStepIsNull) }; } exports.parseRangeForChannel = parseRangeForChannel; function parseScheme(scheme) { if (scale_1.isExtendedScheme(scheme)) { var r = { scheme: scheme.name }; if (scheme.count) { r.count = scheme.count; } if (scheme.extent) { r.extent = scheme.extent; } return r; } return { scheme: scheme }; } function defaultRange(channel, scaleType, type, config, zero, mark, topLevelSize, xyRangeSteps, specifiedRangeStepIsNull) { switch (channel) { case channel_1.X: case channel_1.Y: var size = void 0; if (vega_util_1.isNumber(topLevelSize)) { size = topLevelSize; } else { if (util.contains(['point', 'band'], scaleType) && !specifiedRangeStepIsNull) { if (channel === channel_1.X && mark === 'text') { if (config.scale.textXRangeStep) { return { step: config.scale.textXRangeStep }; } } else { if (config.scale.rangeStep) { return { step: config.scale.rangeStep }; } } } // If specified range step is null or the range step config is null. // Use default topLevelSize rule/config size = channel === channel_1.X ? config.cell.width : config.cell.height; } return channel === channel_1.X ? [0, size] : [size, 0]; case channel_1.SIZE: // TODO: support custom rangeMin, rangeMax var rangeMin = sizeRangeMin(mark, zero, config); var rangeMax = sizeRangeMax(mark, xyRangeSteps, config); return [rangeMin, rangeMax]; case channel_1.SHAPE: return 'symbol'; case channel_1.COLOR: if (scaleType === 'ordinal') { // Only nominal data uses ordinal scale by default return type === 'nominal' ? 'category' : 'ordinal'; } return mark === 'rect' ? 'heatmap' : 'ramp'; case channel_1.OPACITY: // TODO: support custom rangeMin, rangeMax return [config.scale.minOpacity, config.scale.maxOpacity]; } /* istanbul ignore next: should never reach here */ throw new Error("Scale range undefined for channel " + channel); } exports.defaultRange = defaultRange; function sizeRangeMin(mark, zero, config) { if (zero) { return 0; } switch (mark) { case 'bar': return config.scale.minBandSize !== undefined ? config.scale.minBandSize : config.bar.continuousBandSize; case 'tick': return config.scale.minBandSize; case 'line': case 'rule': return config.scale.minStrokeWidth; case 'text': return config.scale.minFontSize; case 'point': case 'square': case 'circle': if (config.scale.minSize) { return config.scale.minSize; } } /* istanbul ignore next: should never reach here */ // sizeRangeMin not implemented for the mark throw new Error(log.message.incompatibleChannel('size', mark)); } function sizeRangeMax(mark, xyRangeSteps, config) { var scaleConfig = config.scale; // TODO(#1168): make max size scale based on rangeStep / overall plot size switch (mark) { case 'bar': case 'tick': if (config.scale.maxBandSize !== undefined) { return config.scale.maxBandSize; } return minXYRangeStep(xyRangeSteps, config.scale) - 1; case 'line': case 'rule': return config.scale.maxStrokeWidth; case 'text': return config.scale.maxFontSize; case 'point': case 'square': case 'circle': if (config.scale.maxSize) { return config.scale.maxSize; } // FIXME this case totally should be refactored var pointStep = minXYRangeStep(xyRangeSteps, scaleConfig); return (pointStep - 2) * (pointStep - 2); } /* istanbul ignore next: should never reach here */ // sizeRangeMax not implemented for the mark throw new Error(log.message.incompatibleChannel('size', mark)); } /** * @returns {number} Range step of x or y or minimum between the two if both are ordinal scale. */ function minXYRangeStep(xyRangeSteps, scaleConfig) { if (xyRangeSteps.length > 0) { return Math.min.apply(null, xyRangeSteps); } if (scaleConfig.rangeStep) { return scaleConfig.rangeStep; } return 21; // FIXME: re-evaluate the default value here. } },{"../../channel":12,"../../log":95,"../../scale":98,"../../util":107,"../../vega.schema":109,"../split":80,"../unit":81,"./properties":65,"vega-util":7}],67:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var channel_1 = require("../../channel"); var log = require("../../log"); var scale_1 = require("../../scale"); var scale_2 = require("../../scale"); var timeunit_1 = require("../../timeunit"); var type_1 = require("../../type"); var util = require("../../util"); var util_1 = require("../../util"); /** * Determine if there is a specified scale type and if it is appropriate, * or determine default type if type is unspecified or inappropriate. */ // NOTE: CompassQL uses this method. function scaleType(specifiedType, channel, fieldDef, mark, specifiedRangeStep, scaleConfig) { var defaultScaleType = defaultType(channel, fieldDef, mark, specifiedRangeStep, scaleConfig); if (!channel_1.hasScale(channel)) { // There is no scale for these channels return null; } if (specifiedType !== undefined) { // Check if explicitly specified scale type is supported by the channel if (!channel_1.supportScaleType(channel, specifiedType)) { log.warn(log.message.scaleTypeNotWorkWithChannel(channel, specifiedType, defaultScaleType)); return defaultScaleType; } // Check if explicitly specified scale type is supported by the data type if (!fieldDefMatchScaleType(specifiedType, fieldDef)) { log.warn(log.message.scaleTypeNotWorkWithFieldDef(specifiedType, defaultScaleType)); return defaultScaleType; } return specifiedType; } return defaultScaleType; } exports.scaleType = scaleType; /** * Determine appropriate default scale type. */ function defaultType(channel, fieldDef, mark, specifiedRangeStep, scaleConfig) { switch (fieldDef.type) { case 'nominal': if (channel === 'color' || channel_1.rangeType(channel) === 'discrete') { return 'ordinal'; } return discreteToContinuousType(channel, mark, specifiedRangeStep, scaleConfig); case 'ordinal': if (channel === 'color') { return 'ordinal'; } else if (channel_1.rangeType(channel) === 'discrete') { if (channel !== 'text' && channel !== 'tooltip') { log.warn(log.message.discreteChannelCannotEncode(channel, 'ordinal')); } return 'ordinal'; } return discreteToContinuousType(channel, mark, specifiedRangeStep, scaleConfig); case 'temporal': if (channel === 'color') { if (timeunit_1.isDiscreteByDefault(fieldDef.timeUnit)) { // For discrete timeUnit, use ordinal scale so that legend produces correct value. // (See https://github.com/vega/vega-lite/issues/2045.) return 'ordinal'; } return 'sequential'; } else if (channel_1.rangeType(channel) === 'discrete') { log.warn(log.message.discreteChannelCannotEncode(channel, 'temporal')); // TODO: consider using quantize (equivalent to binning) once we have it return 'ordinal'; } if (timeunit_1.isDiscreteByDefault(fieldDef.timeUnit)) { return discreteToContinuousType(channel, mark, specifiedRangeStep, scaleConfig); } return 'time'; case 'quantitative': if (channel === 'color') { if (fieldDef.bin) { return 'bin-ordinal'; } // Use `sequential` as the default color scale for continuous data // since it supports both array range and scheme range. return 'sequential'; } else if (channel_1.rangeType(channel) === 'discrete') { log.warn(log.message.discreteChannelCannotEncode(channel, 'quantitative')); // TODO: consider using quantize (equivalent to binning) once we have it return 'ordinal'; } // x and y use a linear scale because selections don't work with bin scales if (fieldDef.bin && channel !== 'x' && channel !== 'y') { return 'bin-linear'; } return 'linear'; } /* istanbul ignore next: should never reach this */ throw new Error(log.message.invalidFieldType(fieldDef.type)); } /** * Determines default scale type for nominal/ordinal field. * @returns BAND or POINT scale based on channel, mark, and rangeStep */ function discreteToContinuousType(channel, mark, specifiedRangeStep, scaleConfig) { if (util.contains(['x', 'y'], channel)) { if (mark === 'rect') { // The rect mark should fit into a band. return 'band'; } if (mark === 'bar') { return 'band'; } } // Otherwise, use ordinal point scale so we can easily get center positions of the marks. return 'point'; } function fieldDefMatchScaleType(specifiedType, fieldDef) { var type = fieldDef.type; if (util_1.contains([type_1.Type.ORDINAL, type_1.Type.NOMINAL], type)) { return specifiedType === undefined || scale_2.hasDiscreteDomain(specifiedType); } else if (type === type_1.Type.TEMPORAL) { if (!fieldDef.timeUnit) { return util_1.contains([scale_1.ScaleType.TIME, scale_1.ScaleType.UTC, undefined], specifiedType); } else { return util_1.contains([scale_1.ScaleType.TIME, scale_1.ScaleType.UTC, undefined], specifiedType) || scale_2.hasDiscreteDomain(specifiedType); } } else if (type === type_1.Type.QUANTITATIVE) { if (fieldDef.bin) { return specifiedType === scale_1.ScaleType.BIN_LINEAR || specifiedType === scale_1.ScaleType.BIN_ORDINAL; } return util_1.contains([scale_1.ScaleType.LOG, scale_1.ScaleType.POW, scale_1.ScaleType.SQRT, scale_1.ScaleType.QUANTILE, scale_1.ScaleType.QUANTIZE, scale_1.ScaleType.LINEAR, undefined], specifiedType); } return true; } exports.fieldDefMatchScaleType = fieldDefMatchScaleType; },{"../../channel":12,"../../log":95,"../../scale":98,"../../timeunit":103,"../../type":106,"../../util":107}],68:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var channel_1 = require("../../channel"); var log_1 = require("../../log"); var scale_1 = require("../../scale"); var util_1 = require("../../util"); var selection_1 = require("./selection"); var scales_1 = require("./transforms/scales"); exports.BRUSH = '_brush'; exports.SCALE_TRIGGER = '_scale_trigger'; var interval = { predicate: 'vlInterval', scaleDomain: 'vlIntervalDomain', signals: function (model, selCmpt) { var name = selCmpt.name; var hasScales = scales_1.default.has(selCmpt); var signals = []; var intervals = []; var scaleTriggers = []; if (selCmpt.translate && !hasScales) { var filterExpr_1 = "!event.item || event.item.mark.name !== " + util_1.stringValue(name + exports.BRUSH); events(selCmpt, function (_, evt) { var filters = evt.between[0].filter || (evt.between[0].filter = []); if (filters.indexOf(filterExpr_1) < 0) { filters.push(filterExpr_1); } }); } selCmpt.project.forEach(function (p) { var channel = p.channel; if (channel !== channel_1.X && channel !== channel_1.Y) { log_1.warn('Interval selections only support x and y encoding channels.'); return; } var cs = channelSignals(model, selCmpt, channel); var dname = selection_1.channelSignalName(selCmpt, channel, 'data'); var vname = selection_1.channelSignalName(selCmpt, channel, 'visual'); var scaleStr = util_1.stringValue(model.scaleName(channel)); var scaleType = model.getScaleComponent(channel).get('type'); var toNum = scale_1.hasContinuousDomain(scaleType) ? '+' : ''; signals.push.apply(signals, cs); intervals.push("{encoding: " + util_1.stringValue(channel) + ", " + ("field: " + util_1.stringValue(p.field) + ", extent: " + dname + "}")); scaleTriggers.push({ scaleName: model.scaleName(channel), expr: "(!isArray(" + dname + ") || " + ("(" + toNum + "invert(" + scaleStr + ", " + vname + ")[0] === " + toNum + dname + "[0] && ") + (toNum + "invert(" + scaleStr + ", " + vname + ")[1] === " + toNum + dname + "[1]))") }); }); // Proxy scale reactions to ensure that an infinite loop doesn't occur // when an interval selection filter touches the scale. if (!hasScales) { signals.push({ name: name + exports.SCALE_TRIGGER, update: scaleTriggers.map(function (t) { return t.expr; }).join(' && ') + (" ? " + (name + exports.SCALE_TRIGGER) + " : {}") }); } return signals.concat({ name: name + selection_1.TUPLE, update: "{unit: " + util_1.stringValue(model.getName('')) + ", intervals: [" + intervals.join(', ') + "]}" }); }, modifyExpr: function (model, selCmpt) { var tpl = selCmpt.name + selection_1.TUPLE; return tpl + ', ' + (selCmpt.resolve === 'global' ? 'true' : "{unit: " + util_1.stringValue(model.getName('')) + "}"); }, marks: function (model, selCmpt, marks) { var name = selCmpt.name; var _a = selection_1.spatialProjections(selCmpt), xi = _a.xi, yi = _a.yi; var tpl = name + selection_1.TUPLE; var store = "data(" + util_1.stringValue(selCmpt.name + selection_1.STORE) + ")"; // Do not add a brush if we're binding to scales. if (scales_1.default.has(selCmpt)) { return marks; } var update = { x: xi !== null ? { signal: name + "_x[0]" } : { value: 0 }, y: yi !== null ? { signal: name + "_y[0]" } : { value: 0 }, x2: xi !== null ? { signal: name + "_x[1]" } : { field: { group: 'width' } }, y2: yi !== null ? { signal: name + "_y[1]" } : { field: { group: 'height' } } }; // If the selection is resolved to global, only a single interval is in // the store. Wrap brush mark's encodings with a production rule to test // this based on the `unit` property. Hide the brush mark if it corresponds // to a unit different from the one in the store. if (selCmpt.resolve === 'global') { util_1.keys(update).forEach(function (key) { update[key] = [tslib_1.__assign({ test: store + ".length && " + store + "[0].unit === " + util_1.stringValue(model.getName('')) }, update[key]), { value: 0 }]; }); } // Two brush marks ensure that fill colors and other aesthetic choices do // not interefere with the core marks, but that the brushed region can still // be interacted with (e.g., dragging it around). var _b = selCmpt.mark, fill = _b.fill, fillOpacity = _b.fillOpacity, stroke = tslib_1.__rest(_b, ["fill", "fillOpacity"]); var vgStroke = util_1.keys(stroke).reduce(function (def, k) { def[k] = { value: stroke[k] }; return def; }, {}); return [{ type: 'rect', encode: { enter: { fill: { value: fill }, fillOpacity: { value: fillOpacity } }, update: update } }].concat(marks, { name: name + exports.BRUSH, type: 'rect', encode: { enter: tslib_1.__assign({ fill: { value: 'transparent' } }, vgStroke), update: update } }); } }; exports.default = interval; /** * Returns the visual and data signals for an interval selection. */ function channelSignals(model, selCmpt, channel) { var vname = selection_1.channelSignalName(selCmpt, channel, 'visual'); var dname = selection_1.channelSignalName(selCmpt, channel, 'data'); var hasScales = scales_1.default.has(selCmpt); var scaleName = model.scaleName(channel); var scaleStr = util_1.stringValue(scaleName); var scale = model.getScaleComponent(channel); var scaleType = scale ? scale.get('type') : undefined; var size = model.getSizeSignalRef(channel === channel_1.X ? 'width' : 'height').signal; var coord = channel + "(unit)"; var on = events(selCmpt, function (def, evt) { return def.concat({ events: evt.between[0], update: "[" + coord + ", " + coord + "]" }, // Brush Start { events: evt, update: "[" + vname + "[0], clamp(" + coord + ", 0, " + size + ")]" } // Brush End ); }); // React to pan/zooms of continuous scales. Non-continuous scales // (bin-linear, band, point) cannot be pan/zoomed and any other changes // to their domains (e.g., filtering) should clear the brushes. on.push({ events: { signal: selCmpt.name + exports.SCALE_TRIGGER }, update: scale_1.hasContinuousDomain(scaleType) && !scale_1.isBinScale(scaleType) ? "[scale(" + scaleStr + ", " + dname + "[0]), scale(" + scaleStr + ", " + dname + "[1])]" : "[0, 0]" }); return hasScales ? [{ name: dname, on: [] }] : [{ name: vname, value: [], on: on }, { name: dname, on: [{ events: { signal: vname }, update: "invert(" + scaleStr + ", " + vname + ")" }] }]; } function events(selCmpt, cb) { return selCmpt.events.reduce(function (on, evt) { if (!evt.between) { log_1.warn(evt + " is not an ordered event stream for interval selections"); return on; } return cb(on, evt); }, []); } },{"../../channel":12,"../../log":95,"../../scale":98,"../../util":107,"./selection":70,"./transforms/scales":75,"tslib":5}],69:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require("../../util"); var selection_1 = require("./selection"); var nearest_1 = require("./transforms/nearest"); var multi = { predicate: 'vlPoint', scaleDomain: 'vlPointDomain', signals: function (model, selCmpt) { var proj = selCmpt.project; var datum = nearest_1.default.has(selCmpt) ? '(item().isVoronoi ? datum.datum : datum)' : 'datum'; var bins = {}; var encodings = proj.map(function (p) { return util_1.stringValue(p.channel); }).filter(function (e) { return e; }).join(', '); var fields = proj.map(function (p) { return util_1.stringValue(p.field); }).join(', '); var values = proj.map(function (p) { var channel = p.channel; var fieldDef = model.fieldDef(channel); // Binned fields should capture extents, for a range test against the raw field. // FIXME: Arvind -- please log proper warning when the specified encoding channel has no field return (fieldDef && fieldDef.bin) ? (bins[p.field] = 1, "[" + datum + "[" + util_1.stringValue(model.field(channel, { binSuffix: 'start' })) + "], " + (datum + "[" + util_1.stringValue(model.field(channel, { binSuffix: 'end' })) + "]]")) : datum + "[" + util_1.stringValue(p.field) + "]"; }).join(', '); return [{ name: selCmpt.name + selection_1.TUPLE, value: {}, on: [{ events: selCmpt.events, update: "datum && {unit: " + util_1.stringValue(model.getName('')) + ", " + ("encodings: [" + encodings + "], fields: [" + fields + "], values: [" + values + "]") + (util_1.keys(bins).length ? ", bins: " + JSON.stringify(bins) + "}" : '}') }] }]; }, modifyExpr: function (model, selCmpt) { var tpl = selCmpt.name + selection_1.TUPLE; return tpl + ', ' + (selCmpt.resolve === 'global' ? 'null' : "{unit: " + util_1.stringValue(model.getName('')) + "}"); } }; exports.default = multi; },{"../../util":107,"./selection":70,"./transforms/nearest":73}],70:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var vega_event_selector_1 = require("vega-event-selector"); var channel_1 = require("../../channel"); var log_1 = require("../../log"); var util_1 = require("../../util"); var layer_1 = require("../layer"); var unit_1 = require("../unit"); var interval_1 = require("./interval"); var multi_1 = require("./multi"); var single_1 = require("./single"); var transforms_1 = require("./transforms/transforms"); exports.STORE = '_store'; exports.TUPLE = '_tuple'; exports.MODIFY = '_modify'; exports.SELECTION_DOMAIN = '_selection_domain_'; function parseUnitSelection(model, selDefs) { var selCmpts = {}; var selectionConfig = model.config.selection; var _loop_1 = function (name_1) { if (!selDefs.hasOwnProperty(name_1)) { return "continue"; } var selDef = selDefs[name_1]; var cfg = selectionConfig[selDef.type]; // Set default values from config if a property hasn't been specified, // or if it is true. E.g., "translate": true should use the default // event handlers for translate. However, true may be a valid value for // a property (e.g., "nearest": true). for (var key in cfg) { // A selection should contain either `encodings` or `fields`, only use // default values for these two values if neither of them is specified. if ((key === 'encodings' && selDef.fields) || (key === 'fields' && selDef.encodings)) { continue; } if (selDef[key] === undefined || selDef[key] === true) { selDef[key] = cfg[key] || selDef[key]; } } name_1 = util_1.varName(name_1); var selCmpt = selCmpts[name_1] = util_1.extend({}, selDef, { name: name_1, events: util_1.isString(selDef.on) ? vega_event_selector_1.selector(selDef.on, 'scope') : selDef.on, }); transforms_1.forEachTransform(selCmpt, function (txCompiler) { if (txCompiler.parse) { txCompiler.parse(model, selDef, selCmpt); } }); }; for (var name_1 in selDefs) { _loop_1(name_1); } return selCmpts; } exports.parseUnitSelection = parseUnitSelection; function assembleUnitSelectionSignals(model, signals) { forEachSelection(model, function (selCmpt, selCompiler) { var name = selCmpt.name; var modifyExpr = selCompiler.modifyExpr(model, selCmpt); signals.push.apply(signals, selCompiler.signals(model, selCmpt)); transforms_1.forEachTransform(selCmpt, function (txCompiler) { if (txCompiler.signals) { signals = txCompiler.signals(model, selCmpt, signals); } if (txCompiler.modifyExpr) { modifyExpr = txCompiler.modifyExpr(model, selCmpt, modifyExpr); } }); signals.push({ name: name + exports.MODIFY, on: [{ events: { signal: name + exports.TUPLE }, update: "modify(" + util_1.stringValue(selCmpt.name + exports.STORE) + ", " + modifyExpr + ")" }] }); }); return signals; } exports.assembleUnitSelectionSignals = assembleUnitSelectionSignals; function assembleTopLevelSignals(model, signals) { var needsUnit = false; forEachSelection(model, function (selCmpt, selCompiler) { if (selCompiler.topLevelSignals) { signals = selCompiler.topLevelSignals(model, selCmpt, signals); } transforms_1.forEachTransform(selCmpt, function (txCompiler) { if (txCompiler.topLevelSignals) { signals = txCompiler.topLevelSignals(model, selCmpt, signals); } }); needsUnit = true; }); if (needsUnit) { var hasUnit = signals.filter(function (s) { return s.name === 'unit'; }); if (!(hasUnit.length)) { signals.unshift({ name: 'unit', value: {}, on: [{ events: 'mousemove', update: 'group()._id ? group() : unit' }] }); } } return signals; } exports.assembleTopLevelSignals = assembleTopLevelSignals; function assembleUnitSelectionData(model, data) { forEachSelection(model, function (selCmpt) { var contains = data.filter(function (d) { return d.name === selCmpt.name + exports.STORE; }); if (!contains.length) { data.push({ name: selCmpt.name + exports.STORE }); } }); return data; } exports.assembleUnitSelectionData = assembleUnitSelectionData; function assembleUnitSelectionMarks(model, marks) { var clipGroup = false; var selMarks = marks; forEachSelection(model, function (selCmpt, selCompiler) { selMarks = selCompiler.marks ? selCompiler.marks(model, selCmpt, selMarks) : selMarks; transforms_1.forEachTransform(selCmpt, function (txCompiler) { clipGroup = clipGroup || txCompiler.clipGroup; if (txCompiler.marks) { selMarks = txCompiler.marks(model, selCmpt, marks, selMarks); } }); }); // In a layered spec, we want to clip all layers together rather than // only the layer within which the selection is defined. Propagate // our assembled state up and let the LayerModel make the right call. if (model.parent && model.parent instanceof layer_1.LayerModel) { return [selMarks, clipMarks]; } else { return clipGroup ? clipMarks(selMarks) : selMarks; } } exports.assembleUnitSelectionMarks = assembleUnitSelectionMarks; function assembleLayerSelectionMarks(model, marks) { var clipGroup = false; model.children.forEach(function (child) { if (child instanceof unit_1.UnitModel) { var unit = assembleUnitSelectionMarks(child, marks); marks = unit[0]; clipGroup = clipGroup || unit[1]; } }); return clipGroup ? clipMarks(marks) : marks; } exports.assembleLayerSelectionMarks = assembleLayerSelectionMarks; var PREDICATES_OPS = { global: '"union", "all"', independent: '"intersect", "unit"', union: '"union", "all"', union_others: '"union", "others"', intersect: '"intersect", "all"', intersect_others: '"intersect", "others"' }; function predicate(model, selections, dfnode) { function expr(name) { var vname = util_1.varName(name); var selCmpt = model.getSelectionComponent(vname, name); var store = util_1.stringValue(vname + exports.STORE); var op = PREDICATES_OPS[selCmpt.resolve]; if (selCmpt.timeUnit) { var child = dfnode || model.component.data.main; var tunode = selCmpt.timeUnit.clone(); if (child.parent) { tunode.insertAsParentOf(child); } else { child.parent = tunode; } } return compiler(selCmpt.type).predicate + ("(" + store + ", " + util_1.stringValue(model.getName('')) + ", datum, " + op + ")"); } return util_1.logicalExpr(selections, expr); } exports.predicate = predicate; // Selections are parsed _after_ scales. If a scale domain is set to // use a selection, the SELECTION_DOMAIN constant is used as the // domainRaw.signal during scale.parse and then replaced with the necessary // selection expression function during scale.assemble. To not pollute the // type signatures to account for this setup, the selection domain definition // is coerced to a string and appended to SELECTION_DOMAIN. function isRawSelectionDomain(domainRaw) { return domainRaw.signal.indexOf(exports.SELECTION_DOMAIN) >= 0; } exports.isRawSelectionDomain = isRawSelectionDomain; function selectionScaleDomain(model, domainRaw) { var selDomain = JSON.parse(domainRaw.signal.replace(exports.SELECTION_DOMAIN, '')); var name = util_1.varName(selDomain.selection); var selCmpt = model.component.selection && model.component.selection[name]; if (selCmpt) { log_1.warn('Use "bind": "scales" to setup a binding for scales and selections within the same view.'); } else if (!selDomain.encoding && !selDomain.field) { log_1.warn('A "field" or "encoding" must be specified when using a selection as a scale domain.'); } else { selCmpt = model.getSelectionComponent(name, selDomain.selection); return { signal: compiler(selCmpt.type).scaleDomain + ("(" + util_1.stringValue(name + exports.STORE) + ", " + util_1.stringValue(selDomain.encoding || null) + ", ") + (util_1.stringValue(selDomain.field || null) + ", " + PREDICATES_OPS[selCmpt.resolve] + ")") }; } return { signal: 'null' }; } exports.selectionScaleDomain = selectionScaleDomain; // Utility functions function forEachSelection(model, cb) { var selections = model.component.selection; for (var name_2 in selections) { if (selections.hasOwnProperty(name_2)) { var sel = selections[name_2]; cb(sel, compiler(sel.type)); } } } function compiler(type) { switch (type) { case 'single': return single_1.default; case 'multi': return multi_1.default; case 'interval': return interval_1.default; } return null; } function channelSignalName(selCmpt, channel, range) { return util_1.varName(selCmpt.name + '_' + (range === 'visual' ? channel : selCmpt.fields[channel])); } exports.channelSignalName = channelSignalName; function clipMarks(marks) { return marks.map(function (m) { return (m.clip = true, m); }); } function spatialProjections(selCmpt) { var x = null; var xi = null; var y = null; var yi = null; selCmpt.project.forEach(function (p, i) { if (p.channel === channel_1.X) { x = p; xi = i; } else if (p.channel === channel_1.Y) { y = p; yi = i; } }); return { x: x, xi: xi, y: y, yi: yi }; } exports.spatialProjections = spatialProjections; },{"../../channel":12,"../../log":95,"../../util":107,"../layer":37,"../unit":81,"./interval":68,"./multi":69,"./single":71,"./transforms/transforms":77,"vega-event-selector":6}],71:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require("../../util"); var multi_1 = require("./multi"); var selection_1 = require("./selection"); var single = { predicate: multi_1.default.predicate, scaleDomain: multi_1.default.scaleDomain, signals: multi_1.default.signals, topLevelSignals: function (model, selCmpt, signals) { var hasSignal = signals.filter(function (s) { return s.name === selCmpt.name; }); var data = "data(" + util_1.stringValue(selCmpt.name + selection_1.STORE) + ")"; var values = data + "[0].values"; return hasSignal.length ? signals : signals.concat({ name: selCmpt.name, update: data + ".length && {" + selCmpt.project.map(function (p, i) { return p.field + ": " + values + "[" + i + "]"; }).join(', ') + '}' }); }, modifyExpr: function (model, selCmpt) { var tpl = selCmpt.name + selection_1.TUPLE; return tpl + ', ' + (selCmpt.resolve === 'global' ? 'true' : "{unit: " + util_1.stringValue(model.getName('')) + "}"); } }; exports.default = single; },{"../../util":107,"./multi":69,"./selection":70}],72:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require("../../../util"); var selection_1 = require("../selection"); var nearest_1 = require("./nearest"); var inputBindings = { has: function (selCmpt) { return selCmpt.type === 'single' && selCmpt.resolve === 'global' && selCmpt.bind && selCmpt.bind !== 'scales'; }, topLevelSignals: function (model, selCmpt, signals) { var name = selCmpt.name; var proj = selCmpt.project; var bind = selCmpt.bind; var datum = nearest_1.default.has(selCmpt) ? '(item().isVoronoi ? datum.datum : datum)' : 'datum'; proj.forEach(function (p) { signals.unshift({ name: name + id(p.field), value: '', on: [{ events: selCmpt.events, update: "datum && " + datum + "[" + util_1.stringValue(p.field) + "]" }], bind: bind[p.field] || bind[p.channel] || bind }); }); return signals; }, signals: function (model, selCmpt, signals) { var name = selCmpt.name; var proj = selCmpt.project; var signal = signals.filter(function (s) { return s.name === name + selection_1.TUPLE; })[0]; var fields = proj.map(function (p) { return util_1.stringValue(p.field); }).join(', '); var values = proj.map(function (p) { return name + id(p.field); }).join(', '); signal.update = "{fields: [" + fields + "], values: [" + values + "]}"; delete signal.value; delete signal.on; return signals; } }; exports.default = inputBindings; function id(str) { return '_' + str.replace(/\W/g, '_'); } },{"../../../util":107,"../selection":70,"./nearest":73}],73:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var selection_1 = require("../selection"); var VORONOI = 'voronoi'; var nearest = { has: function (selCmpt) { return selCmpt.type !== 'interval' && selCmpt.nearest; }, marks: function (model, selCmpt, marks, selMarks) { var _a = selection_1.spatialProjections(selCmpt), x = _a.x, y = _a.y; var mark = marks[0]; var index = selMarks.indexOf(mark); var isPathgroup = mark.name === model.getName('pathgroup'); var exists = (function (m) { return m.name && m.name.indexOf(VORONOI) >= 0; }); var cellDef = { name: model.getName(VORONOI), type: 'path', from: { data: model.getName('marks') }, encode: { enter: { fill: { value: 'transparent' }, strokeWidth: { value: 0.35 }, stroke: { value: 'transparent' }, isVoronoi: { value: true } } }, transform: [{ type: 'voronoi', x: (x || (!x && !y)) ? 'datum.x' : { expr: '0' }, y: (y || (!x && !y)) ? 'datum.y' : { expr: '0' }, size: [model.getSizeSignalRef('width'), model.getSizeSignalRef('height')] }] }; if (isPathgroup && !mark.marks.filter(exists).length) { mark.marks.push(cellDef); selMarks.splice(index, 1, mark); } else if (!isPathgroup && !selMarks.filter(exists).length) { selMarks.splice(index + 1, 0, cellDef); } return selMarks; } }; exports.default = nearest; },{"../selection":70}],74:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var log = require("../../../log"); var util_1 = require("../../../util"); var timeunit_1 = require("../../data/timeunit"); var project = { has: function (selDef) { return selDef.fields !== undefined || selDef.encodings !== undefined; }, parse: function (model, selDef, selCmpt) { var channels = {}; var timeUnits = {}; // TODO: find a possible channel mapping for these fields. (selDef.fields || []).forEach(function (field) { return channels[field] = null; }); (selDef.encodings || []).forEach(function (channel) { var fieldDef = model.fieldDef(channel); if (fieldDef) { if (fieldDef.timeUnit) { var tuField = model.field(channel); channels[tuField] = channel; // Construct TimeUnitComponents which will be combined into a // TimeUnitNode. This node may need to be inserted into the // dataflow if the selection is used across views that do not // have these time units defined. timeUnits[tuField] = { as: tuField, field: fieldDef.field, timeUnit: fieldDef.timeUnit }; } else { channels[fieldDef.field] = channel; } } else { log.warn(log.message.cannotProjectOnChannelWithoutField(channel)); } }); var projection = selCmpt.project || (selCmpt.project = []); for (var field in channels) { if (channels.hasOwnProperty(field)) { projection.push({ field: field, channel: channels[field] }); } } var fields = selCmpt.fields || (selCmpt.fields = {}); projection.filter(function (p) { return p.channel; }).forEach(function (p) { return fields[p.channel] = p.field; }); if (util_1.keys(timeUnits).length) { selCmpt.timeUnit = new timeunit_1.TimeUnitNode(timeUnits); } } }; exports.default = project; },{"../../../log":95,"../../../util":107,"../../data/timeunit":34}],75:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var log_1 = require("../../../log"); var scale_1 = require("../../../scale"); var util_1 = require("../../../util"); var selection_1 = require("../selection"); var scaleBindings = { clipGroup: true, has: function (selCmpt) { return selCmpt.type === 'interval' && selCmpt.resolve === 'global' && selCmpt.bind && selCmpt.bind === 'scales'; }, parse: function (model, selDef, selCmpt) { var bound = selCmpt.scales = []; selCmpt.project.forEach(function (p) { var channel = p.channel; var scale = model.getScaleComponent(channel); var scaleType = scale ? scale.get('type') : undefined; if (!scale || !scale_1.hasContinuousDomain(scaleType) || scale_1.isBinScale(scaleType)) { log_1.warn('Scale bindings are currently only supported for scales with unbinned, continuous domains.'); return; } scale.set('domainRaw', { signal: selection_1.channelSignalName(selCmpt, channel, 'data') }, true); bound.push(channel); }); }, topLevelSignals: function (model, selCmpt, signals) { // Top-level signals are only needed when coordinating composed views. if (!model.parent) { return signals; } var channels = selCmpt.scales.filter(function (channel) { return !(signals.filter(function (s) { return s.name === selection_1.channelSignalName(selCmpt, channel, 'data'); }).length); }); return signals.concat(channels.map(function (channel) { return { name: selection_1.channelSignalName(selCmpt, channel, 'data') }; })); }, signals: function (model, selCmpt, signals) { // Nested signals need only push to top-level signals when within composed views. if (model.parent) { selCmpt.scales.forEach(function (channel) { var signal = signals.filter(function (s) { return s.name === selection_1.channelSignalName(selCmpt, channel, 'data'); })[0]; signal.push = 'outer'; delete signal.value; delete signal.update; }); } return signals; } }; exports.default = scaleBindings; function domain(model, channel) { var scale = util_1.stringValue(model.scaleName(channel)); return "domain(" + scale + ")"; } exports.domain = domain; },{"../../../log":95,"../../../scale":98,"../../../util":107,"../selection":70}],76:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require("../../../util"); var selection_1 = require("../selection"); var TOGGLE = '_toggle'; var toggle = { has: function (selCmpt) { return selCmpt.type === 'multi' && selCmpt.toggle; }, signals: function (model, selCmpt, signals) { return signals.concat({ name: selCmpt.name + TOGGLE, value: false, on: [{ events: selCmpt.events, update: selCmpt.toggle }] }); }, modifyExpr: function (model, selCmpt, expr) { var tpl = selCmpt.name + selection_1.TUPLE; var signal = selCmpt.name + TOGGLE; return signal + " ? null : " + tpl + ", " + (selCmpt.resolve === 'global' ? signal + " ? null : true, " : signal + " ? null : {unit: " + util_1.stringValue(model.getName('')) + "}, ") + (signal + " ? " + tpl + " : null"); } }; exports.default = toggle; },{"../../../util":107,"../selection":70}],77:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var inputs_1 = require("./inputs"); var nearest_1 = require("./nearest"); var project_1 = require("./project"); var scales_1 = require("./scales"); var toggle_1 = require("./toggle"); var translate_1 = require("./translate"); var zoom_1 = require("./zoom"); var compilers = { project: project_1.default, toggle: toggle_1.default, scales: scales_1.default, translate: translate_1.default, zoom: zoom_1.default, inputs: inputs_1.default, nearest: nearest_1.default }; function forEachTransform(selCmpt, cb) { for (var t in compilers) { if (compilers[t].has(selCmpt)) { cb(compilers[t]); } } } exports.forEachTransform = forEachTransform; },{"./inputs":72,"./nearest":73,"./project":74,"./scales":75,"./toggle":76,"./translate":78,"./zoom":79}],78:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var vega_event_selector_1 = require("vega-event-selector"); var channel_1 = require("../../../channel"); var interval_1 = require("../interval"); var selection_1 = require("../selection"); var scales_1 = require("./scales"); var ANCHOR = '_translate_anchor'; var DELTA = '_translate_delta'; var translate = { has: function (selCmpt) { return selCmpt.type === 'interval' && selCmpt.translate; }, signals: function (model, selCmpt, signals) { var name = selCmpt.name; var hasScales = scales_1.default.has(selCmpt); var anchor = name + ANCHOR; var _a = selection_1.spatialProjections(selCmpt), x = _a.x, y = _a.y; var events = vega_event_selector_1.selector(selCmpt.translate, 'scope'); if (!hasScales) { events = events.map(function (e) { return (e.between[0].markname = name + interval_1.BRUSH, e); }); } signals.push({ name: anchor, value: {}, on: [{ events: events.map(function (e) { return e.between[0]; }), update: '{x: x(unit), y: y(unit)' + (x !== null ? ', extent_x: ' + (hasScales ? scales_1.domain(model, channel_1.X) : "slice(" + selection_1.channelSignalName(selCmpt, 'x', 'visual') + ")") : '') + (y !== null ? ', extent_y: ' + (hasScales ? scales_1.domain(model, channel_1.Y) : "slice(" + selection_1.channelSignalName(selCmpt, 'y', 'visual') + ")") : '') + '}' }] }, { name: name + DELTA, value: {}, on: [{ events: events, update: "{x: " + anchor + ".x - x(unit), y: " + anchor + ".y - y(unit)}" }] }); if (x !== null) { onDelta(model, selCmpt, channel_1.X, 'width', signals); } if (y !== null) { onDelta(model, selCmpt, channel_1.Y, 'height', signals); } return signals; } }; exports.default = translate; function onDelta(model, selCmpt, channel, size, signals) { var name = selCmpt.name; var hasScales = scales_1.default.has(selCmpt); var signal = signals.filter(function (s) { return s.name === selection_1.channelSignalName(selCmpt, channel, hasScales ? 'data' : 'visual'); })[0]; var anchor = name + ANCHOR; var delta = name + DELTA; var sizeSg = model.getSizeSignalRef(size).signal; var scaleType = model.getScaleComponent(channel).get('type'); var sign = hasScales && channel === channel_1.X ? '-' : ''; // Invert delta when panning x-scales. var extent = anchor + ".extent_" + channel; var offset = "" + sign + delta + "." + channel + " / " + (hasScales ? "" + sizeSg : "span(" + extent + ")"); var panFn = !hasScales ? 'panLinear' : scaleType === 'log' ? 'panLog' : scaleType === 'pow' ? 'panPow' : 'panLinear'; var update = panFn + "(" + extent + ", " + offset + ")"; signal.on.push({ events: { signal: delta }, update: hasScales ? update : "clampRange(" + update + ", 0, " + sizeSg + ")" }); } },{"../../../channel":12,"../interval":68,"../selection":70,"./scales":75,"vega-event-selector":6}],79:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var vega_event_selector_1 = require("vega-event-selector"); var channel_1 = require("../../../channel"); var util_1 = require("../../../util"); var interval_1 = require("../interval"); var selection_1 = require("../selection"); var scales_1 = require("./scales"); var ANCHOR = '_zoom_anchor'; var DELTA = '_zoom_delta'; var zoom = { has: function (selCmpt) { return selCmpt.type === 'interval' && selCmpt.zoom; }, signals: function (model, selCmpt, signals) { var name = selCmpt.name; var hasScales = scales_1.default.has(selCmpt); var delta = name + DELTA; var _a = selection_1.spatialProjections(selCmpt), x = _a.x, y = _a.y; var sx = util_1.stringValue(model.scaleName(channel_1.X)); var sy = util_1.stringValue(model.scaleName(channel_1.Y)); var events = vega_event_selector_1.selector(selCmpt.zoom, 'scope'); if (!hasScales) { events = events.map(function (e) { return (e.markname = name + interval_1.BRUSH, e); }); } signals.push({ name: name + ANCHOR, on: [{ events: events, update: !hasScales ? "{x: x(unit), y: y(unit)}" : '{' + [ (sx ? "x: invert(" + sx + ", x(unit))" : ''), (sy ? "y: invert(" + sy + ", y(unit))" : '') ].filter(function (expr) { return !!expr; }).join(', ') + '}' }] }, { name: delta, on: [{ events: events, force: true, update: 'pow(1.001, event.deltaY * pow(16, event.deltaMode))' }] }); if (x !== null) { onDelta(model, selCmpt, 'x', 'width', signals); } if (y !== null) { onDelta(model, selCmpt, 'y', 'height', signals); } return signals; } }; exports.default = zoom; function onDelta(model, selCmpt, channel, size, signals) { var name = selCmpt.name; var hasScales = scales_1.default.has(selCmpt); var signal = signals.filter(function (s) { return s.name === selection_1.channelSignalName(selCmpt, channel, hasScales ? 'data' : 'visual'); })[0]; var sizeSg = model.getSizeSignalRef(size).signal; var scaleType = model.getScaleComponent(channel).get('type'); var base = hasScales ? scales_1.domain(model, channel) : signal.name; var delta = name + DELTA; var anchor = "" + name + ANCHOR + "." + channel; var zoomFn = !hasScales ? 'zoomLinear' : scaleType === 'log' ? 'zoomLog' : scaleType === 'pow' ? 'zoomPow' : 'zoomLinear'; var update = zoomFn + "(" + base + ", " + anchor + ", " + delta + ")"; signal.on.push({ events: { signal: delta }, update: hasScales ? update : "clampRange(" + update + ", 0, " + sizeSg + ")" }); } },{"../../../channel":12,"../../../util":107,"../interval":68,"../selection":70,"./scales":75,"vega-event-selector":6}],80:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var log = require("../log"); var util_1 = require("../util"); /** * Generic classs for storing properties that are explicitly specified and implicitly determined by the compiler. */ var Split = (function () { function Split(explicit, implicit) { if (explicit === void 0) { explicit = {}; } if (implicit === void 0) { implicit = {}; } this.explicit = explicit; this.implicit = implicit; } Split.prototype.clone = function () { return new Split(util_1.duplicate(this.explicit), util_1.duplicate(this.implicit)); }; Split.prototype.combine = function (keys) { var _this = this; if (keys === void 0) { keys = []; } var base = keys.reduce(function (b, key) { var value = _this.get(key); if (value) { b[key] = value; } return b; }, {}); // FIXME remove "as any". // Add "as any" to avoid an error "Spread types may only be created from object types". return tslib_1.__assign({}, base, this.explicit, this.implicit); }; Split.prototype.get = function (key) { // Explicit has higher precedence return this.explicit[key] !== undefined ? this.explicit[key] : this.implicit[key]; }; Split.prototype.getWithExplicit = function (key) { // Explicit has higher precedence if (this.explicit[key] !== undefined) { return { explicit: true, value: this.explicit[key] }; } else if (this.implicit[key] !== undefined) { return { explicit: false, value: this.implicit[key] }; } return { explicit: false, value: undefined }; }; Split.prototype.setWithExplicit = function (key, value) { if (value.value !== undefined) { this.set(key, value.value, value.explicit); } }; Split.prototype.set = function (key, value, explicit) { delete this[explicit ? 'implicit' : 'explicit'][key]; this[explicit ? 'explicit' : 'implicit'][key] = value; return this; }; Split.prototype.copyKeyFromSplit = function (key, s) { // Explicit has higher precedence if (s.explicit[key] !== undefined) { this.set(key, s.explicit[key], true); } else if (s.implicit[key] !== undefined) { this.set(key, s.implicit[key], false); } }; Split.prototype.copyKeyFromObject = function (key, s) { // Explicit has higher precedence if (s[key] !== undefined) { this.set(key, s[key], true); } }; Split.prototype.extend = function (mixins, explicit) { return new Split(explicit ? tslib_1.__assign({}, this.explicit, mixins) : this.explicit, explicit ? this.implicit : tslib_1.__assign({}, this.implicit, mixins)); }; return Split; }()); exports.Split = Split; function makeExplicit(value) { return { explicit: true, value: value }; } exports.makeExplicit = makeExplicit; function makeImplicit(value) { return { explicit: false, value: value }; } exports.makeImplicit = makeImplicit; function tieBreakByComparing(compare) { return function (v1, v2, property, propertyOf) { var diff = compare(v1.value, v2.value); if (diff > 0) { return v1; } else if (diff < 0) { return v2; } return defaultTieBreaker(v1, v2, property, propertyOf); }; } exports.tieBreakByComparing = tieBreakByComparing; function defaultTieBreaker(v1, v2, property, propertyOf) { if (v1.explicit && v2.explicit) { log.warn(log.message.mergeConflictingProperty(property, propertyOf, v1.value, v2.value)); } // If equal score, prefer v1. return v1; } exports.defaultTieBreaker = defaultTieBreaker; function mergeValuesWithExplicit(v1, v2, property, propertyOf, tieBreaker) { if (tieBreaker === void 0) { tieBreaker = defaultTieBreaker; } if (v1 === undefined || v1.value === undefined) { // For first run return v2; } if (v1.explicit && !v2.explicit) { return v1; } else if (v2.explicit && !v1.explicit) { return v2; } else if (v1.value === v2.value) { return v1; } else { return tieBreaker(v1, v2, property, propertyOf); } } exports.mergeValuesWithExplicit = mergeValuesWithExplicit; },{"../log":95,"../util":107,"tslib":5}],81:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var channel_1 = require("../channel"); var vlEncoding = require("../encoding"); // TODO: remove var encoding_1 = require("../encoding"); var fielddef_1 = require("../fielddef"); var mark_1 = require("../mark"); var scale_1 = require("../scale"); var stack_1 = require("../stack"); var util_1 = require("../util"); var parse_1 = require("./axis/parse"); var common_1 = require("./common"); var assemble_1 = require("./data/assemble"); var parse_2 = require("./data/parse"); var facet_1 = require("./facet"); var layer_1 = require("./layer"); var assemble_2 = require("./layout/assemble"); var parse_3 = require("./layout/parse"); var parse_4 = require("./legend/parse"); var init_1 = require("./mark/init"); var mark_2 = require("./mark/mark"); var model_1 = require("./model"); var repeat_1 = require("./repeat"); var selection_1 = require("./selection/selection"); /** * Internal model of Vega-Lite specification for the compiler. */ var UnitModel = (function (_super) { tslib_1.__extends(UnitModel, _super); function UnitModel(spec, parent, parentGivenName, parentGivenSize, repeater, config) { if (parentGivenSize === void 0) { parentGivenSize = {}; } var _this = _super.call(this, spec, parent, parentGivenName, config, {}) || this; _this.specifiedScales = {}; _this.specifiedAxes = {}; _this.specifiedLegends = {}; _this.selection = {}; _this.children = []; _this.initSize(tslib_1.__assign({}, parentGivenSize, (spec.width ? { width: spec.width } : {}), (spec.height ? { height: spec.height } : {}))); // FIXME(#2041): copy config.facet.cell to config.cell -- this seems incorrect and should be rewritten _this.initFacetCellConfig(); _this.markDef = mark_1.isMarkDef(spec.mark) ? tslib_1.__assign({}, spec.mark) : { type: spec.mark }; var mark = _this.markDef.type; var encoding = _this.encoding = encoding_1.normalizeEncoding(repeat_1.replaceRepeaterInEncoding(spec.encoding || {}, repeater), mark); // calculate stack properties _this.stack = stack_1.stack(mark, encoding, _this.config.stack); _this.specifiedScales = _this.initScales(mark, encoding); // FIXME: this one seems out of place! _this.encoding = init_1.initEncoding(_this.markDef, encoding, _this.stack, _this.config); _this.specifiedAxes = _this.initAxes(encoding); _this.specifiedLegends = _this.initLegend(encoding); // Selections will be initialized upon parse. _this.selection = spec.selection; return _this; } /** * Return specified Vega-lite scale domain for a particular channel * @param channel */ UnitModel.prototype.scaleDomain = function (channel) { var scale = this.specifiedScales[channel]; return scale ? scale.domain : undefined; }; UnitModel.prototype.hasDiscreteDomain = function (channel) { if (channel_1.isScaleChannel(channel)) { var scaleCmpt = this.getScaleComponent(channel); return scaleCmpt && scale_1.hasDiscreteDomain(scaleCmpt.get('type')); } return false; }; UnitModel.prototype.sort = function (channel) { return (this.getMapping()[channel] || {}).sort; }; UnitModel.prototype.axis = function (channel) { return this.specifiedAxes[channel]; }; UnitModel.prototype.legend = function (channel) { return this.specifiedLegends[channel]; }; UnitModel.prototype.initFacetCellConfig = function () { var config = this.config; var ancestor = this.parent; var hasFacetAncestor = false; while (ancestor !== null) { if (ancestor instanceof facet_1.FacetModel) { hasFacetAncestor = true; break; } ancestor = ancestor.parent; } if (hasFacetAncestor) { config.cell = util_1.extend({}, config.cell, config.facet.cell); } }; UnitModel.prototype.initScales = function (mark, encoding) { return channel_1.SCALE_CHANNELS.reduce(function (scales, channel) { var fieldDef; var specifiedScale; var channelDef = encoding[channel]; if (fielddef_1.isFieldDef(channelDef)) { fieldDef = channelDef; specifiedScale = channelDef.scale; } else if (fielddef_1.isConditionalDef(channelDef) && fielddef_1.isFieldDef(channelDef.condition)) { fieldDef = channelDef.condition; specifiedScale = channelDef.condition.scale; } else if (channel === 'x') { fieldDef = fielddef_1.getFieldDef(encoding.x2); } else if (channel === 'y') { fieldDef = fielddef_1.getFieldDef(encoding.y2); } if (fieldDef) { scales[channel] = specifiedScale || {}; } return scales; }, {}); }; UnitModel.prototype.initAxes = function (encoding) { return [channel_1.X, channel_1.Y].reduce(function (_axis, channel) { // Position Axis // TODO: handle ConditionFieldDef var channelDef = encoding[channel]; if (fielddef_1.isFieldDef(channelDef) || (channel === channel_1.X && fielddef_1.isFieldDef(encoding.x2)) || (channel === channel_1.Y && fielddef_1.isFieldDef(encoding.y2))) { var axisSpec = fielddef_1.isFieldDef(channelDef) ? channelDef.axis : null; // We no longer support false in the schema, but we keep false here for backward compatability. if (axisSpec !== null && axisSpec !== false) { _axis[channel] = tslib_1.__assign({}, axisSpec); } } return _axis; }, {}); }; UnitModel.prototype.initLegend = function (encoding) { return channel_1.NONSPATIAL_SCALE_CHANNELS.reduce(function (_legend, channel) { var channelDef = encoding[channel]; if (channelDef) { var legend = fielddef_1.isFieldDef(channelDef) ? channelDef.legend : (channelDef.condition && fielddef_1.isFieldDef(channelDef.condition)) ? channelDef.condition.legend : null; if (legend !== null && legend !== false) { _legend[channel] = tslib_1.__assign({}, legend); } } return _legend; }, {}); }; UnitModel.prototype.parseData = function () { this.component.data = parse_2.parseData(this); }; UnitModel.prototype.parseLayoutSize = function () { parse_3.parseUnitLayoutSize(this); }; UnitModel.prototype.parseSelection = function () { this.component.selection = selection_1.parseUnitSelection(this, this.selection); }; UnitModel.prototype.parseMarkGroup = function () { this.component.mark = mark_2.parseMarkGroup(this); }; UnitModel.prototype.parseAxisAndHeader = function () { this.component.axes = parse_1.parseUnitAxis(this); }; UnitModel.prototype.parseLegend = function () { this.component.legends = parse_4.parseUnitLegend(this); }; UnitModel.prototype.assembleData = function () { if (!this.parent) { // only assemble data in the root return assemble_1.assembleData(this.component.data); } return []; }; UnitModel.prototype.assembleSelectionTopLevelSignals = function (signals) { return selection_1.assembleTopLevelSignals(this, signals); }; UnitModel.prototype.assembleSelectionSignals = function () { return selection_1.assembleUnitSelectionSignals(this, []); }; UnitModel.prototype.assembleSelectionData = function (data) { return selection_1.assembleUnitSelectionData(this, data); }; UnitModel.prototype.assembleLayout = function () { return null; }; UnitModel.prototype.assembleLayoutSignals = function () { return assemble_2.assembleLayoutSignals(this); }; UnitModel.prototype.assembleMarks = function () { var marks = this.component.mark || []; // If this unit is part of a layer, selections should augment // all in concert rather than each unit individually. This // ensures correct interleaving of clipping and brushed marks. if (!this.parent || !(this.parent instanceof layer_1.LayerModel)) { marks = selection_1.assembleUnitSelectionMarks(this, marks); } return marks.map(this.correctDataNames); }; UnitModel.prototype.assembleParentGroupProperties = function () { return tslib_1.__assign({ width: this.getSizeSignalRef('width'), height: this.getSizeSignalRef('height') }, common_1.applyConfig({}, this.config.cell, mark_1.FILL_STROKE_CONFIG.concat(['clip']))); }; UnitModel.prototype.getMapping = function () { return this.encoding; }; UnitModel.prototype.toSpec = function (excludeConfig, excludeData) { var encoding = util_1.duplicate(this.encoding); var spec; spec = { mark: this.markDef, encoding: encoding }; if (!excludeConfig) { spec.config = util_1.duplicate(this.config); } if (!excludeData) { spec.data = util_1.duplicate(this.data); } // remove defaults return spec; }; UnitModel.prototype.mark = function () { return this.markDef.type; }; UnitModel.prototype.channelHasField = function (channel) { return vlEncoding.channelHasField(this.encoding, channel); }; UnitModel.prototype.fieldDef = function (channel) { var channelDef = this.encoding[channel]; return fielddef_1.getFieldDef(channelDef); }; /** Get "field" reference for vega */ UnitModel.prototype.field = function (channel, opt) { if (opt === void 0) { opt = {}; } var fieldDef = this.fieldDef(channel); if (!fieldDef) { return undefined; } if (fieldDef.bin) { opt = util_1.extend({ binSuffix: this.hasDiscreteDomain(channel) ? 'range' : 'start' }, opt); } return fielddef_1.field(fieldDef, opt); }; return UnitModel; }(model_1.ModelWithField)); exports.UnitModel = UnitModel; },{"../channel":12,"../encoding":88,"../fielddef":90,"../mark":97,"../scale":98,"../stack":102,"../util":107,"./axis/parse":16,"./common":18,"./data/assemble":22,"./data/parse":30,"./facet":36,"./layer":37,"./layout/assemble":38,"./layout/parse":40,"./legend/parse":44,"./mark/init":48,"./mark/mark":50,"./model":58,"./repeat":59,"./selection/selection":70,"tslib":5}],82:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var vega_util_1 = require("vega-util"); var encoding_1 = require("../encoding"); var encoding_2 = require("./../encoding"); var fielddef_1 = require("./../fielddef"); var log = require("./../log"); exports.BOXPLOT = 'box-plot'; function isBoxPlotDef(mark) { return !!mark['type']; } exports.isBoxPlotDef = isBoxPlotDef; exports.BOXPLOT_ROLES = ['boxWhisker', 'box', 'boxMid']; exports.VL_ONLY_BOXPLOT_CONFIG_PROPERTY_INDEX = { box: ['size'] }; var supportedChannels = ['x', 'y', 'color', 'detail', 'opacity', 'size']; function filterUnsupportedChannels(spec) { return tslib_1.__assign({}, spec, { encoding: encoding_1.reduce(spec.encoding, function (newEncoding, fieldDef, channel) { if (supportedChannels.indexOf(channel) > -1) { newEncoding[channel] = fieldDef; } else { log.warn(log.message.incompatibleChannel(channel, exports.BOXPLOT)); } return newEncoding; }, {}) }); } exports.filterUnsupportedChannels = filterUnsupportedChannels; function normalizeBoxPlot(spec, config) { spec = filterUnsupportedChannels(spec); // TODO: use selection var mark = spec.mark, encoding = spec.encoding, _sel = spec.selection, outerSpec = tslib_1.__rest(spec, ["mark", "encoding", "selection"]); var kIQRScalar = undefined; if (isBoxPlotDef(mark)) { if (mark.extent) { if (vega_util_1.isNumber(mark.extent)) { kIQRScalar = mark.extent; } } } var isMinMax = kIQRScalar === undefined; var orient = boxOrient(spec); var _a = boxParams(spec, orient, kIQRScalar), transform = _a.transform, continuousAxisChannelDef = _a.continuousAxisChannelDef, continuousAxis = _a.continuousAxis, encodingWithoutContinuousAxis = _a.encodingWithoutContinuousAxis; var size = encodingWithoutContinuousAxis.size, color = encodingWithoutContinuousAxis.color, nonPositionEncodingWithoutColorSize = tslib_1.__rest(encodingWithoutContinuousAxis, ["size", "color"]); var sizeMixins = size ? { size: size } : { size: { value: config.box.size } }; var continuousAxisScaleAndAxis = {}; if (continuousAxisChannelDef.scale) { continuousAxisScaleAndAxis['scale'] = continuousAxisChannelDef.scale; } if (continuousAxisChannelDef.axis) { continuousAxisScaleAndAxis['axis'] = continuousAxisChannelDef.axis; } return tslib_1.__assign({}, outerSpec, { transform: transform, layer: [ { mark: { type: 'rule', role: 'boxWhisker' }, encoding: tslib_1.__assign((_b = {}, _b[continuousAxis] = tslib_1.__assign({ field: 'lowerWhisker', type: continuousAxisChannelDef.type }, continuousAxisScaleAndAxis), _b[continuousAxis + '2'] = { field: 'lowerBox', type: continuousAxisChannelDef.type }, _b), nonPositionEncodingWithoutColorSize) }, { mark: { type: 'rule', role: 'boxWhisker' }, encoding: tslib_1.__assign((_c = {}, _c[continuousAxis] = { field: 'upperBox', type: continuousAxisChannelDef.type }, _c[continuousAxis + '2'] = { field: 'upperWhisker', type: continuousAxisChannelDef.type }, _c), nonPositionEncodingWithoutColorSize) }, { mark: { type: 'bar', role: 'box' }, encoding: tslib_1.__assign((_d = {}, _d[continuousAxis] = { field: 'lowerBox', type: continuousAxisChannelDef.type }, _d[continuousAxis + '2'] = { field: 'upperBox', type: continuousAxisChannelDef.type }, _d), encodingWithoutContinuousAxis, sizeMixins) }, { mark: { type: 'tick', role: 'boxMid' }, encoding: tslib_1.__assign((_e = {}, _e[continuousAxis] = { field: 'midBox', type: continuousAxisChannelDef.type }, _e), nonPositionEncodingWithoutColorSize, sizeMixins) } ] }); var _b, _c, _d, _e; } exports.normalizeBoxPlot = normalizeBoxPlot; function boxOrient(spec) { var mark = spec.mark, encoding = spec.encoding, outerSpec = tslib_1.__rest(spec, ["mark", "encoding"]); if (fielddef_1.isFieldDef(encoding.x) && fielddef_1.isContinuous(encoding.x)) { // x is continuous if (fielddef_1.isFieldDef(encoding.y) && fielddef_1.isContinuous(encoding.y)) { // both x and y are continuous if (encoding.x.aggregate === undefined && encoding.y.aggregate === exports.BOXPLOT) { return 'vertical'; } else if (encoding.y.aggregate === undefined && encoding.x.aggregate === exports.BOXPLOT) { return 'horizontal'; } else if (encoding.x.aggregate === exports.BOXPLOT && encoding.y.aggregate === exports.BOXPLOT) { throw new Error('Both x and y cannot have aggregate'); } else { if (isBoxPlotDef(mark) && mark.orient) { return mark.orient; } // default orientation = vertical return 'vertical'; } } // x is continuous but y is not return 'horizontal'; } else if (fielddef_1.isFieldDef(encoding.y) && fielddef_1.isContinuous(encoding.y)) { // y is continuous but x is not return 'vertical'; } else { // Neither x nor y is continuous. throw new Error('Need a valid continuous axis for boxplots'); } } function boxContinousAxis(spec, orient) { var mark = spec.mark, encoding = spec.encoding, outerSpec = tslib_1.__rest(spec, ["mark", "encoding"]); var continuousAxisChannelDef; var continuousAxis; if (orient === 'vertical') { continuousAxis = 'y'; continuousAxisChannelDef = encoding.y; // Safe to cast because if y is not continous fielddef, the orient would not be vertical. } else { continuousAxis = 'x'; continuousAxisChannelDef = encoding.x; // Safe to cast because if x is not continous fielddef, the orient would not be horizontal. } if (continuousAxisChannelDef && continuousAxisChannelDef.aggregate) { var aggregate = continuousAxisChannelDef.aggregate, continuousAxisWithoutAggregate = tslib_1.__rest(continuousAxisChannelDef, ["aggregate"]); if (aggregate !== exports.BOXPLOT) { log.warn("Continuous axis should not have customized aggregation function " + aggregate); } continuousAxisChannelDef = continuousAxisWithoutAggregate; } return { continuousAxisChannelDef: continuousAxisChannelDef, continuousAxis: continuousAxis }; } function boxParams(spec, orient, kIQRScalar) { var _a = boxContinousAxis(spec, orient), continuousAxisChannelDef = _a.continuousAxisChannelDef, continuousAxis = _a.continuousAxis; var encoding = spec.encoding; var isMinMax = kIQRScalar === undefined; var summarize = [ { aggregate: 'q1', field: continuousAxisChannelDef.field, as: 'lowerBox' }, { aggregate: 'q3', field: continuousAxisChannelDef.field, as: 'upperBox' }, { aggregate: 'median', field: continuousAxisChannelDef.field, as: 'midBox' } ]; var postAggregateCalculates = []; if (isMinMax) { summarize.push({ aggregate: 'min', field: continuousAxisChannelDef.field, as: 'lowerWhisker' }); summarize.push({ aggregate: 'max', field: continuousAxisChannelDef.field, as: 'upperWhisker' }); } else { postAggregateCalculates = [ { calculate: 'datum.upperBox - datum.lowerBox', as: 'IQR' }, { calculate: 'datum.lowerBox - datum.IQR * ' + kIQRScalar, as: 'lowerWhisker' }, { calculate: 'datum.upperBox + datum.IQR * ' + kIQRScalar, as: 'lowerWhisker' } ]; } var groupby = []; var bins = []; var timeUnits = []; var encodingWithoutContinuousAxis = {}; encoding_2.forEach(encoding, function (channelDef, channel) { if (channel === continuousAxis) { // Skip continuous axis as we already handle it separately return; } if (fielddef_1.isFieldDef(channelDef)) { if (channelDef.aggregate && channelDef.aggregate !== exports.BOXPLOT) { summarize.push({ aggregate: channelDef.aggregate, field: channelDef.field, as: fielddef_1.field(channelDef) }); } else if (channelDef.aggregate === undefined) { var transformedField = fielddef_1.field(channelDef); // Add bin or timeUnit transform if applicable var bin = channelDef.bin; if (bin) { var field_1 = channelDef.field; bins.push({ bin: bin, field: field_1, as: transformedField }); } else if (channelDef.timeUnit) { var timeUnit = channelDef.timeUnit, field_2 = channelDef.field; timeUnits.push({ timeUnit: timeUnit, field: field_2, as: transformedField }); } groupby.push(transformedField); } // now the field should refer to post-transformed field instead encodingWithoutContinuousAxis[channel] = { field: fielddef_1.field(channelDef), type: channelDef.type }; } else { // For value def, just copy encodingWithoutContinuousAxis[channel] = encoding[channel]; } }); return { transform: [].concat(bins, timeUnits, [{ summarize: summarize, groupby: groupby }], postAggregateCalculates), continuousAxisChannelDef: continuousAxisChannelDef, continuousAxis: continuousAxis, encodingWithoutContinuousAxis: encodingWithoutContinuousAxis }; } },{"../encoding":88,"./../encoding":88,"./../fielddef":90,"./../log":95,"tslib":5,"vega-util":7}],83:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); exports.ERRORBAR = 'error-bar'; function normalizeErrorBar(spec) { // TODO: use selection var _m = spec.mark, _sel = spec.selection, encoding = spec.encoding, outerSpec = tslib_1.__rest(spec, ["mark", "selection", "encoding"]); var _s = encoding.size, encodingWithoutSize = tslib_1.__rest(encoding, ["size"]); var _x2 = encoding.x2, _y2 = encoding.y2, encodingWithoutX2Y2 = tslib_1.__rest(encoding, ["x2", "y2"]); var _x = encodingWithoutX2Y2.x, _y = encodingWithoutX2Y2.y, encodingWithoutX_X2_Y_Y2 = tslib_1.__rest(encodingWithoutX2Y2, ["x", "y"]); if (!encoding.x2 && !encoding.y2) { throw new Error('Neither x2 or y2 provided'); } return tslib_1.__assign({}, outerSpec, { layer: [ { mark: 'rule', encoding: encodingWithoutSize }, { mark: 'tick', encoding: encodingWithoutX2Y2 }, { mark: 'tick', encoding: encoding.x2 ? tslib_1.__assign({ x: encoding.x2, y: encoding.y }, encodingWithoutX_X2_Y_Y2) : tslib_1.__assign({ x: encoding.x, y: encoding.y2 }, encodingWithoutX_X2_Y_Y2) } ] }); } exports.normalizeErrorBar = normalizeErrorBar; },{"tslib":5}],84:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var mark_1 = require("./../mark"); var boxplot_1 = require("./boxplot"); var errorbar_1 = require("./errorbar"); /** * Registry index for all composite mark's normalizer */ var normalizerRegistry = {}; function add(mark, normalizer) { normalizerRegistry[mark] = normalizer; } exports.add = add; function remove(mark) { delete normalizerRegistry[mark]; } exports.remove = remove; exports.COMPOSITE_MARK_ROLES = boxplot_1.BOXPLOT_ROLES; exports.VL_ONLY_COMPOSITE_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX = tslib_1.__assign({}, boxplot_1.VL_ONLY_BOXPLOT_CONFIG_PROPERTY_INDEX); add(boxplot_1.BOXPLOT, boxplot_1.normalizeBoxPlot); add(errorbar_1.ERRORBAR, errorbar_1.normalizeErrorBar); /** * Transform a unit spec with composite mark into a normal layer spec. */ function normalize( // This GenericUnitSpec has any as Encoding because unit specs with composite mark can have additional encoding channels. spec, config) { var mark = mark_1.isMarkDef(spec.mark) ? spec.mark.type : spec.mark; var normalizer = normalizerRegistry[mark]; if (normalizer) { return normalizer(spec, config); } throw new Error("Unregistered composite mark " + mark); } exports.normalize = normalize; },{"./../mark":97,"./boxplot":82,"./errorbar":83,"tslib":5}],85:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var compositemark_1 = require("./compositemark"); var index_1 = require("./compositemark/index"); var guide_1 = require("./guide"); var legend_1 = require("./legend"); var mark_1 = require("./mark"); var mark = require("./mark"); var scale_1 = require("./scale"); var selection_1 = require("./selection"); var util_1 = require("./util"); exports.defaultCellConfig = { width: 200, height: 200, fill: 'transparent' }; exports.defaultFacetCellConfig = { stroke: '#ccc', strokeWidth: 1 }; exports.defaultFacetConfig = { cell: exports.defaultFacetCellConfig }; exports.defaultConfig = { padding: 5, timeFormat: '%b %d, %Y', countTitle: 'Number of Records', invalidValues: 'filter', cell: exports.defaultCellConfig, mark: mark.defaultMarkConfig, area: {}, bar: mark.defaultBarConfig, circle: {}, line: {}, point: {}, rect: {}, rule: { color: 'black' }, square: {}, text: { color: 'black' }, tick: mark.defaultTickConfig, box: { size: 14 }, boxWhisker: {}, boxMid: { color: 'white' }, scale: scale_1.defaultScaleConfig, axis: {}, axisX: {}, axisY: {}, axisLeft: {}, axisRight: {}, axisTop: {}, axisBottom: {}, axisBand: {}, legend: legend_1.defaultLegendConfig, facet: exports.defaultFacetConfig, selection: selection_1.defaultConfig, title: {}, }; function initConfig(config) { return util_1.mergeDeep(util_1.duplicate(exports.defaultConfig), config); } exports.initConfig = initConfig; var MARK_ROLES = [].concat(mark_1.PRIMITIVE_MARKS, compositemark_1.COMPOSITE_MARK_ROLES); var VL_ONLY_CONFIG_PROPERTIES = ['padding', 'numberFormat', 'timeFormat', 'countTitle', 'cell', 'stack', 'overlay', 'scale', 'facet', 'selection', 'invalidValues']; var VL_ONLY_ALL_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX = tslib_1.__assign({}, mark_1.VL_ONLY_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX, index_1.VL_ONLY_COMPOSITE_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX); function stripConfig(config) { config = util_1.duplicate(config); for (var _i = 0, VL_ONLY_CONFIG_PROPERTIES_1 = VL_ONLY_CONFIG_PROPERTIES; _i < VL_ONLY_CONFIG_PROPERTIES_1.length; _i++) { var prop = VL_ONLY_CONFIG_PROPERTIES_1[_i]; delete config[prop]; } // Remove Vega-Lite only axis/legend config if (config.axis) { for (var _a = 0, VL_ONLY_GUIDE_CONFIG_1 = guide_1.VL_ONLY_GUIDE_CONFIG; _a < VL_ONLY_GUIDE_CONFIG_1.length; _a++) { var prop = VL_ONLY_GUIDE_CONFIG_1[_a]; delete config.axis[prop]; } } if (config.legend) { for (var _b = 0, VL_ONLY_GUIDE_CONFIG_2 = guide_1.VL_ONLY_GUIDE_CONFIG; _b < VL_ONLY_GUIDE_CONFIG_2.length; _b++) { var prop = VL_ONLY_GUIDE_CONFIG_2[_b]; delete config.legend[prop]; } } // Remove Vega-Lite only generic mark config if (config.mark) { for (var _c = 0, _d = mark.VL_ONLY_MARK_CONFIG_PROPERTIES; _c < _d.length; _c++) { var prop = _d[_c]; delete config.mark[prop]; } } // Remove Vega-Lite Mark/Role config for (var _e = 0, MARK_ROLES_1 = MARK_ROLES; _e < MARK_ROLES_1.length; _e++) { var role = MARK_ROLES_1[_e]; for (var _f = 0, _g = mark.VL_ONLY_MARK_CONFIG_PROPERTIES; _f < _g.length; _f++) { var prop = _g[_f]; delete config[role][prop]; } var vlOnlyMarkSpecificConfigs = VL_ONLY_ALL_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX[role]; if (vlOnlyMarkSpecificConfigs) { for (var _h = 0, vlOnlyMarkSpecificConfigs_1 = vlOnlyMarkSpecificConfigs; _h < vlOnlyMarkSpecificConfigs_1.length; _h++) { var prop = vlOnlyMarkSpecificConfigs_1[_h]; delete config[role][prop]; } } } // Remove empty config objects for (var prop in config) { if (util_1.isObject(config[prop]) && util_1.keys(config[prop]).length === 0) { delete config[prop]; } } return util_1.keys(config).length > 0 ? config : undefined; } exports.stripConfig = stripConfig; },{"./compositemark":84,"./compositemark/index":84,"./guide":92,"./legend":94,"./mark":97,"./scale":98,"./selection":99,"./util":107,"tslib":5}],86:[function(require,module,exports){ "use strict"; /* * Constants and utilities for data. */ Object.defineProperty(exports, "__esModule", { value: true }); function isUrlData(data) { return !!data['url']; } exports.isUrlData = isUrlData; function isInlineData(data) { return !!data['values']; } exports.isInlineData = isInlineData; function isNamedData(data) { return !!data['name']; } exports.isNamedData = isNamedData; exports.MAIN = 'main'; exports.RAW = 'raw'; },{}],87:[function(require,module,exports){ "use strict"; // DateTime definition object Object.defineProperty(exports, "__esModule", { value: true }); var log = require("./log"); var util_1 = require("./util"); /* * A designated year that starts on Sunday. */ var SUNDAY_YEAR = 2006; function isDateTime(o) { return !!o && (!!o.year || !!o.quarter || !!o.month || !!o.date || !!o.day || !!o.hours || !!o.minutes || !!o.seconds || !!o.milliseconds); } exports.isDateTime = isDateTime; exports.MONTHS = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']; exports.SHORT_MONTHS = exports.MONTHS.map(function (m) { return m.substr(0, 3); }); exports.DAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']; exports.SHORT_DAYS = exports.DAYS.map(function (d) { return d.substr(0, 3); }); function normalizeQuarter(q) { if (util_1.isNumber(q)) { if (q > 4) { log.warn(log.message.invalidTimeUnit('quarter', q)); } // We accept 1-based quarter, so need to readjust to 0-based quarter return (q - 1) + ''; } else { // Invalid quarter throw new Error(log.message.invalidTimeUnit('quarter', q)); } } function normalizeMonth(m) { if (util_1.isNumber(m)) { // We accept 1-based month, so need to readjust to 0-based month return (m - 1) + ''; } else { var lowerM = m.toLowerCase(); var monthIndex = exports.MONTHS.indexOf(lowerM); if (monthIndex !== -1) { return monthIndex + ''; // 0 for january, ... } var shortM = lowerM.substr(0, 3); var shortMonthIndex = exports.SHORT_MONTHS.indexOf(shortM); if (shortMonthIndex !== -1) { return shortMonthIndex + ''; } // Invalid month throw new Error(log.message.invalidTimeUnit('month', m)); } } function normalizeDay(d) { if (util_1.isNumber(d)) { // mod so that this can be both 0-based where 0 = sunday // and 1-based where 7=sunday return (d % 7) + ''; } else { var lowerD = d.toLowerCase(); var dayIndex = exports.DAYS.indexOf(lowerD); if (dayIndex !== -1) { return dayIndex + ''; // 0 for january, ... } var shortD = lowerD.substr(0, 3); var shortDayIndex = exports.SHORT_DAYS.indexOf(shortD); if (shortDayIndex !== -1) { return shortDayIndex + ''; } // Invalid day throw new Error(log.message.invalidTimeUnit('day', d)); } } /** * Return Vega Expression for a particular date time. * @param d * @param normalize whether to normalize quarter, month, day. */ function dateTimeExpr(d, normalize) { if (normalize === void 0) { normalize = false; } var units = []; if (normalize && d.day !== undefined) { if (util_1.keys(d).length > 1) { log.warn(log.message.droppedDay(d)); d = util_1.duplicate(d); delete d.day; } } if (d.year !== undefined) { units.push(d.year); } else if (d.day !== undefined) { // Set year to 2006 for working with day since January 1 2006 is a Sunday units.push(SUNDAY_YEAR); } else { units.push(0); } if (d.month !== undefined) { var month = normalize ? normalizeMonth(d.month) : d.month; units.push(month); } else if (d.quarter !== undefined) { var quarter = normalize ? normalizeQuarter(d.quarter) : d.quarter; units.push(quarter + '*3'); } else { units.push(0); // months start at zero in JS } if (d.date !== undefined) { units.push(d.date); } else if (d.day !== undefined) { // HACK: Day only works as a standalone unit // This is only correct because we always set year to 2006 for day var day = normalize ? normalizeDay(d.day) : d.day; units.push(day + '+1'); } else { units.push(1); // Date starts at 1 in JS } // Note: can't use TimeUnit enum here as importing it will create // circular dependency problem! for (var _i = 0, _a = ['hours', 'minutes', 'seconds', 'milliseconds']; _i < _a.length; _i++) { var timeUnit = _a[_i]; if (d[timeUnit] !== undefined) { units.push(d[timeUnit]); } else { units.push(0); } } if (d.utc) { return "utc(" + units.join(', ') + ")"; } else { return "datetime(" + units.join(', ') + ")"; } } exports.dateTimeExpr = dateTimeExpr; },{"./log":95,"./util":107}],88:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var channel_1 = require("./channel"); var fielddef_1 = require("./fielddef"); var log = require("./log"); var util_1 = require("./util"); function channelHasField(encoding, channel) { var channelDef = encoding && encoding[channel]; if (channelDef) { if (util_1.isArray(channelDef)) { return util_1.some(channelDef, function (fieldDef) { return !!fieldDef.field; }); } else { return fielddef_1.isFieldDef(channelDef) || fielddef_1.hasConditionFieldDef(channelDef); } } return false; } exports.channelHasField = channelHasField; function isAggregate(encoding) { return util_1.some(channel_1.CHANNELS, function (channel) { if (channelHasField(encoding, channel)) { var channelDef = encoding[channel]; if (util_1.isArray(channelDef)) { return util_1.some(channelDef, function (fieldDef) { return !!fieldDef.aggregate; }); } else { var fieldDef = fielddef_1.getFieldDef(channelDef); return fieldDef && !!fieldDef.aggregate; } } return false; }); } exports.isAggregate = isAggregate; function normalizeEncoding(encoding, mark) { return util_1.keys(encoding).reduce(function (normalizedEncoding, channel) { if (!channel_1.supportMark(channel, mark)) { // Drop unsupported channel log.warn(log.message.incompatibleChannel(channel, mark)); return normalizedEncoding; } // Drop line's size if the field is aggregated. if (channel === 'size' && mark === 'line') { var fieldDef = fielddef_1.getFieldDef(encoding[channel]); if (fieldDef && fieldDef.aggregate) { log.warn(log.message.incompatibleChannel(channel, mark, 'when the field is aggregated.')); return normalizedEncoding; } } if (channel === 'detail' || channel === 'order') { var channelDef = encoding[channel]; if (channelDef) { // Array of fieldDefs for detail channel (or production rule) normalizedEncoding[channel] = (util_1.isArray(channelDef) ? channelDef : [channelDef]) .reduce(function (fieldDefs, fieldDef) { if (!fielddef_1.isFieldDef(fieldDef)) { log.warn(log.message.emptyFieldDef(fieldDef, channel)); } else { fieldDefs.push(fielddef_1.normalizeFieldDef(fieldDef, channel)); } return fieldDefs; }, []); } } else { // FIXME: remove this casting. (I don't know why Typescript doesn't infer this correctly here.) var channelDef = encoding[channel]; if (!fielddef_1.isFieldDef(channelDef) && !fielddef_1.isValueDef(channelDef) && !fielddef_1.isConditionalDef(channelDef)) { log.warn(log.message.emptyFieldDef(channelDef, channel)); return normalizedEncoding; } normalizedEncoding[channel] = fielddef_1.normalize(channelDef, channel); } return normalizedEncoding; }, {}); } exports.normalizeEncoding = normalizeEncoding; function isRanged(encoding) { return encoding && ((!!encoding.x && !!encoding.x2) || (!!encoding.y && !!encoding.y2)); } exports.isRanged = isRanged; function fieldDefs(encoding) { var arr = []; channel_1.CHANNELS.forEach(function (channel) { if (channelHasField(encoding, channel)) { var channelDef = encoding[channel]; (util_1.isArray(channelDef) ? channelDef : [channelDef]).forEach(function (def) { if (fielddef_1.isFieldDef(def)) { arr.push(def); } else if (fielddef_1.hasConditionFieldDef(def)) { arr.push(def.condition); } }); } }); return arr; } exports.fieldDefs = fieldDefs; function forEach(mapping, f, thisArg) { if (!mapping) { return; } util_1.keys(mapping).forEach(function (c) { var channel = c; if (util_1.isArray(mapping[channel])) { mapping[channel].forEach(function (channelDef) { f.call(thisArg, channelDef, channel); }); } else { f.call(thisArg, mapping[channel], channel); } }); } exports.forEach = forEach; function reduce(mapping, f, init, thisArg) { if (!mapping) { return init; } return util_1.keys(mapping).reduce(function (r, c) { var channel = c; if (util_1.isArray(mapping[channel])) { return mapping[channel].reduce(function (r1, channelDef) { return f.call(thisArg, r1, channelDef, channel); }, r); } else { return f.call(thisArg, r, mapping[channel], channel); } }, init); } exports.reduce = reduce; },{"./channel":12,"./fielddef":90,"./log":95,"./util":107}],89:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); },{}],90:[function(require,module,exports){ "use strict"; // utility for a field definition object Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var aggregate_1 = require("./aggregate"); var bin_1 = require("./bin"); var channel_1 = require("./channel"); var log = require("./log"); var timeunit_1 = require("./timeunit"); var type_1 = require("./type"); var util_1 = require("./util"); function isRepeatRef(field) { return field && !util_1.isString(field) && 'repeat' in field; } exports.isRepeatRef = isRepeatRef; function isConditionalDef(channelDef) { return !!channelDef && !!channelDef.condition; } exports.isConditionalDef = isConditionalDef; /** * Return if a channelDef is a ConditionalValueDef with ConditionFieldDef */ function hasConditionFieldDef(channelDef) { return !!channelDef && !!channelDef.condition && isFieldDef(channelDef.condition); } exports.hasConditionFieldDef = hasConditionFieldDef; function isFieldDef(channelDef) { return !!channelDef && (!!channelDef['field'] || channelDef['aggregate'] === 'count'); } exports.isFieldDef = isFieldDef; function isValueDef(channelDef) { return channelDef && 'value' in channelDef && channelDef['value'] !== undefined; } exports.isValueDef = isValueDef; function isScaleFieldDef(channelDef) { return !!channelDef && (!!channelDef['scale'] || !!channelDef['sort']); } exports.isScaleFieldDef = isScaleFieldDef; function field(fieldDef, opt) { if (opt === void 0) { opt = {}; } var field = fieldDef.field; var prefix = opt.prefix; var suffix = opt.suffix; if (isCount(fieldDef)) { field = 'count_*'; } else { var fn = undefined; if (!opt.nofn) { if (fieldDef.bin) { fn = bin_1.binToString(fieldDef.bin); suffix = opt.binSuffix; } else if (fieldDef.aggregate) { fn = String(opt.aggregate || fieldDef.aggregate); } else if (fieldDef.timeUnit) { fn = String(fieldDef.timeUnit); } } if (fn) { field = fn + "_" + field; } } if (suffix) { field = field + "_" + suffix; } if (prefix) { field = prefix + "_" + field; } if (opt.expr) { field = opt.expr + "[" + util_1.stringValue(field) + "]"; } return field; } exports.field = field; function isDiscrete(fieldDef) { switch (fieldDef.type) { case 'nominal': case 'ordinal': return true; case 'quantitative': return !!fieldDef.bin; case 'temporal': // TODO: deal with custom scale type case. return timeunit_1.isDiscreteByDefault(fieldDef.timeUnit); } throw new Error(log.message.invalidFieldType(fieldDef.type)); } exports.isDiscrete = isDiscrete; function isContinuous(fieldDef) { return !isDiscrete(fieldDef); } exports.isContinuous = isContinuous; function isCount(fieldDef) { return fieldDef.aggregate === 'count'; } exports.isCount = isCount; function title(fieldDef, config) { if (isCount(fieldDef)) { return config.countTitle; } var fn = fieldDef.aggregate || fieldDef.timeUnit || (fieldDef.bin && 'bin'); if (fn) { return fn.toUpperCase() + '(' + fieldDef.field + ')'; } else { return fieldDef.field; } } exports.title = title; function defaultType(fieldDef, channel) { if (fieldDef.timeUnit) { return 'temporal'; } if (fieldDef.bin) { return 'quantitative'; } switch (channel_1.rangeType(channel)) { case 'continuous': return 'quantitative'; case 'discrete': return 'nominal'; case 'flexible':// color return 'nominal'; default: return 'quantitative'; } } exports.defaultType = defaultType; /** * Returns the fieldDef -- either from the outer channelDef or from the condition of channelDef. * @param channelDef */ function getFieldDef(channelDef) { if (isFieldDef(channelDef)) { return channelDef; } else if (hasConditionFieldDef(channelDef)) { return channelDef.condition; } return undefined; } exports.getFieldDef = getFieldDef; /** * Convert type to full, lowercase type, or augment the fieldDef with a default type if missing. */ function normalize(channelDef, channel) { // If a fieldDef contains a field, we need type. if (isFieldDef(channelDef)) { return normalizeFieldDef(channelDef, channel); } else if (hasConditionFieldDef(channelDef)) { return tslib_1.__assign({}, channelDef, { // Need to cast as normalizeFieldDef normally return FieldDef, but here we know that it is definitely Condition<FieldDef> condition: normalizeFieldDef(channelDef.condition, channel) }); } return channelDef; } exports.normalize = normalize; function normalizeFieldDef(fieldDef, channel) { // Drop invalid aggregate if (fieldDef.aggregate && !aggregate_1.AGGREGATE_OP_INDEX[fieldDef.aggregate]) { var aggregate = fieldDef.aggregate, fieldDefWithoutAggregate = tslib_1.__rest(fieldDef, ["aggregate"]); log.warn(log.message.invalidAggregate(fieldDef.aggregate)); fieldDef = fieldDefWithoutAggregate; } // Normalize bin if (fieldDef.bin) { fieldDef = tslib_1.__assign({}, fieldDef, { bin: normalizeBin(fieldDef.bin, channel) }); } // Normalize Type if (fieldDef.type) { var fullType = type_1.getFullName(fieldDef.type); if (fieldDef.type !== fullType) { // convert short type to full type fieldDef = tslib_1.__assign({}, fieldDef, { type: fullType }); } if (aggregate_1.isCountingAggregateOp(fieldDef.aggregate) && fieldDef.type !== 'quantitative') { log.warn(log.message.invalidFieldTypeForCountAggregate(fieldDef.type, fieldDef.aggregate)); fieldDef = tslib_1.__assign({}, fieldDef, { type: 'quantitative' }); } } else { // If type is empty / invalid, then augment with default type var newType = defaultType(fieldDef, channel); log.warn(log.message.emptyOrInvalidFieldType(fieldDef.type, channel, newType)); fieldDef = tslib_1.__assign({}, fieldDef, { type: newType }); } var _a = channelCompatibility(fieldDef, channel), compatible = _a.compatible, warning = _a.warning; if (!compatible) { log.warn(warning); } return fieldDef; } exports.normalizeFieldDef = normalizeFieldDef; function normalizeBin(bin, channel) { if (util_1.isBoolean(bin)) { return { maxbins: bin_1.autoMaxBins(channel) }; } else if (!bin.maxbins && !bin.step) { return tslib_1.__assign({}, bin, { maxbins: bin_1.autoMaxBins(channel) }); } else { return bin; } } exports.normalizeBin = normalizeBin; var COMPATIBLE = { compatible: true }; function channelCompatibility(fieldDef, channel) { switch (channel) { case 'row': case 'column': if (isContinuous(fieldDef) && !fieldDef.timeUnit) { // TODO:(https://github.com/vega/vega-lite/issues/2011): // with timeUnit it's not always strictly continuous return { compatible: false, warning: log.message.facetChannelShouldBeDiscrete(channel) }; } return COMPATIBLE; case 'x': case 'y': case 'color': case 'text': case 'detail': case 'tooltip': return COMPATIBLE; case 'opacity': case 'size': case 'x2': case 'y2': if (isDiscrete(fieldDef) && !fieldDef.bin) { return { compatible: false, warning: "Channel " + channel + " should not be used with discrete field." }; } return COMPATIBLE; case 'shape': if (fieldDef.type !== 'nominal') { return { compatible: false, warning: 'Shape channel should be used with nominal data only' }; } return COMPATIBLE; case 'order': if (fieldDef.type === 'nominal') { return { compatible: false, warning: "Channel order is inappropriate for nominal field, which has no inherent order." }; } return COMPATIBLE; } throw new Error('channelCompatability not implemented for channel ' + channel); } exports.channelCompatibility = channelCompatibility; },{"./aggregate":9,"./bin":11,"./channel":12,"./log":95,"./timeunit":103,"./type":106,"./util":107,"tslib":5}],91:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var selection_1 = require("./compile/selection/selection"); var datetime_1 = require("./datetime"); var fielddef_1 = require("./fielddef"); var timeunit_1 = require("./timeunit"); var util_1 = require("./util"); function isSelectionFilter(filter) { return filter && filter['selection']; } exports.isSelectionFilter = isSelectionFilter; function isEqualFilter(filter) { return filter && !!filter.field && filter.equal !== undefined; } exports.isEqualFilter = isEqualFilter; function isRangeFilter(filter) { if (filter && filter.field) { if (util_1.isArray(filter.range) && filter.range.length === 2) { return true; } } return false; } exports.isRangeFilter = isRangeFilter; function isOneOfFilter(filter) { return filter && !!filter.field && (util_1.isArray(filter.oneOf) || util_1.isArray(filter.in) // backward compatibility ); } exports.isOneOfFilter = isOneOfFilter; /** * Converts a filter into an expression. */ // model is only used for selection filters. function expression(model, filterOp, node) { return util_1.logicalExpr(filterOp, function (filter) { if (util_1.isString(filter)) { return filter; } else if (isSelectionFilter(filter)) { return selection_1.predicate(model, filter.selection, node); } else { var fieldExpr = filter.timeUnit ? // For timeUnit, cast into integer with time() so we can use ===, inrange, indexOf to compare values directly. // TODO: We calculate timeUnit on the fly here. Consider if we would like to consolidate this with timeUnit pipeline // TODO: support utc ('time(' + timeunit_1.fieldExpr(filter.timeUnit, filter.field) + ')') : fielddef_1.field(filter, { expr: 'datum' }); if (isEqualFilter(filter)) { return fieldExpr + '===' + valueExpr(filter.equal, filter.timeUnit); } else if (isOneOfFilter(filter)) { // "oneOf" was formerly "in" -- so we need to add backward compatibility var oneOf = filter.oneOf || filter['in']; return 'indexof([' + oneOf.map(function (v) { return valueExpr(v, filter.timeUnit); }).join(',') + '], ' + fieldExpr + ') !== -1'; } else if (isRangeFilter(filter)) { var lower = filter.range[0]; var upper = filter.range[1]; if (lower !== null && upper !== null) { return 'inrange(' + fieldExpr + ', [' + valueExpr(lower, filter.timeUnit) + ', ' + valueExpr(upper, filter.timeUnit) + '])'; } else if (lower !== null) { return fieldExpr + ' >= ' + lower; } else if (upper !== null) { return fieldExpr + ' <= ' + upper; } } } return undefined; }); } exports.expression = expression; function valueExpr(v, timeUnit) { if (datetime_1.isDateTime(v)) { var expr = datetime_1.dateTimeExpr(v, true); return 'time(' + expr + ')'; } if (timeunit_1.isSingleTimeUnit(timeUnit)) { var datetime = {}; datetime[timeUnit] = v; var expr = datetime_1.dateTimeExpr(datetime, true); return 'time(' + expr + ')'; } return JSON.stringify(v); } },{"./compile/selection/selection":70,"./datetime":87,"./fielddef":90,"./timeunit":103,"./util":107}],92:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.VL_ONLY_GUIDE_CONFIG = ['shortTimeLabels']; },{}],93:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.axis = require("./axis"); exports.aggregate = require("./aggregate"); exports.bin = require("./bin"); exports.channel = require("./channel"); exports.compositeMark = require("./compositemark"); var compile_1 = require("./compile/compile"); exports.compile = compile_1.compile; exports.config = require("./config"); exports.data = require("./data"); exports.datetime = require("./datetime"); exports.encoding = require("./encoding"); exports.facet = require("./facet"); exports.fieldDef = require("./fielddef"); exports.legend = require("./legend"); exports.mark = require("./mark"); exports.scale = require("./scale"); exports.sort = require("./sort"); exports.spec = require("./spec"); exports.stack = require("./stack"); exports.timeUnit = require("./timeunit"); exports.transform = require("./transform"); exports.type = require("./type"); exports.util = require("./util"); exports.validate = require("./validate"); exports.version = require('../package.json').version; },{"../package.json":8,"./aggregate":9,"./axis":10,"./bin":11,"./channel":12,"./compile/compile":19,"./compositemark":84,"./config":85,"./data":86,"./datetime":87,"./encoding":88,"./facet":89,"./fielddef":90,"./legend":94,"./mark":97,"./scale":98,"./sort":100,"./spec":101,"./stack":102,"./timeunit":103,"./transform":105,"./type":106,"./util":107,"./validate":108}],94:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.defaultLegendConfig = { orient: undefined, }; exports.LEGEND_PROPERTIES = ['entryPadding', 'format', 'offset', 'orient', 'tickCount', 'title', 'type', 'values', 'zindex']; exports.VG_LEGEND_PROPERTIES = [].concat(['fill', 'stroke', 'shape', 'size', 'opacity', 'encode'], exports.LEGEND_PROPERTIES); },{}],95:[function(require,module,exports){ "use strict"; /** * Vega-Lite's singleton logger utility. */ Object.defineProperty(exports, "__esModule", { value: true }); var vega_util_1 = require("vega-util"); /** * Main (default) Vega Logger instance for Vega-Lite */ var main = vega_util_1.logger(vega_util_1.Warn); var current = main; /** * Logger tool for checking if the code throws correct warning */ var LocalLogger = (function () { function LocalLogger() { this.warns = []; this.infos = []; this.debugs = []; } LocalLogger.prototype.level = function () { return this; }; LocalLogger.prototype.warn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } (_a = this.warns).push.apply(_a, args); return this; var _a; }; LocalLogger.prototype.info = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } (_a = this.infos).push.apply(_a, args); return this; var _a; }; LocalLogger.prototype.debug = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } (_a = this.debugs).push.apply(_a, args); return this; var _a; }; return LocalLogger; }()); exports.LocalLogger = LocalLogger; function runLocalLogger(f) { var localLogger = current = new LocalLogger(); f(localLogger); reset(); } exports.runLocalLogger = runLocalLogger; function wrap(f) { return function () { var logger = current = new LocalLogger(); f(logger); reset(); }; } exports.wrap = wrap; /** * Set the singleton logger to be a custom logger */ function set(logger) { current = logger; return current; } exports.set = set; /** * Reset the main logger to use the default Vega Logger */ function reset() { current = main; return current; } exports.reset = reset; function warn() { var _ = []; for (var _i = 0; _i < arguments.length; _i++) { _[_i] = arguments[_i]; } current.warn.apply(current, arguments); } exports.warn = warn; function info() { var _ = []; for (var _i = 0; _i < arguments.length; _i++) { _[_i] = arguments[_i]; } current.info.apply(current, arguments); } exports.info = info; function debug() { var _ = []; for (var _i = 0; _i < arguments.length; _i++) { _[_i] = arguments[_i]; } current.debug.apply(current, arguments); } exports.debug = debug; /** * Collection of all Vega-Lite Error Messages */ var message; (function (message) { message.INVALID_SPEC = 'Invalid spec'; // SELECTION function cannotProjectOnChannelWithoutField(channel) { return "Cannot project a selection on encoding channel " + channel + ", which has no field."; } message.cannotProjectOnChannelWithoutField = cannotProjectOnChannelWithoutField; function selectionNotFound(name) { return "Cannot find a selection named \"" + name + "\""; } message.selectionNotFound = selectionNotFound; // REPEAT function noSuchRepeatedValue(field) { return "Unknown repeated value \"" + field + "\"."; } message.noSuchRepeatedValue = noSuchRepeatedValue; // DATA function unrecognizedParse(p) { return "Unrecognized parse " + p + "."; } message.unrecognizedParse = unrecognizedParse; function differentParse(field, local, ancestor) { return "An ancestor parsed field " + field + " as " + ancestor + " but a child wants to parse the field as " + local + "."; } message.differentParse = differentParse; // TRANSFORMS function invalidTransformIgnored(transform) { return "Ignoring an invalid transform: " + JSON.stringify(transform) + "."; } message.invalidTransformIgnored = invalidTransformIgnored; message.NO_FIELDS_NEEDS_AS = 'If `from.fields` is not specified, `as` has to be a string that specifies the key to be used for the the data from the secondary source.'; // ENCODING & FACET function invalidFieldType(type) { return "Invalid field type \"" + type + "\""; } message.invalidFieldType = invalidFieldType; function invalidFieldTypeForCountAggregate(type, aggregate) { return "Invalid field type \"" + type + "\" for aggregate: \"" + aggregate + "\", using \"quantitative\" instead."; } message.invalidFieldTypeForCountAggregate = invalidFieldTypeForCountAggregate; function invalidAggregate(aggregate) { return "Invalid aggregation operator \"" + aggregate + "\""; } message.invalidAggregate = invalidAggregate; function emptyOrInvalidFieldType(type, channel, newType) { return "Invalid field type (" + type + ") for channel " + channel + ", using " + newType + " instead."; } message.emptyOrInvalidFieldType = emptyOrInvalidFieldType; function emptyFieldDef(fieldDef, channel) { return "Dropping " + JSON.stringify(fieldDef) + " from channel " + channel + " since it does not contain data field or value."; } message.emptyFieldDef = emptyFieldDef; function incompatibleChannel(channel, markOrFacet, when) { return channel + " dropped as it is incompatible with " + markOrFacet + (when ? " when " + when : '') + "."; } message.incompatibleChannel = incompatibleChannel; function facetChannelShouldBeDiscrete(channel) { return channel + " encoding should be discrete (ordinal / nominal / binned)."; } message.facetChannelShouldBeDiscrete = facetChannelShouldBeDiscrete; function discreteChannelCannotEncode(channel, type) { return "Using discrete channel " + channel + " to encode " + type + " field can be misleading as it does not encode " + (type === 'ordinal' ? 'order' : 'magnitude') + "."; } message.discreteChannelCannotEncode = discreteChannelCannotEncode; // Mark message.BAR_WITH_POINT_SCALE_AND_RANGESTEP_NULL = 'Bar mark should not be used with point scale when rangeStep is null. Please use band scale instead.'; function unclearOrientContinuous(mark) { return "Cannot clearly determine orientation for " + mark + " since both x and y channel encode continous fields. In this case, we use vertical by default"; } message.unclearOrientContinuous = unclearOrientContinuous; function unclearOrientDiscreteOrEmpty(mark) { return "Cannot clearly determine orientation for " + mark + " since both x and y channel encode discrete or empty fields."; } message.unclearOrientDiscreteOrEmpty = unclearOrientDiscreteOrEmpty; function orientOverridden(original, actual) { return "Specified orient " + original + " overridden with " + actual; } message.orientOverridden = orientOverridden; // SCALE message.CANNOT_UNION_CUSTOM_DOMAIN_WITH_FIELD_DOMAIN = 'custom domain scale cannot be unioned with default field-based domain'; function cannotUseScalePropertyWithNonColor(prop) { return "Cannot use " + prop + " with non-color channel."; } message.cannotUseScalePropertyWithNonColor = cannotUseScalePropertyWithNonColor; function unaggregateDomainHasNoEffectForRawField(fieldDef) { return "Using unaggregated domain with raw field has no effect (" + JSON.stringify(fieldDef) + ")."; } message.unaggregateDomainHasNoEffectForRawField = unaggregateDomainHasNoEffectForRawField; function unaggregateDomainWithNonSharedDomainOp(aggregate) { return "Unaggregated domain not applicable for " + aggregate + " since it produces values outside the origin domain of the source data."; } message.unaggregateDomainWithNonSharedDomainOp = unaggregateDomainWithNonSharedDomainOp; function unaggregatedDomainWithLogScale(fieldDef) { return "Unaggregated domain is currently unsupported for log scale (" + JSON.stringify(fieldDef) + ")."; } message.unaggregatedDomainWithLogScale = unaggregatedDomainWithLogScale; message.CANNOT_USE_RANGE_WITH_POSITION = 'Cannot use custom range with x or y channel. Please customize width, height, padding, or rangeStep instead.'; function cannotUseSizeFieldWithBandSize(positionChannel) { return "Using size field when " + positionChannel + "-channel has a band scale is not supported."; } message.cannotUseSizeFieldWithBandSize = cannotUseSizeFieldWithBandSize; function cannotApplySizeToNonOrientedMark(mark) { return "Cannot apply size to non-oriented mark " + mark + "."; } message.cannotApplySizeToNonOrientedMark = cannotApplySizeToNonOrientedMark; function rangeStepDropped(channel) { return "rangeStep for " + channel + " is dropped as top-level " + (channel === 'x' ? 'width' : 'height') + " is provided."; } message.rangeStepDropped = rangeStepDropped; function scaleTypeNotWorkWithChannel(channel, scaleType, defaultScaleType) { return "Channel " + channel + " does not work with " + scaleType + " scale. We are using " + defaultScaleType + " scale instead."; } message.scaleTypeNotWorkWithChannel = scaleTypeNotWorkWithChannel; function scaleTypeNotWorkWithFieldDef(scaleType, defaultScaleType) { return "FieldDef does not work with " + scaleType + " scale. We are using " + defaultScaleType + " scale instead."; } message.scaleTypeNotWorkWithFieldDef = scaleTypeNotWorkWithFieldDef; function scalePropertyNotWorkWithScaleType(scaleType, propName, channel) { return channel + "-scale's \"" + propName + "\" is dropped as it does not work with " + scaleType + " scale."; } message.scalePropertyNotWorkWithScaleType = scalePropertyNotWorkWithScaleType; function scaleTypeNotWorkWithMark(mark, scaleType) { return "Scale type \"" + scaleType + "\" does not work with mark " + mark + "."; } message.scaleTypeNotWorkWithMark = scaleTypeNotWorkWithMark; function mergeConflictingProperty(property, propertyOf, v1, v2) { return "Conflicting " + propertyOf + " property " + property + " (" + v1 + " and " + v2 + "). Using " + v1 + "."; } message.mergeConflictingProperty = mergeConflictingProperty; function independentScaleMeansIndependentGuide(channel) { return "Setting the scale to be independent for " + channel + " means we also have to set the guide (axis or legend) to be independent."; } message.independentScaleMeansIndependentGuide = independentScaleMeansIndependentGuide; function conflictedDomain(channel) { return "Cannot set " + channel + "-scale's \"domain\" as it is binned. Please use \"bin\"'s \"extent\" instead."; } message.conflictedDomain = conflictedDomain; message.INVAID_DOMAIN = 'Invalid scale domain'; message.UNABLE_TO_MERGE_DOMAINS = 'Unable to merge domains'; // AXIS message.INVALID_CHANNEL_FOR_AXIS = 'Invalid channel for axis.'; // STACK function cannotStackRangedMark(channel) { return "Cannot stack " + channel + " if there is already " + channel + "2"; } message.cannotStackRangedMark = cannotStackRangedMark; function cannotStackNonLinearScale(scaleType) { return "Cannot stack non-linear scale (" + scaleType + ")"; } message.cannotStackNonLinearScale = cannotStackNonLinearScale; function cannotStackNonSummativeAggregate(aggregate) { return "Cannot stack when the aggregate function is non-summative (" + aggregate + ")"; } message.cannotStackNonSummativeAggregate = cannotStackNonSummativeAggregate; // TIMEUNIT function invalidTimeUnit(unitName, value) { return "Invalid " + unitName + ": " + value; } message.invalidTimeUnit = invalidTimeUnit; function dayReplacedWithDate(fullTimeUnit) { return "Time unit \"" + fullTimeUnit + "\" is not supported. We are replacing it with " + fullTimeUnit.replace('day', 'date') + "."; } message.dayReplacedWithDate = dayReplacedWithDate; function droppedDay(d) { return "Dropping day from datetime " + JSON.stringify(d) + " as day cannot be combined with other units."; } message.droppedDay = droppedDay; })(message = exports.message || (exports.message = {})); },{"vega-util":7}],96:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function isLogicalOr(op) { return !!op.or; } exports.isLogicalOr = isLogicalOr; function isLogicalAnd(op) { return !!op.and; } exports.isLogicalAnd = isLogicalAnd; function isLogicalNot(op) { return !!op.not; } exports.isLogicalNot = isLogicalNot; },{}],97:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require("./util"); var Mark; (function (Mark) { Mark.AREA = 'area'; Mark.BAR = 'bar'; Mark.LINE = 'line'; Mark.POINT = 'point'; Mark.RECT = 'rect'; Mark.RULE = 'rule'; Mark.TEXT = 'text'; Mark.TICK = 'tick'; Mark.CIRCLE = 'circle'; Mark.SQUARE = 'square'; })(Mark = exports.Mark || (exports.Mark = {})); exports.AREA = Mark.AREA; exports.BAR = Mark.BAR; exports.LINE = Mark.LINE; exports.POINT = Mark.POINT; exports.TEXT = Mark.TEXT; exports.TICK = Mark.TICK; exports.RECT = Mark.RECT; exports.RULE = Mark.RULE; exports.CIRCLE = Mark.CIRCLE; exports.SQUARE = Mark.SQUARE; exports.PRIMITIVE_MARKS = [exports.AREA, exports.BAR, exports.LINE, exports.POINT, exports.TEXT, exports.TICK, exports.RECT, exports.RULE, exports.CIRCLE, exports.SQUARE]; function isMarkDef(mark) { return mark['type']; } exports.isMarkDef = isMarkDef; var PRIMITIVE_MARK_INDEX = util_1.toSet(exports.PRIMITIVE_MARKS); function isPrimitiveMark(mark) { var markType = isMarkDef(mark) ? mark.type : mark; return markType in PRIMITIVE_MARK_INDEX; } exports.isPrimitiveMark = isPrimitiveMark; exports.STROKE_CONFIG = ['stroke', 'strokeWidth', 'strokeDash', 'strokeDashOffset', 'strokeOpacity']; exports.FILL_CONFIG = ['fill', 'fillOpacity']; exports.FILL_STROKE_CONFIG = [].concat(exports.STROKE_CONFIG, exports.FILL_CONFIG); exports.VL_ONLY_MARK_CONFIG_PROPERTIES = ['filled', 'color']; exports.VL_ONLY_MARK_SPECIFIC_CONFIG_PROPERTY_INDEX = { bar: ['binSpacing', 'continuousBandSize', 'discreteBandSize'], text: ['shortTimeLabels'], tick: ['bandSize', 'thickness'] }; exports.defaultMarkConfig = { color: '#4c78a8', }; exports.defaultBarConfig = { binSpacing: 1, continuousBandSize: 2 }; exports.defaultTickConfig = { thickness: 1 }; },{"./util":107}],98:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var log = require("./log"); var util_1 = require("./util"); var ScaleType; (function (ScaleType) { // Continuous - Quantitative ScaleType.LINEAR = 'linear'; ScaleType.BIN_LINEAR = 'bin-linear'; ScaleType.LOG = 'log'; ScaleType.POW = 'pow'; ScaleType.SQRT = 'sqrt'; // Continuous - Time ScaleType.TIME = 'time'; ScaleType.UTC = 'utc'; // sequential ScaleType.SEQUENTIAL = 'sequential'; // Quantile, Quantize, threshold ScaleType.QUANTILE = 'quantile'; ScaleType.QUANTIZE = 'quantize'; ScaleType.THRESHOLD = 'threshold'; ScaleType.ORDINAL = 'ordinal'; ScaleType.BIN_ORDINAL = 'bin-ordinal'; ScaleType.POINT = 'point'; ScaleType.BAND = 'band'; })(ScaleType = exports.ScaleType || (exports.ScaleType = {})); exports.SCALE_TYPES = [ // Continuous - Quantitative 'linear', 'bin-linear', 'log', 'pow', 'sqrt', // Continuous - Time 'time', 'utc', // Sequential 'sequential', // Discrete 'ordinal', 'bin-ordinal', 'point', 'band', ]; /** * Index for scale categories -- only scale of the same categories can be merged together. * Current implementation is trying to be conservative and avoid merging scale type that might not work together */ var SCALE_CATEGORY_INDEX = { linear: 'numeric', log: 'numeric', pow: 'numeric', sqrt: 'numeric', 'bin-linear': 'bin-linear', time: 'time', utc: 'time', sequential: 'sequential', ordinal: 'ordinal', 'bin-ordinal': 'bin-ordinal', point: 'ordinal-position', band: 'ordinal-position' }; /** * Whether the two given scale types can be merged together. */ function scaleCompatible(scaleType1, scaleType2) { return SCALE_CATEGORY_INDEX[scaleType1] === SCALE_CATEGORY_INDEX[scaleType2]; } exports.scaleCompatible = scaleCompatible; /** * Index for scale predecence -- high score = higher priority for merging. */ var SCALE_PRECEDENCE_INDEX = { // numeric linear: 0, log: 1, pow: 1, sqrt: 1, // time time: 0, utc: 0, // ordinal-position point: 0, band: 1, // non grouped types 'bin-linear': 0, sequential: 0, ordinal: 0, 'bin-ordinal': 0, }; /** * Return scale categories -- only scale of the same categories can be merged together. */ function scaleTypePrecedence(scaleType) { return SCALE_PRECEDENCE_INDEX[scaleType]; } exports.scaleTypePrecedence = scaleTypePrecedence; exports.CONTINUOUS_TO_CONTINUOUS_SCALES = ['linear', 'bin-linear', 'log', 'pow', 'sqrt', 'time', 'utc']; var CONTINUOUS_TO_CONTINUOUS_INDEX = util_1.toSet(exports.CONTINUOUS_TO_CONTINUOUS_SCALES); exports.CONTINUOUS_DOMAIN_SCALES = exports.CONTINUOUS_TO_CONTINUOUS_SCALES.concat(['sequential' /* TODO add 'quantile', 'quantize', 'threshold'*/]); var CONTINUOUS_DOMAIN_INDEX = util_1.toSet(exports.CONTINUOUS_DOMAIN_SCALES); exports.DISCRETE_DOMAIN_SCALES = ['ordinal', 'bin-ordinal', 'point', 'band']; var DISCRETE_DOMAIN_INDEX = util_1.toSet(exports.DISCRETE_DOMAIN_SCALES); var BIN_SCALES_INDEX = util_1.toSet(['bin-linear', 'bin-ordinal']); exports.TIME_SCALE_TYPES = ['time', 'utc']; function hasDiscreteDomain(type) { return type in DISCRETE_DOMAIN_INDEX; } exports.hasDiscreteDomain = hasDiscreteDomain; function isBinScale(type) { return type in BIN_SCALES_INDEX; } exports.isBinScale = isBinScale; function hasContinuousDomain(type) { return type in CONTINUOUS_DOMAIN_INDEX; } exports.hasContinuousDomain = hasContinuousDomain; function isContinuousToContinuous(type) { return type in CONTINUOUS_TO_CONTINUOUS_INDEX; } exports.isContinuousToContinuous = isContinuousToContinuous; exports.defaultScaleConfig = { round: true, textXRangeStep: 90, rangeStep: 21, pointPadding: 0.5, bandPaddingInner: 0.1, facetSpacing: 16, minFontSize: 8, maxFontSize: 40, minOpacity: 0.3, maxOpacity: 0.8, // FIXME: revise if these *can* become ratios of rangeStep minSize: 9, minStrokeWidth: 1, maxStrokeWidth: 4, shapes: ['circle', 'square', 'cross', 'diamond', 'triangle-up', 'triangle-down'] }; function isExtendedScheme(scheme) { return scheme && !!scheme['name']; } exports.isExtendedScheme = isExtendedScheme; function isSelectionDomain(domain) { return domain && domain['selection']; } exports.isSelectionDomain = isSelectionDomain; exports.NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTIES = [ 'reverse', 'round', // quantitative / time 'clamp', 'nice', // quantitative 'exponent', 'interpolate', 'zero', // ordinal 'padding', 'paddingInner', 'paddingOuter', ]; exports.SCALE_PROPERTIES = [].concat([ 'type', 'domain', 'range', 'rangeStep', 'scheme' ], exports.NON_TYPE_DOMAIN_RANGE_VEGA_SCALE_PROPERTIES); function scaleTypeSupportProperty(scaleType, propName) { switch (propName) { case 'type': case 'domain': case 'reverse': case 'range': case 'scheme': return true; case 'interpolate': return util_1.contains(['linear', 'bin-linear', 'pow', 'log', 'sqrt', 'utc', 'time'], scaleType); case 'round': return isContinuousToContinuous(scaleType) || scaleType === 'band' || scaleType === 'point'; case 'rangeStep': case 'padding': case 'paddingOuter': return util_1.contains(['point', 'band'], scaleType); case 'paddingInner': return scaleType === 'band'; case 'clamp': return isContinuousToContinuous(scaleType) || scaleType === 'sequential'; case 'nice': return isContinuousToContinuous(scaleType) || scaleType === 'sequential' || scaleType === 'quantize'; case 'exponent': return scaleType === 'pow' || scaleType === 'log'; case 'zero': // TODO: what about quantize, threshold? return scaleType === 'bin-ordinal' || (!hasDiscreteDomain(scaleType) && !util_1.contains(['log', 'time', 'utc', 'bin-linear'], scaleType)); } /* istanbul ignore next: should never reach here*/ throw new Error("Invalid scale property " + propName + "."); } exports.scaleTypeSupportProperty = scaleTypeSupportProperty; /** * Returns undefined if the input channel supports the input scale property name */ function channelScalePropertyIncompatability(channel, propName) { switch (propName) { case 'range': // User should not customize range for position and facet channel directly. if (channel === 'x' || channel === 'y') { return log.message.CANNOT_USE_RANGE_WITH_POSITION; } return undefined; // GOOD! case 'interpolate': case 'scheme': if (channel !== 'color') { return log.message.cannotUseScalePropertyWithNonColor(channel); } return undefined; case 'type': case 'domain': case 'exponent': case 'nice': case 'padding': case 'paddingInner': case 'paddingOuter': case 'rangeStep': case 'reverse': case 'round': case 'clamp': case 'zero': return undefined; // GOOD! } /* istanbul ignore next: it should never reach here */ throw new Error('Invalid scale property "${propName}".'); } exports.channelScalePropertyIncompatability = channelScalePropertyIncompatability; },{"./log":95,"./util":107}],99:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.defaultConfig = { single: { on: 'click', fields: ['_id'], resolve: 'global' }, multi: { on: 'click', fields: ['_id'], toggle: 'event.shiftKey', resolve: 'global' }, interval: { on: '[mousedown, window:mouseup] > window:mousemove!', encodings: ['x', 'y'], translate: '[mousedown, window:mouseup] > window:mousemove!', zoom: 'wheel!', mark: { fill: '#333', fillOpacity: 0.125, stroke: 'white' }, resolve: 'global' } }; },{}],100:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function isSortField(sort) { return !!sort && (sort['op'] === 'count' || !!sort['field']) && !!sort['op']; } exports.isSortField = isSortField; },{}],101:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var channel_1 = require("./channel"); var compositeMark = require("./compositemark"); var encoding_1 = require("./encoding"); var vlEncoding = require("./encoding"); var log = require("./log"); var mark_1 = require("./mark"); var stack_1 = require("./stack"); var util_1 = require("./util"); /* Custom type guards */ function isFacetSpec(spec) { return spec['facet'] !== undefined; } exports.isFacetSpec = isFacetSpec; function isUnitSpec(spec) { return !!spec['mark']; } exports.isUnitSpec = isUnitSpec; function isLayerSpec(spec) { return spec['layer'] !== undefined; } exports.isLayerSpec = isLayerSpec; function isRepeatSpec(spec) { return spec['repeat'] !== undefined; } exports.isRepeatSpec = isRepeatSpec; function isConcatSpec(spec) { return isVConcatSpec(spec) || isHConcatSpec(spec); } exports.isConcatSpec = isConcatSpec; function isVConcatSpec(spec) { return spec['vconcat'] !== undefined; } exports.isVConcatSpec = isVConcatSpec; function isHConcatSpec(spec) { return spec['hconcat'] !== undefined; } exports.isHConcatSpec = isHConcatSpec; /** * Decompose extended unit specs into composition of pure unit specs. */ // TODO: consider moving this to another file. Maybe vl.spec.normalize or vl.normalize function normalize(spec, config) { if (isFacetSpec(spec)) { return normalizeFacet(spec, config); } if (isLayerSpec(spec)) { return normalizeLayer(spec, config); } if (isRepeatSpec(spec)) { return normalizeRepeat(spec, spec.config); } if (isVConcatSpec(spec)) { return normalizeVConcat(spec, spec.config); } if (isHConcatSpec(spec)) { return normalizeHConcat(spec, spec.config); } if (isUnitSpec(spec)) { var hasRow = encoding_1.channelHasField(spec.encoding, channel_1.ROW); var hasColumn = encoding_1.channelHasField(spec.encoding, channel_1.COLUMN); if (hasRow || hasColumn) { return normalizeFacetedUnit(spec, config); } return normalizeNonFacetUnit(spec, config); } throw new Error(log.message.INVALID_SPEC); } exports.normalize = normalize; function normalizeNonFacet(spec, config) { if (isLayerSpec(spec)) { return normalizeLayer(spec, config); } if (isRepeatSpec(spec)) { return normalizeRepeat(spec, config); } return normalizeNonFacetUnit(spec, config); } function normalizeNonFacetWithRepeat(spec, config) { if (isLayerSpec(spec)) { return normalizeLayer(spec, config); } if (isRepeatSpec(spec)) { return normalizeRepeat(spec, config); } return normalizeNonFacetUnit(spec, config); } function normalizeFacet(spec, config) { var subspec = spec.spec, rest = tslib_1.__rest(spec, ["spec"]); return tslib_1.__assign({}, rest, { spec: normalizeNonFacet(subspec, config) }); } function normalizeLayer(spec, config) { var layer = spec.layer, rest = tslib_1.__rest(spec, ["layer"]); return tslib_1.__assign({}, rest, { layer: layer.map(function (subspec) { return isLayerSpec(subspec) ? normalizeLayer(subspec, config) : normalizeNonFacetUnit(subspec, config); }) }); } function normalizeRepeat(spec, config) { var subspec = spec.spec, rest = tslib_1.__rest(spec, ["spec"]); return tslib_1.__assign({}, rest, { spec: normalizeNonFacetWithRepeat(subspec, config) }); } function normalizeVConcat(spec, config) { var vconcat = spec.vconcat, rest = tslib_1.__rest(spec, ["vconcat"]); return tslib_1.__assign({}, rest, { vconcat: vconcat.map(function (subspec) { return normalizeNonFacet(subspec, config); }) }); } function normalizeHConcat(spec, config) { var hconcat = spec.hconcat, rest = tslib_1.__rest(spec, ["hconcat"]); return tslib_1.__assign({}, rest, { hconcat: hconcat.map(function (subspec) { return normalizeNonFacet(subspec, config); }) }); } function normalizeFacetedUnit(spec, config) { // New encoding in the inside spec should not contain row / column // as row/column should be moved to facet var _a = spec.encoding, row = _a.row, column = _a.column, encoding = tslib_1.__rest(_a, ["row", "column"]); // Mark and encoding should be moved into the inner spec var mark = spec.mark, width = spec.width, height = spec.height, selection = spec.selection, _ = spec.encoding, outerSpec = tslib_1.__rest(spec, ["mark", "width", "height", "selection", "encoding"]); return tslib_1.__assign({}, outerSpec, { facet: tslib_1.__assign({}, (row ? { row: row } : {}), (column ? { column: column } : {})), spec: normalizeNonFacetUnit(tslib_1.__assign({ mark: mark }, (width ? { width: width } : {}), (height ? { height: height } : {}), { encoding: encoding }, (selection ? { selection: selection } : {})), config) }); } function isNonFacetUnitSpecWithPrimitiveMark(spec) { return mark_1.isPrimitiveMark(spec.mark); } function normalizeNonFacetUnit(spec, config) { if (isNonFacetUnitSpecWithPrimitiveMark(spec)) { // TODO: thoroughly test if (encoding_1.isRanged(spec.encoding)) { return normalizeRangedUnit(spec); } var overlayConfig = config && config.overlay; var overlayWithLine = overlayConfig && spec.mark === mark_1.AREA && util_1.contains(['linepoint', 'line'], overlayConfig.area); var overlayWithPoint = overlayConfig && ((overlayConfig.line && spec.mark === mark_1.LINE) || (overlayConfig.area === 'linepoint' && spec.mark === mark_1.AREA)); // TODO: consider moving this to become another case of compositeMark if (overlayWithPoint || overlayWithLine) { return normalizeOverlay(spec, overlayWithPoint, overlayWithLine, config); } return spec; // Nothing to normalize } else { return compositeMark.normalize(spec, config); } } function normalizeRangedUnit(spec) { var hasX = encoding_1.channelHasField(spec.encoding, channel_1.X); var hasY = encoding_1.channelHasField(spec.encoding, channel_1.Y); var hasX2 = encoding_1.channelHasField(spec.encoding, channel_1.X2); var hasY2 = encoding_1.channelHasField(spec.encoding, channel_1.Y2); if ((hasX2 && !hasX) || (hasY2 && !hasY)) { var normalizedSpec = util_1.duplicate(spec); if (hasX2 && !hasX) { normalizedSpec.encoding.x = normalizedSpec.encoding.x2; delete normalizedSpec.encoding.x2; } if (hasY2 && !hasY) { normalizedSpec.encoding.y = normalizedSpec.encoding.y2; delete normalizedSpec.encoding.y2; } return normalizedSpec; } return spec; } // FIXME(#1804): re-design this function normalizeOverlay(spec, overlayWithPoint, overlayWithLine, config) { var mark = spec.mark, selection = spec.selection, encoding = spec.encoding, outerSpec = tslib_1.__rest(spec, ["mark", "selection", "encoding"]); var layer = [{ mark: mark, encoding: encoding }]; // Need to copy stack config to overlayed layer var stackProps = stack_1.stack(mark, encoding, config ? config.stack : undefined); var overlayEncoding = encoding; if (stackProps) { var stackFieldChannel = stackProps.fieldChannel, offset = stackProps.offset; overlayEncoding = tslib_1.__assign({}, encoding, (_a = {}, _a[stackFieldChannel] = tslib_1.__assign({}, encoding[stackFieldChannel], (offset ? { stack: offset } : {})), _a)); } if (overlayWithLine) { layer.push(tslib_1.__assign({ mark: { type: 'line', role: 'lineOverlay' } }, (selection ? { selection: selection } : {}), { encoding: overlayEncoding })); } if (overlayWithPoint) { layer.push(tslib_1.__assign({ mark: { type: 'point', filled: true, role: 'pointOverlay' } }, (selection ? { selection: selection } : {}), { encoding: overlayEncoding })); } return tslib_1.__assign({}, outerSpec, { layer: layer }); var _a; } // TODO: add vl.spec.validate & move stuff from vl.validate to here /* Accumulate non-duplicate fieldDefs in a dictionary */ function accumulate(dict, fieldDefs) { fieldDefs.forEach(function (fieldDef) { // Consider only pure fieldDef properties (ignoring scale, axis, legend) var pureFieldDef = ['field', 'type', 'value', 'timeUnit', 'bin', 'aggregate'].reduce(function (f, key) { if (fieldDef[key] !== undefined) { f[key] = fieldDef[key]; } return f; }, {}); var key = util_1.hash(pureFieldDef); dict[key] = dict[key] || fieldDef; }); return dict; } /* Recursively get fieldDefs from a spec, returns a dictionary of fieldDefs */ function fieldDefIndex(spec, dict) { if (dict === void 0) { dict = {}; } // FIXME(https://github.com/vega/vega-lite/issues/2207): Support fieldDefIndex for repeat if (isLayerSpec(spec)) { spec.layer.forEach(function (layer) { if (isUnitSpec(layer)) { accumulate(dict, vlEncoding.fieldDefs(layer.encoding)); } else { fieldDefIndex(layer, dict); } }); } else if (isFacetSpec(spec)) { accumulate(dict, vlEncoding.fieldDefs(spec.facet)); fieldDefIndex(spec.spec, dict); } else if (isRepeatSpec(spec)) { fieldDefIndex(spec.spec, dict); } else if (isConcatSpec(spec)) { var childSpec = isVConcatSpec(spec) ? spec.vconcat : spec.hconcat; childSpec.forEach(function (child) { return fieldDefIndex(child, dict); }); } else { accumulate(dict, vlEncoding.fieldDefs(spec.encoding)); } return dict; } /* Returns all non-duplicate fieldDefs in a spec in a flat array */ function fieldDefs(spec) { return util_1.vals(fieldDefIndex(spec)); } exports.fieldDefs = fieldDefs; function isStacked(spec, config) { config = config || spec.config; if (mark_1.isPrimitiveMark(spec.mark)) { return stack_1.stack(spec.mark, spec.encoding, config ? config.stack : undefined) !== null; } return false; } exports.isStacked = isStacked; },{"./channel":12,"./compositemark":84,"./encoding":88,"./log":95,"./mark":97,"./stack":102,"./util":107,"tslib":5}],102:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var aggregate_1 = require("./aggregate"); var channel_1 = require("./channel"); var encoding_1 = require("./encoding"); var fielddef_1 = require("./fielddef"); var log = require("./log"); var mark_1 = require("./mark"); var scale_1 = require("./scale"); var util_1 = require("./util"); exports.STACKABLE_MARKS = [mark_1.BAR, mark_1.AREA, mark_1.RULE, mark_1.POINT, mark_1.CIRCLE, mark_1.SQUARE, mark_1.LINE, mark_1.TEXT, mark_1.TICK]; exports.STACK_BY_DEFAULT_MARKS = [mark_1.BAR, mark_1.AREA]; // Note: CompassQL uses this method and only pass in required properties of each argument object. // If required properties change, make sure to update CompassQL. function stack(m, encoding, stackConfig) { var mark = mark_1.isMarkDef(m) ? m.type : m; // Should have stackable mark if (!util_1.contains(exports.STACKABLE_MARKS, mark)) { return null; } // Should be aggregate plot if (!encoding_1.isAggregate(encoding)) { return null; } // Should have grouping level of detail var stackBy = channel_1.STACK_BY_CHANNELS.reduce(function (sc, channel) { if (encoding_1.channelHasField(encoding, channel)) { var channelDef = encoding[channel]; (util_1.isArray(channelDef) ? channelDef : [channelDef]).forEach(function (cDef) { var fieldDef = fielddef_1.getFieldDef(cDef); if (!fieldDef.aggregate) { sc.push({ channel: channel, fieldDef: fieldDef }); } }); } return sc; }, []); if (stackBy.length === 0) { return null; } // Has only one aggregate axis var hasXField = fielddef_1.isFieldDef(encoding.x); var hasYField = fielddef_1.isFieldDef(encoding.y); var xIsAggregate = fielddef_1.isFieldDef(encoding.x) && !!encoding.x.aggregate; var yIsAggregate = fielddef_1.isFieldDef(encoding.y) && !!encoding.y.aggregate; if (xIsAggregate !== yIsAggregate) { var fieldChannel = xIsAggregate ? channel_1.X : channel_1.Y; var fieldDef = encoding[fieldChannel]; var fieldChannelAggregate = fieldDef.aggregate; var fieldChannelScale = fieldDef.scale; var stackOffset = null; if (fieldDef.stack !== undefined) { stackOffset = fieldDef.stack; } else if (util_1.contains(exports.STACK_BY_DEFAULT_MARKS, mark)) { // Bar and Area with sum ops are automatically stacked by default stackOffset = stackConfig === undefined ? 'zero' : stackConfig; } else { stackOffset = stackConfig; } if (!stackOffset || stackOffset === 'none') { return null; } // If stacked, check if it qualifies for stacking (and log warning if not qualified.) if (fieldChannelScale && fieldChannelScale.type && fieldChannelScale.type !== scale_1.ScaleType.LINEAR) { log.warn(log.message.cannotStackNonLinearScale(fieldChannelScale.type)); return null; } if (encoding_1.channelHasField(encoding, fieldChannel === channel_1.X ? channel_1.X2 : channel_1.Y2)) { log.warn(log.message.cannotStackRangedMark(fieldChannel)); return null; } if (!util_1.contains(aggregate_1.SUM_OPS, fieldChannelAggregate)) { log.warn(log.message.cannotStackNonSummativeAggregate(fieldChannelAggregate)); return null; } return { groupbyChannel: xIsAggregate ? (hasYField ? channel_1.Y : null) : (hasXField ? channel_1.X : null), fieldChannel: fieldChannel, stackBy: stackBy, offset: stackOffset }; } return null; } exports.stack = stack; },{"./aggregate":9,"./channel":12,"./encoding":88,"./fielddef":90,"./log":95,"./mark":97,"./scale":98,"./util":107}],103:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var datetime_1 = require("./datetime"); var log = require("./log"); var util_1 = require("./util"); var TimeUnit; (function (TimeUnit) { TimeUnit.YEAR = 'year'; TimeUnit.MONTH = 'month'; TimeUnit.DAY = 'day'; TimeUnit.DATE = 'date'; TimeUnit.HOURS = 'hours'; TimeUnit.MINUTES = 'minutes'; TimeUnit.SECONDS = 'seconds'; TimeUnit.MILLISECONDS = 'milliseconds'; TimeUnit.YEARMONTH = 'yearmonth'; TimeUnit.YEARMONTHDATE = 'yearmonthdate'; TimeUnit.YEARMONTHDATEHOURS = 'yearmonthdatehours'; TimeUnit.YEARMONTHDATEHOURSMINUTES = 'yearmonthdatehoursminutes'; TimeUnit.YEARMONTHDATEHOURSMINUTESSECONDS = 'yearmonthdatehoursminutesseconds'; // MONTHDATE always include 29 February since we use year 0th (which is a leap year); TimeUnit.MONTHDATE = 'monthdate'; TimeUnit.HOURSMINUTES = 'hoursminutes'; TimeUnit.HOURSMINUTESSECONDS = 'hoursminutesseconds'; TimeUnit.MINUTESSECONDS = 'minutesseconds'; TimeUnit.SECONDSMILLISECONDS = 'secondsmilliseconds'; TimeUnit.QUARTER = 'quarter'; TimeUnit.YEARQUARTER = 'yearquarter'; TimeUnit.QUARTERMONTH = 'quartermonth'; TimeUnit.YEARQUARTERMONTH = 'yearquartermonth'; TimeUnit.UTCYEAR = 'utcyear'; TimeUnit.UTCMONTH = 'utcmonth'; TimeUnit.UTCDAY = 'utcday'; TimeUnit.UTCDATE = 'utcdate'; TimeUnit.UTCHOURS = 'utchours'; TimeUnit.UTCMINUTES = 'utcminutes'; TimeUnit.UTCSECONDS = 'utcseconds'; TimeUnit.UTCMILLISECONDS = 'utcmilliseconds'; TimeUnit.UTCYEARMONTH = 'utcyearmonth'; TimeUnit.UTCYEARMONTHDATE = 'utcyearmonthdate'; TimeUnit.UTCYEARMONTHDATEHOURS = 'utcyearmonthdatehours'; TimeUnit.UTCYEARMONTHDATEHOURSMINUTES = 'utcyearmonthdatehoursminutes'; TimeUnit.UTCYEARMONTHDATEHOURSMINUTESSECONDS = 'utcyearmonthdatehoursminutesseconds'; // MONTHDATE always include 29 February since we use year 0th (which is a leap year); TimeUnit.UTCMONTHDATE = 'utcmonthdate'; TimeUnit.UTCHOURSMINUTES = 'utchoursminutes'; TimeUnit.UTCHOURSMINUTESSECONDS = 'utchoursminutesseconds'; TimeUnit.UTCMINUTESSECONDS = 'utcminutesseconds'; TimeUnit.UTCSECONDSMILLISECONDS = 'utcsecondsmilliseconds'; TimeUnit.UTCQUARTER = 'utcquarter'; TimeUnit.UTCYEARQUARTER = 'utcyearquarter'; TimeUnit.UTCQUARTERMONTH = 'utcquartermonth'; TimeUnit.UTCYEARQUARTERMONTH = 'utcyearquartermonth'; })(TimeUnit = exports.TimeUnit || (exports.TimeUnit = {})); /** Time Unit that only corresponds to only one part of Date objects. */ exports.SINGLE_TIMEUNITS = [ TimeUnit.YEAR, TimeUnit.QUARTER, TimeUnit.MONTH, TimeUnit.DAY, TimeUnit.DATE, TimeUnit.HOURS, TimeUnit.MINUTES, TimeUnit.SECONDS, TimeUnit.MILLISECONDS ]; var SINGLE_TIMEUNIT_INDEX = exports.SINGLE_TIMEUNITS.reduce(function (d, timeUnit) { d[timeUnit] = true; return d; }, {}); function isSingleTimeUnit(timeUnit) { return !!SINGLE_TIMEUNIT_INDEX[timeUnit]; } exports.isSingleTimeUnit = isSingleTimeUnit; /** * Converts a date to only have the measurements relevant to the specified unit * i.e. ('yearmonth', '2000-12-04 07:58:14') -> '2000-12-01 00:00:00' * Note: the base date is Jan 01 1900 00:00:00 */ function convert(unit, date) { var result = new Date(0, 0, 1, 0, 0, 0, 0); // start with uniform date exports.SINGLE_TIMEUNITS.forEach(function (singleUnit) { if (containsTimeUnit(unit, singleUnit)) { switch (singleUnit) { case TimeUnit.DAY: throw new Error('Cannot convert to TimeUnits containing \'day\''); case TimeUnit.YEAR: result.setFullYear(date.getFullYear()); break; case TimeUnit.QUARTER: // indicate quarter by setting month to be the first of the quarter i.e. may (4) -> april (3) result.setMonth((Math.floor(date.getMonth() / 3)) * 3); break; case TimeUnit.MONTH: result.setMonth(date.getMonth()); break; case TimeUnit.DATE: result.setDate(date.getDate()); break; case TimeUnit.HOURS: result.setHours(date.getHours()); break; case TimeUnit.MINUTES: result.setMinutes(date.getMinutes()); break; case TimeUnit.SECONDS: result.setSeconds(date.getSeconds()); break; case TimeUnit.MILLISECONDS: result.setMilliseconds(date.getMilliseconds()); break; } } }); return result; } exports.convert = convert; exports.MULTI_TIMEUNITS = [ TimeUnit.YEARQUARTER, TimeUnit.YEARQUARTERMONTH, TimeUnit.YEARMONTH, TimeUnit.YEARMONTHDATE, TimeUnit.YEARMONTHDATEHOURS, TimeUnit.YEARMONTHDATEHOURSMINUTES, TimeUnit.YEARMONTHDATEHOURSMINUTESSECONDS, TimeUnit.QUARTERMONTH, TimeUnit.HOURSMINUTES, TimeUnit.HOURSMINUTESSECONDS, TimeUnit.MINUTESSECONDS, TimeUnit.SECONDSMILLISECONDS, ]; var MULTI_TIMEUNIT_INDEX = exports.MULTI_TIMEUNITS.reduce(function (d, timeUnit) { d[timeUnit] = true; return d; }, {}); function isMultiTimeUnit(timeUnit) { return !!MULTI_TIMEUNIT_INDEX[timeUnit]; } exports.isMultiTimeUnit = isMultiTimeUnit; exports.TIMEUNITS = [ TimeUnit.YEAR, TimeUnit.QUARTER, TimeUnit.MONTH, TimeUnit.DAY, TimeUnit.DATE, TimeUnit.HOURS, TimeUnit.MINUTES, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, TimeUnit.YEARQUARTER, TimeUnit.YEARQUARTERMONTH, TimeUnit.YEARMONTH, TimeUnit.YEARMONTHDATE, TimeUnit.YEARMONTHDATEHOURS, TimeUnit.YEARMONTHDATEHOURSMINUTES, TimeUnit.YEARMONTHDATEHOURSMINUTESSECONDS, TimeUnit.QUARTERMONTH, TimeUnit.HOURSMINUTES, TimeUnit.HOURSMINUTESSECONDS, TimeUnit.MINUTESSECONDS, TimeUnit.SECONDSMILLISECONDS, ]; /** Returns true if fullTimeUnit contains the timeUnit, false otherwise. */ function containsTimeUnit(fullTimeUnit, timeUnit) { var index = fullTimeUnit.indexOf(timeUnit); return index > -1 && (timeUnit !== TimeUnit.SECONDS || index === 0 || fullTimeUnit.charAt(index - 1) !== 'i' // exclude milliseconds ); } exports.containsTimeUnit = containsTimeUnit; /** * Returns Vega expresssion for a given timeUnit and fieldRef */ function fieldExpr(fullTimeUnit, field) { var fieldRef = "datum[" + util_1.stringValue(field) + "]"; var utc = isUTCTimeUnit(fullTimeUnit) ? 'utc' : ''; function func(timeUnit) { if (timeUnit === TimeUnit.QUARTER) { // quarter starting at 0 (0,3,6,9). return "(" + utc + "quarter(" + fieldRef + ")-1)"; } else { return "" + utc + timeUnit + "(" + fieldRef + ")"; } } var d = exports.SINGLE_TIMEUNITS.reduce(function (dateExpr, tu) { if (containsTimeUnit(fullTimeUnit, tu)) { dateExpr[tu] = func(tu); } return dateExpr; }, {}); if (d.day && util_1.keys(d).length > 1) { log.warn(log.message.dayReplacedWithDate(fullTimeUnit)); delete d.day; d.date = func(TimeUnit.DATE); } return datetime_1.dateTimeExpr(d); } exports.fieldExpr = fieldExpr; /** returns the smallest nice unit for scale.nice */ function smallestUnit(timeUnit) { if (!timeUnit) { return undefined; } if (containsTimeUnit(timeUnit, TimeUnit.SECONDS)) { return 'second'; } if (containsTimeUnit(timeUnit, TimeUnit.MINUTES)) { return 'minute'; } if (containsTimeUnit(timeUnit, TimeUnit.HOURS)) { return 'hour'; } if (containsTimeUnit(timeUnit, TimeUnit.DAY) || containsTimeUnit(timeUnit, TimeUnit.DATE)) { return 'day'; } if (containsTimeUnit(timeUnit, TimeUnit.MONTH)) { return 'month'; } if (containsTimeUnit(timeUnit, TimeUnit.YEAR)) { return 'year'; } return undefined; } exports.smallestUnit = smallestUnit; /** * returns the signal expression used for axis labels for a time unit */ function formatExpression(timeUnit, field, shortTimeLabels, isUTCScale) { if (!timeUnit) { return undefined; } var dateComponents = []; var expression = ''; var hasYear = containsTimeUnit(timeUnit, TimeUnit.YEAR); if (containsTimeUnit(timeUnit, TimeUnit.QUARTER)) { // special expression for quarter as prefix expression = "'Q' + quarter(" + field + ")"; } if (containsTimeUnit(timeUnit, TimeUnit.MONTH)) { // By default use short month name dateComponents.push(shortTimeLabels !== false ? '%b' : '%B'); } if (containsTimeUnit(timeUnit, TimeUnit.DAY)) { dateComponents.push(shortTimeLabels ? '%a' : '%A'); } else if (containsTimeUnit(timeUnit, TimeUnit.DATE)) { dateComponents.push('%d' + (hasYear ? ',' : '')); // add comma if there is year } if (hasYear) { dateComponents.push(shortTimeLabels ? '%y' : '%Y'); } var timeComponents = []; if (containsTimeUnit(timeUnit, TimeUnit.HOURS)) { timeComponents.push('%H'); } if (containsTimeUnit(timeUnit, TimeUnit.MINUTES)) { timeComponents.push('%M'); } if (containsTimeUnit(timeUnit, TimeUnit.SECONDS)) { timeComponents.push('%S'); } if (containsTimeUnit(timeUnit, TimeUnit.MILLISECONDS)) { timeComponents.push('%L'); } var dateTimeComponents = []; if (dateComponents.length > 0) { dateTimeComponents.push(dateComponents.join(' ')); } if (timeComponents.length > 0) { dateTimeComponents.push(timeComponents.join(':')); } if (dateTimeComponents.length > 0) { if (expression) { // Add space between quarter and main time format expression += " + ' ' + "; } if (isUTCScale) { expression += "utcFormat(" + field + ", '" + dateTimeComponents.join(' ') + "')"; } else { expression += "timeFormat(" + field + ", '" + dateTimeComponents.join(' ') + "')"; } } // If expression is still an empty string, return undefined instead. return expression || undefined; } exports.formatExpression = formatExpression; function isDiscreteByDefault(timeUnit) { switch (timeUnit) { // These time unit use discrete scale by default case 'hours': case 'day': case 'month': case 'quarter': return true; } return false; } exports.isDiscreteByDefault = isDiscreteByDefault; function isUTCTimeUnit(timeUnit) { return timeUnit.substr(0, 3) === 'utc'; } },{"./datetime":87,"./log":95,"./util":107}],104:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var TOP_LEVEL_PROPERTIES = [ 'background', 'padding', 'autoResize' ]; function extractTopLevelProperties(t) { return TOP_LEVEL_PROPERTIES.reduce(function (o, p) { if (t && t[p] !== undefined) { o[p] = t[p]; } return o; }, {}); } exports.extractTopLevelProperties = extractTopLevelProperties; },{}],105:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function isFilter(t) { return t['filter'] !== undefined; } exports.isFilter = isFilter; function isLookup(t) { return t['lookup'] !== undefined; } exports.isLookup = isLookup; function isCalculate(t) { return t['calculate'] !== undefined; } exports.isCalculate = isCalculate; function isBin(t) { return t['bin'] !== undefined; } exports.isBin = isBin; function isTimeUnit(t) { return t['timeUnit'] !== undefined; } exports.isTimeUnit = isTimeUnit; function isSummarize(t) { return t['summarize'] !== undefined; } exports.isSummarize = isSummarize; },{}],106:[function(require,module,exports){ "use strict"; /** Constants and utilities for data type */ /** Data type based on level of measurement */ Object.defineProperty(exports, "__esModule", { value: true }); var Type; (function (Type) { Type.QUANTITATIVE = 'quantitative'; Type.ORDINAL = 'ordinal'; Type.TEMPORAL = 'temporal'; Type.NOMINAL = 'nominal'; })(Type = exports.Type || (exports.Type = {})); exports.QUANTITATIVE = Type.QUANTITATIVE; exports.ORDINAL = Type.ORDINAL; exports.TEMPORAL = Type.TEMPORAL; exports.NOMINAL = Type.NOMINAL; /** * Get full, lowercase type name for a given type. * @param type * @return Full type name. */ function getFullName(type) { if (type) { type = type.toLowerCase(); switch (type) { case 'q': case exports.QUANTITATIVE: return 'quantitative'; case 't': case exports.TEMPORAL: return 'temporal'; case 'o': case exports.ORDINAL: return 'ordinal'; case 'n': case exports.NOMINAL: return 'nominal'; } } // If we get invalid input, return undefined type. return undefined; } exports.getFullName = getFullName; },{}],107:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var stringify = require("json-stable-stringify"); var vega_util_1 = require("vega-util"); var logical_1 = require("./logical"); var vega_util_2 = require("vega-util"); exports.extend = vega_util_2.extend; exports.isArray = vega_util_2.isArray; exports.isObject = vega_util_2.isObject; exports.isNumber = vega_util_2.isNumber; exports.isString = vega_util_2.isString; exports.truncate = vega_util_2.truncate; exports.toSet = vega_util_2.toSet; exports.stringValue = vega_util_2.stringValue; /** * Creates an object composed of the picked object properties. * * Example: (from lodash) * * var object = {'a': 1, 'b': '2', 'c': 3}; * pick(object, ['a', 'c']); * // → {'a': 1, 'c': 3} * */ function pick(obj, props) { var copy = {}; props.forEach(function (prop) { if (obj.hasOwnProperty(prop)) { copy[prop] = obj[prop]; } }); return copy; } exports.pick = pick; /** * The opposite of _.pick; this method creates an object composed of the own * and inherited enumerable string keyed properties of object that are not omitted. */ function omit(obj, props) { var copy = duplicate(obj); props.forEach(function (prop) { delete copy[prop]; }); return copy; } exports.omit = omit; function hash(a) { if (vega_util_1.isString(a) || vega_util_1.isNumber(a) || isBoolean(a)) { return String(a); } return stringify(a); } exports.hash = hash; function contains(array, item) { return array.indexOf(item) > -1; } exports.contains = contains; /** Returns the array without the elements in item */ function without(array, excludedItems) { return array.filter(function (item) { return !contains(excludedItems, item); }); } exports.without = without; function union(array, other) { return array.concat(without(other, array)); } exports.union = union; /** * Returns true if any item returns true. */ function some(arr, f) { var i = 0; for (var k = 0; k < arr.length; k++) { if (f(arr[k], k, i++)) { return true; } } return false; } exports.some = some; /** * Returns true if all items return true. */ function every(arr, f) { var i = 0; for (var k = 0; k < arr.length; k++) { if (!f(arr[k], k, i++)) { return false; } } return true; } exports.every = every; function flatten(arrays) { return [].concat.apply([], arrays); } exports.flatten = flatten; /** * recursively merges src into dest */ function mergeDeep(dest) { var src = []; for (var _i = 1; _i < arguments.length; _i++) { src[_i - 1] = arguments[_i]; } for (var _a = 0, src_1 = src; _a < src_1.length; _a++) { var s = src_1[_a]; dest = deepMerge_(dest, s); } return dest; } exports.mergeDeep = mergeDeep; // recursively merges src into dest function deepMerge_(dest, src) { if (typeof src !== 'object' || src === null) { return dest; } for (var p in src) { if (!src.hasOwnProperty(p)) { continue; } if (src[p] === undefined) { continue; } if (typeof src[p] !== 'object' || vega_util_1.isArray(src[p]) || src[p] === null) { dest[p] = src[p]; } else if (typeof dest[p] !== 'object' || dest[p] === null) { dest[p] = mergeDeep(vega_util_1.isArray(src[p].constructor) ? [] : {}, src[p]); } else { mergeDeep(dest[p], src[p]); } } return dest; } function unique(values, f) { var results = []; var u = {}; var v; for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { var val = values_1[_i]; v = f(val); if (v in u) { continue; } u[v] = 1; results.push(val); } return results; } exports.unique = unique; /** * Returns true if the two dictionaries disagree. Applies only to defined values. */ function differ(dict, other) { for (var key in dict) { if (dict.hasOwnProperty(key)) { if (other[key] && dict[key] && other[key] !== dict[key]) { return true; } } } return false; } exports.differ = differ; function hasIntersection(a, b) { for (var key in a) { if (key in b) { return true; } } return false; } exports.hasIntersection = hasIntersection; function differArray(array, other) { if (array.length !== other.length) { return true; } array.sort(); other.sort(); for (var i = 0; i < array.length; i++) { if (other[i] !== array[i]) { return true; } } return false; } exports.differArray = differArray; exports.keys = Object.keys; function vals(x) { var _vals = []; for (var k in x) { if (x.hasOwnProperty(k)) { _vals.push(x[k]); } } return _vals; } exports.vals = vals; function duplicate(obj) { return JSON.parse(JSON.stringify(obj)); } exports.duplicate = duplicate; function isBoolean(b) { return b === true || b === false; } exports.isBoolean = isBoolean; /** * Convert a string into a valid variable name */ function varName(s) { // Replace non-alphanumeric characters (anything besides a-zA-Z0-9_) with _ var alphanumericS = s.replace(/\W/g, '_'); // Add _ if the string has leading numbers. return (s.match(/^\d+/) ? '_' : '') + alphanumericS; } exports.varName = varName; function logicalExpr(op, cb) { if (logical_1.isLogicalNot(op)) { return '!(' + logicalExpr(op.not, cb) + ')'; } else if (logical_1.isLogicalAnd(op)) { return '(' + op.and.map(function (and) { return logicalExpr(and, cb); }).join(') && (') + ')'; } else if (logical_1.isLogicalOr(op)) { return '(' + op.or.map(function (or) { return logicalExpr(or, cb); }).join(') || (') + ')'; } else { return cb(op); } } exports.logicalExpr = logicalExpr; },{"./logical":96,"json-stable-stringify":1,"vega-util":7}],108:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var mark_1 = require("./mark"); var mark_2 = require("./mark"); var util_1 = require("./util"); /** * Required Encoding Channels for each mark type * @type {Object} */ exports.DEFAULT_REQUIRED_CHANNEL_MAP = { text: ['text'], line: ['x', 'y'], area: ['x', 'y'] }; /** * Supported Encoding Channel for each mark type */ exports.DEFAULT_SUPPORTED_CHANNEL_TYPE = { bar: util_1.toSet(['row', 'column', 'x', 'y', 'size', 'color', 'detail']), line: util_1.toSet(['row', 'column', 'x', 'y', 'color', 'detail']), area: util_1.toSet(['row', 'column', 'x', 'y', 'color', 'detail']), tick: util_1.toSet(['row', 'column', 'x', 'y', 'color', 'detail']), circle: util_1.toSet(['row', 'column', 'x', 'y', 'color', 'size', 'detail']), square: util_1.toSet(['row', 'column', 'x', 'y', 'color', 'size', 'detail']), point: util_1.toSet(['row', 'column', 'x', 'y', 'color', 'size', 'detail', 'shape']), text: util_1.toSet(['row', 'column', 'size', 'color', 'text']) // TODO(#724) revise }; // TODO: consider if we should add validate method and // requires ZSchema in the main vega-lite repo /** * Further check if encoding mapping of a spec is invalid and * return error if it is invalid. * * This checks if * (1) all the required encoding channels for the mark type are specified * (2) all the specified encoding channels are supported by the mark type * @param {[type]} spec [description] * @param {RequiredChannelMap = DefaultRequiredChannelMap} requiredChannelMap * @param {SupportedChannelMap = DefaultSupportedChannelMap} supportedChannelMap * @return {String} Return one reason why the encoding is invalid, * or null if the encoding is valid. */ function getEncodingMappingError(spec, requiredChannelMap, supportedChannelMap) { if (requiredChannelMap === void 0) { requiredChannelMap = exports.DEFAULT_REQUIRED_CHANNEL_MAP; } if (supportedChannelMap === void 0) { supportedChannelMap = exports.DEFAULT_SUPPORTED_CHANNEL_TYPE; } var mark = mark_1.isMarkDef(spec.mark) ? spec.mark.type : spec.mark; var encoding = spec.encoding; var requiredChannels = requiredChannelMap[mark]; var supportedChannels = supportedChannelMap[mark]; for (var i in requiredChannels) { if (!(requiredChannels[i] in encoding)) { return 'Missing encoding channel \"' + requiredChannels[i] + '\" for mark \"' + mark + '\"'; } } for (var channel in encoding) { if (!supportedChannels[channel]) { return 'Encoding channel \"' + channel + '\" is not supported by mark type \"' + mark + '\"'; } } if (mark === mark_2.BAR && !encoding.x && !encoding.y) { return 'Missing both x and y for bar'; } return null; } exports.getEncodingMappingError = getEncodingMappingError; },{"./mark":97,"./util":107}],109:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require("./util"); function isVgSignalRef(o) { return !!o['signal']; } exports.isVgSignalRef = isVgSignalRef; function isVgRangeStep(range) { return !!range['step']; } exports.isVgRangeStep = isVgRangeStep; function isDataRefUnionedDomain(domain) { if (!util_1.isArray(domain)) { return 'fields' in domain && !('data' in domain); } return false; } exports.isDataRefUnionedDomain = isDataRefUnionedDomain; function isFieldRefUnionDomain(domain) { if (!util_1.isArray(domain)) { return 'fields' in domain && 'data' in domain; } return false; } exports.isFieldRefUnionDomain = isFieldRefUnionDomain; function isDataRefDomain(domain) { if (!util_1.isArray(domain)) { return 'field' in domain && 'data' in domain; } return false; } exports.isDataRefDomain = isDataRefDomain; function isSignalRefDomain(domain) { if (!util_1.isArray(domain)) { return 'signal' in domain; } return false; } exports.isSignalRefDomain = isSignalRefDomain; },{"./util":107}]},{},[93])(93) }); //# sourceMappingURL=vega-lite.js.map
packages/mui-icons-material/lib/esm/NordicWalkingTwoTone.js
oliviertassinari/material-ui
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M19 23h-1.5v-9H19v9zM7.53 14H6l-2 9h1.53l2-9zm5.97-8.5c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zM9.8 8.9 7 23h2.1l1.8-8 2.1 2v6h2v-7.5l-2.1-2 .6-3C14.8 12 16.8 13 19 13v-2c-1.9 0-3.5-1-4.3-2.4l-1-1.6c-.56-.89-1.68-1.25-2.65-.84L6 8.3V13h2V9.6l1.8-.7z" }), 'NordicWalkingTwoTone');
ajax/libs/react-cookie/0.2.1/react-cookie.js
schoren/cdnjs
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ var cookie = require('cookie'); var _rawCookies = {}; var _cookies = {}; if (typeof document !== 'undefined') { setRawCookie(document.cookie); } function load(name, doNotParse) { if (doNotParse) { return _rawCookies[name]; } return _cookies[name]; } function save(name, val, opt) { _cookies[name] = val; _rawCookies[name] = val; // allow you to work with cookies as objects. if (typeof val === 'object') { _rawCookies[name] = JSON.stringify(val); } // Cookies only work in the browser if (typeof document !== 'undefined') { document.cookie = cookie.serialize(name, val, opt); } } function remove(name) { delete _rawCookies[name]; delete _cookies[name]; if (typeof document !== 'undefined') { document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'; } } function setRawCookie(rawCookie) { var rawCookies = cookie.parse(rawCookie); for (var key in rawCookies) { _rawCookies[key] = rawCookies[key]; try { _cookies[key] = JSON.parse(rawCookies[key]); } catch(e) { // Not serialized object _cookies[key] = rawCookies[key]; } } } var reactCookie = { load: load, save: save, remove: remove, setRawCookie: setRawCookie }; if (typeof window !== 'undefined') { window['reactCookie'] = reactCookie; } module.exports = reactCookie; },{"cookie":2}],2:[function(require,module,exports){ /// Serialize the a name value pair into a cookie string suitable for /// http headers. An optional options object specified cookie parameters /// /// serialize('foo', 'bar', { httpOnly: true }) /// => "foo=bar; httpOnly" /// /// @param {String} name /// @param {String} val /// @param {Object} options /// @return {String} var serialize = function(name, val, opt){ opt = opt || {}; var enc = opt.encode || encode; var pairs = [name + '=' + enc(val)]; if (null != opt.maxAge) { var maxAge = opt.maxAge - 0; if (isNaN(maxAge)) throw new Error('maxAge should be a Number'); pairs.push('Max-Age=' + maxAge); } if (opt.domain) pairs.push('Domain=' + opt.domain); if (opt.path) pairs.push('Path=' + opt.path); if (opt.expires) pairs.push('Expires=' + opt.expires.toUTCString()); if (opt.httpOnly) pairs.push('HttpOnly'); if (opt.secure) pairs.push('Secure'); return pairs.join('; '); }; /// Parse the given cookie header string into an object /// The object has the various cookies as keys(names) => values /// @param {String} str /// @return {Object} var parse = function(str, opt) { opt = opt || {}; var obj = {} var pairs = str.split(/; */); var dec = opt.decode || decode; pairs.forEach(function(pair) { var eq_idx = pair.indexOf('=') // skip things that don't look like key=value if (eq_idx < 0) { return; } var key = pair.substr(0, eq_idx).trim() var val = pair.substr(++eq_idx, pair.length).trim(); // quoted values if ('"' == val[0]) { val = val.slice(1, -1); } // only assign once if (undefined == obj[key]) { try { obj[key] = dec(val); } catch (e) { obj[key] = val; } } }); return obj; }; var encode = encodeURIComponent; var decode = decodeURIComponent; module.exports.serialize = serialize; module.exports.parse = parse; },{}]},{},[1]);
Tests/Components/FullButtonTest.js
oreofish/v2exClient
// https://github.com/airbnb/enzyme/blob/master/docs/api/shallow.md import test from 'ava' import React from 'react' import FullButton from '../../App/Components/FullButton' import { shallow } from 'enzyme' // Basic wrapper const wrapper = shallow(<FullButton onPress={() => {}} text='hi' />) test('component exists', (t) => { t.is(wrapper.length, 1) // exists }) test('component structure', (t) => { t.is(wrapper.name(), 'TouchableOpacity') // the right root component t.is(wrapper.children().length, 1) // has 1 child t.is(wrapper.children().first().name(), 'Text') // that child is Text }) test('onPress', (t) => { let i = 0 // i guess i could have used sinon here too... less is more i guess const onPress = () => i++ const wrapperPress = shallow(<FullButton onPress={onPress} text='hi' />) t.is(wrapperPress.prop('onPress'), onPress) // uses the right handler t.is(i, 0) wrapperPress.simulate('press') t.is(i, 1) })
blueocean-material-icons/src/js/components/svg-icons/av/call-to-action.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const AvCallToAction = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3v-3h18v3z"/> </SvgIcon> ); AvCallToAction.displayName = 'AvCallToAction'; AvCallToAction.muiName = 'SvgIcon'; export default AvCallToAction;
src/components/Generations.js
CharmedSatyr/game_of_life
import React from 'react'; import PropTypes from 'prop-types'; const Generations = ({ generation }) => ( <div className="generations"> <h1> Generation: <span className="num">{generation}</span> </h1> </div> ); export default Generations; Generations.propTypes = { generation: PropTypes.number.isRequired, };
client/js/components/Main.js
bmacheski/tech-connect
'use strict'; import React from 'react'; import Navbar from './Navbar'; import Footer from './Footer'; import { RouteHandler } from 'react-router'; import '../styles/HomeStyles.scss'; class Main extends React.Component { render() { return ( <div className="ui grid"> <Navbar /> <div className="main-container"> <RouteHandler {...this.props} /> </div> </div> ) } }; export default Main;
demo/react-0.14.3/react-starter-kit/src/decorators/withViewport.js
waterbolik/prestudy
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { Component } from 'react'; // 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 }); // eslint-disable-line react/no-set-state } }; } export default withViewport;
app/scripts/GalleryTracks.js
hms-dbmi/higlass
import PropTypes from 'prop-types'; import React from 'react'; import TrackControl from './TrackControl'; // Styles import styles from '../styles/GalleryTracks.module.scss'; // eslint-disable-line no-unused-vars import stylesPlot from '../styles/TiledPlot.module.scss'; // eslint-disable-line no-unused-vars import stylesTrack from '../styles/Track.module.scss'; // eslint-disable-line no-unused-vars const STYLES = { pointerEvents: 'all', }; class GalleryTracks extends React.Component { constructor(props) { super(props); this.state = { hovering: false }; } mouseEnterHandler() { this.setState({ hovering: true }); } mouseLeaveHandler() { this.setState({ hovering: false }); } render() { return ( <div className="gallery-tracks" styleName="styles.gallery-tracks"> {this.props.tracks && this.props.tracks.map((track, index) => ( <div key={track.uid || index} onMouseLeave={this.mouseLeaveHandler.bind(this)} style={{ top: track.height * index, right: track.height * index, bottom: track.height * index, left: track.height * index, }} styleName="styles.gallery-track" > <div onMouseEnter={this.mouseEnterHandler.bind(this)} style={{ top: 0, right: 0, left: 0, height: track.height, }} styleName="styles.gallery-sub-track" /> <div onMouseEnter={this.mouseEnterHandler.bind(this)} style={{ top: 0, right: 0, bottom: 0, width: track.height, }} styleName="styles.gallery-sub-track" /> <div onMouseEnter={this.mouseEnterHandler.bind(this)} style={{ right: 0, bottom: 0, left: 0, height: track.height, }} styleName="styles.gallery-sub-track" /> <div onMouseEnter={this.mouseEnterHandler.bind(this)} style={{ top: 0, bottom: 0, left: 0, width: track.height, }} styleName="styles.gallery-sub-track" /> <div onMouseLeave={this.mouseLeaveHandler.bind(this)} style={{ top: track.height, right: track.height, bottom: track.height, left: track.height, }} styleName="styles.gallery-invisible-track" /> {this.props.editable && ( <TrackControl configMenuVisible={true} imgStyleAdd={STYLES} imgStyleClose={STYLES} imgStyleMove={STYLES} imgStyleSettings={STYLES} isMoveable={false} isVisible={this.state.hovering} onCloseTrackMenuOpened={this.props.onCloseTrackMenuOpened} onConfigTrackMenuOpened={this.props.onConfigTrackMenuOpened} uid={track.uid || index} /> )} </div> ))} </div> ); } } GalleryTracks.propTypes = { editable: PropTypes.bool.isRequired, onCloseTrackMenuOpened: PropTypes.func.isRequired, onConfigTrackMenuOpened: PropTypes.func.isRequired, tracks: PropTypes.array.isRequired, }; export default GalleryTracks;
node_modules/bower/node_modules/inquirer/node_modules/rx/dist/rx.all.js
JasonYoungtheThird/localjams
// 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'; }, 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; }()); function cloneArray(arr) { for(var a = [], i = 0, len = arr.length; i < len; i++) { a.push(arr[i]); } return a;} Rx.config.longStackSupport = false; var hasStacks = false; try { throw new Error(); } catch (e) { hasStacks = !!e.stack; } // All code after this point will be filtered from stack traces reported by RxJS var rStartingLine = captureLine(), rFileName; var STACK_JUMP_SEPARATOR = "From previous event:"; function makeStackTraceLong(error, observable) { // If possible, transform the error stack trace by removing Node and RxJS // cruft, then concatenating with the stack trace of `observable`. if (hasStacks && observable.stack && typeof error === "object" && error !== null && error.stack && error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 ) { var stacks = []; for (var o = observable; !!o; o = o.source) { if (o.stack) { stacks.unshift(o.stack); } } stacks.unshift(error.stack); var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); error.stack = filterStackString(concatedStacks); } } function filterStackString(stackString) { var lines = stackString.split("\n"), desiredLines = []; for (var i = 0, len = lines.length; i < len; i++) { var line = lines[i]; if (!isInternalFrame(line) && !isNodeFrame(line) && line) { desiredLines.push(line); } } return desiredLines.join("\n"); } function isInternalFrame(stackLine) { var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); if (!fileNameAndLineNumber) { return false; } var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1]; return fileName === rFileName && lineNumber >= rStartingLine && lineNumber <= rEndingLine; } function isNodeFrame(stackLine) { return stackLine.indexOf("(module.js:") !== -1 || stackLine.indexOf("(node.js:") !== -1; } function captureLine() { if (!hasStacks) { return; } try { throw new Error(); } catch (e) { var lines = e.stack.split("\n"); var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); if (!fileNameAndLineNumber) { return; } rFileName = fileNameAndLineNumber[0]; return fileNameAndLineNumber[1]; } } function getFileNameAndLineNumber(stackLine) { // Named functions: "at functionName (filename:lineNumber:columnNumber)" var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); if (attempt1) { return [attempt1[1], Number(attempt1[2])]; } // Anonymous functions: "at filename:lineNumber:columnNumber" var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } // Firefox style: "function@filename:lineNumber or @filename:lineNumber" var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } } var EmptyError = Rx.EmptyError = function() { this.message = 'Sequence contains no elements.'; Error.call(this); }; EmptyError.prototype = Error.prototype; var ObjectDisposedError = Rx.ObjectDisposedError = function() { this.message = 'Object has been disposed'; Error.call(this); }; ObjectDisposedError.prototype = Error.prototype; var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () { this.message = 'Argument out of range'; Error.call(this); }; ArgumentOutOfRangeError.prototype = Error.prototype; var NotSupportedError = Rx.NotSupportedError = function (message) { this.message = message || 'This operation is not supported'; Error.call(this); }; NotSupportedError.prototype = Error.prototype; var NotImplementedError = Rx.NotImplementedError = function (message) { this.message = message || 'This operation is not implemented'; Error.call(this); }; NotImplementedError.prototype = Error.prototype; var notImplemented = Rx.helpers.notImplemented = function () { throw new NotImplementedError(); }; var notSupported = Rx.helpers.notSupported = function () { throw new NotSupportedError(); }; // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; var isIterable = Rx.helpers.isIterable = function (o) { return o[$iterator$] !== undefined; } var isArrayLike = Rx.helpers.isArrayLike = function (o) { return o && o.length !== undefined; } Rx.helpers.iterator = $iterator$; var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) { if (typeof thisArg === 'undefined') { return func; } switch(argCount) { case 0: return function() { return func.call(thisArg) }; case 1: return function(arg) { return func.call(thisArg, arg); } case 2: return function(value, index) { return func.call(thisArg, value, index); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; } return function() { return func.apply(thisArg, arguments); }; }; /** Used to determine if values are of the language type Object */ var dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'], dontEnumsLength = dontEnums.length; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 supportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, stringProto = String.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch (e) { supportNodeClass = true; } var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); var isObject = Rx.internals.isObject = function(value) { var type = typeof value; return value && (type == 'function' || type == 'object') || false; }; function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = dontEnumsLength; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = dontEnums[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } var isArguments = function(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b : // but treat `-0` vs. `+0` as not equal (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; var result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var hasProp = {}.hasOwnProperty, slice = Array.prototype.slice; var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; var addProperties = Rx.internals.addProperties = function (obj) { for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } for (var idx = 0, ln = sources.length; idx < ln; idx++) { var source = sources[idx]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } var errorObj = {e: {}}; var tryCatchTarget; function tryCatcher() { try { return tryCatchTarget.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch(fn) { if (!isFunction(fn)) { throw new TypeError('fn must be a function'); } tryCatchTarget = fn; return tryCatcher; } function thrower(e) { throw e; } // Collections function IndexedItem(id, value) { this.id = id; this.value = value; } IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); c === 0 && (c = this.id - other.id); return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { +index || (index = 0); if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; this.items[this.length] = undefined; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { var args = [], i, len; if (Array.isArray(arguments[0])) { args = arguments[0]; len = args.length; } else { len = arguments.length; args = new Array(len); for(i = 0; i < len; i++) { args[i] = arguments[i]; } } for(i = 0; i < len; i++) { if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); } } this.disposables = args; this.isDisposed = false; this.length = args.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var len = this.disposables.length, currentDisposables = new Array(len); for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; } this.disposables = []; this.length = 0; for (i = 0; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Provides a set of static methods for creating Disposables. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; /** * Validates whether the given object is a disposable * @param {Object} Object to test whether it has a dispose method * @returns {Boolean} true if a disposable object, else false. */ var isDisposable = Disposable.isDisposable = function (d) { return d && isFunction(d.dispose); }; var checkDisposed = Disposable.checkDisposed = function (disposable) { if (disposable.isDisposed) { throw new ObjectDisposedError(); } }; // Single assignment var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () { this.isDisposed = false; this.current = null; }; SingleAssignmentDisposable.prototype.getDisposable = function () { return this.current; }; SingleAssignmentDisposable.prototype.setDisposable = function (value) { if (this.current) { throw new Error('Disposable has already been assigned'); } var shouldDispose = this.isDisposed; !shouldDispose && (this.current = value); shouldDispose && value && value.dispose(); }; SingleAssignmentDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var old = this.current; this.current = null; } old && old.dispose(); }; // Multiple assignment disposable var SerialDisposable = Rx.SerialDisposable = function () { this.isDisposed = false; this.current = null; }; SerialDisposable.prototype.getDisposable = function () { return this.current; }; SerialDisposable.prototype.setDisposable = function (value) { var shouldDispose = this.isDisposed; if (!shouldDispose) { var old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; SerialDisposable.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var old = this.current; this.current = null; } old && old.dispose(); }; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed && !this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed && !this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } function scheduleItem(s, self) { if (!self.isDisposed) { self.isDisposed = true; self.disposable.dispose(); } } ScheduledDisposable.prototype.dispose = function () { this.scheduler.scheduleWithState(this, scheduleItem); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } /** Determines whether the given object is a scheduler */ Scheduler.isScheduler = function (s) { return s instanceof Scheduler; } 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, isScheduler = Scheduler.isScheduler; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); function recursiveAction(state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); } recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); function recursiveAction(state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method](state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function scheduleInnerRecursive(action, self) { action(function(dt) { self(action, dt); }); } /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState([state, action], invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative([state, action], dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute([state, action], dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, action); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) { if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); } period = normalizeTime(period); var s = state, id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchError = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; }(Scheduler.prototype)); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); /** Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline () { while (queue.length > 0) { var item = queue.dequeue(); !item.isCancelled() && item.invoke(); } } function scheduleNow(state, action) { var si = new ScheduledItem(this, state, action, this.now()); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); var result = tryCatch(runTrampoline)(); queue = null; if (result === errorObj) { return thrower(result.e); } } else { queue.enqueue(si); } return si.disposable; } var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); currentScheduler.scheduleRequired = function () { return !queue; }; return currentScheduler; }()); var scheduleMethod, clearMethod; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else if (!!root.WScript) { localSetTimeout = function (fn, time) { root.WScript.Sleep(time); fn(); }; } else { throw new NotSupportedError(); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false; clearMethod = function (handle) { delete tasksByHandle[handle]; }; function runTask(handle) { if (currentlyRunning) { localSetTimeout(function () { runTask(handle) }, 0); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunning = true; var result = tryCatch(task)(); clearMethod(handle); currentlyRunning = false; if (result === errorObj) { return thrower(result.e); } } } } var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('', '*'); root.onmessage = oldHandler; return isAsync; } // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout if (isFunction(setImmediate)) { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; setImmediate(function () { runTask(id); }); return id; }; } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; process.nextTick(function () { runTask(id); }); return id; }; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(); function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { runTask(event.data.substring(MSG_PREFIX.length)); } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else if (root.attachEvent) { root.attachEvent('onmessage', onGlobalPostMessage); } else { root.onmessage = onGlobalPostMessage; } scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; root.postMessage(MSG_PREFIX + currentId, '*'); return id; }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(); channel.port1.onmessage = function (e) { runTask(e.data); }; scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; channel.port2.postMessage(id); return id; }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); var id = nextHandle++; tasksByHandle[id] = action; scriptElement.onreadystatechange = function () { runTask(id); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); return id; }; } else { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; localSetTimeout(function () { runTask(id); }, 0); return id; }; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = Scheduler['default'] = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { !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), disposable = new SingleAssignmentDisposable(); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var id = localSetTimeout(function () { !disposable.isDisposed && disposable.setDisposable(action(scheduler, state)); }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { localClearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); var CatchScheduler = (function (__super__) { function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, __super__); function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; __super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute); } CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, value, exception, accept, acceptObservable, toString) { this.kind = kind; this.value = value; this.exception = exception; this._accept = accept; this._acceptObservable = acceptObservable; this.toString = toString; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var self = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithState(self, function (_, notification) { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept(onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString() { return 'OnNext(' + this.value + ')'; } return function (value) { return new Notification('N', value, null, _accept, _acceptObservable, toString); }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (e) { return new Notification('E', null, e, _accept, _acceptObservable, toString); }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { return new Notification('C', null, null, _accept, _acceptObservable, toString); }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { return o.onCompleted(); } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function(err) { o.onError(err); }, self) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchError = function () { var sources = this; return new AnonymousObservable(function (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return observer.onError(ex); } if (currentItem.done) { if (lastException !== null) { o.onError(lastException); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, self, function() { o.onCompleted(); })); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchErrorWhen = function (notificationHandler) { var sources = this; return new AnonymousObservable(function (o) { var exceptions = new Subject(), notifier = new Subject(), handled = notificationHandler(exceptions), notificationDisposable = handled.subscribe(notifier); var e = sources[$iterator$](); var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { if (lastException) { o.onError(lastException); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var outer = new SingleAssignmentDisposable(); var inner = new SingleAssignmentDisposable(); subscription.setDisposable(new CompositeDisposable(inner, outer)); outer.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function (exn) { inner.setDisposable(notifier.subscribe(self, function(ex) { o.onError(ex); }, function() { o.onCompleted(); })); exceptions.onNext(exn); }, function() { o.onCompleted(); })); }); return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableOf = Enumerable.of = function (source, selector, thisArg) { if (selector) { var selectorFn = bindCallback(selector, thisArg, 3); } return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: !selector ? source[index] : selectorFn(source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler, thisArg) { return new AnonymousObserver(function (x) { return handler.call(thisArg, notificationCreateOnNext(x)); }, function (e) { return handler.call(thisArg, notificationCreateOnError(e)); }, function () { return handler.call(thisArg, notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.prototype.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; Observer.prototype.makeSafe = function(disposable) { return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { inherits(AbstractObserver, __super__); /** * Creates a new observer in a non-stopped state. */ function AbstractObserver() { this.isStopped = false; __super__.call(this); } // Must be implemented by other observers AbstractObserver.prototype.next = notImplemented; AbstractObserver.prototype.error = notImplemented; AbstractObserver.prototype.completed = notImplemented; /** * Notifies the observer of a new element in the sequence. * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { inherits(AnonymousObserver, __super__); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { __super__.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (error) { this._onError(error); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (__super__) { inherits(CheckedObserver, __super__); function CheckedObserver(observer) { __super__.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); var res = tryCatch(this._observer.onNext).call(this._observer, value); this._state = 0; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); var res = tryCatch(this._observer.onError).call(this._observer, err); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); var res = tryCatch(this._observer.onCompleted).call(this._observer); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); function ScheduledObserver(scheduler, observer) { __super__.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (e) { var self = this; this.queue.push(function () { self.observer.onError(e); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver(scheduler, observer, cancel) { __super__.call(this, scheduler, observer); this._cancel = cancel; } ObserveOnObserver.prototype.next = function (value) { __super__.prototype.next.call(this, value); this.ensureActive(); }; ObserveOnObserver.prototype.error = function (e) { __super__.prototype.error.call(this, e); this.ensureActive(); }; ObserveOnObserver.prototype.completed = function () { __super__.prototype.completed.call(this); this.ensureActive(); }; ObserveOnObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this._cancel && this._cancel.dispose(); this._cancel = null; }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { if (Rx.config.longStackSupport && hasStacks) { try { throw new Error(); } catch (e) { this.stack = e.stack.substring(e.stack.indexOf("\n") + 1); } var self = this; this._subscribe = function (observer) { var oldOnError = observer.onError.bind(observer); observer.onError = function (err) { makeStackTraceLong(err, self); oldOnError(err); }; return subscribe.call(self, observer); }; } else { this._subscribe = subscribe; } } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { return this._subscribe(typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnNext = function (onNext, thisArg) { return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext)); }; /** * Subscribes to an exceptional condition in the sequence with an optional "this" argument. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnError = function (onError, thisArg) { return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); var ObservableBase = Rx.ObservableBase = (function (__super__) { inherits(ObservableBase, __super__); function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], self = state[1]; var sub = tryCatch(self.subscribeCore).call(self, ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function subscribe(observer) { var ado = new AutoDetachObserver(observer), state = [ado, this]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } function ObservableBase() { __super__.call(this, subscribe); } ObservableBase.prototype.subscribeCore = notImplemented; return ObservableBase; }(Observable)); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }, source); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }, source); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return observableDefer(function () { var subject = new Rx.AsyncSubject(); promise.then( function (value) { subject.onNext(value); subject.onCompleted(); }, subject.onError.bind(subject)); return subject; }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, reject, function () { hasValue && resolve(value); }); }); }; var ToArrayObservable = (function(__super__) { inherits(ToArrayObservable, __super__); function ToArrayObservable(source) { this.source = source; __super__.call(this); } ToArrayObservable.prototype.subscribeCore = function(observer) { return this.source.subscribe(new ToArrayObserver(observer)); }; return ToArrayObservable; }(ObservableBase)); function ToArrayObserver(observer) { this.observer = observer; this.a = []; this.isStopped = false; } ToArrayObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } }; ToArrayObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; ToArrayObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.observer.onNext(this.a); this.observer.onCompleted(); } }; ToArrayObserver.prototype.dispose = function () { this.isStopped = true; } ToArrayObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Creates an array from an observable sequence. * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { return new ToArrayObservable(this); }; /** * Creates an observable sequence from a specified subscribe method implementation. * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe, parent) { return new AnonymousObservable(subscribe, parent); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; var EmptyObservable = (function(__super__) { inherits(EmptyObservable, __super__); function EmptyObservable(scheduler) { this.scheduler = scheduler; __super__.call(this); } EmptyObservable.prototype.subscribeCore = function (observer) { var sink = new EmptySink(observer, this); return sink.run(); }; function EmptySink(observer, parent) { this.observer = observer; this.parent = parent; } function scheduleItem(s, state) { state.onCompleted(); } EmptySink.prototype.run = function () { return this.parent.scheduler.scheduleWithState(this.observer, scheduleItem); }; return EmptyObservable; }(ObservableBase)); /** * 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 EmptyObservable(scheduler); }; var FromObservable = (function(__super__) { inherits(FromObservable, __super__); function FromObservable(iterable, mapper, scheduler) { this.iterable = iterable; this.mapper = mapper; this.scheduler = scheduler; __super__.call(this); } FromObservable.prototype.subscribeCore = function (observer) { var sink = new FromSink(observer, this); return sink.run(); }; return FromObservable; }(ObservableBase)); var FromSink = (function () { function FromSink(observer, parent) { this.observer = observer; this.parent = parent; } FromSink.prototype.run = function () { var list = Object(this.parent.iterable), it = getIterable(list), observer = this.observer, mapper = this.parent.mapper; function loopRecursive(i, recurse) { try { var next = it.next(); } catch (e) { return observer.onError(e); } if (next.done) { return observer.onCompleted(); } var result = next.value; if (mapper) { try { result = mapper(result, i); } catch (e) { return observer.onError(e); } } observer.onNext(result); recurse(i + 1); } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return FromSink; }()); var maxSafeInteger = Math.pow(2, 53) - 1; function StringIterable(str) { this._s = s; } StringIterable.prototype[$iterator$] = function () { return new StringIterator(this._s); }; function StringIterator(str) { this._s = s; this._l = s.length; this._i = 0; } StringIterator.prototype[$iterator$] = function () { return this; }; StringIterator.prototype.next = function () { return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator; }; function ArrayIterable(a) { this._a = a; } ArrayIterable.prototype[$iterator$] = function () { return new ArrayIterator(this._a); }; function ArrayIterator(a) { this._a = a; this._l = toLength(a); this._i = 0; } ArrayIterator.prototype[$iterator$] = function () { return this; }; ArrayIterator.prototype.next = function () { return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator; }; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function getIterable(o) { var i = o[$iterator$], it; if (!i && typeof o === 'string') { it = new StringIterable(o); return it[$iterator$](); } if (!i && o.length !== undefined) { it = new ArrayIterable(o); return it[$iterator$](); } if (!i) { throw new TypeError('Object is not iterable'); } return o[$iterator$](); } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isFunction(mapFn)) { throw new Error('mapFn when provided must be a function'); } if (mapFn) { var mapper = bindCallback(mapFn, thisArg, 2); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromObservable(iterable, mapper, scheduler); } var FromArrayObservable = (function(__super__) { inherits(FromArrayObservable, __super__); function FromArrayObservable(args, scheduler) { this.args = args; this.scheduler = scheduler; __super__.call(this); } FromArrayObservable.prototype.subscribeCore = function (observer) { var sink = new FromArraySink(observer, this); return sink.run(); }; return FromArrayObservable; }(ObservableBase)); function FromArraySink(observer, parent) { this.observer = observer; this.parent = parent; } FromArraySink.prototype.run = function () { var observer = this.observer, args = this.parent.args, len = args.length; function loopRecursive(i, recurse) { if (i < len) { observer.onNext(args[i]); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * @deprecated use Observable.from or Observable.of * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler) }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (o) { var first = true; return scheduler.scheduleRecursiveWithState(initialState, function (state, self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); hasResult && (result = resultSelector(state)); } catch (e) { return o.onError(e); } if (hasResult) { o.onNext(result); self(state); } else { o.onCompleted(); } }); }); }; function observableOf (scheduler, array) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler); } /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new FromArrayObservable(args, currentThreadScheduler); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.ofWithScheduler = function (scheduler) { var len = arguments.length, args = new Array(len - 1); for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; } return new FromArrayObservable(args, scheduler); }; /** * Creates an Observable sequence from changes to an array using Array.observe. * @param {Array} array An array to observe changes. * @returns {Observable} An observable sequence containing changes to an array from Array.observe. */ Observable.ofArrayChanges = function(array) { if (!Array.isArray(array)) { throw new TypeError('Array.observe only accepts arrays.'); } if (typeof Array.observe !== 'function' && typeof Array.unobserve !== 'function') { throw new TypeError('Array.observe is not supported on your platform') } return new AnonymousObservable(function(observer) { function observerFn(changes) { for(var i = 0, len = changes.length; i < len; i++) { observer.onNext(changes[i]); } } Array.observe(array, observerFn); return function () { Array.unobserve(array, observerFn); }; }); }; /** * Creates an Observable sequence from changes to an object using Object.observe. * @param {Object} obj An object to observe changes. * @returns {Observable} An observable sequence containing changes to an object from Object.observe. */ Observable.ofObjectChanges = function(obj) { if (obj == null) { throw new TypeError('object must not be null or undefined.'); } if (typeof Object.observe !== 'function' && typeof Object.unobserve !== 'function') { throw new TypeError('Array.observe is not supported on your platform') } return new AnonymousObservable(function(observer) { function observerFn(changes) { for(var i = 0, len = changes.length; i < len; i++) { observer.onNext(changes[i]); } } Object.observe(obj, observerFn); return function () { Object.unobserve(obj, observerFn); }; }); }; var NeverObservable = (function(__super__) { inherits(NeverObservable, __super__); function NeverObservable() { __super__.call(this); } NeverObservable.prototype.subscribeCore = function (observer) { return disposableEmpty; }; return NeverObservable; }(ObservableBase)); /** * 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 NeverObservable(); }; var PairsObservable = (function(__super__) { inherits(PairsObservable, __super__); function PairsObservable(obj, scheduler) { this.obj = obj; this.keys = Object.keys(obj); this.scheduler = scheduler; __super__.call(this); } PairsObservable.prototype.subscribeCore = function (observer) { var sink = new PairsSink(observer, this); return sink.run(); }; return PairsObservable; }(ObservableBase)); function PairsSink(observer, parent) { this.observer = observer; this.parent = parent; } PairsSink.prototype.run = function () { var observer = this.observer, obj = this.parent.obj, keys = this.parent.keys, len = keys.length; function loopRecursive(i, recurse) { if (i < len) { var key = keys[i]; observer.onNext([key, obj[key]]); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; /** * Convert an object into an observable sequence of [key, value] pairs. * @param {Object} obj The object to inspect. * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} An observable sequence of [key, value] pairs from the object. */ Observable.pairs = function (obj, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new PairsObservable(obj, scheduler); }; var RangeObservable = (function(__super__) { inherits(RangeObservable, __super__); function RangeObservable(start, count, scheduler) { this.start = start; this.count = count; this.scheduler = scheduler; __super__.call(this); } RangeObservable.prototype.subscribeCore = function (observer) { var sink = new RangeSink(observer, this); return sink.run(); }; return RangeObservable; }(ObservableBase)); var RangeSink = (function () { function RangeSink(observer, parent) { this.observer = observer; this.parent = parent; } RangeSink.prototype.run = function () { var start = this.parent.start, count = this.parent.count, observer = this.observer; function loopRecursive(i, recurse) { if (i < count) { observer.onNext(start + i); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return RangeSink; }()); /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new RangeObservable(start, count, scheduler); }; var RepeatObservable = (function(__super__) { inherits(RepeatObservable, __super__); function RepeatObservable(value, repeatCount, scheduler) { this.value = value; this.repeatCount = repeatCount == null ? -1 : repeatCount; this.scheduler = scheduler; __super__.call(this); } RepeatObservable.prototype.subscribeCore = function (observer) { var sink = new RepeatSink(observer, this); return sink.run(); }; return RepeatObservable; }(ObservableBase)); function RepeatSink(observer, parent) { this.observer = observer; this.parent = parent; } RepeatSink.prototype.run = function () { var observer = this.observer, value = this.parent.value; function loopRecursive(i, recurse) { if (i === -1 || i > 0) { observer.onNext(value); i > 0 && i--; } if (i === 0) { return observer.onCompleted(); } recurse(i); } return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount, loopRecursive); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new RepeatObservable(value, repeatCount, scheduler); }; var JustObservable = (function(__super__) { inherits(JustObservable, __super__); function JustObservable(value, scheduler) { this.value = value; this.scheduler = scheduler; __super__.call(this); } JustObservable.prototype.subscribeCore = function (observer) { var sink = new JustSink(observer, this); return sink.run(); }; function JustSink(observer, parent) { this.observer = observer; this.parent = parent; } function scheduleItem(s, state) { var value = state[0], observer = state[1]; observer.onNext(value); observer.onCompleted(); } JustSink.prototype.run = function () { return this.parent.scheduler.scheduleWithState([this.parent.value, this.observer], scheduleItem); }; return JustObservable; }(ObservableBase)); /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just' or browsers <IE9. * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.just = Observable.returnValue = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new JustObservable(value, scheduler); }; var ThrowObservable = (function(__super__) { inherits(ThrowObservable, __super__); function ThrowObservable(error, scheduler) { this.error = error; this.scheduler = scheduler; __super__.call(this); } ThrowObservable.prototype.subscribeCore = function (observer) { var sink = new ThrowSink(observer, this); return sink.run(); }; function ThrowSink(observer, parent) { this.observer = observer; this.parent = parent; } function scheduleItem(s, state) { var error = state[0], observer = state[1]; observer.onError(error); } ThrowSink.prototype.run = function () { return this.parent.scheduler.scheduleWithState([this.parent.error, this.observer], scheduleItem); }; return ThrowObservable; }(ObservableBase)); /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwError' for browsers <IE9. * @param {Mixed} error An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwError = Observable.throwException = function (error, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new ThrowObservable(error, scheduler); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); resource && (disposable = resource); source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (o) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) { try { var result = handler(e); } catch (ex) { return o.onError(ex); } isPromise(result) && (result = observableFromPromise(result)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(o)); }, function (x) { o.onCompleted(x); })); return subscription; }, source); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () { var items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } return enumerableOf(items).catchError(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(); Array.isArray(args[0]) && (args = args[0]); return new AnonymousObservable(function (o) { var n = args.length, falseFactory = function () { return false; }, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { var res = resultSelector.apply(null, values); } catch (e) { return o.onError(e); } o.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { o.onCompleted(); } } function done (i) { isDone[i] = true; isDone.every(identity) && o.onCompleted(); } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, function(e) { o.onError(e); }, function () { done(i); } )); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }, this); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } args.unshift(this); return observableConcat.apply(null, args); }; /** * Concatenates all the observable sequences. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { args = new Array(arguments.length); for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; } } return enumerableOf(args).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatAll = observableProto.concatObservable = function () { return this.merge(1); }; var MergeObservable = (function (__super__) { inherits(MergeObservable, __super__); function MergeObservable(source, maxConcurrent) { this.source = source; this.maxConcurrent = maxConcurrent; __super__.call(this); } MergeObservable.prototype.subscribeCore = function(observer) { var g = new CompositeDisposable(); g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g))); return g; }; return MergeObservable; }(ObservableBase)); var MergeObserver = (function () { function MergeObserver(o, max, g) { this.o = o; this.max = max; this.g = g; this.done = false; this.q = []; this.activeCount = 0; this.isStopped = false; } MergeObserver.prototype.handleSubscribe = function (xs) { var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(xs) && (xs = observableFromPromise(xs)); sad.setDisposable(xs.subscribe(new InnerObserver(this, sad))); }; MergeObserver.prototype.onNext = function (innerSource) { if (this.isStopped) { return; } if(this.activeCount < this.max) { this.activeCount++; this.handleSubscribe(innerSource); } else { this.q.push(innerSource); } }; MergeObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.done = true; this.activeCount === 0 && this.o.onCompleted(); } }; MergeObserver.prototype.dispose = function() { this.isStopped = true; }; MergeObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, sad) { this.parent = parent; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; var parent = this.parent; parent.g.remove(this.sad); if (parent.q.length > 0) { parent.handleSubscribe(parent.q.shift()); } else { parent.activeCount--; parent.done && parent.activeCount === 0 && parent.o.onCompleted(); } } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeObserver; }()); /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { return typeof maxConcurrentOrOther !== 'number' ? observableMerge(this, maxConcurrentOrOther) : new MergeObservable(this, maxConcurrentOrOther); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources = [], i, len = arguments.length; if (!arguments[0]) { scheduler = immediateScheduler; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else if (isScheduler(arguments[0])) { scheduler = arguments[0]; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else { scheduler = immediateScheduler; for(i = 0; i < len; i++) { sources.push(arguments[i]); } } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableOf(scheduler, sources).mergeAll(); }; var MergeAllObservable = (function (__super__) { inherits(MergeAllObservable, __super__); function MergeAllObservable(source) { this.source = source; __super__.call(this); } MergeAllObservable.prototype.subscribeCore = function (observer) { var g = new CompositeDisposable(), m = new SingleAssignmentDisposable(); g.add(m); m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g))); return g; }; return MergeAllObservable; }(ObservableBase)); var MergeAllObserver = (function() { function MergeAllObserver(o, g) { this.o = o; this.g = g; this.isStopped = false; this.done = false; } MergeAllObserver.prototype.onNext = function(innerSource) { if(this.isStopped) { return; } var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad))); }; MergeAllObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeAllObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.done = true; this.g.length === 1 && this.o.onCompleted(); } }; MergeAllObserver.prototype.dispose = function() { this.isStopped = true; }; MergeAllObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, g, sad) { this.parent = parent; this.g = g; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { var parent = this.parent; this.isStopped = true; parent.g.remove(this.sad); parent.done && parent.g.length === 1 && parent.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeAllObserver; }()); /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeAll = observableProto.mergeObservable = function () { return new MergeAllObservable(this); }; var CompositeError = Rx.CompositeError = function(errors) { this.name = "NotImplementedError"; this.innerErrors = errors; this.message = 'This contains multiple errors. Check the innerErrors'; Error.call(this); } CompositeError.prototype = Error.prototype; /** * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to * receive all successfully emitted items from all of the source Observables without being interrupted by * an error notification from one of them. * * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an * error via the Observer's onError, mergeDelayError will refrain from propagating that * error notification until all of the merged Observables have finished emitting items. * @param {Array | Arguments} args Arguments or an array to merge. * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable */ Observable.mergeDelayError = function() { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { var len = arguments.length; args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } } var source = observableOf(null, args); return new AnonymousObservable(function (o) { var group = new CompositeDisposable(), m = new SingleAssignmentDisposable(), isStopped = false, errors = []; function setCompletion() { if (errors.length === 0) { o.onCompleted(); } else if (errors.length === 1) { o.onError(errors[0]); } else { o.onError(new CompositeError(errors)); } } group.add(m); m.setDisposable(source.subscribe( function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { o.onNext(x); }, function (e) { errors.push(e); group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); }, function () { group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); })); }, function (e) { errors.push(e); isStopped = true; group.length === 1 && setCompletion(); }, function () { isStopped = true; group.length === 1 && setCompletion(); })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = []; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } } return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (o) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && o.onNext(left); }, function (e) { o.onError(e); }, function () { isOpen && o.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, function (e) { o.onError(e); }, function () { rightSubscription.dispose(); })); return disposables; }, source); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe( function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe( function (x) { latest === id && observer.onNext(x); }, function (e) { latest === id && observer.onError(e); }, function () { if (latest === id) { hasLatest = false; isStopped && observer.onCompleted(); } })); }, function (e) { observer.onError(e); }, function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }, sources); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (o) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(o), other.subscribe(function () { o.onCompleted(); }, function (e) { o.onError(e); }, noop) ); }, source); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element. * * @example * 1 - obs = obs1.withLatestFrom(obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = obs1.withLatestFrom([obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.withLatestFrom = function () { var len = arguments.length, args = new Array(len) for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(), source = this; if (typeof source === 'undefined') { throw new Error('Source observable not found for withLatestFrom().'); } if (typeof resultSelector !== 'function') { throw new Error('withLatestFrom() expects a resultSelector function.'); } if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, values = new Array(n); var subscriptions = new Array(n + 1); for (var idx = 0; idx < n; idx++) { (function (i) { var other = args[i], sad = new SingleAssignmentDisposable(); isPromise(other) && (other = observableFromPromise(other)); sad.setDisposable(other.subscribe(function (x) { values[i] = x; hasValue[i] = true; hasValueAll = hasValue.every(identity); }, observer.onError.bind(observer), function () {})); subscriptions[i] = sad; }(idx)); } var sad = new SingleAssignmentDisposable(); sad.setDisposable(source.subscribe(function (x) { var res; var allValues = [x].concat(values); if (!hasValueAll) return; try { res = resultSelector.apply(null, allValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); }, observer.onError.bind(observer), function () { observer.onCompleted(); })); subscriptions[n] = sad; return new CompositeDisposable(subscriptions); }, this); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { return observer.onError(e); } observer.onNext(result); } else { observer.onCompleted(); } }, function (e) { observer.onError(e); }, function () { observer.onCompleted(); }); }, first); } function falseFactory() { return false; } function emptyArrayFactory() { return []; } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var parent = this, resultSelector = args.pop(); args.unshift(parent); return new AnonymousObservable(function (observer) { var n = args.length, queues = arrayInitialize(n, emptyArrayFactory), isDone = arrayInitialize(n, falseFactory); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, function (e) { observer.onError(e); }, function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }, parent); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { var len = arguments.length; sources = new Array(len); for(var i = 0; i < len; i++) { sources[i] = arguments[i]; } } return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, function (e) { observer.onError(e); }, function () { done(i); })); })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(o); }, this); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var key = value; if (keySelector) { try { key = keySelector(value); } catch (e) { o.onError(e); return; } } if (hasCurrentKey) { try { var comparerEquals = comparer(currentKey, key); } catch (e) { o.onError(e); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; o.onNext(value); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this; return new AnonymousObservable(function (observer) { var tapObserver = !observerOrOnNext || isFunction(observerOrOnNext) ? observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) : observerOrOnNext; return source.subscribe(function (x) { try { tapObserver.onNext(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { try { tapObserver.onError(err); } catch (e) { observer.onError(e); } observer.onError(err); }, function () { try { tapObserver.onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); }); }, this); }; /** * Invokes an action for each element in the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onNext Action to invoke for each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext); }; /** * Invokes an action upon exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError); }; /** * Invokes an action upon graceful termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.ensure = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }, this); }; /** * @deprecated use #finally or #ensure instead. */ observableProto.finallyAction = function (action) { //deprecate('finallyAction', 'finally or ensure'); return this.ensure(action); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(noop, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }, source); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchError(); }; /** * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates. * if the notifier completes, the observable sequence completes. * * @example * var timer = Observable.timer(500); * var source = observable.retryWhen(timer); * @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retryWhen = function (notifier) { return enumerableRepeat(this).catchErrorWhen(notifier); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (o) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { o.onError(e); return; } o.onNext(accumulation); }, function (e) { o.onError(e); }, function () { !hasValue && hasSeed && o.onNext(seed); o.onCompleted(); } ); }, source); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && o.onNext(q.shift()); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); } return enumerableOf([observableFromArray(args, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { while (q.length > 0) { o.onNext(q.shift()); } o.onCompleted(); }); }, source); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { o.onNext(q); o.onCompleted(); }); }, source); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; +count || (count = 0); Math.abs(count) === Infinity && (count = 0); if (count <= 0) { throw new ArgumentOutOfRangeError(); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = []; function createWindow () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } createWindow(); m.setDisposable(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; c >= 0 && c % skip === 0 && q.shift().onCompleted(); ++n % skip === 0 && createWindow(); }, function (e) { while (q.length > 0) { q.shift().onError(e); } observer.onError(e); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; function concatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }); } return isFunction(selector) ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { var source = this, onNextFunc = bindCallback(onNext, thisArg, 2), onErrorFunc = bindCallback(onError, thisArg, 1), onCompletedFunc = bindCallback(onCompleted, thisArg, 0); return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNextFunc(x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onErrorFunc(err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompletedFunc(); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, this).concatAll(); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; defaultValue === undefined && (defaultValue = null); return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, function (e) { observer.onError(e); }, function () { !found && observer.onNext(defaultValue); observer.onCompleted(); }); }, source); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { o.onError(e); return; } } hashSet.push(key) && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [comparer] Used to determine whether the objects are equal. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, comparer) { return this.groupByUntil(keySelector, elementSelector, observableNever, comparer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) { var source = this; elementSelector || (elementSelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { function handleError(e) { return function (item) { item.onError(e); }; } var map = new Dictionary(0, comparer), groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var key; try { key = keySelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } var fireNewMapEntry = false, writer = map.tryGetValue(key); if (!writer) { writer = new Subject(); map.set(key, writer); fireNewMapEntry = true; } if (fireNewMapEntry) { var group = new GroupedObservable(key, writer, refCountDisposable), durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(group); var md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { map.remove(key) && writer.onCompleted(); groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe( noop, function (exn) { map.getValues().forEach(handleError(exn)); observer.onError(exn); }, expire) ); } var element; try { element = elementSelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } writer.onNext(element); }, function (ex) { map.getValues().forEach(handleError(ex)); observer.onError(ex); }, function () { map.getValues().forEach(function (item) { item.onCompleted(); }); observer.onCompleted(); })); return refCountDisposable; }, source); }; var MapObservable = (function (__super__) { inherits(MapObservable, __super__); function MapObservable(source, selector, thisArg) { this.source = source; this.selector = bindCallback(selector, thisArg, 3); __super__.call(this); } MapObservable.prototype.internalMap = function (selector, thisArg) { var self = this; return new MapObservable(this.source, function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); }, thisArg) }; MapObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new MapObserver(observer, this.selector, this)); }; return MapObservable; }(ObservableBase)); function MapObserver(observer, selector, source) { this.observer = observer; this.selector = selector; this.source = source; this.i = 0; this.isStopped = false; } MapObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var result = tryCatch(this.selector).call(this, x, this.i++, this.source); if (result === errorObj) { return this.observer.onError(result.e); } this.observer.onNext(result); }; MapObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; MapObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; MapObserver.prototype.dispose = function() { this.isStopped = true; }; MapObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.map = observableProto.select = function (selector, thisArg) { var selectorFn = typeof selector === 'function' ? selector : function () { return selector; }; return this instanceof MapObservable ? this.internalMap(selectorFn, thisArg) : new MapObservable(this, selectorFn, thisArg); }; /** * Retrieves the value of a specified nested property from all elements in * the Observable sequence. * @param {Arguments} arguments The nested properties to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function () { var args = arguments, len = arguments.length; if (len === 0) { throw new Error('List of properties cannot be empty.'); } return this.map(function (x) { var currentProp = x; for (var i = 0; i < len; i++) { var p = currentProp[args[i]]; if (typeof p !== 'undefined') { currentProp = p; } else { return undefined; } } return currentProp; }); }; function flatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).mergeAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }, thisArg); } return isFunction(selector) ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, source).mergeAll(); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining <= 0) { o.onNext(x); } else { remaining--; } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !callback(x, i++, source); } catch (e) { o.onError(e); return; } } running && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new ArgumentOutOfRangeError(); } if (count === 0) { return observableEmpty(scheduler); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining-- > 0) { o.onNext(x); remaining === 0 && o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = true; return source.subscribe(function (x) { if (running) { try { running = callback(x, i++, source); } catch (e) { o.onError(e); return; } if (running) { o.onNext(x); } else { o.onCompleted(); } } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; var FilterObservable = (function (__super__) { inherits(FilterObservable, __super__); function FilterObservable(source, predicate, thisArg) { this.source = source; this.predicate = bindCallback(predicate, thisArg, 3); __super__.call(this); } FilterObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new FilterObserver(observer, this.predicate, this)); }; FilterObservable.prototype.internalFilter = function(predicate, thisArg) { var self = this; return new FilterObservable(this.source, function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); }, thisArg); }; return FilterObservable; }(ObservableBase)); function FilterObserver(observer, predicate, source) { this.observer = observer; this.predicate = predicate; this.source = source; this.i = 0; this.isStopped = false; } FilterObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var shouldYield = tryCatch(this.predicate).call(this, x, this.i++, this.source); if (shouldYield === errorObj) { return this.observer.onError(shouldYield.e); } shouldYield && this.observer.onNext(x); }; FilterObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; FilterObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; FilterObserver.prototype.dispose = function() { this.isStopped = true; }; FilterObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.filter = observableProto.where = function (predicate, thisArg) { return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) : new FilterObservable(this, predicate, thisArg); }; function extremaBy(source, keySelector, comparer) { return new AnonymousObservable(function (o) { var hasValue = false, lastKey = null, list = []; return source.subscribe(function (x) { var comparison, key; try { key = keySelector(x); } catch (ex) { o.onError(ex); return; } comparison = 0; if (!hasValue) { hasValue = true; lastKey = key; } else { try { comparison = comparer(key, lastKey); } catch (ex1) { o.onError(ex1); return; } } if (comparison > 0) { lastKey = key; list = []; } if (comparison >= 0) { list.push(x); } }, function (e) { o.onError(e); }, function () { o.onNext(list); o.onCompleted(); }); }, source); } function firstOnly(x) { if (x.length === 0) { throw new EmptyError(); } return x[0]; } /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @deprecated Use #reduce instead * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.aggregate = function () { var hasSeed = false, accumulator, seed, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (o) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { return o.onError(e); } }, function (e) { o.onError(e); }, function () { hasValue && o.onNext(accumulation); !hasValue && hasSeed && o.onNext(seed); !hasValue && !hasSeed && o.onError(new EmptyError()); o.onCompleted(); } ); }, source); }; /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @param {Function} accumulator An accumulator function to be invoked on each element. * @param {Any} [seed] The initial accumulator value. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.reduce = function (accumulator) { var hasSeed = false, seed, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[1]; } return new AnonymousObservable(function (o) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { return o.onError(e); } }, function (e) { o.onError(e); }, function () { hasValue && o.onNext(accumulation); !hasValue && hasSeed && o.onNext(seed); !hasValue && !hasSeed && o.onError(new EmptyError()); o.onCompleted(); } ); }, source); }; /** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @param {Function} [predicate] A function to test each element for a condition. * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence. */ observableProto.some = function (predicate, thisArg) { var source = this; return predicate ? source.filter(predicate, thisArg).some() : new AnonymousObservable(function (observer) { return source.subscribe(function () { observer.onNext(true); observer.onCompleted(); }, function (e) { observer.onError(e); }, function () { observer.onNext(false); observer.onCompleted(); }); }, source); }; /** @deprecated use #some instead */ observableProto.any = function () { //deprecate('any', 'some'); return this.some.apply(this, arguments); }; /** * Determines whether an observable sequence is empty. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty. */ observableProto.isEmpty = function () { return this.any().map(not); }; /** * Determines whether all elements of an observable sequence satisfy a condition. * @param {Function} [predicate] A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate. */ observableProto.every = function (predicate, thisArg) { return this.filter(function (v) { return !predicate(v); }, thisArg).some().map(not); }; /** @deprecated use #every instead */ observableProto.all = function () { //deprecate('all', 'every'); return this.every.apply(this, arguments); }; /** * Determines whether an observable sequence includes a specified element with an optional equality comparer. * @param searchElement The value to locate in the source sequence. * @param {Number} [fromIndex] An equality comparer to compare elements. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence includes an element that has the specified value from the given index. */ observableProto.includes = function (searchElement, fromIndex) { var source = this; function comparer(a, b) { return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b))); } return new AnonymousObservable(function (o) { var i = 0, n = +fromIndex || 0; Math.abs(n) === Infinity && (n = 0); if (n < 0) { o.onNext(false); o.onCompleted(); return disposableEmpty; } return source.subscribe( function (x) { if (i++ >= n && comparer(x, searchElement)) { o.onNext(true); o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onNext(false); o.onCompleted(); }); }, this); }; /** * @deprecated use #includes instead. */ observableProto.contains = function (searchElement, fromIndex) { //deprecate('contains', 'includes'); observableProto.includes(searchElement, fromIndex); }; /** * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. * @example * res = source.count(); * res = source.count(function (x) { return x > 3; }); * @param {Function} [predicate]A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence. */ observableProto.count = function (predicate, thisArg) { return predicate ? this.filter(predicate, thisArg).count() : this.reduce(function (count) { return count + 1; }, 0); }; /** * Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present. * @param {Any} searchElement Element to locate in the array. * @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0. * @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present. */ observableProto.indexOf = function(searchElement, fromIndex) { var source = this; return new AnonymousObservable(function (o) { var i = 0, n = +fromIndex || 0; Math.abs(n) === Infinity && (n = 0); if (n < 0) { o.onNext(-1); o.onCompleted(); return disposableEmpty; } return source.subscribe( function (x) { if (i >= n && x === searchElement) { o.onNext(i); o.onCompleted(); } i++; }, function (e) { o.onError(e); }, function () { o.onNext(-1); o.onCompleted(); }); }, source); }; /** * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence. * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence. */ observableProto.sum = function (keySelector, thisArg) { return keySelector && isFunction(keySelector) ? this.map(keySelector, thisArg).sum() : this.reduce(function (prev, curr) { return prev + curr; }, 0); }; /** * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. * @example * var res = source.minBy(function (x) { return x.value; }); * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value. */ observableProto.minBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; }); }; /** * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. * @example * var res = source.min(); * var res = source.min(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence. */ observableProto.min = function (comparer) { return this.minBy(identity, comparer).map(function (x) { return firstOnly(x); }); }; /** * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. * @example * var res = source.maxBy(function (x) { return x.value; }); * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value. */ observableProto.maxBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, comparer); }; /** * Returns the maximum value in an observable sequence according to the specified comparer. * @example * var res = source.max(); * var res = source.max(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence. */ observableProto.max = function (comparer) { return this.maxBy(identity, comparer).map(function (x) { return firstOnly(x); }); }; /** * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. */ observableProto.average = function (keySelector, thisArg) { return keySelector && isFunction(keySelector) ? this.map(keySelector, thisArg).average() : this.reduce(function (prev, cur) { return { sum: prev.sum + cur, count: prev.count + 1 }; }, {sum: 0, count: 0 }).map(function (s) { if (s.count === 0) { throw new EmptyError(); } return s.sum / s.count; }); }; /** * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. * * @example * var res = res = source.sequenceEqual([1,2,3]); * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; }); * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42)); * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; }); * @param {Observable} second Second observable sequence or array to compare. * @param {Function} [comparer] Comparer used to compare elements of both sequences. * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer. */ observableProto.sequenceEqual = function (second, comparer) { var first = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var donel = false, doner = false, ql = [], qr = []; var subscription1 = first.subscribe(function (x) { var equal, v; if (qr.length > 0) { v = qr.shift(); try { equal = comparer(v, x); } catch (e) { o.onError(e); return; } if (!equal) { o.onNext(false); o.onCompleted(); } } else if (doner) { o.onNext(false); o.onCompleted(); } else { ql.push(x); } }, function(e) { o.onError(e); }, function () { donel = true; if (ql.length === 0) { if (qr.length > 0) { o.onNext(false); o.onCompleted(); } else if (doner) { o.onNext(true); o.onCompleted(); } } }); (isArrayLike(second) || isIterable(second)) && (second = observableFrom(second)); isPromise(second) && (second = observableFromPromise(second)); var subscription2 = second.subscribe(function (x) { var equal; if (ql.length > 0) { var v = ql.shift(); try { equal = comparer(v, x); } catch (exception) { o.onError(exception); return; } if (!equal) { o.onNext(false); o.onCompleted(); } } else if (donel) { o.onNext(false); o.onCompleted(); } else { qr.push(x); } }, function(e) { o.onError(e); }, function () { doner = true; if (qr.length === 0) { if (ql.length > 0) { o.onNext(false); o.onCompleted(); } else if (donel) { o.onNext(true); o.onCompleted(); } } }); return new CompositeDisposable(subscription1, subscription2); }, first); }; function elementAtOrDefault(source, index, hasDefault, defaultValue) { if (index < 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (o) { var i = index; return source.subscribe(function (x) { if (i-- === 0) { o.onNext(x); o.onCompleted(); } }, function (e) { o.onError(e); }, function () { if (!hasDefault) { o.onError(new ArgumentOutOfRangeError()); } else { o.onNext(defaultValue); o.onCompleted(); } }); }, source); } /** * Returns the element at a specified index in a sequence. * @example * var res = source.elementAt(5); * @param {Number} index The zero-based index of the element to retrieve. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. */ observableProto.elementAt = function (index) { return elementAtOrDefault(this, index, false); }; /** * Returns the element at a specified index in a sequence or a default value if the index is out of range. * @example * var res = source.elementAtOrDefault(5); * var res = source.elementAtOrDefault(5, 0); * @param {Number} index The zero-based index of the element to retrieve. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence. */ observableProto.elementAtOrDefault = function (index, defaultValue) { return elementAtOrDefault(this, index, true, defaultValue); }; function singleOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { if (seenValue) { o.onError(new Error('Sequence contains more than one element')); } else { value = x; seenValue = true; } }, function (e) { o.onError(e); }, function () { if (!seenValue && !hasDefault) { o.onError(new EmptyError()); } else { o.onNext(value); o.onCompleted(); } }); }, source); } /** * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. */ observableProto.single = function (predicate, thisArg) { return predicate && isFunction(predicate) ? this.where(predicate, thisArg).single() : singleOrDefaultAsync(this, false); }; /** * Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence. * @example * var res = res = source.singleOrDefault(); * var res = res = source.singleOrDefault(function (x) { return x === 42; }); * res = source.singleOrDefault(function (x) { return x === 42; }, 0); * res = source.singleOrDefault(null, 0); * @memberOf Observable# * @param {Function} predicate A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) { return predicate && isFunction(predicate) ? this.filter(predicate, thisArg).singleOrDefault(null, defaultValue) : singleOrDefaultAsync(this, true, defaultValue); }; function firstOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { return source.subscribe(function (x) { o.onNext(x); o.onCompleted(); }, function (e) { o.onError(e); }, function () { if (!hasDefault) { o.onError(new EmptyError()); } else { o.onNext(defaultValue); o.onCompleted(); } }); }, source); } /** * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. * @example * var res = res = source.first(); * var res = res = source.first(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. */ observableProto.first = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).first() : firstOrDefaultAsync(this, false); }; /** * Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate).firstOrDefault(null, defaultValue) : firstOrDefaultAsync(this, true, defaultValue); }; function lastOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { value = x; seenValue = true; }, function (e) { o.onError(e); }, function () { if (!seenValue && !hasDefault) { o.onError(new EmptyError()); } else { o.onNext(value); o.onCompleted(); } }); }, source); } /** * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate. */ observableProto.last = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).last() : lastOrDefaultAsync(this, false); }; /** * Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate, thisArg).lastOrDefault(null, defaultValue) : lastOrDefaultAsync(this, true, defaultValue); }; function findValue (source, predicate, thisArg, yieldIndex) { var callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0; return source.subscribe(function (x) { var shouldRun; try { shouldRun = callback(x, i, source); } catch (e) { o.onError(e); return; } if (shouldRun) { o.onNext(yieldIndex ? i : x); o.onCompleted(); } else { i++; } }, function (e) { o.onError(e); }, function () { o.onNext(yieldIndex ? -1 : undefined); o.onCompleted(); }); }, source); } /** * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined. */ observableProto.find = function (predicate, thisArg) { return findValue(this, predicate, thisArg, false); }; /** * Searches for an element that matches the conditions defined by the specified predicate, and returns * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1. */ observableProto.findIndex = function (predicate, thisArg) { return findValue(this, predicate, thisArg, true); }; /** * Converts the observable sequence to a Set if it exists. * @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence. */ observableProto.toSet = function () { if (typeof root.Set === 'undefined') { throw new TypeError(); } var source = this; return new AnonymousObservable(function (o) { var s = new root.Set(); return source.subscribe( function (x) { s.add(x); }, function (e) { o.onError(e); }, function () { o.onNext(s); o.onCompleted(); }); }, source); }; /** * Converts the observable sequence to a Map if it exists. * @param {Function} keySelector A function which produces the key for the Map. * @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence. * @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence. */ observableProto.toMap = function (keySelector, elementSelector) { if (typeof root.Map === 'undefined') { throw new TypeError(); } var source = this; return new AnonymousObservable(function (o) { var m = new root.Map(); return source.subscribe( function (x) { var key; try { key = keySelector(x); } catch (e) { o.onError(e); return; } var element = x; if (elementSelector) { try { element = elementSelector(x); } catch (e) { o.onError(e); return; } } m.set(key, element); }, function (e) { o.onError(e); }, function () { o.onNext(m); o.onCompleted(); }); }, source); }; var fnString = 'function', throwString = 'throw', isObject = Rx.internals.isObject; function toThunk(obj, ctx) { if (Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } if (isGeneratorFunction(obj)) { return observableSpawn(obj.call(ctx)); } if (isGenerator(obj)) { return observableSpawn(obj); } if (isObservable(obj)) { return observableToThunk(obj); } if (isPromise(obj)) { return promiseToThunk(obj); } if (typeof obj === fnString) { return obj; } if (isObject(obj) || Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } return obj; } function objectToThunk(obj) { var ctx = this; return function (done) { var keys = Object.keys(obj), pending = keys.length, results = new obj.constructor(), finished; if (!pending) { timeoutScheduler.schedule(function () { done(null, results); }); return; } for (var i = 0, len = keys.length; i < len; i++) { run(obj[keys[i]], keys[i]); } function run(fn, key) { if (finished) { return; } try { fn = toThunk(fn, ctx); if (typeof fn !== fnString) { results[key] = fn; return --pending || done(null, results); } fn.call(ctx, function(err, res) { if (finished) { return; } if (err) { finished = true; return done(err); } results[key] = res; --pending || done(null, results); }); } catch (e) { finished = true; done(e); } } } } function observableToThunk(observable) { return function (fn) { var value, hasValue = false; observable.subscribe( function (v) { value = v; hasValue = true; }, fn, function () { hasValue && fn(null, value); }); } } function promiseToThunk(promise) { return function(fn) { promise.then(function(res) { fn(null, res); }, fn); } } function isObservable(obj) { return obj && typeof obj.subscribe === fnString; } function isGeneratorFunction(obj) { return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction'; } function isGenerator(obj) { return obj && typeof obj.next === fnString && typeof obj[throwString] === fnString; } /* * Spawns a generator function which allows for Promises, Observable sequences, Arrays, Objects, Generators and functions. * @param {Function} The spawning function. * @returns {Function} a function which has a done continuation. */ var observableSpawn = Rx.spawn = function (fn) { var isGenFun = isGeneratorFunction(fn); return function (done) { var ctx = this, gen = fn; if (isGenFun) { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } var len = args.length, hasCallback = len && typeof args[len - 1] === fnString; done = hasCallback ? args.pop() : handleError; gen = fn.apply(this, args); } else { done = done || handleError; } next(); function exit(err, res) { timeoutScheduler.schedule(done.bind(ctx, err, res)); } function next(err, res) { var ret; // multiple args if (arguments.length > 2) { for(var res = [], i = 1, len = arguments.length; i < len; i++) { res.push(arguments[i]); } } if (err) { try { ret = gen[throwString](err); } catch (e) { return exit(e); } } if (!err) { try { ret = gen.next(res); } catch (e) { return exit(e); } } if (ret.done) { return exit(null, ret.value); } ret.value = toThunk(ret.value, ctx); if (typeof ret.value === fnString) { var called = false; try { ret.value.call(ctx, function() { if (called) { return; } called = true; next.apply(ctx, arguments); }); } catch (e) { timeoutScheduler.schedule(function () { if (called) { return; } called = true; next.call(ctx, e); }); } return; } // Not supported next(new TypeError('Rx.spawn only supports a function, Promise, Observable, Object or Array.')); } } }; function handleError(err) { if (!err) { return; } timeoutScheduler.schedule(function() { throw err; }); } /** * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. * * @example * var res = Rx.Observable.start(function () { console.log('hello'); }); * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console); * * @param {Function} func Function to run asynchronously. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. * * Remarks * * The function is called immediately, not during the subscription of the resulting sequence. * * Multiple subscriptions to the resulting sequence can observe the function's result. */ Observable.start = function (func, context, scheduler) { return observableToAsync(func, context, scheduler)(); }; /** * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. * @param {Function} function Function to convert to an asynchronous function. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Function} Asynchronous function. */ var observableToAsync = Observable.toAsync = function (func, context, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return function () { var args = arguments, subject = new AsyncSubject(); scheduler.schedule(function () { var result; try { result = func.apply(context, args); } catch (e) { subject.onError(e); return; } subject.onNext(result); subject.onCompleted(); }); return subject.asObservable(); }; }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, context, selector) { return function () { var len = arguments.length, args = new Array(len) for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new AnonymousObservable(function (observer) { function handler() { var len = arguments.length, results = new Array(len); for(var i = 0; i < len; i++) { results[i] = arguments[i]; } if (selector) { try { results = selector.apply(context, results); } catch (e) { return observer.onError(e); } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, context, selector) { return function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new AnonymousObservable(function (observer) { function handler(err) { if (err) { observer.onError(err); return; } var len = arguments.length, results = []; for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; } if (selector) { try { results = selector.apply(context, results); } catch (e) { return observer.onError(e); } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; function 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, Ember.js if (typeof element.on === 'function' && typeof element.off === 'function') { return fromEventPattern( function (h) { element.on(eventName, h); }, function (h) { element.off(eventName, h); }, selector); } } return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { return observer.onError(err); } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { return observer.onError(err); } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } var PausableObservable = (function (__super__) { inherits(PausableObservable, __super__); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this, subscribe, source); } PausableObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (o) { var hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(2), err; function next(x, i) { values[i] = x var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { if (err) { o.onError(err); return; } try { res = resultSelector.apply(null, values); } catch (ex) { o.onError(ex); return; } o.onNext(res); } if (isDone && values[1]) { o.onCompleted(); } } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, function (e) { if (values[1]) { o.onError(e); } else { err = e; } }, function () { isDone = true; values[1] && o.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, function (e) { o.onError(e); }, function () { isDone = true; next(true, 1); }) ); }, source); } var PausableBufferedObservable = (function (__super__) { inherits(PausableBufferedObservable, __super__); function subscribe(o) { var q = [], previousShouldFire; var subscription = combineLatestSource( this.source, this.pauser.distinctUntilChanged().startWith(false), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) { previousShouldFire = results.shouldFire; // change in shouldFire if (results.shouldFire) { while (q.length > 0) { o.onNext(q.shift()); } } } else { previousShouldFire = results.shouldFire; // new data if (results.shouldFire) { o.onNext(results.data); } else { q.push(results.data); } } }, function (err) { // Empty buffer before sending error while (q.length > 0) { o.onNext(q.shift()); } o.onError(err); }, function () { // Empty buffer before sending completion while (q.length > 0) { o.onNext(q.shift()); } o.onCompleted(); } ); return subscription; } function PausableBufferedObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this, subscribe, source); } PausableBufferedObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; var ControlledObservable = (function (__super__) { inherits(ControlledObservable, __super__); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue, scheduler) { __super__.call(this, subscribe, source); this.subject = new ControlledSubject(enableQueue, scheduler); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { return this.subject.request(numberOfItems == null ? -1 : numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = (function (__super__) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, __super__); function ControlledSubject(enableQueue, scheduler) { 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.scheduler = scheduler || currentThreadScheduler; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) { this.subject.onCompleted(); } else { this.queue.push(Notification.createOnCompleted()); } }, onError: function (error) { this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) { this.subject.onError(error); } else { this.queue.push(Notification.createOnError(error)); } }, onNext: function (value) { var hasRequested = false; if (this.requestedCount === 0) { this.enableQueue && this.queue.push(Notification.createOnNext(value)); } else { (this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest(); hasRequested = true; } hasRequested && this.subject.onNext(value); }, _processRequest: function (numberOfItems) { if (this.enableQueue) { while ((this.queue.length >= numberOfItems && numberOfItems > 0) || (this.queue.length > 0 && this.queue[0].kind !== 'N')) { var first = this.queue.shift(); first.accept(this.subject); if (first.kind === 'N') { numberOfItems--; } else { this.disposeCurrentRequest(); this.queue = []; } } return { numberOfItems : numberOfItems, returnValue: this.queue.length !== 0}; } return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { this.disposeCurrentRequest(); var self = this; this.requestedDisposable = this.scheduler.scheduleWithState(number, function(s, i) { var r = self._processRequest(i), remaining = r.numberOfItems; if (!r.returnValue) { self.requestedCount = remaining; self.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); } }); return this.requestedDisposable; }, 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 {bool} enableQueue truthy value to determine if values should be queued pending the next request * @param {Scheduler} scheduler determines how the requests will be scheduled * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.controlled = function (enableQueue, scheduler) { if (enableQueue && isScheduler(enableQueue)) { scheduler = enableQueue; enableQueue = true; } if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue, scheduler); }; var StopAndWaitObservable = (function (__super__) { function subscribe (observer) { this.subscription = this.source.subscribe(new StopAndWaitObserver(observer, this, this.subscription)); var self = this; timeoutScheduler.schedule(function () { self.source.request(1); }); return this.subscription; } inherits(StopAndWaitObservable, __super__); function StopAndWaitObservable (source) { __super__.call(this, subscribe, source); this.source = source; } var StopAndWaitObserver = (function (__sub__) { inherits(StopAndWaitObserver, __sub__); function StopAndWaitObserver (observer, observable, cancel) { __sub__.call(this); this.observer = observer; this.observable = observable; this.cancel = cancel; } var stopAndWaitObserverProto = StopAndWaitObserver.prototype; stopAndWaitObserverProto.completed = function () { this.observer.onCompleted(); this.dispose(); }; stopAndWaitObserverProto.error = function (error) { this.observer.onError(error); this.dispose(); } stopAndWaitObserverProto.next = function (value) { this.observer.onNext(value); var self = this; timeoutScheduler.schedule(function () { self.observable.source.request(1); }); }; stopAndWaitObserverProto.dispose = function () { this.observer = null; if (this.cancel) { this.cancel.dispose(); this.cancel = null; } __sub__.prototype.dispose.call(this); }; return StopAndWaitObserver; }(AbstractObserver)); return StopAndWaitObservable; }(Observable)); /** * Attaches a stop and wait observable to the current observable. * @returns {Observable} A stop and wait observable. */ ControlledObservable.prototype.stopAndWait = function () { return new StopAndWaitObservable(this); }; var WindowedObservable = (function (__super__) { function subscribe (observer) { this.subscription = this.source.subscribe(new WindowedObserver(observer, this, this.subscription)); var self = this; timeoutScheduler.schedule(function () { self.source.request(self.windowSize); }); return this.subscription; } inherits(WindowedObservable, __super__); function WindowedObservable(source, windowSize) { __super__.call(this, subscribe, source); this.source = source; this.windowSize = windowSize; } var WindowedObserver = (function (__sub__) { inherits(WindowedObserver, __sub__); function WindowedObserver(observer, observable, cancel) { this.observer = observer; this.observable = observable; this.cancel = cancel; this.received = 0; } var windowedObserverPrototype = WindowedObserver.prototype; windowedObserverPrototype.completed = function () { this.observer.onCompleted(); this.dispose(); }; windowedObserverPrototype.error = function (error) { this.observer.onError(error); this.dispose(); }; windowedObserverPrototype.next = function (value) { this.observer.onNext(value); this.received = ++this.received % this.observable.windowSize; if (this.received === 0) { var self = this; timeoutScheduler.schedule(function () { self.observable.source.request(self.observable.windowSize); }); } }; windowedObserverPrototype.dispose = function () { this.observer = null; if (this.cancel) { this.cancel.dispose(); this.cancel = null; } __sub__.prototype.dispose.call(this); }; return WindowedObserver; }(AbstractObserver)); return WindowedObservable; }(Observable)); /** * Creates a sliding windowed observable based upon the window size. * @param {Number} windowSize The number of items in the window * @returns {Observable} A windowed observable based upon the window size. */ ControlledObservable.prototype.windowed = function (windowSize) { return new WindowedObservable(this, windowSize); }; /** * Pipes the existing Observable sequence into a Node.js Stream. * @param {Stream} dest The destination Node.js stream. * @returns {Stream} The destination stream. */ observableProto.pipe = function (dest) { var source = this.pausableBuffered(); function onDrain() { source.resume(); } dest.addListener('drain', onDrain); source.subscribe( function (x) { !dest.write(String(x)) && source.pause(); }, function (err) { dest.emit('error', err); }, function () { // Hack check because STDIO is not closable !dest._isStdio && dest.end(); dest.removeListener('drain', onDrain); }); source.resume(); return dest; }; /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }, source) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new Subject(); }, selector) : this.multicast(new Subject()); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish().refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new AsyncSubject(); }, selector) : this.multicast(new AsyncSubject()); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param windowSize [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, windowSize, scheduler) { return selector && isFunction(selector) ? this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) : this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, windowSize, scheduler) { return this.replay(null, bufferSize, windowSize, scheduler).refCount(); }; var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, __super__); /** * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { __super__.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.hasError = false; } addProperties(BehaviorSubject.prototype, Observer, { /** * Gets the current value or throws an exception. * Value is frozen after onCompleted is called. * After onError is called always throws the specified exception. * An exception is always thrown after dispose is called. * @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext. */ getValue: function () { checkDisposed(this); if (this.hasError) { throw this.error; } return this.value; }, /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } this.value = value; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onNext(value); } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (__super__) { var maxSafeInteger = Math.pow(2, 53) - 1; function createRemovableDisposable(subject, observer) { return disposableCreate(function () { observer.dispose(); !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); }); } function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = createRemovableDisposable(this, so); checkDisposed(this); this._trim(this.scheduler.now()); this.observers.push(so); for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { so.onError(this.error); } else if (this.isStopped) { so.onCompleted(); } so.ensureActive(); return subscription; } inherits(ReplaySubject, __super__); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize; this.windowSize = windowSize == null ? maxSafeInteger : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; __super__.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer.prototype, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onNext(value); observer.ensureActive(); } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onError(error); observer.ensureActive(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onCompleted(); observer.ensureActive(); } this.observers.length = 0; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); function ConnectableObservable(source, subject) { var hasSubscription = false, subscription, sourceObservable = source.asObservable(); this.connect = function () { if (!hasSubscription) { hasSubscription = true; subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { hasSubscription = false; })); } return subscription; }; __super__.call(this, function (o) { return subject.subscribe(o); }); } ConnectableObservable.prototype.refCount = function () { var connectableSubscription, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect = ++count === 1, subscription = source.subscribe(observer); shouldConnect && (connectableSubscription = source.connect()); return function () { subscription.dispose(); --count === 0 && connectableSubscription.dispose(); }; }); }; return ConnectableObservable; }(Observable)); var Dictionary = (function () { var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647], noSuchkey = "no such key", duplicatekey = "duplicate key"; function isPrime(candidate) { if ((candidate & 1) === 0) { return candidate === 2; } var num1 = Math.sqrt(candidate), num2 = 3; while (num2 <= num1) { if (candidate % num2 === 0) { return false; } num2 += 2; } return true; } function getPrime(min) { var index, num, candidate; for (index = 0; index < primes.length; ++index) { num = primes[index]; if (num >= min) { return num; } } candidate = min | 1; while (candidate < primes[primes.length - 1]) { if (isPrime(candidate)) { return candidate; } candidate += 2; } return min; } function stringHashFn(str) { var hash = 757602046; if (!str.length) { return hash; } for (var i = 0, len = str.length; i < len; i++) { var character = str.charCodeAt(i); hash = ((hash << 5) - hash) + character; hash = hash & hash; } return hash; } function numberHashFn(key) { var c2 = 0x27d4eb2d; key = (key ^ 61) ^ (key >>> 16); key = key + (key << 3); key = key ^ (key >>> 4); key = key * c2; key = key ^ (key >>> 15); return key; } var getHashCode = (function () { var uniqueIdCounter = 0; return function (obj) { if (obj == null) { throw new Error(noSuchkey); } // Check for built-ins before tacking on our own for any object if (typeof obj === 'string') { return stringHashFn(obj); } if (typeof obj === 'number') { return numberHashFn(obj); } if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } if (obj instanceof Date) { return numberHashFn(obj.valueOf()); } if (obj instanceof RegExp) { return stringHashFn(obj.toString()); } if (typeof obj.valueOf === 'function') { // Hack check for valueOf var valueOf = obj.valueOf(); if (typeof valueOf === 'number') { return numberHashFn(valueOf); } if (typeof valueOf === 'string') { return stringHashFn(valueOf); } } if (obj.hashCode) { return obj.hashCode(); } var id = 17 * uniqueIdCounter++; obj.hashCode = function () { return id; }; return id; }; }()); function newEntry() { return { key: null, value: null, next: 0, hashCode: 0 }; } function Dictionary(capacity, comparer) { if (capacity < 0) { throw new ArgumentOutOfRangeError(); } if (capacity > 0) { this._initialize(capacity); } this.comparer = comparer || defaultComparer; this.freeCount = 0; this.size = 0; this.freeList = -1; } var dictionaryProto = Dictionary.prototype; dictionaryProto._initialize = function (capacity) { var prime = getPrime(capacity), i; this.buckets = new Array(prime); this.entries = new Array(prime); for (i = 0; i < prime; i++) { this.buckets[i] = -1; this.entries[i] = newEntry(); } this.freeList = -1; }; dictionaryProto.add = function (key, value) { this._insert(key, value, true); }; dictionaryProto._insert = function (key, value, add) { if (!this.buckets) { this._initialize(0); } var index3, num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length; for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { if (add) { throw new Error(duplicatekey); } this.entries[index2].value = value; return; } } if (this.freeCount > 0) { index3 = this.freeList; this.freeList = this.entries[index3].next; --this.freeCount; } else { if (this.size === this.entries.length) { this._resize(); index1 = num % this.buckets.length; } index3 = this.size; ++this.size; } this.entries[index3].hashCode = num; this.entries[index3].next = this.buckets[index1]; this.entries[index3].key = key; this.entries[index3].value = value; this.buckets[index1] = index3; }; dictionaryProto._resize = function () { var prime = getPrime(this.size * 2), numArray = new Array(prime); for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } var entryArray = new Array(prime); for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } for (var index1 = 0; index1 < this.size; ++index1) { var index2 = entryArray[index1].hashCode % prime; entryArray[index1].next = numArray[index2]; numArray[index2] = index1; } this.buckets = numArray; this.entries = entryArray; }; dictionaryProto.remove = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length, index2 = -1; for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { if (index2 < 0) { this.buckets[index1] = this.entries[index3].next; } else { this.entries[index2].next = this.entries[index3].next; } this.entries[index3].hashCode = -1; this.entries[index3].next = this.freeList; this.entries[index3].key = null; this.entries[index3].value = null; this.freeList = index3; ++this.freeCount; return true; } else { index2 = index3; } } } return false; }; dictionaryProto.clear = function () { var index, len; if (this.size <= 0) { return; } for (index = 0, len = this.buckets.length; index < len; ++index) { this.buckets[index] = -1; } for (index = 0; index < this.size; ++index) { this.entries[index] = newEntry(); } this.freeList = -1; this.size = 0; }; dictionaryProto._findEntry = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647; for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { return index; } } } return -1; }; dictionaryProto.count = function () { return this.size - this.freeCount; }; dictionaryProto.tryGetValue = function (key) { var entry = this._findEntry(key); return entry >= 0 ? this.entries[entry].value : undefined; }; dictionaryProto.getValues = function () { var index = 0, results = []; if (this.entries) { for (var index1 = 0; index1 < this.size; index1++) { if (this.entries[index1].hashCode >= 0) { results[index++] = this.entries[index1].value; } } } return results; }; dictionaryProto.get = function (key) { var entry = this._findEntry(key); if (entry >= 0) { return this.entries[entry].value; } throw new Error(noSuchkey); }; dictionaryProto.set = function (key, value) { this._insert(key, value, false); }; dictionaryProto.containskey = function (key) { return this._findEntry(key) >= 0; }; return Dictionary; }()); /** * Correlates the elements of two sequences based on overlapping durations. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var leftDone = false, rightDone = false; var leftId = 0, rightId = 0; var leftMap = new Dictionary(), rightMap = new Dictionary(); group.add(left.subscribe( function (value) { var id = leftId++; var md = new SingleAssignmentDisposable(); leftMap.add(id, value); group.add(md); var expire = function () { leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); rightMap.getValues().forEach(function (v) { var result; try { result = resultSelector(value, v); } catch (exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { leftDone = true; (rightDone || leftMap.count() === 0) && observer.onCompleted(); }) ); group.add(right.subscribe( function (value) { var id = rightId++; var md = new SingleAssignmentDisposable(); rightMap.add(id, value); group.add(md); var expire = function () { rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); leftMap.getValues().forEach(function (v) { var result; try { result = resultSelector(v, value); } catch (exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { rightDone = true; (leftDone || rightMap.count() === 0) && observer.onCompleted(); }) ); return group; }, left); }; /** * Correlates the elements of two sequences based on overlapping durations, and groups the results. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var r = new RefCountDisposable(group); var leftMap = new Dictionary(), rightMap = new Dictionary(); var leftId = 0, rightId = 0; function handleError(e) { return function (v) { v.onError(e); }; }; group.add(left.subscribe( function (value) { var s = new Subject(); var id = leftId++; leftMap.add(id, s); var result; try { result = resultSelector(value, addRef(s, r)); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(result); rightMap.getValues().forEach(function (v) { s.onNext(v); }); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { leftMap.remove(id) && s.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, observer.onCompleted.bind(observer)) ); group.add(right.subscribe( function (value) { var id = rightId++; rightMap.add(id, value); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { rightMap.remove(id); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); leftMap.getValues().forEach(function (v) { v.onNext(value); }); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }) ); return r; }, left); }; /** * Projects each element of an observable sequence into zero or more buffers. * * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into zero or more windows. * * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { if (arguments.length === 1 && typeof arguments[0] !== 'function') { return observableWindowWithBoundaries.call(this, windowOpeningsOrClosingSelector); } return typeof windowOpeningsOrClosingSelector === 'function' ? observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); }; function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) { return win; }); } function observableWindowWithBoundaries(windowBoundaries) { var source = this; return new AnonymousObservable(function (observer) { var win = new Subject(), d = new CompositeDisposable(), r = new RefCountDisposable(d); observer.onNext(addRef(win, r)); d.add(source.subscribe(function (x) { win.onNext(x); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries)); d.add(windowBoundaries.subscribe(function (w) { win.onCompleted(); win = new Subject(); observer.onNext(addRef(win, r)); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); return r; }, source); } function observableWindowWithClosingSelector(windowClosingSelector) { var source = this; return new AnonymousObservable(function (observer) { var m = new SerialDisposable(), d = new CompositeDisposable(m), r = new RefCountDisposable(d), win = new Subject(); observer.onNext(addRef(win, r)); d.add(source.subscribe(function (x) { win.onNext(x); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); function createWindowClose () { var windowClose; try { windowClose = windowClosingSelector(); } catch (e) { observer.onError(e); return; } isPromise(windowClose) && (windowClose = observableFromPromise(windowClose)); var m1 = new SingleAssignmentDisposable(); m.setDisposable(m1); m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); win = new Subject(); observer.onNext(addRef(win, r)); createWindowClose(); })); } createWindowClose(); return r; }, source); } /** * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. */ observableProto.pairwise = function () { var source = this; return new AnonymousObservable(function (observer) { var previous, hasPrevious = false; return source.subscribe( function (x) { if (hasPrevious) { observer.onNext([previous, x]); } else { hasPrevious = true; } previous = x; }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }, source); }; /** * Returns two observables which partition the observations of the source by the given function. * The first will trigger observations for those values for which the predicate returns true. * The second will trigger observations for those values where the predicate returns false. * The predicate is executed once for each subscribed observer. * Both also propagate all error observations arising from the source and each completes * when the source completes. * @param {Function} predicate * The function to determine which output Observable will trigger a particular observation. * @returns {Array} * An array of observables. The first triggers when the predicate returns true, * and the second triggers when the predicate returns false. */ observableProto.partition = function(predicate, thisArg) { return [ this.filter(predicate, thisArg), this.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) ]; }; function enumerableWhile(condition, source) { return new Enumerable(function () { return new Enumerator(function () { return condition() ? { done: false, value: source } : { done: true, value: undefined }; }); }); } /** * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. * This operator allows for a fluent style of writing queries that use the same sequence multiple times. * * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.letBind = observableProto['let'] = function (func) { return func(this); }; /** * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9 * * @example * 1 - res = Rx.Observable.if(condition, obs1); * 2 - res = Rx.Observable.if(condition, obs1, obs2); * 3 - res = Rx.Observable.if(condition, obs1, scheduler); * @param {Function} condition The condition which determines if the thenSource or elseSource will be run. * @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler. * @returns {Observable} An observable sequence which is either the thenSource or elseSource. */ Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) { return observableDefer(function () { elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty()); isPromise(thenSource) && (thenSource = observableFromPromise(thenSource)); isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler)); // Assume a scheduler for empty only typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler)); return condition() ? thenSource : elseSourceOrScheduler; }); }; /** * Concatenates the observable sequences obtained by running the specified result selector for each element in source. * There is an alias for this method called 'forIn' for browsers <IE9 * @param {Array} sources An array of values to turn into an observable sequence. * @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence. * @returns {Observable} An observable sequence from the concatenated observable sequences. */ Observable['for'] = Observable.forIn = function (sources, resultSelector, thisArg) { return enumerableOf(sources, resultSelector, thisArg).concat(); }; /** * Repeats source as long as condition holds emulating a while loop. * There is an alias for this method called 'whileDo' for browsers <IE9 * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) { isPromise(source) && (source = observableFromPromise(source)); return enumerableWhile(condition, source).concat(); }; /** * Repeats source as long as condition holds emulating a do while loop. * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ observableProto.doWhile = function (condition) { return observableConcat([this, observableWhileDo(condition, this)]); }; /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers <IE9. * * @example * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler); * * @param {Function} selector The function which extracts the value for to test in a case statement. * @param {Array} sources A object which has keys which correspond to the case statement labels. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler. * * @returns {Observable} An observable sequence which is determined by a case statement. */ Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) { return observableDefer(function () { isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler)); defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty()); typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler)); var result = sources[selector()]; isPromise(result) && (result = observableFromPromise(result)); return result || defaultSourceOrScheduler; }); }; /** * Expands an observable sequence by recursively invoking selector. * * @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again. * @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler. * @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion. */ observableProto.expand = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = [], m = new SerialDisposable(), d = new CompositeDisposable(m), activeCount = 0, isAcquired = false; var ensureActive = function () { var isOwner = false; if (q.length > 0) { isOwner = !isAcquired; isAcquired = true; } if (isOwner) { m.setDisposable(scheduler.scheduleRecursive(function (self) { var work; if (q.length > 0) { work = q.shift(); } else { isAcquired = false; return; } var m1 = new SingleAssignmentDisposable(); d.add(m1); m1.setDisposable(work.subscribe(function (x) { observer.onNext(x); var result = null; try { result = selector(x); } catch (e) { observer.onError(e); } q.push(result); activeCount++; ensureActive(); }, observer.onError.bind(observer), function () { d.remove(m1); activeCount--; if (activeCount === 0) { observer.onCompleted(); } })); self(); })); } }; q.push(source); activeCount++; ensureActive(); return d; }, this); }; /** * Runs all observable sequences in parallel and collect their last elements. * * @example * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. */ Observable.forkJoin = function () { var allSources = []; if (Array.isArray(arguments[0])) { allSources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { allSources.push(arguments[i]); } } return new AnonymousObservable(function (subscriber) { var count = allSources.length; if (count === 0) { subscriber.onCompleted(); return disposableEmpty; } var group = new CompositeDisposable(), finished = false, hasResults = new Array(count), hasCompleted = new Array(count), results = new Array(count); for (var idx = 0; idx < count; idx++) { (function (i) { var source = allSources[i]; isPromise(source) && (source = observableFromPromise(source)); group.add( source.subscribe( function (value) { if (!finished) { hasResults[i] = true; results[i] = value; } }, function (e) { finished = true; subscriber.onError(e); group.dispose(); }, function () { if (!finished) { if (!hasResults[i]) { subscriber.onCompleted(); return; } hasCompleted[i] = true; for (var ix = 0; ix < count; ix++) { if (!hasCompleted[ix]) { return; } } finished = true; subscriber.onNext(results); subscriber.onCompleted(); } })); })(idx); } return group; }); }; /** * Runs two observable sequences in parallel and combines their last elemenets. * * @param {Observable} second Second observable sequence. * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. */ observableProto.forkJoin = function (second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var leftStopped = false, rightStopped = false, hasLeft = false, hasRight = false, lastLeft, lastRight, leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(second) && (second = observableFromPromise(second)); leftSubscription.setDisposable( first.subscribe(function (left) { hasLeft = true; lastLeft = left; }, function (err) { rightSubscription.dispose(); observer.onError(err); }, function () { leftStopped = true; if (rightStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); rightSubscription.setDisposable( second.subscribe(function (right) { hasRight = true; lastRight = right; }, function (err) { leftSubscription.dispose(); observer.onError(err); }, function () { rightStopped = true; if (leftStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); return new CompositeDisposable(leftSubscription, rightSubscription); }, first); }; /** * Comonadic bind operator. * @param {Function} selector A transform function to apply to each element. * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. * @returns {Observable} An observable sequence which results from the comonadic bind operation. */ observableProto.manySelect = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return observableDefer(function () { var chain; return source .map(function (x) { var curr = new ChainObservable(x); chain && chain.onNext(x); chain = curr; return curr; }) .tap( noop, function (e) { chain && chain.onError(e); }, function () { chain && chain.onCompleted(); } ) .observeOn(scheduler) .map(selector); }, source); }; var ChainObservable = (function (__super__) { function subscribe (observer) { var self = this, g = new CompositeDisposable(); g.add(currentThreadScheduler.schedule(function () { observer.onNext(self.head); g.add(self.tail.mergeAll().subscribe(observer)); })); return g; } inherits(ChainObservable, __super__); function ChainObservable(head) { __super__.call(this, subscribe); this.head = head; this.tail = new AsyncSubject(); } addProperties(ChainObservable.prototype, Observer, { onCompleted: function () { this.onNext(Observable.empty()); }, onError: function (e) { this.onNext(Observable.throwError(e)); }, onNext: function (v) { this.tail.onNext(v); this.tail.onCompleted(); } }); return ChainObservable; }(Observable)); /** @private */ var Map = root.Map || (function () { function Map() { this._keys = []; this._values = []; } Map.prototype.get = function (key) { var i = this._keys.indexOf(key); return i !== -1 ? this._values[i] : undefined; }; Map.prototype.set = function (key, value) { var i = this._keys.indexOf(key); i !== -1 && (this._values[i] = value); this._values[this._keys.push(key) - 1] = value; }; Map.prototype.forEach = function (callback, thisArg) { for (var i = 0, len = this._keys.length; i < len; i++) { callback.call(thisArg, this._values[i], this._keys[i]); } }; return Map; }()); /** * @constructor * Represents a join pattern over observable sequences. */ function Pattern(patterns) { this.patterns = patterns; } /** * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. * @param other Observable sequence to match in addition to the current pattern. * @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value. */ Pattern.prototype.and = function (other) { return new Pattern(this.patterns.concat(other)); }; /** * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. * @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. * @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ Pattern.prototype.thenDo = function (selector) { return new Plan(this, selector); }; function Plan(expression, selector) { this.expression = expression; this.selector = selector; } Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { var self = this; var joinObservers = []; for (var i = 0, len = this.expression.patterns.length; i < len; i++) { joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); } var activePlan = new ActivePlan(joinObservers, function () { var result; try { result = self.selector.apply(self, arguments); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, function () { for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { joinObservers[j].removeActivePlan(activePlan); } deactivate(activePlan); }); for (i = 0, len = joinObservers.length; i < len; i++) { joinObservers[i].addActivePlan(activePlan); } return activePlan; }; function planCreateObserver(externalSubscriptions, observable, onError) { var entry = externalSubscriptions.get(observable); if (!entry) { var observer = new JoinObserver(observable, onError); externalSubscriptions.set(observable, observer); return observer; } return entry; } function ActivePlan(joinObserverArray, onNext, onCompleted) { this.joinObserverArray = joinObserverArray; this.onNext = onNext; this.onCompleted = onCompleted; this.joinObservers = new Map(); for (var i = 0, len = this.joinObserverArray.length; i < len; i++) { var joinObserver = this.joinObserverArray[i]; this.joinObservers.set(joinObserver, joinObserver); } } ActivePlan.prototype.dequeue = function () { this.joinObservers.forEach(function (v) { v.queue.shift(); }); }; ActivePlan.prototype.match = function () { var i, len, hasValues = true; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { if (this.joinObserverArray[i].queue.length === 0) { hasValues = false; break; } } if (hasValues) { var firstValues = [], isCompleted = false; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { firstValues.push(this.joinObserverArray[i].queue[0]); this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true); } if (isCompleted) { this.onCompleted(); } else { this.dequeue(); var values = []; for (i = 0, len = firstValues.length; i < firstValues.length; i++) { values.push(firstValues[i].value); } this.onNext.apply(this, values); } } }; var JoinObserver = (function (__super__) { inherits(JoinObserver, __super__); function JoinObserver(source, onError) { __super__.call(this); this.source = source; this.onError = onError; this.queue = []; this.activePlans = []; this.subscription = new SingleAssignmentDisposable(); this.isDisposed = false; } var JoinObserverPrototype = JoinObserver.prototype; JoinObserverPrototype.next = function (notification) { if (!this.isDisposed) { if (notification.kind === 'E') { return this.onError(notification.exception); } this.queue.push(notification); var activePlans = this.activePlans.slice(0); for (var i = 0, len = activePlans.length; i < len; i++) { activePlans[i].match(); } } }; JoinObserverPrototype.error = noop; JoinObserverPrototype.completed = noop; JoinObserverPrototype.addActivePlan = function (activePlan) { this.activePlans.push(activePlan); }; JoinObserverPrototype.subscribe = function () { this.subscription.setDisposable(this.source.materialize().subscribe(this)); }; JoinObserverPrototype.removeActivePlan = function (activePlan) { this.activePlans.splice(this.activePlans.indexOf(activePlan), 1); this.activePlans.length === 0 && this.dispose(); }; JoinObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); if (!this.isDisposed) { this.isDisposed = true; this.subscription.dispose(); } }; return JoinObserver; } (AbstractObserver)); /** * Creates a pattern that matches when both observable sequences have an available value. * * @param right Observable sequence to match with the current sequence. * @return {Pattern} Pattern object that matches when both observable sequences have an available value. */ observableProto.and = function (right) { return new Pattern([this, right]); }; /** * Matches when the observable sequence has an available value and projects the value. * * @param {Function} selector Selector that will be invoked for values in the source sequence. * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ observableProto.thenDo = function (selector) { return new Pattern([this]).thenDo(selector); }; /** * Joins together the results from several patterns. * * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. * @returns {Observable} Observable sequence with the results form matching several patterns. */ Observable.when = function () { var len = arguments.length, plans; if (Array.isArray(arguments[0])) { plans = arguments[0]; } else { plans = new Array(len); for(var i = 0; i < len; i++) { plans[i] = arguments[i]; } } return new AnonymousObservable(function (o) { var activePlans = [], externalSubscriptions = new Map(); var outObserver = observerCreate( function (x) { o.onNext(x); }, function (err) { externalSubscriptions.forEach(function (v) { v.onError(err); }); o.onError(err); }, function (x) { o.onCompleted(); } ); try { for (var i = 0, len = plans.length; i < len; i++) { activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { var idx = activePlans.indexOf(activePlan); activePlans.splice(idx, 1); activePlans.length === 0 && o.onCompleted(); })); } } catch (e) { observableThrow(e).subscribe(o); } var group = new CompositeDisposable(); externalSubscriptions.forEach(function (joinObserver) { joinObserver.subscribe(); group.add(joinObserver); }); return group; }); }; function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { return new AnonymousObservable(function (observer) { var d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveWithAbsoluteAndState(0, d, function (count, self) { if (p > 0) { var now = scheduler.now(); d = d + p; d <= now && (d = now + p); } observer.onNext(count); self(count + 1, d); }); }); } function observableTimerTimeSpan(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { return dueTime === period ? new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }) : observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; isScheduler(scheduler) || (scheduler = timeoutScheduler); if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (isScheduler(periodOrScheduler)) { scheduler = periodOrScheduler; } if (dueTime instanceof Date && period === undefined) { return observableTimerDate(dueTime.getTime(), scheduler); } if (dueTime instanceof Date && period !== undefined) { period = periodOrScheduler; return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); } return period === undefined ? observableTimerTimeSpan(dueTime, scheduler) : observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; function observableDelayTimeSpan(source, dueTime, scheduler) { return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }, source); } function observableDelayDate(source, dueTime, scheduler) { return observableDefer(function () { return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); }); } /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * 1 - res = Rx.Observable.delay(new Date()); * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); * * 3 - res = Rx.Observable.delay(5000); * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return dueTime instanceof Date ? observableDelayDate(this, dueTime.getTime(), scheduler) : observableDelayTimeSpan(this, dueTime, scheduler); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The debounced sequence. */ observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0; var subscription = source.subscribe( function (x) { hasvalue = true; value = x; id++; var currentId = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () { hasvalue && id === currentId && observer.onNext(value); hasvalue = false; })); }, function (e) { cancelable.dispose(); observer.onError(e); hasvalue = false; id++; }, function () { cancelable.dispose(); hasvalue && observer.onNext(value); observer.onCompleted(); hasvalue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }, this); }; /** * @deprecated use #debounce or #throttleWithTimeout instead. */ observableProto.throttle = function(dueTime, scheduler) { //deprecate('throttle', 'debounce or throttleWithTimeout'); return this.debounce(dueTime, scheduler); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { var source = this, timeShift; timeShiftOrScheduler == null && (timeShift = timeSpan); isScheduler(scheduler) || (scheduler = timeoutScheduler); if (typeof timeShiftOrScheduler === 'number') { timeShift = timeShiftOrScheduler; } else if (isScheduler(timeShiftOrScheduler)) { timeShift = timeSpan; scheduler = timeShiftOrScheduler; } return new AnonymousObservable(function (observer) { var groupDisposable, nextShift = timeShift, nextSpan = timeSpan, q = [], refCountDisposable, timerD = new SerialDisposable(), totalTime = 0; groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable); function createTimer () { var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false; timerD.setDisposable(m); if (nextSpan === nextShift) { isSpan = true; isShift = true; } else if (nextSpan < nextShift) { isSpan = true; } else { isShift = true; } var newTotalTime = isSpan ? nextSpan : nextShift, ts = newTotalTime - totalTime; totalTime = newTotalTime; if (isSpan) { nextSpan += timeShift; } if (isShift) { nextShift += timeShift; } m.setDisposable(scheduler.scheduleWithRelative(ts, function () { if (isShift) { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } isSpan && q.shift().onCompleted(); createTimer(); })); }; q.push(new Subject()); observer.onNext(addRef(q[0], refCountDisposable)); createTimer(); groupDisposable.add(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } }, function (e) { for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); } observer.onError(e); }, function () { for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; /** * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. * @param {Number} timeSpan Maximum time length of a window. * @param {Number} count Maximum element count of a window. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var timerD = new SerialDisposable(), groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable), n = 0, windowId = 0, s = new Subject(); function createTimer(id) { var m = new SingleAssignmentDisposable(); timerD.setDisposable(m); m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { if (id !== windowId) { return; } n = 0; var newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(newId); })); } observer.onNext(addRef(s, refCountDisposable)); createTimer(0); groupDisposable.add(source.subscribe( function (x) { var newId = 0, newWindow = false; s.onNext(x); if (++n === count) { newWindow = true; n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); } newWindow && createTimer(newId); }, function (e) { s.onError(e); observer.onError(e); }, function () { s.onCompleted(); observer.onCompleted(); } )); return refCountDisposable; }, source); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. * * @example * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. * * @example * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array * * @param {Number} timeSpan Maximum time length of a buffer. * @param {Number} count Maximum element count of a buffer. * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { return x.toArray(); }); }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return observableDefer(function () { var last = scheduler.now(); return source.map(function (x) { var now = scheduler.now(), span = now - last; last = now; return { value: x, interval: span }; }); }); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.default); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the default scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.map(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } atEnd && observer.onCompleted(); } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }, source); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return typeof intervalOrSampler === 'number' ? sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { (other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout'))); isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); function createTimer() { var myId = id; timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { if (id === myId) { isPromise(other) && (other = observableFromPromise(other)); subscription.setDisposable(other.subscribe(observer)); } })); } createTimer(); original.setDisposable(source.subscribe(function (x) { if (!switched) { id++; observer.onNext(x); createTimer(); } }, function (e) { if (!switched) { id++; observer.onError(e); } }, function () { if (!switched) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }, source); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithAbsoluteTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return new Date(); } * }); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithRelative(0, function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.default); // 5 seconds * * @param {Number} dueTime Relative or absolute time shift of the subscription. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { var scheduleMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { var d = new SerialDisposable(); d.setDisposable(scheduler[scheduleMethod](dueTime, function() { d.setDisposable(source.subscribe(o)); })); return d; }, this); }; /** * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector * * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. * @returns {Observable} Time-shifted sequence. */ observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { var source = this, subDelay, selector; if (isFunction(subscriptionDelay)) { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (observer) { var delays = new CompositeDisposable(), atEnd = false, subscription = new SerialDisposable(); function start() { subscription.setDisposable(source.subscribe( function (x) { var delay = tryCatch(selector)(x); if (delay === errorObj) { return observer.onError(delay.e); } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe( function () { observer.onNext(x); delays.remove(d); done(); }, function (e) { observer.onError(e); }, function () { observer.onNext(x); delays.remove(d); done(); } )) }, function (e) { observer.onError(e); }, function () { atEnd = true; subscription.dispose(); done(); } )) } function done () { atEnd && delays.length === 0 && observer.onCompleted(); } if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(start, function (e) { observer.onError(e); }, start)); } return new CompositeDisposable(subscription, delays); }, this); }; /** * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). * @param {Function} timeoutDurationSelector Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { if (arguments.length === 1) { timeoutdurationSelector = firstTimeout; firstTimeout = observableNever(); } other || (other = observableThrow(new Error('Timeout'))); var source = this; return new AnonymousObservable(function (observer) { var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); subscription.setDisposable(original); var id = 0, switched = false; function setTimer(timeout) { var myId = id; function timerWins () { return id === myId; } var d = new SingleAssignmentDisposable(); timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { timerWins() && subscription.setDisposable(other.subscribe(observer)); d.dispose(); }, function (e) { timerWins() && observer.onError(e); }, function () { timerWins() && subscription.setDisposable(other.subscribe(observer)); })); }; setTimer(firstTimeout); function observerWins() { var res = !switched; if (res) { id++; } return res; } original.setDisposable(source.subscribe(function (x) { if (observerWins()) { observer.onNext(x); var timeout; try { timeout = timeoutdurationSelector(x); } catch (e) { observer.onError(e); return; } setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout); } }, function (e) { observerWins() && observer.onError(e); }, function () { observerWins() && observer.onCompleted(); })); return new CompositeDisposable(subscription, timer); }, source); }; /** * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. * @param {Function} durationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. * @returns {Observable} The debounced sequence. */ observableProto.debounceWithSelector = function (durationSelector) { var source = this; return new AnonymousObservable(function (observer) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0; var subscription = source.subscribe(function (x) { var throttle; try { throttle = durationSelector(x); } catch (e) { observer.onError(e); return; } isPromise(throttle) && (throttle = observableFromPromise(throttle)); hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe(function () { hasValue && id === currentid && observer.onNext(value); hasValue = false; d.dispose(); }, observer.onError.bind(observer), function () { hasValue && id === currentid && observer.onNext(value); hasValue = false; d.dispose(); })); }, function (e) { cancelable.dispose(); observer.onError(e); hasValue = false; id++; }, function () { cancelable.dispose(); hasValue && observer.onNext(value); observer.onCompleted(); hasValue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }, source); }; /** * @deprecated use #debounceWithSelector instead. */ observableProto.throttleWithSelector = function (durationSelector) { //deprecate('throttleWithSelector', 'debounceWithSelector'); return this.debounceWithSelector(durationSelector); }; /** * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * 1 - res = source.skipLastWithTime(5000); * 2 - res = source.skipLastWithTime(5000, scheduler); * * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for skipping elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. */ observableProto.skipLastWithTime = function (duration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { o.onNext(q.shift().value); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(); while (q.length > 0 && now - q[0].interval >= duration) { o.onNext(q.shift().value); } o.onCompleted(); }); }, source); }; /** * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(); while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { o.onNext(next.value); } } o.onCompleted(); }); }, source); }; /** * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastBufferWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(), res = []; while (q.length > 0) { var next = q.shift(); now - next.interval <= duration && res.push(next.value); } o.onNext(res); o.onCompleted(); }); }, source); }; /** * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ observableProto.takeWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { return new CompositeDisposable(scheduler.scheduleWithRelative(duration, function () { o.onCompleted(); }), source.subscribe(o)); }, source); }; /** * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.skipWithTime(5000, [optional scheduler]); * * @description * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded * may not execute immediately, despite the zero due time. * * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. * @param {Number} duration Duration for skipping elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ observableProto.skipWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler.scheduleWithRelative(duration, function () { open = true; }), source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }, source); }; /** * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. * * @examples * 1 - res = source.skipUntilWithTime(new Date(), [scheduler]); * 2 - res = source.skipUntilWithTime(5000, [scheduler]); * @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped until the specified start time. */ observableProto.skipUntilWithTime = function (startTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = startTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (o) { var open = false; return new CompositeDisposable( scheduler[schedulerMethod](startTime, function () { open = true; }), source.subscribe( function (x) { open && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); })); }, source); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} [scheduler] Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = endTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (o) { return new CompositeDisposable( scheduler[schedulerMethod](endTime, function () { o.onCompleted(); }), source.subscribe(o)); }, source); }; /** * Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration. * @param {Number} windowDuration time to wait before emitting another item after emitting the last item * @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout. * @returns {Observable} An Observable that performs the throttle operation. */ observableProto.throttleFirst = function (windowDuration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var duration = +windowDuration || 0; if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); } var source = this; return new AnonymousObservable(function (o) { var lastOnNext = 0; return source.subscribe( function (x) { var now = scheduler.now(); if (lastOnNext === 0 || now - lastOnNext >= duration) { lastOnNext = now; o.onNext(x); } },function (e) { o.onError(e); }, function () { o.onCompleted(); } ); }, source); }; /** * 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(o) { return { '@@transducer/init': function() { return o; }, '@@transducer/step': function(obs, input) { return obs.onNext(input); }, '@@transducer/result': function(obs) { return obs.onCompleted(); } }; } return new AnonymousObservable(function(o) { var xform = transducer(transformForObserver(o)); return source.subscribe( function(v) { try { xform['@@transducer/step'](o, v); } catch (e) { o.onError(e); } }, function (e) { o.onError(e); }, function() { xform['@@transducer/result'](o); } ); }, source); }; /* * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @returns {Observable} A exclusive observable with only the results that happen when subscribed. */ observableProto.exclusive = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasCurrent = false, isStopped = false, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); var innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); innerSubscription.setDisposable(innerSource.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (!hasCurrent && g.length === 1) { observer.onCompleted(); } })); return g; }, this); }; /* * Performs a exclusive map waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @param {Function} selector Selector to invoke for every item in the current subscription. * @param {Any} [thisArg] An optional context to invoke with the selector parameter. * @returns {Observable} An exclusive observable with only the results that happen when subscribed. */ observableProto.exclusiveMap = function (selector, thisArg) { var sources = this, selectorFunc = bindCallback(selector, thisArg, 3); return new AnonymousObservable(function (observer) { var index = 0, hasCurrent = false, isStopped = true, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { var result; try { result = selectorFunc(x, index++, innerSource); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, function (e) { observer.onError(e); }, function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, function (e) { observer.onError(e); }, function () { isStopped = true; if (g.length === 1 && !hasCurrent) { observer.onCompleted(); } })); return g; }, this); }; /** Provides a set of extension methods for virtual time scheduling. */ Rx.VirtualTimeScheduler = (function (__super__) { function localNow() { return this.toDateTimeOffset(this.clock); } function scheduleNow(state, action) { return this.scheduleAbsoluteWithState(state, this.clock, action); } function scheduleRelative(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); } function invokeAction(scheduler, action) { action(); return disposableEmpty; } inherits(VirtualTimeScheduler, __super__); /** * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function VirtualTimeScheduler(initialClock, comparer) { this.clock = initialClock; this.comparer = comparer; this.isEnabled = false; this.queue = new PriorityQueue(1024); __super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ VirtualTimeSchedulerPrototype.add = notImplemented; /** * Converts an absolute time to a number * @param {Any} The absolute time. * @returns {Number} The absolute time in ms */ VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; /** * Converts the TimeSpan value to a relative virtual time value. * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ VirtualTimeSchedulerPrototype.toRelative = notImplemented; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { var s = new SchedulePeriodicRecursive(this, state, period, action); return s.start(); }; /** * Schedules an action to be executed after dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { var runAt = this.add(this.clock, dueTime); return this.scheduleAbsoluteWithState(state, runAt, action); }; /** * Schedules an action to be executed at dueTime. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { return this.scheduleRelativeWithState(action, dueTime, invokeAction); }; /** * Starts the virtual time scheduler. */ VirtualTimeSchedulerPrototype.start = function () { if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); } }; /** * Stops the virtual time scheduler. */ VirtualTimeSchedulerPrototype.stop = function () { this.isEnabled = false; }; /** * Advances the scheduler's clock to the specified time, running all work till that point. * @param {Number} time Absolute time to advance the scheduler's clock to. */ VirtualTimeSchedulerPrototype.advanceTo = function (time) { var dueToClock = this.comparer(this.clock, time); if (this.comparer(this.clock, time) > 0) { throw new ArgumentOutOfRangeError(); } if (dueToClock === 0) { return; } if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null && this.comparer(next.dueTime, time) <= 0) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); this.clock = time; } }; /** * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.advanceBy = function (time) { var dt = this.add(this.clock, time), dueToClock = this.comparer(this.clock, dt); if (dueToClock > 0) { throw new ArgumentOutOfRangeError(); } if (dueToClock === 0) { return; } this.advanceTo(dt); }; /** * Advances the scheduler's clock by the specified relative time. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.sleep = function (time) { var dt = this.add(this.clock, time); if (this.comparer(this.clock, dt) >= 0) { throw new ArgumentOutOfRangeError(); } this.clock = dt; }; /** * Gets the next scheduled item to be executed. * @returns {ScheduledItem} The next scheduled item. */ VirtualTimeSchedulerPrototype.getNext = function () { while (this.queue.length > 0) { var next = this.queue.peek(); if (next.isCancelled()) { this.queue.dequeue(); } else { return next; } } return null; }; /** * Schedules an action to be executed at dueTime. * @param {Scheduler} scheduler Scheduler to execute the action on. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { var self = this; function run(scheduler, state1) { self.queue.remove(si); return action(scheduler, state1); } var si = new ScheduledItem(this, state, run, dueTime, this.comparer); this.queue.enqueue(si); return si.disposable; }; return VirtualTimeScheduler; }(Scheduler)); /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ Rx.HistoricalScheduler = (function (__super__) { inherits(HistoricalScheduler, __super__); /** * Creates a new historical scheduler with the specified initial clock value. * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function HistoricalScheduler(initialClock, comparer) { var clock = initialClock == null ? 0 : initialClock; var cmp = comparer || defaultSubComparer; __super__.call(this, clock, cmp); } var HistoricalSchedulerProto = HistoricalScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ HistoricalSchedulerProto.add = function (absolute, relative) { return absolute + relative; }; HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { return new Date(absolute).getTime(); }; /** * Converts the TimeSpan value to a relative virtual time value. * @memberOf HistoricalScheduler * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ HistoricalSchedulerProto.toRelative = function (timeSpan) { return timeSpan; }; return HistoricalScheduler; }(Rx.VirtualTimeScheduler)); var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], subscribe = state[1]; var sub = tryCatch(subscribe)(ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function AnonymousObservable(subscribe, parent) { this.source = parent; function s(observer) { var ado = new AutoDetachObserver(observer), state = [ado, subscribe]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); var AutoDetachObserver = (function (__super__) { inherits(AutoDetachObserver, __super__); function AutoDetachObserver(observer) { __super__.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var result = tryCatch(this.observer.onNext).call(this.observer, value); if (result === errorObj) { this.dispose(); thrower(result.e); } }; AutoDetachObserverPrototype.error = function (err) { var result = tryCatch(this.observer.onError).call(this.observer, err); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.completed = function () { var result = tryCatch(this.observer.onCompleted).call(this.observer); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); }; AutoDetachObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); var GroupedObservable = (function (__super__) { inherits(GroupedObservable, __super__); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } function GroupedObservable(key, underlyingObservable, mergedDisposable) { __super__.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, __super__); /** * Creates a subject. */ function Subject() { __super__.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; this.hasError = false; } addProperties(Subject.prototype, Observer.prototype, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (!this.isStopped) { for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); } else if (this.hasValue) { observer.onNext(this.value); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.hasValue = false; this.observers = []; this.hasError = false; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var i, len; checkDisposed(this); if (!this.isStopped) { this.isStopped = true; var os = cloneArray(this.observers), len = os.length; if (this.hasValue) { for (i = 0; i < len; i++) { var o = os[i]; o.onNext(this.value); o.onCompleted(); } } else { for (i = 0; i < len; i++) { os[i].onCompleted(); } } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } this.value = value; this.hasValue = true; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function subscribe(observer) { return this.observable.subscribe(observer); } function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, subscribe); } addProperties(AnonymousSubject.prototype, Observer.prototype, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (error) { this.observer.onError(error); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); /** * Used to pause and resume streams. */ Rx.Pauser = (function (__super__) { inherits(Pauser, __super__); function Pauser() { __super__.call(this); } /** * Pauses the underlying sequence. */ Pauser.prototype.pause = function () { this.onNext(false); }; /** * Resumes the underlying sequence. */ Pauser.prototype.resume = function () { this.onNext(true); }; return Pauser; }(Subject)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } // All code before this point will be filtered from stack traces. var rEndingLine = captureLine(); }.call(this));
node_modules/react-icons/fa/dashboard.js
bengimbel/Solstice-React-Contacts-Project
import React from 'react' import Icon from 'react-icon-base' const FaDashboard = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m8.6 25.7q0-1.2-0.9-2t-2-0.8-2 0.8-0.8 2 0.8 2 2 0.9 2-0.9 0.9-2z m4.3-10q0-1.2-0.9-2t-2-0.8-2 0.8-0.9 2 0.9 2 2 0.9 2-0.9 0.9-2z m9.5 10.7l2.3-8.5q0.1-0.6-0.2-1.1t-0.9-0.6-1 0.1-0.7 0.9l-2.3 8.5q-1.3 0.1-2.3 1t-1.5 2.2q-0.4 1.7 0.5 3.3t2.6 2 3.3-0.5 2-2.6q0.3-1.3-0.2-2.6t-1.6-2z m14.7-0.7q0-1.2-0.8-2t-2-0.8-2 0.8-0.9 2 0.9 2 2 0.9 2-0.9 0.8-2z m-14.2-14.3q0-1.2-0.9-2t-2-0.8-2 0.8-0.9 2 0.9 2 2 0.9 2-0.9 0.9-2z m10 4.3q0-1.2-0.9-2t-2-0.8-2 0.8-0.9 2 0.9 2 2 0.9 2-0.9 0.9-2z m7.1 10q0 5.8-3.1 10.8-0.5 0.6-1.3 0.6h-31.2q-0.8 0-1.3-0.6-3.1-4.9-3.1-10.8 0-4 1.6-7.8t4.2-6.3 6.4-4.3 7.8-1.6 7.8 1.6 6.4 4.3 4.2 6.3 1.6 7.8z"/></g> </Icon> ) export default FaDashboard
ajax/libs/react-ios-switch/0.1.5-rc5/bundle.js
rlugojr/cdnjs
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else { var a = factory(); for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; } })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _Switch = __webpack_require__(1); Object.defineProperty(exports, 'default', { enumerable: true, get: function get() { return _interopRequireDefault(_Switch).default; } }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _dynamics = __webpack_require__(2); var _dynamics2 = _interopRequireDefault(_dynamics); var _d3Interpolate = __webpack_require__(3); var _classnames = __webpack_require__(5); var _classnames2 = _interopRequireDefault(_classnames); var _invariant = __webpack_require__(6); var _invariant2 = _interopRequireDefault(_invariant); var _react = __webpack_require__(8); var _react2 = _interopRequireDefault(_react); var _Switch = __webpack_require__(164); var _Switch2 = _interopRequireDefault(_Switch); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Switch = function (_React$Component) { _inherits(Switch, _React$Component); function Switch(props) { _classCallCheck(this, Switch); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Switch).call(this, props)); var offset = _this.getCheckedStateOffset(props); // During a drag, we track the starting mouse position and the current mouse position. // This allows us to avoid accumulating deltas, and thus avoid accumulating errors. _this.state = { currentClientX: 0, dragging: false, offset: offset, startClientX: 0 }; // The state offset should always eventually match the animated properties offset. // The component should interact with the state offset, while dynamics should interact with // the animated properties offset. _this.animatedProperties = { offset: offset }; _this.handleAnimationChange = _this.handleAnimationChange.bind(_this); _this.handleClick = _this.handleClick.bind(_this); _this.handleHandleClick = _this.handleHandleClick.bind(_this); _this.handleInputChange = _this.handleInputChange.bind(_this); _this.handleMouseDown = _this.handleMouseDown.bind(_this); _this.handleMouseMove = _this.handleMouseMove.bind(_this); _this.handleMouseUp = _this.handleMouseUp.bind(_this); return _this; } _createClass(Switch, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { // Assume the props change occurred because the checked state changed. Animate back to the // rest state. this.startAnimation(nextProps); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { var dragging = this.state.dragging; this.cancelAnimation(); if (dragging) { this.removeListeners(); } } // We should be able to compute the offset from the checked state. }, { key: 'getCheckedStateOffset', value: function getCheckedStateOffset(props) { var checked = props.checked; var maxOffset = props.maxOffset; return checked ? maxOffset : 0; } }, { key: 'addListeners', value: function addListeners() { document.addEventListener('mousemove', this.handleMouseMove); document.addEventListener('mouseup', this.handleMouseUp); } }, { key: 'cancelAnimation', value: function cancelAnimation() { _dynamics2.default.stop(this.animatedProperties); } }, { key: 'handleAnimationChange', value: function handleAnimationChange() { this.setState({ offset: this.animatedProperties.offset }); } }, { key: 'handleClick', value: function handleClick(e) { var _props = this.props; var checked = _props.checked; var onChange = _props.onChange; // Prevent the outer label from receiving the event. e.preventDefault(); onChange(!checked); } // If a click event occurs on the handle, drop the event. The mouseup handler will decide // whether to consider the mouseup event a "click to toggle" interaction or a "drag end" // interaction. }, { key: 'handleHandleClick', value: function handleHandleClick(e) { // Prevent the outer label from receiving the event. e.preventDefault(); // Prevent the switch click handler from receiving the event. e.stopPropagation(); } // If there is an outer label, and it is clicked, the input receives a click event and a change // event. Because we use the click event to set the checked state (the click event propagates to // the switch), we can ignore the change event. }, { key: 'handleInputChange', value: function handleInputChange() {} }, { key: 'handleMouseDown', value: function handleMouseDown(e) { var dragging = this.state.dragging; (0, _invariant2.default)(!dragging, 'Mouse down handler called inside of a drag'); // Left click only if (e.button !== 0) { return; } this.cancelAnimation(); this.setState({ currentClientX: e.clientX, dragging: true, startClientX: e.clientX }); // While the drag is ongoing, we set document-level event handlers to capture mousemove and // mouseup. This way, the drag doesn't end if the user mouses off the handle. These event // handlers are expensive and global, so we need to make sure we remove them when the drag ends. this.addListeners(); } }, { key: 'handleMouseMove', value: function handleMouseMove(e) { var dragging = this.state.dragging; (0, _invariant2.default)(dragging, 'Mouse move handler called outside of a drag'); this.setState({ currentClientX: e.clientX }); } }, { key: 'handleMouseUp', value: function handleMouseUp() { var _props2 = this.props; var checked = _props2.checked; var maxOffset = _props2.maxOffset; var onChange = _props2.onChange; var _state = this.state; var currentClientX = _state.currentClientX; var dragging = _state.dragging; var offset = _state.offset; var startClientX = _state.startClientX; (0, _invariant2.default)(dragging, 'Mouse up handler called outside of a drag'); this.removeListeners(); // If the mouse hasn't changed position by the end of a drag, treat it as a click on the handle. var deltaX = currentClientX - startClientX; if (!deltaX) { this.setState({ dragging: false }); onChange(!checked); return; } // The checked state is a function of the mouse offset. var newOffset = offset + deltaX; var newChecked = newOffset > maxOffset / 2; this.setState({ dragging: false, offset: newOffset }); onChange(newChecked); } }, { key: 'removeListeners', value: function removeListeners() { document.removeEventListener('mousemove', this.handleMouseMove); document.removeEventListener('mouseup', this.handleMouseUp); } }, { key: 'startAnimation', value: function startAnimation(props) { var offset = this.state.offset; this.animatedProperties.offset = offset; // Note that spring animation always results in a bounce at the end. Choose parameters to // minimize this bounce. _dynamics2.default.animate(this.animatedProperties, { offset: this.getCheckedStateOffset(props) }, { change: this.handleAnimationChange, frequency: 200, friction: 400, type: _dynamics2.default.spring }); } }, { key: 'render', value: function render() { var _props3 = this.props; var checked = _props3.checked; var disabled = _props3.disabled; var handleColor = _props3.handleColor; var maxOffset = _props3.maxOffset; var offColor = _props3.offColor; var onColor = _props3.onColor; var pendingOffColor = _props3.pendingOffColor; var _state2 = this.state; var currentClientX = _state2.currentClientX; var dragging = _state2.dragging; var offset = _state2.offset; var startClientX = _state2.startClientX; // The handle position is a function of the mouse offset. var deltaX = dragging ? currentClientX - startClientX : 0; var clampedOffset = Math.min(maxOffset, Math.max(0, offset + deltaX)); var handleTransform = 'translateX(' + clampedOffset + 'px)'; // The interpolation parameter is a function of the mouse offset. var t = clampedOffset / maxOffset; // The switch color is a function of the interpolation parameter. var color = (0, _d3Interpolate.interpolate)(pendingOffColor, onColor)(t); // The off state size is a function of the interpolation parameter. var offStateTransform = 'scale(' + (1 - t) + ')'; return _react2.default.createElement( 'div', { className: (0, _classnames2.default)(_Switch2.default.switch, disabled && _Switch2.default['switch--disabled']), onClick: this.handleClick, style: { backgroundColor: color } }, _react2.default.createElement('div', { className: _Switch2.default.offState, style: { backgroundColor: offColor, msTransform: offStateTransform, transform: offStateTransform, WebkitTransform: offStateTransform } }), _react2.default.createElement('div', { className: _Switch2.default.handle, onClick: this.handleHandleClick, onMouseDown: !disabled && this.handleMouseDown, style: { backgroundColor: handleColor, msTransform: handleTransform, transform: handleTransform, WebkitTransform: handleTransform } }), _react2.default.createElement('input', { className: _Switch2.default.input, checked: checked, disabled: disabled, onChange: this.handleInputChange, type: 'checkbox' }) ); } }]); return Switch; }(_react2.default.Component); Switch.defaultProps = { disabled: false, handleColor: 'white', maxOffset: 20, offColor: 'white', onColor: '#4cd964', pendingOffColor: '#e5e5e5' }; exports.default = Switch; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;// Generated by CoffeeScript 1.7.1 (function() { var Color, DecomposedMatrix, DecomposedMatrix2D, InterpolableArray, InterpolableColor, InterpolableObject, InterpolableWithUnit, Matrix, Matrix2D, Set, Vector, addTimeout, animationTick, animations, animationsTimeouts, applyDefaults, applyFrame, applyProperties, baseSVG, cacheFn, cancelTimeout, clone, createInterpolable, defaultValueForKey, degProperties, dynamics, getCurrentProperties, interpolate, isDocumentVisible, isSVGElement, lastTime, leftDelayForTimeout, makeArrayFn, observeVisibilityChange, parseProperties, prefixFor, propertyWithPrefix, pxProperties, rAF, roundf, runLoopPaused, runLoopRunning, runLoopTick, setRealTimeout, slow, slowRatio, startAnimation, startRunLoop, svgProperties, timeBeforeVisibilityChange, timeoutLastId, timeouts, toDashed, transformProperties, transformValueForProperty, unitForProperty, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; isDocumentVisible = function() { return document.visibilityState === "visible" || (dynamics.tests != null); }; observeVisibilityChange = (function() { var fns; fns = []; if (typeof document !== "undefined" && document !== null) { document.addEventListener("visibilitychange", function() { var fn, _i, _len, _results; _results = []; for (_i = 0, _len = fns.length; _i < _len; _i++) { fn = fns[_i]; _results.push(fn(isDocumentVisible())); } return _results; }); } return function(fn) { return fns.push(fn); }; })(); clone = function(o) { var k, newO, v; newO = {}; for (k in o) { v = o[k]; newO[k] = v; } return newO; }; cacheFn = function(func) { var data; data = {}; return function() { var k, key, result, _i, _len; key = ""; for (_i = 0, _len = arguments.length; _i < _len; _i++) { k = arguments[_i]; key += k.toString() + ","; } result = data[key]; if (!result) { data[key] = result = func.apply(this, arguments); } return result; }; }; makeArrayFn = function(fn) { return function(el) { var args, i, res; if (el instanceof Array || el instanceof NodeList || el instanceof HTMLCollection) { res = (function() { var _i, _ref, _results; _results = []; for (i = _i = 0, _ref = el.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { args = Array.prototype.slice.call(arguments, 1); args.splice(0, 0, el[i]); _results.push(fn.apply(this, args)); } return _results; }).apply(this, arguments); return res; } return fn.apply(this, arguments); }; }; applyDefaults = function(options, defaults) { var k, v, _results; _results = []; for (k in defaults) { v = defaults[k]; _results.push(options[k] != null ? options[k] : options[k] = v); } return _results; }; applyFrame = function(el, properties) { var k, v, _results; if ((el.style != null)) { return applyProperties(el, properties); } else { _results = []; for (k in properties) { v = properties[k]; _results.push(el[k] = v.format()); } return _results; } }; applyProperties = function(el, properties) { var isSVG, k, matrix, transforms, v; properties = parseProperties(properties); transforms = []; isSVG = isSVGElement(el); for (k in properties) { v = properties[k]; if (transformProperties.contains(k)) { transforms.push([k, v]); } else { if (v.format != null) { v = v.format(); } else { v = "" + v + (unitForProperty(k, v)); } if (isSVG && svgProperties.contains(k)) { el.setAttribute(k, v); } else { el.style[propertyWithPrefix(k)] = v; } } } if (transforms.length > 0) { if (isSVG) { matrix = new Matrix2D(); matrix.applyProperties(transforms); return el.setAttribute("transform", matrix.decompose().format()); } else { v = (transforms.map(function(transform) { return transformValueForProperty(transform[0], transform[1]); })).join(" "); return el.style[propertyWithPrefix("transform")] = v; } } }; isSVGElement = function(el) { var _ref, _ref1; if ((typeof SVGElement !== "undefined" && SVGElement !== null) && (typeof SVGSVGElement !== "undefined" && SVGSVGElement !== null)) { return el instanceof SVGElement && !(el instanceof SVGSVGElement); } else { return (_ref = (_ref1 = dynamics.tests) != null ? typeof _ref1.isSVG === "function" ? _ref1.isSVG(el) : void 0 : void 0) != null ? _ref : false; } }; roundf = function(v, decimal) { var d; d = Math.pow(10, decimal); return Math.round(v * d) / d; }; Set = (function() { function Set(array) { var v, _i, _len; this.obj = {}; for (_i = 0, _len = array.length; _i < _len; _i++) { v = array[_i]; this.obj[v] = 1; } } Set.prototype.contains = function(v) { return this.obj[v] === 1; }; return Set; })(); toDashed = function(str) { return str.replace(/([A-Z])/g, function($1) { return "-" + $1.toLowerCase(); }); }; pxProperties = new Set('marginTop,marginLeft,marginBottom,marginRight,paddingTop,paddingLeft,paddingBottom,paddingRight,top,left,bottom,right,translateX,translateY,translateZ,perspectiveX,perspectiveY,perspectiveZ,width,height,maxWidth,maxHeight,minWidth,minHeight,borderRadius'.split(',')); degProperties = new Set('rotate,rotateX,rotateY,rotateZ,skew,skewX,skewY,skewZ'.split(',')); transformProperties = new Set('translate,translateX,translateY,translateZ,scale,scaleX,scaleY,scaleZ,rotate,rotateX,rotateY,rotateZ,rotateC,rotateCX,rotateCY,skew,skewX,skewY,skewZ,perspective'.split(',')); svgProperties = new Set('accent-height,ascent,azimuth,baseFrequency,baseline-shift,bias,cx,cy,d,diffuseConstant,divisor,dx,dy,elevation,filterRes,fx,fy,gradientTransform,height,k1,k2,k3,k4,kernelMatrix,kernelUnitLength,letter-spacing,limitingConeAngle,markerHeight,markerWidth,numOctaves,order,overline-position,overline-thickness,pathLength,points,pointsAtX,pointsAtY,pointsAtZ,r,radius,rx,ry,seed,specularConstant,specularExponent,stdDeviation,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,surfaceScale,target,targetX,targetY,transform,underline-position,underline-thickness,viewBox,width,x,x1,x2,y,y1,y2,z'.split(',')); unitForProperty = function(k, v) { if (typeof v !== 'number') { return ''; } if (pxProperties.contains(k)) { return 'px'; } else if (degProperties.contains(k)) { return 'deg'; } return ''; }; transformValueForProperty = function(k, v) { var match, unit; match = ("" + v).match(/^([0-9.-]*)([^0-9]*)$/); if (match != null) { v = match[1]; unit = match[2]; } else { v = parseFloat(v); } v = roundf(parseFloat(v), 10); if ((unit == null) || unit === "") { unit = unitForProperty(k, v); } return "" + k + "(" + v + unit + ")"; }; parseProperties = function(properties) { var axis, match, parsed, property, value, _i, _len, _ref; parsed = {}; for (property in properties) { value = properties[property]; if (transformProperties.contains(property)) { match = property.match(/(translate|rotateC|rotate|skew|scale|perspective)(X|Y|Z|)/); if (match && match[2].length > 0) { parsed[property] = value; } else { _ref = ['X', 'Y', 'Z']; for (_i = 0, _len = _ref.length; _i < _len; _i++) { axis = _ref[_i]; parsed[match[1] + axis] = value; } } } else { parsed[property] = value; } } return parsed; }; defaultValueForKey = function(key) { var v; v = key === 'opacity' ? 1 : 0; return "" + v + (unitForProperty(key, v)); }; getCurrentProperties = function(el, keys) { var isSVG, key, matrix, properties, style, v, _i, _j, _len, _len1, _ref; properties = {}; isSVG = isSVGElement(el); if (el.style != null) { style = window.getComputedStyle(el, null); for (_i = 0, _len = keys.length; _i < _len; _i++) { key = keys[_i]; if (transformProperties.contains(key)) { if (properties['transform'] == null) { if (isSVG) { matrix = new Matrix2D((_ref = el.transform.baseVal.consolidate()) != null ? _ref.matrix : void 0); } else { matrix = Matrix.fromTransform(style[propertyWithPrefix('transform')]); } properties['transform'] = matrix.decompose(); } } else { v = style[key]; if ((v == null) && svgProperties.contains(key)) { v = el.getAttribute(key); } if (v === "" || (v == null)) { v = defaultValueForKey(key); } properties[key] = createInterpolable(v); } } } else { for (_j = 0, _len1 = keys.length; _j < _len1; _j++) { key = keys[_j]; properties[key] = createInterpolable(el[key]); } } return properties; }; createInterpolable = function(value) { var interpolable, klass, klasses, _i, _len; klasses = [InterpolableColor, InterpolableArray, InterpolableObject, InterpolableWithUnit]; for (_i = 0, _len = klasses.length; _i < _len; _i++) { klass = klasses[_i]; interpolable = klass.create(value); if (interpolable != null) { return interpolable; } } return null; }; InterpolableObject = (function() { function InterpolableObject(obj) { this.format = __bind(this.format, this); this.interpolate = __bind(this.interpolate, this); this.obj = obj; } InterpolableObject.prototype.interpolate = function(endInterpolable, t) { var end, k, newObj, start, v; start = this.obj; end = endInterpolable.obj; newObj = {}; for (k in start) { v = start[k]; if (v.interpolate != null) { newObj[k] = v.interpolate(end[k], t); } else { newObj[k] = v; } } return new InterpolableObject(newObj); }; InterpolableObject.prototype.format = function() { return this.obj; }; InterpolableObject.create = function(value) { var k, obj, v; if (value instanceof Object) { obj = {}; for (k in value) { v = value[k]; obj[k] = createInterpolable(v); } return new InterpolableObject(obj); } return null; }; return InterpolableObject; })(); InterpolableWithUnit = (function() { function InterpolableWithUnit(value, prefix, suffix) { this.prefix = prefix; this.suffix = suffix; this.format = __bind(this.format, this); this.interpolate = __bind(this.interpolate, this); this.value = parseFloat(value); } InterpolableWithUnit.prototype.interpolate = function(endInterpolable, t) { var end, start; start = this.value; end = endInterpolable.value; return new InterpolableWithUnit((end - start) * t + start, endInterpolable.prefix || this.prefix, endInterpolable.suffix || this.suffix); }; InterpolableWithUnit.prototype.format = function() { if ((this.prefix == null) && (this.suffix == null)) { return roundf(this.value, 5); } return this.prefix + roundf(this.value, 5) + this.suffix; }; InterpolableWithUnit.create = function(value) { var match; if (typeof value !== "string") { return new InterpolableWithUnit(value); } match = ("" + value).match("([^0-9.+-]*)([0-9.+-]+)([^0-9.+-]*)"); if (match != null) { return new InterpolableWithUnit(match[2], match[1], match[3]); } return null; }; return InterpolableWithUnit; })(); InterpolableArray = (function() { function InterpolableArray(values, sep) { this.values = values; this.sep = sep; this.format = __bind(this.format, this); this.interpolate = __bind(this.interpolate, this); } InterpolableArray.prototype.interpolate = function(endInterpolable, t) { var end, i, newValues, start, _i, _ref; start = this.values; end = endInterpolable.values; newValues = []; for (i = _i = 0, _ref = Math.min(start.length, end.length); 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { if (start[i].interpolate != null) { newValues.push(start[i].interpolate(end[i], t)); } else { newValues.push(start[i]); } } return new InterpolableArray(newValues, this.sep); }; InterpolableArray.prototype.format = function() { var values; values = this.values.map(function(val) { if (val.format != null) { return val.format(); } else { return val; } }); if (this.sep != null) { return values.join(this.sep); } else { return values; } }; InterpolableArray.createFromArray = function(arr, sep) { var values; values = arr.map(function(val) { return createInterpolable(val) || val; }); values = values.filter(function(val) { return val != null; }); return new InterpolableArray(values, sep); }; InterpolableArray.create = function(value) { var arr, sep, seps, _i, _len; if (value instanceof Array) { return InterpolableArray.createFromArray(value, null); } if (typeof value !== "string") { return; } seps = [' ', ',', '|', ';', '/', ':']; for (_i = 0, _len = seps.length; _i < _len; _i++) { sep = seps[_i]; arr = value.split(sep); if (arr.length > 1) { return InterpolableArray.createFromArray(arr, sep); } } return null; }; return InterpolableArray; })(); Color = (function() { function Color(rgb, format) { this.rgb = rgb != null ? rgb : {}; this.format = format; this.toRgba = __bind(this.toRgba, this); this.toRgb = __bind(this.toRgb, this); this.toHex = __bind(this.toHex, this); } Color.fromHex = function(hex) { var hex3, result; hex3 = hex.match(/^#([a-f\d]{1})([a-f\d]{1})([a-f\d]{1})$/i); if (hex3 != null) { hex = "#" + hex3[1] + hex3[1] + hex3[2] + hex3[2] + hex3[3] + hex3[3]; } result = hex.match(/^#([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i); if (result != null) { return new Color({ r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16), a: 1 }, "hex"); } return null; }; Color.fromRgb = function(rgb) { var match, _ref; match = rgb.match(/^rgba?\(([0-9.]*), ?([0-9.]*), ?([0-9.]*)(?:, ?([0-9.]*))?\)$/); if (match != null) { return new Color({ r: parseFloat(match[1]), g: parseFloat(match[2]), b: parseFloat(match[3]), a: parseFloat((_ref = match[4]) != null ? _ref : 1) }, match[4] != null ? "rgba" : "rgb"); } return null; }; Color.componentToHex = function(c) { var hex; hex = c.toString(16); if (hex.length === 1) { return "0" + hex; } else { return hex; } }; Color.prototype.toHex = function() { return "#" + Color.componentToHex(this.rgb.r) + Color.componentToHex(this.rgb.g) + Color.componentToHex(this.rgb.b); }; Color.prototype.toRgb = function() { return "rgb(" + this.rgb.r + ", " + this.rgb.g + ", " + this.rgb.b + ")"; }; Color.prototype.toRgba = function() { return "rgba(" + this.rgb.r + ", " + this.rgb.g + ", " + this.rgb.b + ", " + this.rgb.a + ")"; }; return Color; })(); InterpolableColor = (function() { function InterpolableColor(color) { this.color = color; this.format = __bind(this.format, this); this.interpolate = __bind(this.interpolate, this); } InterpolableColor.prototype.interpolate = function(endInterpolable, t) { var end, k, rgb, start, v, _i, _len, _ref; start = this.color; end = endInterpolable.color; rgb = {}; _ref = ['r', 'g', 'b']; for (_i = 0, _len = _ref.length; _i < _len; _i++) { k = _ref[_i]; v = Math.round((end.rgb[k] - start.rgb[k]) * t + start.rgb[k]); rgb[k] = Math.min(255, Math.max(0, v)); } k = "a"; v = roundf((end.rgb[k] - start.rgb[k]) * t + start.rgb[k], 5); rgb[k] = Math.min(1, Math.max(0, v)); return new InterpolableColor(new Color(rgb, end.format)); }; InterpolableColor.prototype.format = function() { if (this.color.format === "hex") { return this.color.toHex(); } else if (this.color.format === "rgb") { return this.color.toRgb(); } else if (this.color.format === "rgba") { return this.color.toRgba(); } }; InterpolableColor.create = function(value) { var color; if (typeof value !== "string") { return; } color = Color.fromHex(value) || Color.fromRgb(value); if (color != null) { return new InterpolableColor(color); } return null; }; return InterpolableColor; })(); DecomposedMatrix2D = (function() { function DecomposedMatrix2D(props) { this.props = props; this.applyRotateCenter = __bind(this.applyRotateCenter, this); this.format = __bind(this.format, this); this.interpolate = __bind(this.interpolate, this); } DecomposedMatrix2D.prototype.interpolate = function(endMatrix, t) { var i, k, newProps, _i, _j, _k, _l, _len, _len1, _ref, _ref1, _ref2; newProps = {}; _ref = ['translate', 'scale', 'rotate']; for (_i = 0, _len = _ref.length; _i < _len; _i++) { k = _ref[_i]; newProps[k] = []; for (i = _j = 0, _ref1 = this.props[k].length; 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) { newProps[k][i] = (endMatrix.props[k][i] - this.props[k][i]) * t + this.props[k][i]; } } for (i = _k = 1; _k <= 2; i = ++_k) { newProps['rotate'][i] = endMatrix.props['rotate'][i]; } _ref2 = ['skew']; for (_l = 0, _len1 = _ref2.length; _l < _len1; _l++) { k = _ref2[_l]; newProps[k] = (endMatrix.props[k] - this.props[k]) * t + this.props[k]; } return new DecomposedMatrix2D(newProps); }; DecomposedMatrix2D.prototype.format = function() { return "translate(" + (this.props.translate.join(',')) + ") rotate(" + (this.props.rotate.join(',')) + ") skewX(" + this.props.skew + ") scale(" + (this.props.scale.join(',')) + ")"; }; DecomposedMatrix2D.prototype.applyRotateCenter = function(rotateC) { var i, m, m2d, negativeTranslate, _i, _results; m = baseSVG.createSVGMatrix(); m = m.translate(rotateC[0], rotateC[1]); m = m.rotate(this.props.rotate[0]); m = m.translate(-rotateC[0], -rotateC[1]); m2d = new Matrix2D(m); negativeTranslate = m2d.decompose().props.translate; _results = []; for (i = _i = 0; _i <= 1; i = ++_i) { _results.push(this.props.translate[i] -= negativeTranslate[i]); } return _results; }; return DecomposedMatrix2D; })(); baseSVG = typeof document !== "undefined" && document !== null ? document.createElementNS("http://www.w3.org/2000/svg", "svg") : void 0; Matrix2D = (function() { function Matrix2D(m) { this.m = m; this.applyProperties = __bind(this.applyProperties, this); this.decompose = __bind(this.decompose, this); if (!this.m) { this.m = baseSVG.createSVGMatrix(); } } Matrix2D.prototype.decompose = function() { var kx, ky, kz, r0, r1; r0 = new Vector([this.m.a, this.m.b]); r1 = new Vector([this.m.c, this.m.d]); kx = r0.length(); kz = r0.dot(r1); r0 = r0.normalize(); ky = r1.combine(r0, 1, -kz).length(); return new DecomposedMatrix2D({ translate: [this.m.e, this.m.f], rotate: [Math.atan2(this.m.b, this.m.a) * 180 / Math.PI, this.rotateCX, this.rotateCY], scale: [kx, ky], skew: kz / ky * 180 / Math.PI }); }; Matrix2D.prototype.applyProperties = function(properties) { var hash, k, props, v, _i, _len, _ref, _ref1; hash = {}; for (_i = 0, _len = properties.length; _i < _len; _i++) { props = properties[_i]; hash[props[0]] = props[1]; } for (k in hash) { v = hash[k]; if (k === "translateX") { this.m = this.m.translate(v, 0); } else if (k === "translateY") { this.m = this.m.translate(0, v); } else if (k === "scaleX") { this.m = this.m.scale(v, 1); } else if (k === "scaleY") { this.m = this.m.scale(1, v); } else if (k === "rotateZ") { this.m = this.m.rotate(v); } else if (k === "skewX") { this.m = this.m.skewX(v); } else if (k === "skewY") { this.m = this.m.skewY(v); } } this.rotateCX = (_ref = hash.rotateCX) != null ? _ref : 0; return this.rotateCY = (_ref1 = hash.rotateCY) != null ? _ref1 : 0; }; return Matrix2D; })(); Vector = (function() { function Vector(els) { this.els = els; this.combine = __bind(this.combine, this); this.normalize = __bind(this.normalize, this); this.length = __bind(this.length, this); this.cross = __bind(this.cross, this); this.dot = __bind(this.dot, this); this.e = __bind(this.e, this); } Vector.prototype.e = function(i) { if (i < 1 || i > this.els.length) { return null; } else { return this.els[i - 1]; } }; Vector.prototype.dot = function(vector) { var V, n, product; V = vector.els || vector; product = 0; n = this.els.length; if (n !== V.length) { return null; } n += 1; while (--n) { product += this.els[n - 1] * V[n - 1]; } return product; }; Vector.prototype.cross = function(vector) { var A, B; B = vector.els || vector; if (this.els.length !== 3 || B.length !== 3) { return null; } A = this.els; return new Vector([(A[1] * B[2]) - (A[2] * B[1]), (A[2] * B[0]) - (A[0] * B[2]), (A[0] * B[1]) - (A[1] * B[0])]); }; Vector.prototype.length = function() { var a, e, _i, _len, _ref; a = 0; _ref = this.els; for (_i = 0, _len = _ref.length; _i < _len; _i++) { e = _ref[_i]; a += Math.pow(e, 2); } return Math.sqrt(a); }; Vector.prototype.normalize = function() { var e, i, length, newElements, _ref; length = this.length(); newElements = []; _ref = this.els; for (i in _ref) { e = _ref[i]; newElements[i] = e / length; } return new Vector(newElements); }; Vector.prototype.combine = function(b, ascl, bscl) { var i, result, _i, _ref; result = []; for (i = _i = 0, _ref = this.els.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { result[i] = (ascl * this.els[i]) + (bscl * b.els[i]); } return new Vector(result); }; return Vector; })(); DecomposedMatrix = (function() { function DecomposedMatrix() { this.toMatrix = __bind(this.toMatrix, this); this.format = __bind(this.format, this); this.interpolate = __bind(this.interpolate, this); } DecomposedMatrix.prototype.interpolate = function(decomposedB, t, only) { var angle, decomposed, decomposedA, i, invscale, invth, k, qa, qb, scale, th, _i, _j, _k, _l, _len, _ref, _ref1; if (only == null) { only = null; } decomposedA = this; decomposed = new DecomposedMatrix; _ref = ['translate', 'scale', 'skew', 'perspective']; for (_i = 0, _len = _ref.length; _i < _len; _i++) { k = _ref[_i]; decomposed[k] = []; for (i = _j = 0, _ref1 = decomposedA[k].length - 1; 0 <= _ref1 ? _j <= _ref1 : _j >= _ref1; i = 0 <= _ref1 ? ++_j : --_j) { if ((only == null) || only.indexOf(k) > -1 || only.indexOf("" + k + ['x', 'y', 'z'][i]) > -1) { decomposed[k][i] = (decomposedB[k][i] - decomposedA[k][i]) * t + decomposedA[k][i]; } else { decomposed[k][i] = decomposedA[k][i]; } } } if ((only == null) || only.indexOf('rotate') !== -1) { qa = decomposedA.quaternion; qb = decomposedB.quaternion; angle = qa[0] * qb[0] + qa[1] * qb[1] + qa[2] * qb[2] + qa[3] * qb[3]; if (angle < 0.0) { for (i = _k = 0; _k <= 3; i = ++_k) { qa[i] = -qa[i]; } angle = -angle; } if (angle + 1.0 > .05) { if (1.0 - angle >= .05) { th = Math.acos(angle); invth = 1.0 / Math.sin(th); scale = Math.sin(th * (1.0 - t)) * invth; invscale = Math.sin(th * t) * invth; } else { scale = 1.0 - t; invscale = t; } } else { qb[0] = -qa[1]; qb[1] = qa[0]; qb[2] = -qa[3]; qb[3] = qa[2]; scale = Math.sin(piDouble * (.5 - t)); invscale = Math.sin(piDouble * t); } decomposed.quaternion = []; for (i = _l = 0; _l <= 3; i = ++_l) { decomposed.quaternion[i] = qa[i] * scale + qb[i] * invscale; } } else { decomposed.quaternion = decomposedA.quaternion; } return decomposed; }; DecomposedMatrix.prototype.format = function() { return this.toMatrix().toString(); }; DecomposedMatrix.prototype.toMatrix = function() { var decomposedMatrix, i, j, match, matrix, quaternion, skew, temp, w, x, y, z, _i, _j, _k, _l; decomposedMatrix = this; matrix = Matrix.I(4); for (i = _i = 0; _i <= 3; i = ++_i) { matrix.els[i][3] = decomposedMatrix.perspective[i]; } quaternion = decomposedMatrix.quaternion; x = quaternion[0]; y = quaternion[1]; z = quaternion[2]; w = quaternion[3]; skew = decomposedMatrix.skew; match = [[1, 0], [2, 0], [2, 1]]; for (i = _j = 2; _j >= 0; i = --_j) { if (skew[i]) { temp = Matrix.I(4); temp.els[match[i][0]][match[i][1]] = skew[i]; matrix = matrix.multiply(temp); } } matrix = matrix.multiply(new Matrix([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w), 0], [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w), 0], [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y), 0], [0, 0, 0, 1]])); for (i = _k = 0; _k <= 2; i = ++_k) { for (j = _l = 0; _l <= 2; j = ++_l) { matrix.els[i][j] *= decomposedMatrix.scale[i]; } matrix.els[3][i] = decomposedMatrix.translate[i]; } return matrix; }; return DecomposedMatrix; })(); Matrix = (function() { function Matrix(els) { this.els = els; this.toString = __bind(this.toString, this); this.decompose = __bind(this.decompose, this); this.inverse = __bind(this.inverse, this); this.augment = __bind(this.augment, this); this.toRightTriangular = __bind(this.toRightTriangular, this); this.transpose = __bind(this.transpose, this); this.multiply = __bind(this.multiply, this); this.dup = __bind(this.dup, this); this.e = __bind(this.e, this); } Matrix.prototype.e = function(i, j) { if (i < 1 || i > this.els.length || j < 1 || j > this.els[0].length) { return null; } return this.els[i - 1][j - 1]; }; Matrix.prototype.dup = function() { return new Matrix(this.els); }; Matrix.prototype.multiply = function(matrix) { var M, c, cols, elements, i, j, ki, kj, nc, ni, nj, returnVector, sum; returnVector = matrix.modulus ? true : false; M = matrix.els || matrix; if (typeof M[0][0] === 'undefined') { M = new Matrix(M).els; } ni = this.els.length; ki = ni; kj = M[0].length; cols = this.els[0].length; elements = []; ni += 1; while (--ni) { i = ki - ni; elements[i] = []; nj = kj; nj += 1; while (--nj) { j = kj - nj; sum = 0; nc = cols; nc += 1; while (--nc) { c = cols - nc; sum += this.els[i][c] * M[c][j]; } elements[i][j] = sum; } } M = new Matrix(elements); if (returnVector) { return M.col(1); } else { return M; } }; Matrix.prototype.transpose = function() { var cols, elements, i, j, ni, nj, rows; rows = this.els.length; cols = this.els[0].length; elements = []; ni = cols; ni += 1; while (--ni) { i = cols - ni; elements[i] = []; nj = rows; nj += 1; while (--nj) { j = rows - nj; elements[i][j] = this.els[j][i]; } } return new Matrix(elements); }; Matrix.prototype.toRightTriangular = function() { var M, els, i, j, k, kp, multiplier, n, np, p, _i, _j, _ref, _ref1; M = this.dup(); n = this.els.length; k = n; kp = this.els[0].length; while (--n) { i = k - n; if (M.els[i][i] === 0) { for (j = _i = _ref = i + 1; _ref <= k ? _i < k : _i > k; j = _ref <= k ? ++_i : --_i) { if (M.els[j][i] !== 0) { els = []; np = kp; np += 1; while (--np) { p = kp - np; els.push(M.els[i][p] + M.els[j][p]); } M.els[i] = els; break; } } } if (M.els[i][i] !== 0) { for (j = _j = _ref1 = i + 1; _ref1 <= k ? _j < k : _j > k; j = _ref1 <= k ? ++_j : --_j) { multiplier = M.els[j][i] / M.els[i][i]; els = []; np = kp; np += 1; while (--np) { p = kp - np; els.push(p <= i ? 0 : M.els[j][p] - M.els[i][p] * multiplier); } M.els[j] = els; } } } return M; }; Matrix.prototype.augment = function(matrix) { var M, T, cols, i, j, ki, kj, ni, nj; M = matrix.els || matrix; if (typeof M[0][0] === 'undefined') { M = new Matrix(M).els; } T = this.dup(); cols = T.els[0].length; ni = T.els.length; ki = ni; kj = M[0].length; if (ni !== M.length) { return null; } ni += 1; while (--ni) { i = ki - ni; nj = kj; nj += 1; while (--nj) { j = kj - nj; T.els[i][cols + j] = M[i][j]; } } return T; }; Matrix.prototype.inverse = function() { var M, divisor, els, i, inverse_elements, j, ki, kp, new_element, ni, np, p, _i; ni = this.els.length; ki = ni; M = this.augment(Matrix.I(ni)).toRightTriangular(); kp = M.els[0].length; inverse_elements = []; ni += 1; while (--ni) { i = ni - 1; els = []; np = kp; inverse_elements[i] = []; divisor = M.els[i][i]; np += 1; while (--np) { p = kp - np; new_element = M.els[i][p] / divisor; els.push(new_element); if (p >= ki) { inverse_elements[i].push(new_element); } } M.els[i] = els; for (j = _i = 0; 0 <= i ? _i < i : _i > i; j = 0 <= i ? ++_i : --_i) { els = []; np = kp; np += 1; while (--np) { p = kp - np; els.push(M.els[j][p] - M.els[i][p] * M.els[j][i]); } M.els[j] = els; } } return new Matrix(inverse_elements); }; Matrix.I = function(n) { var els, i, j, k, nj; els = []; k = n; n += 1; while (--n) { i = k - n; els[i] = []; nj = k; nj += 1; while (--nj) { j = k - nj; els[i][j] = i === j ? 1 : 0; } } return new Matrix(els); }; Matrix.prototype.decompose = function() { var els, i, inversePerspectiveMatrix, j, k, matrix, pdum3, perspective, perspectiveMatrix, quaternion, result, rightHandSide, rotate, row, rowElement, s, scale, skew, t, translate, transposedInversePerspectiveMatrix, type, typeKey, v, w, x, y, z, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r; matrix = this; translate = []; scale = []; skew = []; quaternion = []; perspective = []; els = []; for (i = _i = 0; _i <= 3; i = ++_i) { els[i] = []; for (j = _j = 0; _j <= 3; j = ++_j) { els[i][j] = matrix.els[i][j]; } } if (els[3][3] === 0) { return false; } for (i = _k = 0; _k <= 3; i = ++_k) { for (j = _l = 0; _l <= 3; j = ++_l) { els[i][j] /= els[3][3]; } } perspectiveMatrix = matrix.dup(); for (i = _m = 0; _m <= 2; i = ++_m) { perspectiveMatrix.els[i][3] = 0; } perspectiveMatrix.els[3][3] = 1; if (els[0][3] !== 0 || els[1][3] !== 0 || els[2][3] !== 0) { rightHandSide = new Vector(els.slice(0, 4)[3]); inversePerspectiveMatrix = perspectiveMatrix.inverse(); transposedInversePerspectiveMatrix = inversePerspectiveMatrix.transpose(); perspective = transposedInversePerspectiveMatrix.multiply(rightHandSide).els; for (i = _n = 0; _n <= 2; i = ++_n) { els[i][3] = 0; } els[3][3] = 1; } else { perspective = [0, 0, 0, 1]; } for (i = _o = 0; _o <= 2; i = ++_o) { translate[i] = els[3][i]; els[3][i] = 0; } row = []; for (i = _p = 0; _p <= 2; i = ++_p) { row[i] = new Vector(els[i].slice(0, 3)); } scale[0] = row[0].length(); row[0] = row[0].normalize(); skew[0] = row[0].dot(row[1]); row[1] = row[1].combine(row[0], 1.0, -skew[0]); scale[1] = row[1].length(); row[1] = row[1].normalize(); skew[0] /= scale[1]; skew[1] = row[0].dot(row[2]); row[2] = row[2].combine(row[0], 1.0, -skew[1]); skew[2] = row[1].dot(row[2]); row[2] = row[2].combine(row[1], 1.0, -skew[2]); scale[2] = row[2].length(); row[2] = row[2].normalize(); skew[1] /= scale[2]; skew[2] /= scale[2]; pdum3 = row[1].cross(row[2]); if (row[0].dot(pdum3) < 0) { for (i = _q = 0; _q <= 2; i = ++_q) { scale[i] *= -1; for (j = _r = 0; _r <= 2; j = ++_r) { row[i].els[j] *= -1; } } } rowElement = function(index, elementIndex) { return row[index].els[elementIndex]; }; rotate = []; rotate[1] = Math.asin(-rowElement(0, 2)); if (Math.cos(rotate[1]) !== 0) { rotate[0] = Math.atan2(rowElement(1, 2), rowElement(2, 2)); rotate[2] = Math.atan2(rowElement(0, 1), rowElement(0, 0)); } else { rotate[0] = Math.atan2(-rowElement(2, 0), rowElement(1, 1)); rotate[1] = 0; } t = rowElement(0, 0) + rowElement(1, 1) + rowElement(2, 2) + 1.0; if (t > 1e-4) { s = 0.5 / Math.sqrt(t); w = 0.25 / s; x = (rowElement(2, 1) - rowElement(1, 2)) * s; y = (rowElement(0, 2) - rowElement(2, 0)) * s; z = (rowElement(1, 0) - rowElement(0, 1)) * s; } else if ((rowElement(0, 0) > rowElement(1, 1)) && (rowElement(0, 0) > rowElement(2, 2))) { s = Math.sqrt(1.0 + rowElement(0, 0) - rowElement(1, 1) - rowElement(2, 2)) * 2.0; x = 0.25 * s; y = (rowElement(0, 1) + rowElement(1, 0)) / s; z = (rowElement(0, 2) + rowElement(2, 0)) / s; w = (rowElement(2, 1) - rowElement(1, 2)) / s; } else if (rowElement(1, 1) > rowElement(2, 2)) { s = Math.sqrt(1.0 + rowElement(1, 1) - rowElement(0, 0) - rowElement(2, 2)) * 2.0; x = (rowElement(0, 1) + rowElement(1, 0)) / s; y = 0.25 * s; z = (rowElement(1, 2) + rowElement(2, 1)) / s; w = (rowElement(0, 2) - rowElement(2, 0)) / s; } else { s = Math.sqrt(1.0 + rowElement(2, 2) - rowElement(0, 0) - rowElement(1, 1)) * 2.0; x = (rowElement(0, 2) + rowElement(2, 0)) / s; y = (rowElement(1, 2) + rowElement(2, 1)) / s; z = 0.25 * s; w = (rowElement(1, 0) - rowElement(0, 1)) / s; } quaternion = [x, y, z, w]; result = new DecomposedMatrix; result.translate = translate; result.scale = scale; result.skew = skew; result.quaternion = quaternion; result.perspective = perspective; result.rotate = rotate; for (typeKey in result) { type = result[typeKey]; for (k in type) { v = type[k]; if (isNaN(v)) { type[k] = 0; } } } return result; }; Matrix.prototype.toString = function() { var i, j, str, _i, _j; str = 'matrix3d('; for (i = _i = 0; _i <= 3; i = ++_i) { for (j = _j = 0; _j <= 3; j = ++_j) { str += roundf(this.els[i][j], 10); if (!(i === 3 && j === 3)) { str += ','; } } } str += ')'; return str; }; Matrix.matrixForTransform = cacheFn(function(transform) { var matrixEl, result, style, _ref, _ref1, _ref2; matrixEl = document.createElement('div'); matrixEl.style.position = 'absolute'; matrixEl.style.visibility = 'hidden'; matrixEl.style[propertyWithPrefix("transform")] = transform; document.body.appendChild(matrixEl); style = window.getComputedStyle(matrixEl, null); result = (_ref = (_ref1 = style.transform) != null ? _ref1 : style[propertyWithPrefix("transform")]) != null ? _ref : (_ref2 = dynamics.tests) != null ? _ref2.matrixForTransform(transform) : void 0; document.body.removeChild(matrixEl); return result; }); Matrix.fromTransform = function(transform) { var digits, elements, i, match, matrixElements, _i; match = transform != null ? transform.match(/matrix3?d?\(([-0-9,e \.]*)\)/) : void 0; if (match) { digits = match[1].split(','); digits = digits.map(parseFloat); if (digits.length === 6) { elements = [digits[0], digits[1], 0, 0, digits[2], digits[3], 0, 0, 0, 0, 1, 0, digits[4], digits[5], 0, 1]; } else { elements = digits; } } else { elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; } matrixElements = []; for (i = _i = 0; _i <= 3; i = ++_i) { matrixElements.push(elements.slice(i * 4, i * 4 + 4)); } return new Matrix(matrixElements); }; return Matrix; })(); prefixFor = cacheFn(function(property) { var k, prefix, prop, propArray, propertyName, _i, _j, _len, _len1, _ref; if (document.body.style[property] !== void 0) { return ''; } propArray = property.split('-'); propertyName = ""; for (_i = 0, _len = propArray.length; _i < _len; _i++) { prop = propArray[_i]; propertyName += prop.substring(0, 1).toUpperCase() + prop.substring(1); } _ref = ["Webkit", "Moz", "ms"]; for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) { prefix = _ref[_j]; k = prefix + propertyName; if (document.body.style[k] !== void 0) { return prefix; } } return ''; }); propertyWithPrefix = cacheFn(function(property) { var prefix; prefix = prefixFor(property); if (prefix === 'Moz') { return "" + prefix + (property.substring(0, 1).toUpperCase() + property.substring(1)); } if (prefix !== '') { return "-" + (prefix.toLowerCase()) + "-" + (toDashed(property)); } return toDashed(property); }); rAF = typeof window !== "undefined" && window !== null ? window.requestAnimationFrame : void 0; animations = []; animationsTimeouts = []; slow = false; slowRatio = 1; if (typeof window !== "undefined" && window !== null) { window.addEventListener('keyup', function(e) { if (e.keyCode === 68 && e.shiftKey && e.ctrlKey) { return dynamics.toggleSlow(); } }); } if (rAF == null) { lastTime = 0; rAF = function(callback) { var currTime, id, timeToCall; currTime = Date.now(); timeToCall = Math.max(0, 16 - (currTime - lastTime)); id = window.setTimeout(function() { return callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; } runLoopRunning = false; runLoopPaused = false; startRunLoop = function() { if (!runLoopRunning) { runLoopRunning = true; return rAF(runLoopTick); } }; runLoopTick = function(t) { var animation, toRemoveAnimations, _i, _len; if (runLoopPaused) { rAF(runLoopTick); return; } toRemoveAnimations = []; for (_i = 0, _len = animations.length; _i < _len; _i++) { animation = animations[_i]; if (!animationTick(t, animation)) { toRemoveAnimations.push(animation); } } animations = animations.filter(function(animation) { return toRemoveAnimations.indexOf(animation) === -1; }); if (animations.length === 0) { return runLoopRunning = false; } else { return rAF(runLoopTick); } }; animationTick = function(t, animation) { var key, properties, property, tt, y, _base, _base1, _ref; if (animation.tStart == null) { animation.tStart = t; } tt = (t - animation.tStart) / animation.options.duration; y = animation.curve(tt); properties = {}; if (tt >= 1) { if (animation.curve.initialForce) { properties = animation.properties.start; } else { properties = animation.properties.end; } } else { _ref = animation.properties.start; for (key in _ref) { property = _ref[key]; properties[key] = interpolate(property, animation.properties.end[key], y); } } applyFrame(animation.el, properties); if (typeof (_base = animation.options).change === "function") { _base.change(animation.el); } if (tt >= 1) { if (typeof (_base1 = animation.options).complete === "function") { _base1.complete(animation.el); } } return tt < 1; }; interpolate = function(start, end, y) { if ((start != null) && (start.interpolate != null)) { return start.interpolate(end, y); } return null; }; startAnimation = function(el, properties, options, timeoutId) { var endProperties, isSVG, k, matrix, startProperties, transforms, v, _base; if (timeoutId != null) { animationsTimeouts = animationsTimeouts.filter(function(timeout) { return timeout.id !== timeoutId; }); } dynamics.stop(el, { timeout: false }); if (!options.animated) { dynamics.css(el, properties); if (typeof options.complete === "function") { options.complete(this); } return; } properties = parseProperties(properties); startProperties = getCurrentProperties(el, Object.keys(properties)); endProperties = {}; transforms = []; for (k in properties) { v = properties[k]; if ((el.style != null) && transformProperties.contains(k)) { transforms.push([k, v]); } else { endProperties[k] = createInterpolable(v); if (endProperties[k] instanceof InterpolableWithUnit && (el.style != null)) { endProperties[k].prefix = ''; if ((_base = endProperties[k]).suffix == null) { _base.suffix = unitForProperty(k, 0); } } } } if (transforms.length > 0) { isSVG = isSVGElement(el); if (isSVG) { matrix = new Matrix2D(); matrix.applyProperties(transforms); } else { v = (transforms.map(function(transform) { return transformValueForProperty(transform[0], transform[1]); })).join(" "); matrix = Matrix.fromTransform(Matrix.matrixForTransform(v)); } endProperties['transform'] = matrix.decompose(); if (isSVG) { startProperties.transform.applyRotateCenter([endProperties.transform.props.rotate[1], endProperties.transform.props.rotate[2]]); } } animations.push({ el: el, properties: { start: startProperties, end: endProperties }, options: options, curve: options.type.call(options.type, options) }); return startRunLoop(); }; timeouts = []; timeoutLastId = 0; setRealTimeout = function(timeout) { if (!isDocumentVisible()) { return; } return timeout.realTimeoutId = setTimeout(function() { timeout.fn(); return cancelTimeout(timeout.id); }, timeout.delay); }; addTimeout = function(fn, delay) { var timeout; timeoutLastId += 1; timeout = { id: timeoutLastId, tStart: Date.now(), fn: fn, delay: delay, originalDelay: delay }; setRealTimeout(timeout); timeouts.push(timeout); return timeoutLastId; }; cancelTimeout = function(id) { return timeouts = timeouts.filter(function(timeout) { if (timeout.id === id) { clearTimeout(timeout.realTimeoutId); } return timeout.id !== id; }); }; leftDelayForTimeout = function(time, timeout) { var consumedDelay; if (time != null) { consumedDelay = time - timeout.tStart; return timeout.originalDelay - consumedDelay; } else { return timeout.originalDelay; } }; if (typeof window !== "undefined" && window !== null) { window.addEventListener('unload', function() {}); } timeBeforeVisibilityChange = null; observeVisibilityChange(function(visible) { var animation, difference, timeout, _i, _j, _k, _len, _len1, _len2, _results; runLoopPaused = !visible; if (!visible) { timeBeforeVisibilityChange = Date.now(); _results = []; for (_i = 0, _len = timeouts.length; _i < _len; _i++) { timeout = timeouts[_i]; _results.push(clearTimeout(timeout.realTimeoutId)); } return _results; } else { if (runLoopRunning) { difference = Date.now() - timeBeforeVisibilityChange; for (_j = 0, _len1 = animations.length; _j < _len1; _j++) { animation = animations[_j]; if (animation.tStart != null) { animation.tStart += difference; } } } for (_k = 0, _len2 = timeouts.length; _k < _len2; _k++) { timeout = timeouts[_k]; timeout.delay = leftDelayForTimeout(timeBeforeVisibilityChange, timeout); setRealTimeout(timeout); } return timeBeforeVisibilityChange = null; } }); dynamics = {}; dynamics.linear = function() { return function(t) { return t; }; }; dynamics.spring = function(options) { var A1, A2, decal, frequency, friction, s; if (options == null) { options = {}; } applyDefaults(options, arguments.callee.defaults); frequency = Math.max(1, options.frequency / 20); friction = Math.pow(20, options.friction / 100); s = options.anticipationSize / 1000; decal = Math.max(0, s); A1 = function(t) { var M, a, b, x0, x1; M = 0.8; x0 = s / (1 - s); x1 = 0; b = (x0 - (M * x1)) / (x0 - x1); a = (M - b) / x0; return (a * t * options.anticipationStrength / 100) + b; }; A2 = function(t) { return Math.pow(friction / 10, -t) * (1 - t); }; return function(t) { var A, At, a, angle, b, frictionT, y0, yS; frictionT = (t / (1 - s)) - (s / (1 - s)); if (t < s) { yS = (s / (1 - s)) - (s / (1 - s)); y0 = (0 / (1 - s)) - (s / (1 - s)); b = Math.acos(1 / A1(yS)); a = (Math.acos(1 / A1(y0)) - b) / (frequency * (-s)); A = A1; } else { A = A2; b = 0; a = 1; } At = A(frictionT); angle = frequency * (t - s) * a + b; return 1 - (At * Math.cos(angle)); }; }; dynamics.bounce = function(options) { var A, fn, frequency, friction; if (options == null) { options = {}; } applyDefaults(options, arguments.callee.defaults); frequency = Math.max(1, options.frequency / 20); friction = Math.pow(20, options.friction / 100); A = function(t) { return Math.pow(friction / 10, -t) * (1 - t); }; fn = function(t) { var At, a, angle, b; b = -3.14 / 2; a = 1; At = A(t); angle = frequency * t * a + b; return At * Math.cos(angle); }; fn.initialForce = true; return fn; }; dynamics.gravity = function(options) { var L, bounciness, curves, elasticity, fn, getPointInCurve, gravity; if (options == null) { options = {}; } applyDefaults(options, arguments.callee.defaults); bounciness = Math.min(options.bounciness / 1250, 0.8); elasticity = options.elasticity / 1000; gravity = 100; curves = []; L = (function() { var b, curve; b = Math.sqrt(2 / gravity); curve = { a: -b, b: b, H: 1 }; if (options.initialForce) { curve.a = 0; curve.b = curve.b * 2; } while (curve.H > 0.001) { L = curve.b - curve.a; curve = { a: curve.b, b: curve.b + L * bounciness, H: curve.H * bounciness * bounciness }; } return curve.b; })(); getPointInCurve = function(a, b, H, t) { var c, t2; L = b - a; t2 = (2 / L) * t - 1 - (a * 2 / L); c = t2 * t2 * H - H + 1; if (options.initialForce) { c = 1 - c; } return c; }; (function() { var L2, b, curve, _results; b = Math.sqrt(2 / (gravity * L * L)); curve = { a: -b, b: b, H: 1 }; if (options.initialForce) { curve.a = 0; curve.b = curve.b * 2; } curves.push(curve); L2 = L; _results = []; while (curve.b < 1 && curve.H > 0.001) { L2 = curve.b - curve.a; curve = { a: curve.b, b: curve.b + L2 * bounciness, H: curve.H * elasticity }; _results.push(curves.push(curve)); } return _results; })(); fn = function(t) { var curve, i, v; i = 0; curve = curves[i]; while (!(t >= curve.a && t <= curve.b)) { i += 1; curve = curves[i]; if (!curve) { break; } } if (!curve) { v = options.initialForce ? 0 : 1; } else { v = getPointInCurve(curve.a, curve.b, curve.H, t); } return v; }; fn.initialForce = options.initialForce; return fn; }; dynamics.forceWithGravity = function(options) { if (options == null) { options = {}; } applyDefaults(options, arguments.callee.defaults); options.initialForce = true; return dynamics.gravity(options); }; dynamics.bezier = (function() { var Bezier, Bezier_, yForX; Bezier_ = function(t, p0, p1, p2, p3) { return (Math.pow(1 - t, 3) * p0) + (3 * Math.pow(1 - t, 2) * t * p1) + (3 * (1 - t) * Math.pow(t, 2) * p2) + Math.pow(t, 3) * p3; }; Bezier = function(t, p0, p1, p2, p3) { return { x: Bezier_(t, p0.x, p1.x, p2.x, p3.x), y: Bezier_(t, p0.y, p1.y, p2.y, p3.y) }; }; yForX = function(xTarget, Bs, returnsToSelf) { var B, aB, i, lower, percent, upper, x, xTolerance, _i, _len; B = null; for (_i = 0, _len = Bs.length; _i < _len; _i++) { aB = Bs[_i]; if (xTarget >= aB(0).x && xTarget <= aB(1).x) { B = aB; } if (B !== null) { break; } } if (!B) { if (returnsToSelf) { return 0; } else { return 1; } } xTolerance = 0.0001; lower = 0; upper = 1; percent = (upper + lower) / 2; x = B(percent).x; i = 0; while (Math.abs(xTarget - x) > xTolerance && i < 100) { if (xTarget > x) { lower = percent; } else { upper = percent; } percent = (upper + lower) / 2; x = B(percent).x; i += 1; } return B(percent).y; }; return function(options) { var Bs, points, returnsToSelf; if (options == null) { options = {}; } points = options.points; returnsToSelf = false; Bs = (function() { var i, k, _fn; Bs = []; _fn = function(pointA, pointB) { var B2; B2 = function(t) { return Bezier(t, pointA, pointA.cp[pointA.cp.length - 1], pointB.cp[0], pointB); }; return Bs.push(B2); }; for (i in points) { k = parseInt(i); if (k >= points.length - 1) { break; } _fn(points[k], points[k + 1]); } return Bs; })(); return function(t) { if (t === 0) { return 0; } else if (t === 1) { return 1; } else { return yForX(t, Bs, returnsToSelf); } }; }; })(); dynamics.easeInOut = function(options) { var friction, _ref; if (options == null) { options = {}; } friction = (_ref = options.friction) != null ? _ref : arguments.callee.defaults.friction; return dynamics.bezier({ points: [ { x: 0, y: 0, cp: [ { x: 0.92 - (friction / 1000), y: 0 } ] }, { x: 1, y: 1, cp: [ { x: 0.08 + (friction / 1000), y: 1 } ] } ] }); }; dynamics.easeIn = function(options) { var friction, _ref; if (options == null) { options = {}; } friction = (_ref = options.friction) != null ? _ref : arguments.callee.defaults.friction; return dynamics.bezier({ points: [ { x: 0, y: 0, cp: [ { x: 0.92 - (friction / 1000), y: 0 } ] }, { x: 1, y: 1, cp: [ { x: 1, y: 1 } ] } ] }); }; dynamics.easeOut = function(options) { var friction, _ref; if (options == null) { options = {}; } friction = (_ref = options.friction) != null ? _ref : arguments.callee.defaults.friction; return dynamics.bezier({ points: [ { x: 0, y: 0, cp: [ { x: 0, y: 0 } ] }, { x: 1, y: 1, cp: [ { x: 0.08 + (friction / 1000), y: 1 } ] } ] }); }; dynamics.spring.defaults = { frequency: 300, friction: 200, anticipationSize: 0, anticipationStrength: 0 }; dynamics.bounce.defaults = { frequency: 300, friction: 200 }; dynamics.forceWithGravity.defaults = dynamics.gravity.defaults = { bounciness: 400, elasticity: 200 }; dynamics.easeInOut.defaults = dynamics.easeIn.defaults = dynamics.easeOut.defaults = { friction: 500 }; dynamics.css = makeArrayFn(function(el, properties) { return applyProperties(el, properties, true); }); dynamics.animate = makeArrayFn(function(el, properties, options) { var id; if (options == null) { options = {}; } options = clone(options); applyDefaults(options, { type: dynamics.easeInOut, duration: 1000, delay: 0, animated: true }); options.duration = Math.max(0, options.duration * slowRatio); options.delay = Math.max(0, options.delay); if (options.delay === 0) { return startAnimation(el, properties, options); } else { id = dynamics.setTimeout(function() { return startAnimation(el, properties, options, id); }, options.delay); return animationsTimeouts.push({ id: id, el: el }); } }); dynamics.stop = makeArrayFn(function(el, options) { if (options == null) { options = {}; } if (options.timeout == null) { options.timeout = true; } if (options.timeout) { animationsTimeouts = animationsTimeouts.filter(function(timeout) { if (timeout.el === el && ((options.filter == null) || options.filter(timeout))) { dynamics.clearTimeout(timeout.id); return false; } return true; }); } return animations = animations.filter(function(animation) { return animation.el !== el; }); }); dynamics.setTimeout = function(fn, delay) { return addTimeout(fn, delay * slowRatio); }; dynamics.clearTimeout = function(id) { return cancelTimeout(id); }; dynamics.toggleSlow = function() { slow = !slow; if (slow) { slowRatio = 3; } else { slowRatio = 1; } return typeof console !== "undefined" && console !== null ? typeof console.log === "function" ? console.log("dynamics.js: slow animations " + (slow ? "enabled" : "disabled")) : void 0 : void 0; }; if (typeof module === "object" && typeof module.exports === "object") { module.exports = dynamics; } else if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return dynamics; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { window.dynamics = dynamics; } }).call(this); /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { (function (global, factory) { true ? factory(exports, __webpack_require__(4)) : typeof define === 'function' && define.amd ? define(['exports', 'd3-color'], factory) : (factory((global.d3_interpolate = global.d3_interpolate || {}),global.d3_color)); }(this, function (exports,d3Color) { 'use strict'; function constant(x) { return function() { return x; }; } function linear(a, d) { return function(t) { return a + t * d; }; } function exponential(a, b, y) { return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) { return Math.pow(a + t * b, y); }; } function interpolateHue(a, b) { var d = b - a; return d ? linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : constant(isNaN(a) ? b : a); } function gamma(y) { return (y = +y) === 1 ? nogamma : function(a, b) { return b - a ? exponential(a, b, y) : constant(isNaN(a) ? b : a); }; } function nogamma(a, b) { var d = b - a; return d ? linear(a, d) : constant(isNaN(a) ? b : a); } var rgb$1 = (function gamma$$(y) { var interpolateColor = gamma(y); function interpolateRgb(start, end) { var r = interpolateColor((start = d3Color.rgb(start)).r, (end = d3Color.rgb(end)).r), g = interpolateColor(start.g, end.g), b = interpolateColor(start.b, end.b), opacity = interpolateColor(start.opacity, end.opacity); return function(t) { start.r = r(t); start.g = g(t); start.b = b(t); start.opacity = opacity(t); return start + ""; }; } interpolateRgb.gamma = gamma$$; return interpolateRgb; })(1); // TODO sparse arrays? function array(a, b) { var x = [], c = [], na = a ? a.length : 0, nb = b ? b.length : 0, n0 = Math.min(na, nb), i; for (i = 0; i < n0; ++i) x.push(value(a[i], b[i])); for (; i < na; ++i) c[i] = a[i]; for (; i < nb; ++i) c[i] = b[i]; return function(t) { for (i = 0; i < n0; ++i) c[i] = x[i](t); return c; }; } function number(a, b) { return a = +a, b -= a, function(t) { return a + b * t; }; } function object(a, b) { var i = {}, c = {}, k; if (a === null || typeof a !== "object") a = {}; if (b === null || typeof b !== "object") b = {}; for (k in a) { if (k in b) { i[k] = value(a[k], b[k]); } else { c[k] = a[k]; } } for (k in b) { if (!(k in a)) { c[k] = b[k]; } } return function(t) { for (k in i) c[k] = i[k](t); return c; }; } var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g; var reB = new RegExp(reA.source, "g"); function zero(b) { return function() { return b; }; } function one(b) { return function(t) { return b(t) + ""; }; } function string(a, b) { var bi = reA.lastIndex = reB.lastIndex = 0, // scan index for next number in b am, // current match in a bm, // current match in b bs, // string preceding current number in b, if any i = -1, // index in s s = [], // string constants and placeholders q = []; // number interpolators // Coerce inputs to strings. a = a + "", b = b + ""; // Interpolate pairs of numbers in a & b. while ((am = reA.exec(a)) && (bm = reB.exec(b))) { if ((bs = bm.index) > bi) { // a string precedes the next number in b bs = b.slice(bi, bs); if (s[i]) s[i] += bs; // coalesce with previous string else s[++i] = bs; } if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match if (s[i]) s[i] += bm; // coalesce with previous string else s[++i] = bm; } else { // interpolate non-matching numbers s[++i] = null; q.push({i: i, x: number(am, bm)}); } bi = reB.lastIndex; } // Add remains of b. if (bi < b.length) { bs = b.slice(bi); if (s[i]) s[i] += bs; // coalesce with previous string else s[++i] = bs; } // Special optimization for only a single match. // Otherwise, interpolate each of the numbers and rejoin the string. return s.length < 2 ? (q[0] ? one(q[0].x) : zero(b)) : (b = q.length, function(t) { for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t); return s.join(""); }); } var values = [ function(a, b) { var t = typeof b, c; return (t === "string" ? ((c = d3Color.color(b)) ? (b = c, rgb$1) : string) : b instanceof d3Color.color ? rgb$1 : Array.isArray(b) ? array : t === "object" && isNaN(b) ? object : number)(a, b); } ]; function value(a, b) { var i = values.length, f; while (--i >= 0 && !(f = values[i](a, b))); return f; } function round(a, b) { return a = +a, b -= a, function(t) { return Math.round(a + b * t); }; } var rad2deg = 180 / Math.PI; var identity = { translateX: 0, translateY: 0, rotate: 0, skewX: 0, scaleX: 1, scaleY: 1 }; function decompose(a, b, c, d, e, f) { if (a * d === b * c) return null; var scaleX = Math.sqrt(a * a + b * b); a /= scaleX, b /= scaleX; var skewX = a * c + b * d; c -= a * skewX, d -= b * skewX; var scaleY = Math.sqrt(c * c + d * d); c /= scaleY, d /= scaleY, skewX /= scaleY; if (a * d < b * c) a = -a, b = -b, skewX = -skewX, scaleX = -scaleX; return { translateX: e, translateY: f, rotate: Math.atan2(b, a) * rad2deg, skewX: Math.atan(skewX) * rad2deg, scaleX: scaleX, scaleY: scaleY }; } var cssNode; var cssRoot; var cssView; var svgNode; function parseCss(value) { if (value === "none") return identity; if (!cssNode) cssNode = document.createElement("DIV"), cssRoot = document.documentElement, cssView = document.defaultView; cssNode.style.transform = value; cssRoot.appendChild(cssNode); value = cssView.getComputedStyle(cssNode, null).getPropertyValue("transform"); cssRoot.removeChild(cssNode); var m = value.slice(7, -1).split(","); return decompose(+m[0], +m[1], +m[2], +m[3], +m[4], +m[5]); } function parseSvg(value) { if (!svgNode) svgNode = document.createElementNS("http://www.w3.org/2000/svg", "g"); svgNode.setAttribute("transform", value == null ? "" : value); var m = svgNode.transform.baseVal.consolidate().matrix; return decompose(m.a, m.b, m.c, m.d, m.e, m.f); } function interpolateTransform(parse, pxComma, pxParen, degParen) { function pop(s) { return s.length ? s.pop() + " " : ""; } function translate(xa, ya, xb, yb, s, q) { if (xa !== xb || ya !== yb) { var i = s.push("translate(", null, pxComma, null, pxParen); q.push({i: i - 4, x: number(xa, xb)}, {i: i - 2, x: number(ya, yb)}); } else if (xb || yb) { s.push("translate(" + xb + pxComma + yb + pxParen); } } function rotate(a, b, s, q) { if (a !== b) { if (a - b > 180) b += 360; else if (b - a > 180) a += 360; // shortest path q.push({i: s.push(pop(s) + "rotate(", null, degParen) - 2, x: number(a, b)}); } else if (b) { s.push(pop(s) + "rotate(" + b + degParen); } } function skewX(a, b, s, q) { if (a !== b) { q.push({i: s.push(pop(s) + "skewX(", null, degParen) - 2, x: number(a, b)}); } else if (b) { s.push(pop(s) + "skewX(" + b + degParen); } } function scale(xa, ya, xb, yb, s, q) { if (xa !== xb || ya !== yb) { var i = s.push(pop(s) + "scale(", null, ",", null, ")"); q.push({i: i - 4, x: number(xa, xb)}, {i: i - 2, x: number(ya, yb)}); } else if (xb !== 1 || yb !== 1) { s.push(pop(s) + "scale(" + xb + "," + yb + ")"); } } return function(a, b) { var s = [], // string constants and placeholders q = []; // number interpolators a = parse(a), b = parse(b); translate(a.translateX, a.translateY, b.translateX, b.translateY, s, q); rotate(a.rotate, b.rotate, s, q); skewX(a.skewX, b.skewX, s, q); scale(a.scaleX, a.scaleY, b.scaleX, b.scaleY, s, q); a = b = null; // gc return function(t) { var i = -1, n = q.length, o; while (++i < n) s[(o = q[i]).i] = o.x(t); return s.join(""); }; }; } var interpolateTransformCss = interpolateTransform(parseCss, "px, ", "px)", "deg)"); var interpolateTransformSvg = interpolateTransform(parseSvg, ", ", ")", ")"); var rho = Math.SQRT2; var rho2 = 2; var rho4 = 4; var epsilon2 = 1e-12; function cosh(x) { return ((x = Math.exp(x)) + 1 / x) / 2; } function sinh(x) { return ((x = Math.exp(x)) - 1 / x) / 2; } function tanh(x) { return ((x = Math.exp(2 * x)) - 1) / (x + 1); } // p0 = [ux0, uy0, w0] // p1 = [ux1, uy1, w1] function zoom(p0, p1) { var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S; // Special case for u0 ≅ u1. if (d2 < epsilon2) { S = Math.log(w1 / w0) / rho; i = function(t) { return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(rho * t * S) ]; } } // General case. else { var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + rho4 * d2) / (2 * w0 * rho2 * d1), b1 = (w1 * w1 - w0 * w0 - rho4 * d2) / (2 * w1 * rho2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1); S = (r1 - r0) / rho; i = function(t) { var s = t * S, coshr0 = cosh(r0), u = w0 / (rho2 * d1) * (coshr0 * tanh(rho * s + r0) - sinh(r0)); return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / cosh(rho * s + r0) ]; } } i.duration = S * 1000; return i; } function interpolateHsl(start, end) { var h = interpolateHue((start = d3Color.hsl(start)).h, (end = d3Color.hsl(end)).h), s = nogamma(start.s, end.s), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); return function(t) { start.h = h(t); start.s = s(t); start.l = l(t); start.opacity = opacity(t); return start + ""; }; } function interpolateHslLong(start, end) { var h = nogamma((start = d3Color.hsl(start)).h, (end = d3Color.hsl(end)).h), s = nogamma(start.s, end.s), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); return function(t) { start.h = h(t); start.s = s(t); start.l = l(t); start.opacity = opacity(t); return start + ""; }; } function interpolateLab(start, end) { var l = nogamma((start = d3Color.lab(start)).l, (end = d3Color.lab(end)).l), a = nogamma(start.a, end.a), b = nogamma(start.b, end.b), opacity = nogamma(start.opacity, end.opacity); return function(t) { start.l = l(t); start.a = a(t); start.b = b(t); start.opacity = opacity(t); return start + ""; }; } function interpolateHcl(start, end) { var h = interpolateHue((start = d3Color.hcl(start)).h, (end = d3Color.hcl(end)).h), c = nogamma(start.c, end.c), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); return function(t) { start.h = h(t); start.c = c(t); start.l = l(t); start.opacity = opacity(t); return start + ""; }; } function interpolateHclLong(start, end) { var h = nogamma((start = d3Color.hcl(start)).h, (end = d3Color.hcl(end)).h), c = nogamma(start.c, end.c), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); return function(t) { start.h = h(t); start.c = c(t); start.l = l(t); start.opacity = opacity(t); return start + ""; }; } var cubehelix$1 = (function gamma(y) { y = +y; function interpolateCubehelix(start, end) { var h = interpolateHue((start = d3Color.cubehelix(start)).h, (end = d3Color.cubehelix(end)).h), s = nogamma(start.s, end.s), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); return function(t) { start.h = h(t); start.s = s(t); start.l = l(Math.pow(t, y)); start.opacity = opacity(t); return start + ""; }; } interpolateCubehelix.gamma = gamma; return interpolateCubehelix; })(1); var cubehelixLong = (function gamma(y) { y = +y; function interpolateCubehelixLong(start, end) { var h = nogamma((start = d3Color.cubehelix(start)).h, (end = d3Color.cubehelix(end)).h), s = nogamma(start.s, end.s), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); return function(t) { start.h = h(t); start.s = s(t); start.l = l(Math.pow(t, y)); start.opacity = opacity(t); return start + ""; }; } interpolateCubehelixLong.gamma = gamma; return interpolateCubehelixLong; })(1); var version = "0.6.0"; exports.version = version; exports.interpolate = value; exports.interpolators = values; exports.interpolateArray = array; exports.interpolateNumber = number; exports.interpolateObject = object; exports.interpolateRound = round; exports.interpolateString = string; exports.interpolateTransformCss = interpolateTransformCss; exports.interpolateTransformSvg = interpolateTransformSvg; exports.interpolateZoom = zoom; exports.interpolateRgb = rgb$1; exports.interpolateHsl = interpolateHsl; exports.interpolateHslLong = interpolateHslLong; exports.interpolateLab = interpolateLab; exports.interpolateHcl = interpolateHcl; exports.interpolateHclLong = interpolateHclLong; exports.interpolateCubehelix = cubehelix$1; exports.interpolateCubehelixLong = cubehelixLong; })); /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { (function (global, factory) { true ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.d3_color = global.d3_color || {}))); }(this, function (exports) { 'use strict'; function define(constructor, factory, prototype) { constructor.prototype = factory.prototype = prototype; prototype.constructor = constructor; } function extend(parent, definition) { var prototype = Object.create(parent.prototype); for (var key in definition) prototype[key] = definition[key]; return prototype; } function Color() {} var darker = 0.7; var brighter = 1 / darker; var reHex3 = /^#([0-9a-f]{3})$/; var reHex6 = /^#([0-9a-f]{6})$/; var reRgbInteger = /^rgb\(\s*([-+]?\d+)\s*,\s*([-+]?\d+)\s*,\s*([-+]?\d+)\s*\)$/; var reRgbPercent = /^rgb\(\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*\)$/; var reRgbaInteger = /^rgba\(\s*([-+]?\d+)\s*,\s*([-+]?\d+)\s*,\s*([-+]?\d+)\s*,\s*([-+]?\d+(?:\.\d+)?)\s*\)$/; var reRgbaPercent = /^rgba\(\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)\s*\)$/; var reHslPercent = /^hsl\(\s*([-+]?\d+(?:\.\d+)?)\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*\)$/; var reHslaPercent = /^hsla\(\s*([-+]?\d+(?:\.\d+)?)\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)\s*\)$/; var named = { aliceblue: 0xf0f8ff, antiquewhite: 0xfaebd7, aqua: 0x00ffff, aquamarine: 0x7fffd4, azure: 0xf0ffff, beige: 0xf5f5dc, bisque: 0xffe4c4, black: 0x000000, blanchedalmond: 0xffebcd, blue: 0x0000ff, blueviolet: 0x8a2be2, brown: 0xa52a2a, burlywood: 0xdeb887, cadetblue: 0x5f9ea0, chartreuse: 0x7fff00, chocolate: 0xd2691e, coral: 0xff7f50, cornflowerblue: 0x6495ed, cornsilk: 0xfff8dc, crimson: 0xdc143c, cyan: 0x00ffff, darkblue: 0x00008b, darkcyan: 0x008b8b, darkgoldenrod: 0xb8860b, darkgray: 0xa9a9a9, darkgreen: 0x006400, darkgrey: 0xa9a9a9, darkkhaki: 0xbdb76b, darkmagenta: 0x8b008b, darkolivegreen: 0x556b2f, darkorange: 0xff8c00, darkorchid: 0x9932cc, darkred: 0x8b0000, darksalmon: 0xe9967a, darkseagreen: 0x8fbc8f, darkslateblue: 0x483d8b, darkslategray: 0x2f4f4f, darkslategrey: 0x2f4f4f, darkturquoise: 0x00ced1, darkviolet: 0x9400d3, deeppink: 0xff1493, deepskyblue: 0x00bfff, dimgray: 0x696969, dimgrey: 0x696969, dodgerblue: 0x1e90ff, firebrick: 0xb22222, floralwhite: 0xfffaf0, forestgreen: 0x228b22, fuchsia: 0xff00ff, gainsboro: 0xdcdcdc, ghostwhite: 0xf8f8ff, gold: 0xffd700, goldenrod: 0xdaa520, gray: 0x808080, green: 0x008000, greenyellow: 0xadff2f, grey: 0x808080, honeydew: 0xf0fff0, hotpink: 0xff69b4, indianred: 0xcd5c5c, indigo: 0x4b0082, ivory: 0xfffff0, khaki: 0xf0e68c, lavender: 0xe6e6fa, lavenderblush: 0xfff0f5, lawngreen: 0x7cfc00, lemonchiffon: 0xfffacd, lightblue: 0xadd8e6, lightcoral: 0xf08080, lightcyan: 0xe0ffff, lightgoldenrodyellow: 0xfafad2, lightgray: 0xd3d3d3, lightgreen: 0x90ee90, lightgrey: 0xd3d3d3, lightpink: 0xffb6c1, lightsalmon: 0xffa07a, lightseagreen: 0x20b2aa, lightskyblue: 0x87cefa, lightslategray: 0x778899, lightslategrey: 0x778899, lightsteelblue: 0xb0c4de, lightyellow: 0xffffe0, lime: 0x00ff00, limegreen: 0x32cd32, linen: 0xfaf0e6, magenta: 0xff00ff, maroon: 0x800000, mediumaquamarine: 0x66cdaa, mediumblue: 0x0000cd, mediumorchid: 0xba55d3, mediumpurple: 0x9370db, mediumseagreen: 0x3cb371, mediumslateblue: 0x7b68ee, mediumspringgreen: 0x00fa9a, mediumturquoise: 0x48d1cc, mediumvioletred: 0xc71585, midnightblue: 0x191970, mintcream: 0xf5fffa, mistyrose: 0xffe4e1, moccasin: 0xffe4b5, navajowhite: 0xffdead, navy: 0x000080, oldlace: 0xfdf5e6, olive: 0x808000, olivedrab: 0x6b8e23, orange: 0xffa500, orangered: 0xff4500, orchid: 0xda70d6, palegoldenrod: 0xeee8aa, palegreen: 0x98fb98, paleturquoise: 0xafeeee, palevioletred: 0xdb7093, papayawhip: 0xffefd5, peachpuff: 0xffdab9, peru: 0xcd853f, pink: 0xffc0cb, plum: 0xdda0dd, powderblue: 0xb0e0e6, purple: 0x800080, rebeccapurple: 0x663399, red: 0xff0000, rosybrown: 0xbc8f8f, royalblue: 0x4169e1, saddlebrown: 0x8b4513, salmon: 0xfa8072, sandybrown: 0xf4a460, seagreen: 0x2e8b57, seashell: 0xfff5ee, sienna: 0xa0522d, silver: 0xc0c0c0, skyblue: 0x87ceeb, slateblue: 0x6a5acd, slategray: 0x708090, slategrey: 0x708090, snow: 0xfffafa, springgreen: 0x00ff7f, steelblue: 0x4682b4, tan: 0xd2b48c, teal: 0x008080, thistle: 0xd8bfd8, tomato: 0xff6347, turquoise: 0x40e0d0, violet: 0xee82ee, wheat: 0xf5deb3, white: 0xffffff, whitesmoke: 0xf5f5f5, yellow: 0xffff00, yellowgreen: 0x9acd32 }; define(Color, color, { displayable: function() { return this.rgb().displayable(); }, toString: function() { return this.rgb() + ""; } }); function color(format) { var m; format = (format + "").trim().toLowerCase(); return (m = reHex3.exec(format)) ? (m = parseInt(m[1], 16), new Rgb((m >> 8 & 0xf) | (m >> 4 & 0x0f0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1)) // #f00 : (m = reHex6.exec(format)) ? rgbn(parseInt(m[1], 16)) // #ff0000 : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0) : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%) : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1) : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1) : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%) : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1) : named.hasOwnProperty(format) ? rgbn(named[format]) : format === "transparent" ? new Rgb(NaN, NaN, NaN, 0) : null; } function rgbn(n) { return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1); } function rgba(r, g, b, a) { if (a <= 0) r = g = b = NaN; return new Rgb(r, g, b, a); } function rgbConvert(o) { if (!(o instanceof Color)) o = color(o); if (!o) return new Rgb; o = o.rgb(); return new Rgb(o.r, o.g, o.b, o.opacity); } function rgb(r, g, b, opacity) { return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity); } function Rgb(r, g, b, opacity) { this.r = +r; this.g = +g; this.b = +b; this.opacity = +opacity; } define(Rgb, rgb, extend(Color, { brighter: function(k) { k = k == null ? brighter : Math.pow(brighter, k); return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity); }, darker: function(k) { k = k == null ? darker : Math.pow(darker, k); return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity); }, rgb: function() { return this; }, displayable: function() { return (0 <= this.r && this.r <= 255) && (0 <= this.g && this.g <= 255) && (0 <= this.b && this.b <= 255) && (0 <= this.opacity && this.opacity <= 1); }, toString: function() { var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a)); return (a === 1 ? "rgb(" : "rgba(") + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + ", " + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + ", " + Math.max(0, Math.min(255, Math.round(this.b) || 0)) + (a === 1 ? ")" : ", " + a + ")"); } })); function hsla(h, s, l, a) { if (a <= 0) h = s = l = NaN; else if (l <= 0 || l >= 1) h = s = NaN; else if (s <= 0) h = NaN; return new Hsl(h, s, l, a); } function hslConvert(o) { if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity); if (!(o instanceof Color)) o = color(o); if (!o) return new Hsl; if (o instanceof Hsl) return o; o = o.rgb(); var r = o.r / 255, g = o.g / 255, b = o.b / 255, min = Math.min(r, g, b), max = Math.max(r, g, b), h = NaN, s = max - min, l = (max + min) / 2; if (s) { if (r === max) h = (g - b) / s + (g < b) * 6; else if (g === max) h = (b - r) / s + 2; else h = (r - g) / s + 4; s /= l < 0.5 ? max + min : 2 - max - min; h *= 60; } else { s = l > 0 && l < 1 ? 0 : h; } return new Hsl(h, s, l, o.opacity); } function hsl(h, s, l, opacity) { return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity); } function Hsl(h, s, l, opacity) { this.h = +h; this.s = +s; this.l = +l; this.opacity = +opacity; } define(Hsl, hsl, extend(Color, { brighter: function(k) { k = k == null ? brighter : Math.pow(brighter, k); return new Hsl(this.h, this.s, this.l * k, this.opacity); }, darker: function(k) { k = k == null ? darker : Math.pow(darker, k); return new Hsl(this.h, this.s, this.l * k, this.opacity); }, rgb: function() { var h = this.h % 360 + (this.h < 0) * 360, s = isNaN(h) || isNaN(this.s) ? 0 : this.s, l = this.l, m2 = l + (l < 0.5 ? l : 1 - l) * s, m1 = 2 * l - m2; return new Rgb( hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2), hsl2rgb(h, m1, m2), hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2), this.opacity ); }, displayable: function() { return (0 <= this.s && this.s <= 1 || isNaN(this.s)) && (0 <= this.l && this.l <= 1) && (0 <= this.opacity && this.opacity <= 1); } })); /* From FvD 13.37, CSS Color Module Level 3 */ function hsl2rgb(h, m1, m2) { return (h < 60 ? m1 + (m2 - m1) * h / 60 : h < 180 ? m2 : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60 : m1) * 255; } var deg2rad = Math.PI / 180; var rad2deg = 180 / Math.PI; var Kn = 18; var Xn = 0.950470; var Yn = 1; var Zn = 1.088830; var t0 = 4 / 29; var t1 = 6 / 29; var t2 = 3 * t1 * t1; var t3 = t1 * t1 * t1; function labConvert(o) { if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity); if (o instanceof Hcl) { var h = o.h * deg2rad; return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity); } if (!(o instanceof Rgb)) o = rgbConvert(o); var b = rgb2xyz(o.r), a = rgb2xyz(o.g), l = rgb2xyz(o.b), x = xyz2lab((0.4124564 * b + 0.3575761 * a + 0.1804375 * l) / Xn), y = xyz2lab((0.2126729 * b + 0.7151522 * a + 0.0721750 * l) / Yn), z = xyz2lab((0.0193339 * b + 0.1191920 * a + 0.9503041 * l) / Zn); return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity); } function lab(l, a, b, opacity) { return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity); } function Lab(l, a, b, opacity) { this.l = +l; this.a = +a; this.b = +b; this.opacity = +opacity; } define(Lab, lab, extend(Color, { brighter: function(k) { return new Lab(this.l + Kn * (k == null ? 1 : k), this.a, this.b, this.opacity); }, darker: function(k) { return new Lab(this.l - Kn * (k == null ? 1 : k), this.a, this.b, this.opacity); }, rgb: function() { var y = (this.l + 16) / 116, x = isNaN(this.a) ? y : y + this.a / 500, z = isNaN(this.b) ? y : y - this.b / 200; y = Yn * lab2xyz(y); x = Xn * lab2xyz(x); z = Zn * lab2xyz(z); return new Rgb( xyz2rgb( 3.2404542 * x - 1.5371385 * y - 0.4985314 * z), // D65 -> sRGB xyz2rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z), xyz2rgb( 0.0556434 * x - 0.2040259 * y + 1.0572252 * z), this.opacity ); } })); function xyz2lab(t) { return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0; } function lab2xyz(t) { return t > t1 ? t * t * t : t2 * (t - t0); } function xyz2rgb(x) { return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055); } function rgb2xyz(x) { return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4); } function hclConvert(o) { if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity); if (!(o instanceof Lab)) o = labConvert(o); var h = Math.atan2(o.b, o.a) * rad2deg; return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity); } function hcl(h, c, l, opacity) { return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity); } function Hcl(h, c, l, opacity) { this.h = +h; this.c = +c; this.l = +l; this.opacity = +opacity; } define(Hcl, hcl, extend(Color, { brighter: function(k) { return new Hcl(this.h, this.c, this.l + Kn * (k == null ? 1 : k), this.opacity); }, darker: function(k) { return new Hcl(this.h, this.c, this.l - Kn * (k == null ? 1 : k), this.opacity); }, rgb: function() { return labConvert(this).rgb(); } })); var A = -0.14861; var B = +1.78277; var C = -0.29227; var D = -0.90649; var E = +1.97294; var ED = E * D; var EB = E * B; var BC_DA = B * C - D * A; function cubehelixConvert(o) { if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity); if (!(o instanceof Rgb)) o = rgbConvert(o); var r = o.r / 255, g = o.g / 255, b = o.b / 255, l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB), bl = b - l, k = (E * (g - l) - C * bl) / D, s = Math.sqrt(k * k + bl * bl) / (E * l * (1 - l)), // NaN if l=0 or l=1 h = s ? Math.atan2(k, bl) * rad2deg - 120 : NaN; return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity); } function cubehelix(h, s, l, opacity) { return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s, l, opacity == null ? 1 : opacity); } function Cubehelix(h, s, l, opacity) { this.h = +h; this.s = +s; this.l = +l; this.opacity = +opacity; } define(Cubehelix, cubehelix, extend(Color, { brighter: function(k) { k = k == null ? brighter : Math.pow(brighter, k); return new Cubehelix(this.h, this.s, this.l * k, this.opacity); }, darker: function(k) { k = k == null ? darker : Math.pow(darker, k); return new Cubehelix(this.h, this.s, this.l * k, this.opacity); }, rgb: function() { var h = isNaN(this.h) ? 0 : (this.h + 120) * deg2rad, l = +this.l, a = isNaN(this.s) ? 0 : this.s * l * (1 - l), cosh = Math.cos(h), sinh = Math.sin(h); return new Rgb( 255 * (l + a * (A * cosh + B * sinh)), 255 * (l + a * (C * cosh + D * sinh)), 255 * (l + a * (E * cosh)), this.opacity ); } })); var version = "0.4.2"; exports.version = version; exports.color = color; exports.rgb = rgb; exports.hsl = hsl; exports.lab = lab; exports.hcl = hcl; exports.cubehelix = cubehelix; })); /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg)) { classes.push(classNames.apply(null, arg)); } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } else if (true) { // register as 'classnames', consistent with npm package name !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { window.classNames = classNames; } }()); /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function(condition, format, a, b, c, d, e, f) { if (process.env.NODE_ENV !== 'production') { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error( 'Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.' ); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error( format.replace(/%s/g, function() { return args[argIndex++]; }) ); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 7 */ /***/ function(module, exports) { // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = __webpack_require__(9); /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule React */ 'use strict'; var ReactDOM = __webpack_require__(10); var ReactDOMServer = __webpack_require__(154); var ReactIsomorphic = __webpack_require__(158); var assign = __webpack_require__(45); var deprecated = __webpack_require__(163); // `version` will be added here by ReactIsomorphic. var React = {}; assign(React, ReactIsomorphic); assign(React, { // ReactDOM findDOMNode: deprecated('findDOMNode', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.findDOMNode), render: deprecated('render', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.render), unmountComponentAtNode: deprecated('unmountComponentAtNode', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.unmountComponentAtNode), // ReactDOMServer renderToString: deprecated('renderToString', 'ReactDOMServer', 'react-dom/server', ReactDOMServer, ReactDOMServer.renderToString), renderToStaticMarkup: deprecated('renderToStaticMarkup', 'ReactDOMServer', 'react-dom/server', ReactDOMServer, ReactDOMServer.renderToStaticMarkup) }); React.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOM; React.__SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOMServer; module.exports = React; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOM */ /* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/ 'use strict'; var ReactCurrentOwner = __webpack_require__(11); var ReactDOMTextComponent = __webpack_require__(12); var ReactDefaultInjection = __webpack_require__(77); var ReactInstanceHandles = __webpack_require__(51); var ReactMount = __webpack_require__(34); var ReactPerf = __webpack_require__(24); var ReactReconciler = __webpack_require__(56); var ReactUpdates = __webpack_require__(60); var ReactVersion = __webpack_require__(152); var findDOMNode = __webpack_require__(97); var renderSubtreeIntoContainer = __webpack_require__(153); var warning = __webpack_require__(31); ReactDefaultInjection.inject(); var render = ReactPerf.measure('React', 'render', ReactMount.render); var React = { findDOMNode: findDOMNode, render: render, unmountComponentAtNode: ReactMount.unmountComponentAtNode, version: ReactVersion, /* eslint-disable camelcase */ unstable_batchedUpdates: ReactUpdates.batchedUpdates, unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer }; // Inject the runtime into a devtools global hook regardless of browser. // Allows for debugging when the hook is injected on the page. /* eslint-enable camelcase */ if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') { __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ CurrentOwner: ReactCurrentOwner, InstanceHandles: ReactInstanceHandles, Mount: ReactMount, Reconciler: ReactReconciler, TextComponent: ReactDOMTextComponent }); } if (process.env.NODE_ENV !== 'production') { var ExecutionEnvironment = __webpack_require__(15); if (ExecutionEnvironment.canUseDOM && window.top === window.self) { // First check if devtools is not installed if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { // If we're in Chrome or Firefox, provide a download link if not installed. if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) { console.debug('Download the React DevTools for a better development experience: ' + 'https://fb.me/react-devtools'); } } // If we're in IE8, check to see if we are in compatibility mode and provide // information on preventing compatibility mode var ieCompatibilityMode = document.documentMode && document.documentMode < 8; process.env.NODE_ENV !== 'production' ? warning(!ieCompatibilityMode, 'Internet Explorer is running in compatibility mode; please add the ' + 'following tag to your HTML to prevent this from happening: ' + '<meta http-equiv="X-UA-Compatible" content="IE=edge" />') : undefined; var expectedFeatures = [ // shims Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.split, String.prototype.trim, // shams Object.create, Object.freeze]; for (var i = 0; i < expectedFeatures.length; i++) { if (!expectedFeatures[i]) { console.error('One or more ES5 shim/shams expected by React are not available: ' + 'https://fb.me/react-warning-polyfills'); break; } } } } module.exports = React; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 11 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCurrentOwner */ 'use strict'; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTextComponent * @typechecks static-only */ 'use strict'; var DOMChildrenOperations = __webpack_require__(13); var DOMPropertyOperations = __webpack_require__(28); var ReactComponentBrowserEnvironment = __webpack_require__(32); var ReactMount = __webpack_require__(34); var assign = __webpack_require__(45); var escapeTextContentForBrowser = __webpack_require__(27); var setTextContent = __webpack_require__(26); var validateDOMNesting = __webpack_require__(76); /** * Text nodes violate a couple assumptions that React makes about components: * * - When mounting text into the DOM, adjacent text nodes are merged. * - Text nodes cannot be assigned a React root ID. * * This component is used to wrap strings in elements so that they can undergo * the same reconciliation that is applied to elements. * * TODO: Investigate representing React components in the DOM with text nodes. * * @class ReactDOMTextComponent * @extends ReactComponent * @internal */ var ReactDOMTextComponent = function (props) { // This constructor and its argument is currently used by mocks. }; assign(ReactDOMTextComponent.prototype, { /** * @param {ReactText} text * @internal */ construct: function (text) { // TODO: This is really a ReactText (ReactNode), not a ReactElement this._currentElement = text; this._stringText = '' + text; // Properties this._rootNodeID = null; this._mountIndex = 0; }, /** * Creates the markup for this text node. This node is not intended to have * any features besides containing text content. * * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {string} Markup for this text node. * @internal */ mountComponent: function (rootID, transaction, context) { if (process.env.NODE_ENV !== 'production') { if (context[validateDOMNesting.ancestorInfoContextKey]) { validateDOMNesting('span', null, context[validateDOMNesting.ancestorInfoContextKey]); } } this._rootNodeID = rootID; if (transaction.useCreateElement) { var ownerDocument = context[ReactMount.ownerDocumentContextKey]; var el = ownerDocument.createElement('span'); DOMPropertyOperations.setAttributeForID(el, rootID); // Populate node cache ReactMount.getID(el); setTextContent(el, this._stringText); return el; } else { var escapedText = escapeTextContentForBrowser(this._stringText); if (transaction.renderToStaticMarkup) { // Normally we'd wrap this in a `span` for the reasons stated above, but // since this is a situation where React won't take over (static pages), // we can simply return the text as it is. return escapedText; } return '<span ' + DOMPropertyOperations.createMarkupForID(rootID) + '>' + escapedText + '</span>'; } }, /** * Updates this component by updating the text content. * * @param {ReactText} nextText The next text content * @param {ReactReconcileTransaction} transaction * @internal */ receiveComponent: function (nextText, transaction) { if (nextText !== this._currentElement) { this._currentElement = nextText; var nextStringText = '' + nextText; if (nextStringText !== this._stringText) { // TODO: Save this as pending props and use performUpdateIfNecessary // and/or updateComponent to do the actual update for consistency with // other component types? this._stringText = nextStringText; var node = ReactMount.getNode(this._rootNodeID); DOMChildrenOperations.updateTextContent(node, nextStringText); } } }, unmountComponent: function () { ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID); } }); module.exports = ReactDOMTextComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMChildrenOperations * @typechecks static-only */ 'use strict'; var Danger = __webpack_require__(14); var ReactMultiChildUpdateTypes = __webpack_require__(22); var ReactPerf = __webpack_require__(24); var setInnerHTML = __webpack_require__(25); var setTextContent = __webpack_require__(26); var invariant = __webpack_require__(19); /** * Inserts `childNode` as a child of `parentNode` at the `index`. * * @param {DOMElement} parentNode Parent node in which to insert. * @param {DOMElement} childNode Child node to insert. * @param {number} index Index at which to insert the child. * @internal */ function insertChildAt(parentNode, childNode, index) { // By exploiting arrays returning `undefined` for an undefined index, we can // rely exclusively on `insertBefore(node, null)` instead of also using // `appendChild(node)`. However, using `undefined` is not allowed by all // browsers so we must replace it with `null`. // fix render order error in safari // IE8 will throw error when index out of list size. var beforeChild = index >= parentNode.childNodes.length ? null : parentNode.childNodes.item(index); parentNode.insertBefore(childNode, beforeChild); } /** * Operations for updating with DOM children. */ var DOMChildrenOperations = { dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup, updateTextContent: setTextContent, /** * Updates a component's children by processing a series of updates. The * update configurations are each expected to have a `parentNode` property. * * @param {array<object>} updates List of update configurations. * @param {array<string>} markupList List of markup strings. * @internal */ processUpdates: function (updates, markupList) { var update; // Mapping from parent IDs to initial child orderings. var initialChildren = null; // List of children that will be moved or removed. var updatedChildren = null; for (var i = 0; i < updates.length; i++) { update = updates[i]; if (update.type === ReactMultiChildUpdateTypes.MOVE_EXISTING || update.type === ReactMultiChildUpdateTypes.REMOVE_NODE) { var updatedIndex = update.fromIndex; var updatedChild = update.parentNode.childNodes[updatedIndex]; var parentID = update.parentID; !updatedChild ? process.env.NODE_ENV !== 'production' ? invariant(false, 'processUpdates(): Unable to find child %s of element. This ' + 'probably means the DOM was unexpectedly mutated (e.g., by the ' + 'browser), usually due to forgetting a <tbody> when using tables, ' + 'nesting tags like <form>, <p>, or <a>, or using non-SVG elements ' + 'in an <svg> parent. Try inspecting the child nodes of the element ' + 'with React ID `%s`.', updatedIndex, parentID) : invariant(false) : undefined; initialChildren = initialChildren || {}; initialChildren[parentID] = initialChildren[parentID] || []; initialChildren[parentID][updatedIndex] = updatedChild; updatedChildren = updatedChildren || []; updatedChildren.push(updatedChild); } } var renderedMarkup; // markupList is either a list of markup or just a list of elements if (markupList.length && typeof markupList[0] === 'string') { renderedMarkup = Danger.dangerouslyRenderMarkup(markupList); } else { renderedMarkup = markupList; } // Remove updated children first so that `toIndex` is consistent. if (updatedChildren) { for (var j = 0; j < updatedChildren.length; j++) { updatedChildren[j].parentNode.removeChild(updatedChildren[j]); } } for (var k = 0; k < updates.length; k++) { update = updates[k]; switch (update.type) { case ReactMultiChildUpdateTypes.INSERT_MARKUP: insertChildAt(update.parentNode, renderedMarkup[update.markupIndex], update.toIndex); break; case ReactMultiChildUpdateTypes.MOVE_EXISTING: insertChildAt(update.parentNode, initialChildren[update.parentID][update.fromIndex], update.toIndex); break; case ReactMultiChildUpdateTypes.SET_MARKUP: setInnerHTML(update.parentNode, update.content); break; case ReactMultiChildUpdateTypes.TEXT_CONTENT: setTextContent(update.parentNode, update.content); break; case ReactMultiChildUpdateTypes.REMOVE_NODE: // Already removed by the for-loop above. break; } } } }; ReactPerf.measureMethods(DOMChildrenOperations, 'DOMChildrenOperations', { updateTextContent: 'updateTextContent' }); module.exports = DOMChildrenOperations; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Danger * @typechecks static-only */ 'use strict'; var ExecutionEnvironment = __webpack_require__(15); var createNodesFromMarkup = __webpack_require__(16); var emptyFunction = __webpack_require__(21); var getMarkupWrap = __webpack_require__(20); var invariant = __webpack_require__(19); var OPEN_TAG_NAME_EXP = /^(<[^ \/>]+)/; var RESULT_INDEX_ATTR = 'data-danger-index'; /** * Extracts the `nodeName` from a string of markup. * * NOTE: Extracting the `nodeName` does not require a regular expression match * because we make assumptions about React-generated markup (i.e. there are no * spaces surrounding the opening tag and there is at least one attribute). * * @param {string} markup String of markup. * @return {string} Node name of the supplied markup. * @see http://jsperf.com/extract-nodename */ function getNodeName(markup) { return markup.substring(1, markup.indexOf(' ')); } var Danger = { /** * Renders markup into an array of nodes. The markup is expected to render * into a list of root nodes. Also, the length of `resultList` and * `markupList` should be the same. * * @param {array<string>} markupList List of markup strings to render. * @return {array<DOMElement>} List of rendered nodes. * @internal */ dangerouslyRenderMarkup: function (markupList) { !ExecutionEnvironment.canUseDOM ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Cannot render markup in a worker ' + 'thread. Make sure `window` and `document` are available globally ' + 'before requiring React when unit testing or use ' + 'ReactDOMServer.renderToString for server rendering.') : invariant(false) : undefined; var nodeName; var markupByNodeName = {}; // Group markup by `nodeName` if a wrap is necessary, else by '*'. for (var i = 0; i < markupList.length; i++) { !markupList[i] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Missing markup.') : invariant(false) : undefined; nodeName = getNodeName(markupList[i]); nodeName = getMarkupWrap(nodeName) ? nodeName : '*'; markupByNodeName[nodeName] = markupByNodeName[nodeName] || []; markupByNodeName[nodeName][i] = markupList[i]; } var resultList = []; var resultListAssignmentCount = 0; for (nodeName in markupByNodeName) { if (!markupByNodeName.hasOwnProperty(nodeName)) { continue; } var markupListByNodeName = markupByNodeName[nodeName]; // This for-in loop skips the holes of the sparse array. The order of // iteration should follow the order of assignment, which happens to match // numerical index order, but we don't rely on that. var resultIndex; for (resultIndex in markupListByNodeName) { if (markupListByNodeName.hasOwnProperty(resultIndex)) { var markup = markupListByNodeName[resultIndex]; // Push the requested markup with an additional RESULT_INDEX_ATTR // attribute. If the markup does not start with a < character, it // will be discarded below (with an appropriate console.error). markupListByNodeName[resultIndex] = markup.replace(OPEN_TAG_NAME_EXP, // This index will be parsed back out below. '$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" '); } } // Render each group of markup with similar wrapping `nodeName`. var renderNodes = createNodesFromMarkup(markupListByNodeName.join(''), emptyFunction // Do nothing special with <script> tags. ); for (var j = 0; j < renderNodes.length; ++j) { var renderNode = renderNodes[j]; if (renderNode.hasAttribute && renderNode.hasAttribute(RESULT_INDEX_ATTR)) { resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR); renderNode.removeAttribute(RESULT_INDEX_ATTR); !!resultList.hasOwnProperty(resultIndex) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Danger: Assigning to an already-occupied result index.') : invariant(false) : undefined; resultList[resultIndex] = renderNode; // This should match resultList.length and markupList.length when // we're done. resultListAssignmentCount += 1; } else if (process.env.NODE_ENV !== 'production') { console.error('Danger: Discarding unexpected node:', renderNode); } } } // Although resultList was populated out of order, it should now be a dense // array. !(resultListAssignmentCount === resultList.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Danger: Did not assign to every index of resultList.') : invariant(false) : undefined; !(resultList.length === markupList.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Danger: Expected markup to render %s nodes, but rendered %s.', markupList.length, resultList.length) : invariant(false) : undefined; return resultList; }, /** * Replaces a node with a string of markup at its current position within its * parent. The markup must render into a single root node. * * @param {DOMElement} oldChild Child node to replace. * @param {string} markup Markup to render in place of the child node. * @internal */ dangerouslyReplaceNodeWithMarkup: function (oldChild, markup) { !ExecutionEnvironment.canUseDOM ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a ' + 'worker thread. Make sure `window` and `document` are available ' + 'globally before requiring React when unit testing or use ' + 'ReactDOMServer.renderToString() for server rendering.') : invariant(false) : undefined; !markup ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : invariant(false) : undefined; !(oldChild.tagName.toLowerCase() !== 'html') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the ' + '<html> node. This is because browser quirks make this unreliable ' + 'and/or slow. If you want to render to the root you must use ' + 'server rendering. See ReactDOMServer.renderToString().') : invariant(false) : undefined; var newChild; if (typeof markup === 'string') { newChild = createNodesFromMarkup(markup, emptyFunction)[0]; } else { newChild = markup; } oldChild.parentNode.replaceChild(newChild, oldChild); } }; module.exports = Danger; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 15 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ExecutionEnvironment */ 'use strict'; var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule createNodesFromMarkup * @typechecks */ /*eslint-disable fb-www/unsafe-html*/ 'use strict'; var ExecutionEnvironment = __webpack_require__(15); var createArrayFromMixed = __webpack_require__(17); var getMarkupWrap = __webpack_require__(20); var invariant = __webpack_require__(19); /** * Dummy container used to render all markup. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Pattern used by `getNodeName`. */ var nodeNamePattern = /^\s*<(\w+)/; /** * Extracts the `nodeName` of the first element in a string of markup. * * @param {string} markup String of markup. * @return {?string} Node name of the supplied markup. */ function getNodeName(markup) { var nodeNameMatch = markup.match(nodeNamePattern); return nodeNameMatch && nodeNameMatch[1].toLowerCase(); } /** * Creates an array containing the nodes rendered from the supplied markup. The * optionally supplied `handleScript` function will be invoked once for each * <script> element that is rendered. If no `handleScript` function is supplied, * an exception is thrown if any <script> elements are rendered. * * @param {string} markup A string of valid HTML markup. * @param {?function} handleScript Invoked once for each rendered <script>. * @return {array<DOMElement|DOMTextNode>} An array of rendered nodes. */ function createNodesFromMarkup(markup, handleScript) { var node = dummyNode; !!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup dummy not initialized') : invariant(false) : undefined; var nodeName = getNodeName(markup); var wrap = nodeName && getMarkupWrap(nodeName); if (wrap) { node.innerHTML = wrap[1] + markup + wrap[2]; var wrapDepth = wrap[0]; while (wrapDepth--) { node = node.lastChild; } } else { node.innerHTML = markup; } var scripts = node.getElementsByTagName('script'); if (scripts.length) { !handleScript ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup(...): Unexpected <script> element rendered.') : invariant(false) : undefined; createArrayFromMixed(scripts).forEach(handleScript); } var nodes = createArrayFromMixed(node.childNodes); while (node.lastChild) { node.removeChild(node.lastChild); } return nodes; } module.exports = createNodesFromMarkup; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule createArrayFromMixed * @typechecks */ 'use strict'; var toArray = __webpack_require__(18); /** * Perform a heuristic test to determine if an object is "array-like". * * A monk asked Joshu, a Zen master, "Has a dog Buddha nature?" * Joshu replied: "Mu." * * This function determines if its argument has "array nature": it returns * true if the argument is an actual array, an `arguments' object, or an * HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()). * * It will return false for other array-like objects like Filelist. * * @param {*} obj * @return {boolean} */ function hasArrayNature(obj) { return( // not null/false !!obj && ( // arrays are objects, NodeLists are functions in Safari typeof obj == 'object' || typeof obj == 'function') && // quacks like an array 'length' in obj && // not window !('setInterval' in obj) && // no DOM node should be considered an array-like // a 'select' element has 'length' and 'item' properties on IE8 typeof obj.nodeType != 'number' && ( // a real array Array.isArray(obj) || // arguments 'callee' in obj || // HTMLCollection/NodeList 'item' in obj) ); } /** * Ensure that the argument is an array by wrapping it in an array if it is not. * Creates a copy of the argument if it is already an array. * * This is mostly useful idiomatically: * * var createArrayFromMixed = require('createArrayFromMixed'); * * function takesOneOrMoreThings(things) { * things = createArrayFromMixed(things); * ... * } * * This allows you to treat `things' as an array, but accept scalars in the API. * * If you need to convert an array-like object, like `arguments`, into an array * use toArray instead. * * @param {*} obj * @return {array} */ function createArrayFromMixed(obj) { if (!hasArrayNature(obj)) { return [obj]; } else if (Array.isArray(obj)) { return obj.slice(); } else { return toArray(obj); } } module.exports = createArrayFromMixed; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule toArray * @typechecks */ 'use strict'; var invariant = __webpack_require__(19); /** * Convert array-like objects to arrays. * * This API assumes the caller knows the contents of the data type. For less * well defined inputs use createArrayFromMixed. * * @param {object|function|filelist} obj * @return {array} */ function toArray(obj) { var length = obj.length; // Some browse builtin objects can report typeof 'function' (e.g. NodeList in // old versions of Safari). !(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : undefined; !(typeof length === 'number') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : undefined; !(length === 0 || length - 1 in obj) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : undefined; // Old IE doesn't give collections access to hasOwnProperty. Assume inputs // without method will throw during the slice call and skip straight to the // fallback. if (obj.hasOwnProperty) { try { return Array.prototype.slice.call(obj); } catch (e) { // IE < 9 does not support Array#slice on collections objects } } // Fall back to copying key by key. This assumes all keys have a value, // so will not preserve sparsely populated inputs. var ret = Array(length); for (var ii = 0; ii < length; ii++) { ret[ii] = obj[ii]; } return ret; } module.exports = toArray; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule invariant */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ function invariant(condition, format, a, b, c, d, e, f) { if (process.env.NODE_ENV !== 'production') { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getMarkupWrap */ /*eslint-disable fb-www/unsafe-html */ 'use strict'; var ExecutionEnvironment = __webpack_require__(15); var invariant = __webpack_require__(19); /** * Dummy container used to detect which wraps are necessary. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Some browsers cannot use `innerHTML` to render certain elements standalone, * so we wrap them, render the wrapped nodes, then extract the desired node. * * In IE8, certain elements cannot render alone, so wrap all elements ('*'). */ var shouldWrap = {}; var selectWrap = [1, '<select multiple="true">', '</select>']; var tableWrap = [1, '<table>', '</table>']; var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>']; var svgWrap = [1, '<svg xmlns="http://www.w3.org/2000/svg">', '</svg>']; var markupWrap = { '*': [1, '?<div>', '</div>'], 'area': [1, '<map>', '</map>'], 'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], 'legend': [1, '<fieldset>', '</fieldset>'], 'param': [1, '<object>', '</object>'], 'tr': [2, '<table><tbody>', '</tbody></table>'], 'optgroup': selectWrap, 'option': selectWrap, 'caption': tableWrap, 'colgroup': tableWrap, 'tbody': tableWrap, 'tfoot': tableWrap, 'thead': tableWrap, 'td': trWrap, 'th': trWrap }; // Initialize the SVG elements since we know they'll always need to be wrapped // consistently. If they are created inside a <div> they will be initialized in // the wrong namespace (and will not display). var svgElements = ['circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'text', 'tspan']; svgElements.forEach(function (nodeName) { markupWrap[nodeName] = svgWrap; shouldWrap[nodeName] = true; }); /** * Gets the markup wrap configuration for the supplied `nodeName`. * * NOTE: This lazily detects which wraps are necessary for the current browser. * * @param {string} nodeName Lowercase `nodeName`. * @return {?array} Markup wrap configuration, if applicable. */ function getMarkupWrap(nodeName) { !!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Markup wrapping node not initialized') : invariant(false) : undefined; if (!markupWrap.hasOwnProperty(nodeName)) { nodeName = '*'; } if (!shouldWrap.hasOwnProperty(nodeName)) { if (nodeName === '*') { dummyNode.innerHTML = '<link />'; } else { dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>'; } shouldWrap[nodeName] = !dummyNode.firstChild; } return shouldWrap[nodeName] ? markupWrap[nodeName] : null; } module.exports = getMarkupWrap; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 21 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyFunction */ "use strict"; function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ function emptyFunction() {} emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMultiChildUpdateTypes */ 'use strict'; var keyMirror = __webpack_require__(23); /** * When a component's children are updated, a series of update configuration * objects are created in order to batch and serialize the required changes. * * Enumerates all the possible types of update configurations. * * @internal */ var ReactMultiChildUpdateTypes = keyMirror({ INSERT_MARKUP: null, MOVE_EXISTING: null, REMOVE_NODE: null, SET_MARKUP: null, TEXT_CONTENT: null }); module.exports = ReactMultiChildUpdateTypes; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyMirror * @typechecks static-only */ 'use strict'; var invariant = __webpack_require__(19); /** * Constructs an enumeration with keys equal to their value. * * For example: * * var COLORS = keyMirror({blue: null, red: null}); * var myColor = COLORS.blue; * var isColorValid = !!COLORS[myColor]; * * The last line could not be performed if the values of the generated enum were * not equal to their keys. * * Input: {key1: val1, key2: val2} * Output: {key1: key1, key2: key2} * * @param {object} obj * @return {object} */ var keyMirror = function (obj) { var ret = {}; var key; !(obj instanceof Object && !Array.isArray(obj)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'keyMirror(...): Argument must be an object.') : invariant(false) : undefined; for (key in obj) { if (!obj.hasOwnProperty(key)) { continue; } ret[key] = key; } return ret; }; module.exports = keyMirror; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPerf * @typechecks static-only */ 'use strict'; /** * ReactPerf is a general AOP system designed to measure performance. This * module only has the hooks: see ReactDefaultPerf for the analysis tool. */ var ReactPerf = { /** * Boolean to enable/disable measurement. Set to false by default to prevent * accidental logging and perf loss. */ enableMeasure: false, /** * Holds onto the measure function in use. By default, don't measure * anything, but we'll override this if we inject a measure function. */ storedMeasure: _noMeasure, /** * @param {object} object * @param {string} objectName * @param {object<string>} methodNames */ measureMethods: function (object, objectName, methodNames) { if (process.env.NODE_ENV !== 'production') { for (var key in methodNames) { if (!methodNames.hasOwnProperty(key)) { continue; } object[key] = ReactPerf.measure(objectName, methodNames[key], object[key]); } } }, /** * Use this to wrap methods you want to measure. Zero overhead in production. * * @param {string} objName * @param {string} fnName * @param {function} func * @return {function} */ measure: function (objName, fnName, func) { if (process.env.NODE_ENV !== 'production') { var measuredFunc = null; var wrapper = function () { if (ReactPerf.enableMeasure) { if (!measuredFunc) { measuredFunc = ReactPerf.storedMeasure(objName, fnName, func); } return measuredFunc.apply(this, arguments); } return func.apply(this, arguments); }; wrapper.displayName = objName + '_' + fnName; return wrapper; } return func; }, injection: { /** * @param {function} measure */ injectMeasure: function (measure) { ReactPerf.storedMeasure = measure; } } }; /** * Simply passes through the measured function, without measuring it. * * @param {string} objName * @param {string} fnName * @param {function} func * @return {function} */ function _noMeasure(objName, fnName, func) { return func; } module.exports = ReactPerf; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule setInnerHTML */ /* globals MSApp */ 'use strict'; var ExecutionEnvironment = __webpack_require__(15); var WHITESPACE_TEST = /^[ \r\n\t\f]/; var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/; /** * Set the innerHTML property of a node, ensuring that whitespace is preserved * even in IE8. * * @param {DOMElement} node * @param {string} html * @internal */ var setInnerHTML = function (node, html) { node.innerHTML = html; }; // Win8 apps: Allow all html to be inserted if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) { setInnerHTML = function (node, html) { MSApp.execUnsafeLocalFunction(function () { node.innerHTML = html; }); }; } if (ExecutionEnvironment.canUseDOM) { // IE8: When updating a just created node with innerHTML only leading // whitespace is removed. When updating an existing node with innerHTML // whitespace in root TextNodes is also collapsed. // @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html // Feature detection; only IE8 is known to behave improperly like this. var testElement = document.createElement('div'); testElement.innerHTML = ' '; if (testElement.innerHTML === '') { setInnerHTML = function (node, html) { // Magic theory: IE8 supposedly differentiates between added and updated // nodes when processing innerHTML, innerHTML on updated nodes suffers // from worse whitespace behavior. Re-adding a node like this triggers // the initial and more favorable whitespace behavior. // TODO: What to do on a detached node? if (node.parentNode) { node.parentNode.replaceChild(node, node); } // We also implement a workaround for non-visible tags disappearing into // thin air on IE8, this only happens if there is no visible text // in-front of the non-visible tags. Piggyback on the whitespace fix // and simply check if any non-visible tags appear in the source. if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) { // Recover leading whitespace by temporarily prepending any character. // \uFEFF has the potential advantage of being zero-width/invisible. // UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode // in hopes that this is preserved even if "\uFEFF" is transformed to // the actual Unicode character (by Babel, for example). // https://github.com/mishoo/UglifyJS2/blob/v2.4.20/lib/parse.js#L216 node.innerHTML = String.fromCharCode(0xFEFF) + html; // deleteData leaves an empty `TextNode` which offsets the index of all // children. Definitely want to avoid this. var textNode = node.firstChild; if (textNode.data.length === 1) { node.removeChild(textNode); } else { textNode.deleteData(0, 1); } } else { node.innerHTML = html; } }; } } module.exports = setInnerHTML; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule setTextContent */ 'use strict'; var ExecutionEnvironment = __webpack_require__(15); var escapeTextContentForBrowser = __webpack_require__(27); var setInnerHTML = __webpack_require__(25); /** * Set the textContent property of a node, ensuring that whitespace is preserved * even in IE8. innerText is a poor substitute for textContent and, among many * issues, inserts <br> instead of the literal newline chars. innerHTML behaves * as it should. * * @param {DOMElement} node * @param {string} text * @internal */ var setTextContent = function (node, text) { node.textContent = text; }; if (ExecutionEnvironment.canUseDOM) { if (!('textContent' in document.documentElement)) { setTextContent = function (node, text) { setInnerHTML(node, escapeTextContentForBrowser(text)); }; } } module.exports = setTextContent; /***/ }, /* 27 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule escapeTextContentForBrowser */ 'use strict'; var ESCAPE_LOOKUP = { '&': '&amp;', '>': '&gt;', '<': '&lt;', '"': '&quot;', '\'': '&#x27;' }; var ESCAPE_REGEX = /[&><"']/g; function escaper(match) { return ESCAPE_LOOKUP[match]; } /** * Escapes text to prevent scripting attacks. * * @param {*} text Text value to escape. * @return {string} An escaped string. */ function escapeTextContentForBrowser(text) { return ('' + text).replace(ESCAPE_REGEX, escaper); } module.exports = escapeTextContentForBrowser; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMPropertyOperations * @typechecks static-only */ 'use strict'; var DOMProperty = __webpack_require__(29); var ReactPerf = __webpack_require__(24); var quoteAttributeValueForBrowser = __webpack_require__(30); var warning = __webpack_require__(31); // Simplified subset var VALID_ATTRIBUTE_NAME_REGEX = /^[a-zA-Z_][\w\.\-]*$/; var illegalAttributeNameCache = {}; var validatedAttributeNameCache = {}; function isAttributeNameSafe(attributeName) { if (validatedAttributeNameCache.hasOwnProperty(attributeName)) { return true; } if (illegalAttributeNameCache.hasOwnProperty(attributeName)) { return false; } if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { validatedAttributeNameCache[attributeName] = true; return true; } illegalAttributeNameCache[attributeName] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid attribute name: `%s`', attributeName) : undefined; return false; } function shouldIgnoreValue(propertyInfo, value) { return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false; } if (process.env.NODE_ENV !== 'production') { var reactProps = { children: true, dangerouslySetInnerHTML: true, key: true, ref: true }; var warnedProperties = {}; var warnUnknownProperty = function (name) { if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) { return; } warnedProperties[name] = true; var lowerCasedName = name.toLowerCase(); // data-* attributes should be lowercase; suggest the lowercase version var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null; // For now, only warn when we have a suggested correction. This prevents // logging too much when using transferPropsTo. process.env.NODE_ENV !== 'production' ? warning(standardName == null, 'Unknown DOM property %s. Did you mean %s?', name, standardName) : undefined; }; } /** * Operations for dealing with DOM properties. */ var DOMPropertyOperations = { /** * Creates markup for the ID property. * * @param {string} id Unescaped ID. * @return {string} Markup string. */ createMarkupForID: function (id) { return DOMProperty.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser(id); }, setAttributeForID: function (node, id) { node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id); }, /** * Creates markup for a property. * * @param {string} name * @param {*} value * @return {?string} Markup string, or null if the property was invalid. */ createMarkupForProperty: function (name, value) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { if (shouldIgnoreValue(propertyInfo, value)) { return ''; } var attributeName = propertyInfo.attributeName; if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { return attributeName + '=""'; } return attributeName + '=' + quoteAttributeValueForBrowser(value); } else if (DOMProperty.isCustomAttribute(name)) { if (value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); } else if (process.env.NODE_ENV !== 'production') { warnUnknownProperty(name); } return null; }, /** * Creates markup for a custom property. * * @param {string} name * @param {*} value * @return {string} Markup string, or empty string if the property was invalid. */ createMarkupForCustomAttribute: function (name, value) { if (!isAttributeNameSafe(name) || value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); }, /** * Sets the value for a property on a node. * * @param {DOMElement} node * @param {string} name * @param {*} value */ setValueForProperty: function (node, name, value) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, value); } else if (shouldIgnoreValue(propertyInfo, value)) { this.deleteValueForProperty(node, name); } else if (propertyInfo.mustUseAttribute) { var attributeName = propertyInfo.attributeName; var namespace = propertyInfo.attributeNamespace; // `setAttribute` with objects becomes only `[object]` in IE8/9, // ('' + value) makes it output the correct toString()-value. if (namespace) { node.setAttributeNS(namespace, attributeName, '' + value); } else if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { node.setAttribute(attributeName, ''); } else { node.setAttribute(attributeName, '' + value); } } else { var propName = propertyInfo.propertyName; // Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the // property type before comparing; only `value` does and is string. if (!propertyInfo.hasSideEffects || '' + node[propName] !== '' + value) { // Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node[propName] = value; } } } else if (DOMProperty.isCustomAttribute(name)) { DOMPropertyOperations.setValueForAttribute(node, name, value); } else if (process.env.NODE_ENV !== 'production') { warnUnknownProperty(name); } }, setValueForAttribute: function (node, name, value) { if (!isAttributeNameSafe(name)) { return; } if (value == null) { node.removeAttribute(name); } else { node.setAttribute(name, '' + value); } }, /** * Deletes the value for a property on a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForProperty: function (node, name) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, undefined); } else if (propertyInfo.mustUseAttribute) { node.removeAttribute(propertyInfo.attributeName); } else { var propName = propertyInfo.propertyName; var defaultValue = DOMProperty.getDefaultValueForProperty(node.nodeName, propName); if (!propertyInfo.hasSideEffects || '' + node[propName] !== defaultValue) { node[propName] = defaultValue; } } } else if (DOMProperty.isCustomAttribute(name)) { node.removeAttribute(name); } else if (process.env.NODE_ENV !== 'production') { warnUnknownProperty(name); } } }; ReactPerf.measureMethods(DOMPropertyOperations, 'DOMPropertyOperations', { setValueForProperty: 'setValueForProperty', setValueForAttribute: 'setValueForAttribute', deleteValueForProperty: 'deleteValueForProperty' }); module.exports = DOMPropertyOperations; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMProperty * @typechecks static-only */ 'use strict'; var invariant = __webpack_require__(19); function checkMask(value, bitmask) { return (value & bitmask) === bitmask; } var DOMPropertyInjection = { /** * Mapping from normalized, camelcased property names to a configuration that * specifies how the associated DOM property should be accessed or rendered. */ MUST_USE_ATTRIBUTE: 0x1, MUST_USE_PROPERTY: 0x2, HAS_SIDE_EFFECTS: 0x4, HAS_BOOLEAN_VALUE: 0x8, HAS_NUMERIC_VALUE: 0x10, HAS_POSITIVE_NUMERIC_VALUE: 0x20 | 0x10, HAS_OVERLOADED_BOOLEAN_VALUE: 0x40, /** * Inject some specialized knowledge about the DOM. This takes a config object * with the following properties: * * isCustomAttribute: function that given an attribute name will return true * if it can be inserted into the DOM verbatim. Useful for data-* or aria-* * attributes where it's impossible to enumerate all of the possible * attribute names, * * Properties: object mapping DOM property name to one of the * DOMPropertyInjection constants or null. If your attribute isn't in here, * it won't get written to the DOM. * * DOMAttributeNames: object mapping React attribute name to the DOM * attribute name. Attribute names not specified use the **lowercase** * normalized name. * * DOMAttributeNamespaces: object mapping React attribute name to the DOM * attribute namespace URL. (Attribute names not specified use no namespace.) * * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties. * Property names not specified use the normalized name. * * DOMMutationMethods: Properties that require special mutation methods. If * `value` is undefined, the mutation method should unset the property. * * @param {object} domPropertyConfig the config as described above. */ injectDOMPropertyConfig: function (domPropertyConfig) { var Injection = DOMPropertyInjection; var Properties = domPropertyConfig.Properties || {}; var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {}; var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {}; var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {}; var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {}; if (domPropertyConfig.isCustomAttribute) { DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute); } for (var propName in Properties) { !!DOMProperty.properties.hasOwnProperty(propName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' + '\'%s\' which has already been injected. You may be accidentally ' + 'injecting the same DOM property config twice, or you may be ' + 'injecting two configs that have conflicting property names.', propName) : invariant(false) : undefined; var lowerCased = propName.toLowerCase(); var propConfig = Properties[propName]; var propertyInfo = { attributeName: lowerCased, attributeNamespace: null, propertyName: propName, mutationMethod: null, mustUseAttribute: checkMask(propConfig, Injection.MUST_USE_ATTRIBUTE), mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY), hasSideEffects: checkMask(propConfig, Injection.HAS_SIDE_EFFECTS), hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE), hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE), hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE), hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE) }; !(!propertyInfo.mustUseAttribute || !propertyInfo.mustUseProperty) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Cannot require using both attribute and property: %s', propName) : invariant(false) : undefined; !(propertyInfo.mustUseProperty || !propertyInfo.hasSideEffects) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Properties that have side effects must use property: %s', propName) : invariant(false) : undefined; !(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or ' + 'numeric value, but not a combination: %s', propName) : invariant(false) : undefined; if (process.env.NODE_ENV !== 'production') { DOMProperty.getPossibleStandardName[lowerCased] = propName; } if (DOMAttributeNames.hasOwnProperty(propName)) { var attributeName = DOMAttributeNames[propName]; propertyInfo.attributeName = attributeName; if (process.env.NODE_ENV !== 'production') { DOMProperty.getPossibleStandardName[attributeName] = propName; } } if (DOMAttributeNamespaces.hasOwnProperty(propName)) { propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName]; } if (DOMPropertyNames.hasOwnProperty(propName)) { propertyInfo.propertyName = DOMPropertyNames[propName]; } if (DOMMutationMethods.hasOwnProperty(propName)) { propertyInfo.mutationMethod = DOMMutationMethods[propName]; } DOMProperty.properties[propName] = propertyInfo; } } }; var defaultValueCache = {}; /** * DOMProperty exports lookup objects that can be used like functions: * * > DOMProperty.isValid['id'] * true * > DOMProperty.isValid['foobar'] * undefined * * Although this may be confusing, it performs better in general. * * @see http://jsperf.com/key-exists * @see http://jsperf.com/key-missing */ var DOMProperty = { ID_ATTRIBUTE_NAME: 'data-reactid', /** * Map from property "standard name" to an object with info about how to set * the property in the DOM. Each object contains: * * attributeName: * Used when rendering markup or with `*Attribute()`. * attributeNamespace * propertyName: * Used on DOM node instances. (This includes properties that mutate due to * external factors.) * mutationMethod: * If non-null, used instead of the property or `setAttribute()` after * initial render. * mustUseAttribute: * Whether the property must be accessed and mutated using `*Attribute()`. * (This includes anything that fails `<propName> in <element>`.) * mustUseProperty: * Whether the property must be accessed and mutated as an object property. * hasSideEffects: * Whether or not setting a value causes side effects such as triggering * resources to be loaded or text selection changes. If true, we read from * the DOM before updating to ensure that the value is only set if it has * changed. * hasBooleanValue: * Whether the property should be removed when set to a falsey value. * hasNumericValue: * Whether the property must be numeric or parse as a numeric and should be * removed when set to a falsey value. * hasPositiveNumericValue: * Whether the property must be positive numeric or parse as a positive * numeric and should be removed when set to a falsey value. * hasOverloadedBooleanValue: * Whether the property can be used as a flag as well as with a value. * Removed when strictly equal to false; present without a value when * strictly equal to true; present with a value otherwise. */ properties: {}, /** * Mapping from lowercase property names to the properly cased version, used * to warn in the case of missing properties. Available only in __DEV__. * @type {Object} */ getPossibleStandardName: process.env.NODE_ENV !== 'production' ? {} : null, /** * All of the isCustomAttribute() functions that have been injected. */ _isCustomAttributeFunctions: [], /** * Checks whether a property name is a custom attribute. * @method */ isCustomAttribute: function (attributeName) { for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) { var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i]; if (isCustomAttributeFn(attributeName)) { return true; } } return false; }, /** * Returns the default property value for a DOM property (i.e., not an * attribute). Most default values are '' or false, but not all. Worse yet, * some (in particular, `type`) vary depending on the type of element. * * TODO: Is it better to grab all the possible properties when creating an * element to avoid having to create the same element twice? */ getDefaultValueForProperty: function (nodeName, prop) { var nodeDefaults = defaultValueCache[nodeName]; var testElement; if (!nodeDefaults) { defaultValueCache[nodeName] = nodeDefaults = {}; } if (!(prop in nodeDefaults)) { testElement = document.createElement(nodeName); nodeDefaults[prop] = testElement[prop]; } return nodeDefaults[prop]; }, injection: DOMPropertyInjection }; module.exports = DOMProperty; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule quoteAttributeValueForBrowser */ 'use strict'; var escapeTextContentForBrowser = __webpack_require__(27); /** * Escapes attribute value to prevent scripting attacks. * * @param {*} value Value to escape. * @return {string} An escaped string. */ function quoteAttributeValueForBrowser(value) { return '"' + escapeTextContentForBrowser(value) + '"'; } module.exports = quoteAttributeValueForBrowser; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule warning */ 'use strict'; var emptyFunction = __webpack_require__(21); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if (process.env.NODE_ENV !== 'production') { warning = function (condition, format) { for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} } }; } module.exports = warning; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentBrowserEnvironment */ 'use strict'; var ReactDOMIDOperations = __webpack_require__(33); var ReactMount = __webpack_require__(34); /** * Abstracts away all functionality of the reconciler that requires knowledge of * the browser context. TODO: These callers should be refactored to avoid the * need for this injection. */ var ReactComponentBrowserEnvironment = { processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates, replaceNodeWithMarkupByID: ReactDOMIDOperations.dangerouslyReplaceNodeWithMarkupByID, /** * If a particular environment requires that some resources be cleaned up, * specify this in the injected Mixin. In the DOM, we would likely want to * purge any cached node ID lookups. * * @private */ unmountIDFromEnvironment: function (rootNodeID) { ReactMount.purgeID(rootNodeID); } }; module.exports = ReactComponentBrowserEnvironment; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMIDOperations * @typechecks static-only */ 'use strict'; var DOMChildrenOperations = __webpack_require__(13); var DOMPropertyOperations = __webpack_require__(28); var ReactMount = __webpack_require__(34); var ReactPerf = __webpack_require__(24); var invariant = __webpack_require__(19); /** * Errors for properties that should not be updated with `updatePropertyByID()`. * * @type {object} * @private */ var INVALID_PROPERTY_ERRORS = { dangerouslySetInnerHTML: '`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.', style: '`style` must be set using `updateStylesByID()`.' }; /** * Operations used to process updates to DOM nodes. */ var ReactDOMIDOperations = { /** * Updates a DOM node with new property values. This should only be used to * update DOM properties in `DOMProperty`. * * @param {string} id ID of the node to update. * @param {string} name A valid property name, see `DOMProperty`. * @param {*} value New value of the property. * @internal */ updatePropertyByID: function (id, name, value) { var node = ReactMount.getNode(id); !!INVALID_PROPERTY_ERRORS.hasOwnProperty(name) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'updatePropertyByID(...): %s', INVALID_PROPERTY_ERRORS[name]) : invariant(false) : undefined; // If we're updating to null or undefined, we should remove the property // from the DOM node instead of inadvertantly setting to a string. This // brings us in line with the same behavior we have on initial render. if (value != null) { DOMPropertyOperations.setValueForProperty(node, name, value); } else { DOMPropertyOperations.deleteValueForProperty(node, name); } }, /** * Replaces a DOM node that exists in the document with markup. * * @param {string} id ID of child to be replaced. * @param {string} markup Dangerous markup to inject in place of child. * @internal * @see {Danger.dangerouslyReplaceNodeWithMarkup} */ dangerouslyReplaceNodeWithMarkupByID: function (id, markup) { var node = ReactMount.getNode(id); DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup); }, /** * Updates a component's children by processing a series of updates. * * @param {array<object>} updates List of update configurations. * @param {array<string>} markup List of markup strings. * @internal */ dangerouslyProcessChildrenUpdates: function (updates, markup) { for (var i = 0; i < updates.length; i++) { updates[i].parentNode = ReactMount.getNode(updates[i].parentID); } DOMChildrenOperations.processUpdates(updates, markup); } }; ReactPerf.measureMethods(ReactDOMIDOperations, 'ReactDOMIDOperations', { dangerouslyReplaceNodeWithMarkupByID: 'dangerouslyReplaceNodeWithMarkupByID', dangerouslyProcessChildrenUpdates: 'dangerouslyProcessChildrenUpdates' }); module.exports = ReactDOMIDOperations; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMount */ 'use strict'; var DOMProperty = __webpack_require__(29); var ReactBrowserEventEmitter = __webpack_require__(35); var ReactCurrentOwner = __webpack_require__(11); var ReactDOMFeatureFlags = __webpack_require__(47); var ReactElement = __webpack_require__(48); var ReactEmptyComponentRegistry = __webpack_require__(50); var ReactInstanceHandles = __webpack_require__(51); var ReactInstanceMap = __webpack_require__(53); var ReactMarkupChecksum = __webpack_require__(54); var ReactPerf = __webpack_require__(24); var ReactReconciler = __webpack_require__(56); var ReactUpdateQueue = __webpack_require__(59); var ReactUpdates = __webpack_require__(60); var assign = __webpack_require__(45); var emptyObject = __webpack_require__(64); var containsNode = __webpack_require__(65); var instantiateReactComponent = __webpack_require__(68); var invariant = __webpack_require__(19); var setInnerHTML = __webpack_require__(25); var shouldUpdateReactComponent = __webpack_require__(73); var validateDOMNesting = __webpack_require__(76); var warning = __webpack_require__(31); var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var nodeCache = {}; var ELEMENT_NODE_TYPE = 1; var DOC_NODE_TYPE = 9; var DOCUMENT_FRAGMENT_NODE_TYPE = 11; var ownerDocumentContextKey = '__ReactMount_ownerDocument$' + Math.random().toString(36).slice(2); /** Mapping from reactRootID to React component instance. */ var instancesByReactRootID = {}; /** Mapping from reactRootID to `container` nodes. */ var containersByReactRootID = {}; if (process.env.NODE_ENV !== 'production') { /** __DEV__-only mapping from reactRootID to root elements. */ var rootElementsByReactRootID = {}; } // Used to store breadth-first search state in findComponentRoot. var findComponentRootReusableArray = []; /** * Finds the index of the first character * that's not common between the two given strings. * * @return {number} the index of the character where the strings diverge */ function firstDifferenceIndex(string1, string2) { var minLen = Math.min(string1.length, string2.length); for (var i = 0; i < minLen; i++) { if (string1.charAt(i) !== string2.charAt(i)) { return i; } } return string1.length === string2.length ? -1 : minLen; } /** * @param {DOMElement|DOMDocument} container DOM element that may contain * a React component * @return {?*} DOM element that may have the reactRoot ID, or null. */ function getReactRootElementInContainer(container) { if (!container) { return null; } if (container.nodeType === DOC_NODE_TYPE) { return container.documentElement; } else { return container.firstChild; } } /** * @param {DOMElement} container DOM element that may contain a React component. * @return {?string} A "reactRoot" ID, if a React component is rendered. */ function getReactRootID(container) { var rootElement = getReactRootElementInContainer(container); return rootElement && ReactMount.getID(rootElement); } /** * Accessing node[ATTR_NAME] or calling getAttribute(ATTR_NAME) on a form * element can return its control whose name or ID equals ATTR_NAME. All * DOM nodes support `getAttributeNode` but this can also get called on * other objects so just return '' if we're given something other than a * DOM node (such as window). * * @param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node. * @return {string} ID of the supplied `domNode`. */ function getID(node) { var id = internalGetID(node); if (id) { if (nodeCache.hasOwnProperty(id)) { var cached = nodeCache[id]; if (cached !== node) { !!isValid(cached, id) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactMount: Two valid but unequal nodes with the same `%s`: %s', ATTR_NAME, id) : invariant(false) : undefined; nodeCache[id] = node; } } else { nodeCache[id] = node; } } return id; } function internalGetID(node) { // If node is something like a window, document, or text node, none of // which support attributes or a .getAttribute method, gracefully return // the empty string, as if the attribute were missing. return node && node.getAttribute && node.getAttribute(ATTR_NAME) || ''; } /** * Sets the React-specific ID of the given node. * * @param {DOMElement} node The DOM node whose ID will be set. * @param {string} id The value of the ID attribute. */ function setID(node, id) { var oldID = internalGetID(node); if (oldID !== id) { delete nodeCache[oldID]; } node.setAttribute(ATTR_NAME, id); nodeCache[id] = node; } /** * Finds the node with the supplied React-generated DOM ID. * * @param {string} id A React-generated DOM ID. * @return {DOMElement} DOM node with the suppled `id`. * @internal */ function getNode(id) { if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) { nodeCache[id] = ReactMount.findReactNodeByID(id); } return nodeCache[id]; } /** * Finds the node with the supplied public React instance. * * @param {*} instance A public React instance. * @return {?DOMElement} DOM node with the suppled `id`. * @internal */ function getNodeFromInstance(instance) { var id = ReactInstanceMap.get(instance)._rootNodeID; if (ReactEmptyComponentRegistry.isNullComponentID(id)) { return null; } if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) { nodeCache[id] = ReactMount.findReactNodeByID(id); } return nodeCache[id]; } /** * A node is "valid" if it is contained by a currently mounted container. * * This means that the node does not have to be contained by a document in * order to be considered valid. * * @param {?DOMElement} node The candidate DOM node. * @param {string} id The expected ID of the node. * @return {boolean} Whether the node is contained by a mounted container. */ function isValid(node, id) { if (node) { !(internalGetID(node) === id) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactMount: Unexpected modification of `%s`', ATTR_NAME) : invariant(false) : undefined; var container = ReactMount.findReactContainerForID(id); if (container && containsNode(container, node)) { return true; } } return false; } /** * Causes the cache to forget about one React-specific ID. * * @param {string} id The ID to forget. */ function purgeID(id) { delete nodeCache[id]; } var deepestNodeSoFar = null; function findDeepestCachedAncestorImpl(ancestorID) { var ancestor = nodeCache[ancestorID]; if (ancestor && isValid(ancestor, ancestorID)) { deepestNodeSoFar = ancestor; } else { // This node isn't populated in the cache, so presumably none of its // descendants are. Break out of the loop. return false; } } /** * Return the deepest cached node whose ID is a prefix of `targetID`. */ function findDeepestCachedAncestor(targetID) { deepestNodeSoFar = null; ReactInstanceHandles.traverseAncestors(targetID, findDeepestCachedAncestorImpl); var foundNode = deepestNodeSoFar; deepestNodeSoFar = null; return foundNode; } /** * Mounts this component and inserts it into the DOM. * * @param {ReactComponent} componentInstance The instance to mount. * @param {string} rootID DOM ID of the root node. * @param {DOMElement} container DOM element to mount into. * @param {ReactReconcileTransaction} transaction * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function mountComponentIntoNode(componentInstance, rootID, container, transaction, shouldReuseMarkup, context) { if (ReactDOMFeatureFlags.useCreateElement) { context = assign({}, context); if (container.nodeType === DOC_NODE_TYPE) { context[ownerDocumentContextKey] = container; } else { context[ownerDocumentContextKey] = container.ownerDocument; } } if (process.env.NODE_ENV !== 'production') { if (context === emptyObject) { context = {}; } var tag = container.nodeName.toLowerCase(); context[validateDOMNesting.ancestorInfoContextKey] = validateDOMNesting.updatedAncestorInfo(null, tag, null); } var markup = ReactReconciler.mountComponent(componentInstance, rootID, transaction, context); componentInstance._renderedComponent._topLevelWrapper = componentInstance; ReactMount._mountImageIntoNode(markup, container, shouldReuseMarkup, transaction); } /** * Batched mount. * * @param {ReactComponent} componentInstance The instance to mount. * @param {string} rootID DOM ID of the root node. * @param {DOMElement} container DOM element to mount into. * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function batchedMountComponentIntoNode(componentInstance, rootID, container, shouldReuseMarkup, context) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* forceHTML */shouldReuseMarkup); transaction.perform(mountComponentIntoNode, null, componentInstance, rootID, container, transaction, shouldReuseMarkup, context); ReactUpdates.ReactReconcileTransaction.release(transaction); } /** * Unmounts a component and removes it from the DOM. * * @param {ReactComponent} instance React component instance. * @param {DOMElement} container DOM element to unmount from. * @final * @internal * @see {ReactMount.unmountComponentAtNode} */ function unmountComponentFromNode(instance, container) { ReactReconciler.unmountComponent(instance); if (container.nodeType === DOC_NODE_TYPE) { container = container.documentElement; } // http://jsperf.com/emptying-a-node while (container.lastChild) { container.removeChild(container.lastChild); } } /** * True if the supplied DOM node has a direct React-rendered child that is * not a React root element. Useful for warning in `render`, * `unmountComponentAtNode`, etc. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM element contains a direct child that was * rendered by React but is not a root element. * @internal */ function hasNonRootReactChild(node) { var reactRootID = getReactRootID(node); return reactRootID ? reactRootID !== ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID) : false; } /** * Returns the first (deepest) ancestor of a node which is rendered by this copy * of React. */ function findFirstReactDOMImpl(node) { // This node might be from another React instance, so we make sure not to // examine the node cache here for (; node && node.parentNode !== node; node = node.parentNode) { if (node.nodeType !== 1) { // Not a DOMElement, therefore not a React component continue; } var nodeID = internalGetID(node); if (!nodeID) { continue; } var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID); // If containersByReactRootID contains the container we find by crawling up // the tree, we know that this instance of React rendered the node. // nb. isValid's strategy (with containsNode) does not work because render // trees may be nested and we don't want a false positive in that case. var current = node; var lastID; do { lastID = internalGetID(current); current = current.parentNode; if (current == null) { // The passed-in node has been detached from the container it was // originally rendered into. return null; } } while (lastID !== reactRootID); if (current === containersByReactRootID[reactRootID]) { return node; } } return null; } /** * Temporary (?) hack so that we can store all top-level pending updates on * composites instead of having to worry about different types of components * here. */ var TopLevelWrapper = function () {}; TopLevelWrapper.prototype.isReactComponent = {}; if (process.env.NODE_ENV !== 'production') { TopLevelWrapper.displayName = 'TopLevelWrapper'; } TopLevelWrapper.prototype.render = function () { // this.props is actually a ReactElement return this.props; }; /** * Mounting is the process of initializing a React component by creating its * representative DOM elements and inserting them into a supplied `container`. * Any prior content inside `container` is destroyed in the process. * * ReactMount.render( * component, * document.getElementById('container') * ); * * <div id="container"> <-- Supplied `container`. * <div data-reactid=".3"> <-- Rendered reactRoot of React * // ... component. * </div> * </div> * * Inside of `container`, the first element rendered is the "reactRoot". */ var ReactMount = { TopLevelWrapper: TopLevelWrapper, /** Exposed for debugging purposes **/ _instancesByReactRootID: instancesByReactRootID, /** * This is a hook provided to support rendering React components while * ensuring that the apparent scroll position of its `container` does not * change. * * @param {DOMElement} container The `container` being rendered into. * @param {function} renderCallback This must be called once to do the render. */ scrollMonitor: function (container, renderCallback) { renderCallback(); }, /** * Take a component that's already mounted into the DOM and replace its props * @param {ReactComponent} prevComponent component instance already in the DOM * @param {ReactElement} nextElement component instance to render * @param {DOMElement} container container to render into * @param {?function} callback function triggered on completion */ _updateRootComponent: function (prevComponent, nextElement, container, callback) { ReactMount.scrollMonitor(container, function () { ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement); if (callback) { ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback); } }); if (process.env.NODE_ENV !== 'production') { // Record the root element in case it later gets transplanted. rootElementsByReactRootID[getReactRootID(container)] = getReactRootElementInContainer(container); } return prevComponent; }, /** * Register a component into the instance map and starts scroll value * monitoring * @param {ReactComponent} nextComponent component instance to render * @param {DOMElement} container container to render into * @return {string} reactRoot ID prefix */ _registerComponent: function (nextComponent, container) { !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : invariant(false) : undefined; ReactBrowserEventEmitter.ensureScrollValueMonitoring(); var reactRootID = ReactMount.registerContainer(container); instancesByReactRootID[reactRootID] = nextComponent; return reactRootID; }, /** * Render a new component into the DOM. * @param {ReactElement} nextElement element to render * @param {DOMElement} container container to render into * @param {boolean} shouldReuseMarkup if we should skip the markup insertion * @return {ReactComponent} nextComponent */ _renderNewRootComponent: function (nextElement, container, shouldReuseMarkup, context) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : undefined; var componentInstance = instantiateReactComponent(nextElement, null); var reactRootID = ReactMount._registerComponent(componentInstance, container); // The initial render is synchronous but any updates that happen during // rendering, in componentWillMount or componentDidMount, will be batched // according to the current batching strategy. ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, reactRootID, container, shouldReuseMarkup, context); if (process.env.NODE_ENV !== 'production') { // Record the root element in case it later gets transplanted. rootElementsByReactRootID[reactRootID] = getReactRootElementInContainer(container); } return componentInstance; }, /** * Renders a React component into the DOM in the supplied `container`. * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactComponent} parentComponent The conceptual parent of this render tree. * @param {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { !(parentComponent != null && parentComponent._reactInternalInstance != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'parentComponent must be a valid React Component') : invariant(false) : undefined; return ReactMount._renderSubtreeIntoContainer(parentComponent, nextElement, container, callback); }, _renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { !ReactElement.isValidElement(nextElement) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOM.render(): Invalid component element.%s', typeof nextElement === 'string' ? ' Instead of passing an element string, make sure to instantiate ' + 'it by passing it to React.createElement.' : typeof nextElement === 'function' ? ' Instead of passing a component class, make sure to instantiate ' + 'it by passing it to React.createElement.' : // Check if it quacks like an element nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : invariant(false) : undefined; process.env.NODE_ENV !== 'production' ? warning(!container || !container.tagName || container.tagName.toUpperCase() !== 'BODY', 'render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.') : undefined; var nextWrappedElement = new ReactElement(TopLevelWrapper, null, null, null, null, null, nextElement); var prevComponent = instancesByReactRootID[getReactRootID(container)]; if (prevComponent) { var prevWrappedElement = prevComponent._currentElement; var prevElement = prevWrappedElement.props; if (shouldUpdateReactComponent(prevElement, nextElement)) { var publicInst = prevComponent._renderedComponent.getPublicInstance(); var updatedCallback = callback && function () { callback.call(publicInst); }; ReactMount._updateRootComponent(prevComponent, nextWrappedElement, container, updatedCallback); return publicInst; } else { ReactMount.unmountComponentAtNode(container); } } var reactRootElement = getReactRootElementInContainer(container); var containerHasReactMarkup = reactRootElement && !!internalGetID(reactRootElement); var containerHasNonRootReactChild = hasNonRootReactChild(container); if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, 'render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.') : undefined; if (!containerHasReactMarkup || reactRootElement.nextSibling) { var rootElementSibling = reactRootElement; while (rootElementSibling) { if (internalGetID(rootElementSibling)) { process.env.NODE_ENV !== 'production' ? warning(false, 'render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.') : undefined; break; } rootElementSibling = rootElementSibling.nextSibling; } } } var shouldReuseMarkup = containerHasReactMarkup && !prevComponent && !containerHasNonRootReactChild; var component = ReactMount._renderNewRootComponent(nextWrappedElement, container, shouldReuseMarkup, parentComponent != null ? parentComponent._reactInternalInstance._processChildContext(parentComponent._reactInternalInstance._context) : emptyObject)._renderedComponent.getPublicInstance(); if (callback) { callback.call(component); } return component; }, /** * Renders a React component into the DOM in the supplied `container`. * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ render: function (nextElement, container, callback) { return ReactMount._renderSubtreeIntoContainer(null, nextElement, container, callback); }, /** * Registers a container node into which React components will be rendered. * This also creates the "reactRoot" ID that will be assigned to the element * rendered within. * * @param {DOMElement} container DOM element to register as a container. * @return {string} The "reactRoot" ID of elements rendered within. */ registerContainer: function (container) { var reactRootID = getReactRootID(container); if (reactRootID) { // If one exists, make sure it is a valid "reactRoot" ID. reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID); } if (!reactRootID) { // No valid "reactRoot" ID found, create one. reactRootID = ReactInstanceHandles.createReactRootID(); } containersByReactRootID[reactRootID] = container; return reactRootID; }, /** * Unmounts and destroys the React component rendered in the `container`. * * @param {DOMElement} container DOM element containing a React component. * @return {boolean} True if a component was found in and unmounted from * `container` */ unmountComponentAtNode: function (container) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (Strictly speaking, unmounting won't cause a // render but we still don't expect to be in a render call here.) process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, 'unmountComponentAtNode(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from render ' + 'is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : undefined; !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : invariant(false) : undefined; var reactRootID = getReactRootID(container); var component = instancesByReactRootID[reactRootID]; if (!component) { // Check if the node being unmounted was rendered by React, but isn't a // root node. var containerHasNonRootReactChild = hasNonRootReactChild(container); // Check if the container itself is a React root node. var containerID = internalGetID(container); var isContainerReactRoot = containerID && containerID === ReactInstanceHandles.getReactRootIDFromNodeID(containerID); if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.') : undefined; } return false; } ReactUpdates.batchedUpdates(unmountComponentFromNode, component, container); delete instancesByReactRootID[reactRootID]; delete containersByReactRootID[reactRootID]; if (process.env.NODE_ENV !== 'production') { delete rootElementsByReactRootID[reactRootID]; } return true; }, /** * Finds the container DOM element that contains React component to which the * supplied DOM `id` belongs. * * @param {string} id The ID of an element rendered by a React component. * @return {?DOMElement} DOM element that contains the `id`. */ findReactContainerForID: function (id) { var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(id); var container = containersByReactRootID[reactRootID]; if (process.env.NODE_ENV !== 'production') { var rootElement = rootElementsByReactRootID[reactRootID]; if (rootElement && rootElement.parentNode !== container) { process.env.NODE_ENV !== 'production' ? warning( // Call internalGetID here because getID calls isValid which calls // findReactContainerForID (this function). internalGetID(rootElement) === reactRootID, 'ReactMount: Root element ID differed from reactRootID.') : undefined; var containerChild = container.firstChild; if (containerChild && reactRootID === internalGetID(containerChild)) { // If the container has a new child with the same ID as the old // root element, then rootElementsByReactRootID[reactRootID] is // just stale and needs to be updated. The case that deserves a // warning is when the container is empty. rootElementsByReactRootID[reactRootID] = containerChild; } else { process.env.NODE_ENV !== 'production' ? warning(false, 'ReactMount: Root element has been removed from its original ' + 'container. New container: %s', rootElement.parentNode) : undefined; } } } return container; }, /** * Finds an element rendered by React with the supplied ID. * * @param {string} id ID of a DOM node in the React component. * @return {DOMElement} Root DOM node of the React component. */ findReactNodeByID: function (id) { var reactRoot = ReactMount.findReactContainerForID(id); return ReactMount.findComponentRoot(reactRoot, id); }, /** * Traverses up the ancestors of the supplied node to find a node that is a * DOM representation of a React component rendered by this copy of React. * * @param {*} node * @return {?DOMEventTarget} * @internal */ getFirstReactDOM: function (node) { return findFirstReactDOMImpl(node); }, /** * Finds a node with the supplied `targetID` inside of the supplied * `ancestorNode`. Exploits the ID naming scheme to perform the search * quickly. * * @param {DOMEventTarget} ancestorNode Search from this root. * @pararm {string} targetID ID of the DOM representation of the component. * @return {DOMEventTarget} DOM node with the supplied `targetID`. * @internal */ findComponentRoot: function (ancestorNode, targetID) { var firstChildren = findComponentRootReusableArray; var childIndex = 0; var deepestAncestor = findDeepestCachedAncestor(targetID) || ancestorNode; if (process.env.NODE_ENV !== 'production') { // This will throw on the next line; give an early warning process.env.NODE_ENV !== 'production' ? warning(deepestAncestor != null, 'React can\'t find the root component node for data-reactid value ' + '`%s`. If you\'re seeing this message, it probably means that ' + 'you\'ve loaded two copies of React on the page. At this time, only ' + 'a single copy of React can be loaded at a time.', targetID) : undefined; } firstChildren[0] = deepestAncestor.firstChild; firstChildren.length = 1; while (childIndex < firstChildren.length) { var child = firstChildren[childIndex++]; var targetChild; while (child) { var childID = ReactMount.getID(child); if (childID) { // Even if we find the node we're looking for, we finish looping // through its siblings to ensure they're cached so that we don't have // to revisit this node again. Otherwise, we make n^2 calls to getID // when visiting the many children of a single node in order. if (targetID === childID) { targetChild = child; } else if (ReactInstanceHandles.isAncestorIDOf(childID, targetID)) { // If we find a child whose ID is an ancestor of the given ID, // then we can be sure that we only want to search the subtree // rooted at this child, so we can throw out the rest of the // search state. firstChildren.length = childIndex = 0; firstChildren.push(child.firstChild); } } else { // If this child had no ID, then there's a chance that it was // injected automatically by the browser, as when a `<table>` // element sprouts an extra `<tbody>` child as a side effect of // `.innerHTML` parsing. Optimistically continue down this // branch, but not before examining the other siblings. firstChildren.push(child.firstChild); } child = child.nextSibling; } if (targetChild) { // Emptying firstChildren/findComponentRootReusableArray is // not necessary for correctness, but it helps the GC reclaim // any nodes that were left at the end of the search. firstChildren.length = 0; return targetChild; } } firstChildren.length = 0; true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'findComponentRoot(..., %s): Unable to find element. This probably ' + 'means the DOM was unexpectedly mutated (e.g., by the browser), ' + 'usually due to forgetting a <tbody> when using tables, nesting tags ' + 'like <form>, <p>, or <a>, or using non-SVG elements in an <svg> ' + 'parent. ' + 'Try inspecting the child nodes of the element with React ID `%s`.', targetID, ReactMount.getID(ancestorNode)) : invariant(false) : undefined; }, _mountImageIntoNode: function (markup, container, shouldReuseMarkup, transaction) { !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mountComponentIntoNode(...): Target container is not valid.') : invariant(false) : undefined; if (shouldReuseMarkup) { var rootElement = getReactRootElementInContainer(container); if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) { return; } else { var checksum = rootElement.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); var rootMarkup = rootElement.outerHTML; rootElement.setAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME, checksum); var normalizedMarkup = markup; if (process.env.NODE_ENV !== 'production') { // because rootMarkup is retrieved from the DOM, various normalizations // will have occurred which will not be present in `markup`. Here, // insert markup into a <div> or <iframe> depending on the container // type to perform the same normalizations before comparing. var normalizer; if (container.nodeType === ELEMENT_NODE_TYPE) { normalizer = document.createElement('div'); normalizer.innerHTML = markup; normalizedMarkup = normalizer.innerHTML; } else { normalizer = document.createElement('iframe'); document.body.appendChild(normalizer); normalizer.contentDocument.write(markup); normalizedMarkup = normalizer.contentDocument.documentElement.outerHTML; document.body.removeChild(normalizer); } } var diffIndex = firstDifferenceIndex(normalizedMarkup, rootMarkup); var difference = ' (client) ' + normalizedMarkup.substring(diffIndex - 20, diffIndex + 20) + '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20); !(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You\'re trying to render a component to the document using ' + 'server rendering but the checksum was invalid. This usually ' + 'means you rendered a different component type or props on ' + 'the client from the one on the server, or your render() ' + 'methods are impure. React cannot handle this case due to ' + 'cross-browser quirks by rendering at the document root. You ' + 'should look for environment dependent code in your components ' + 'and ensure the props are the same client and server side:\n%s', difference) : invariant(false) : undefined; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, 'React attempted to reuse markup in a container but the ' + 'checksum was invalid. This generally means that you are ' + 'using server rendering and the markup generated on the ' + 'server was not what the client was expecting. React injected ' + 'new markup to compensate which works but you have lost many ' + 'of the benefits of server rendering. Instead, figure out ' + 'why the markup being generated is different on the client ' + 'or server:\n%s', difference) : undefined; } } } !(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You\'re trying to render a component to the document but ' + 'you didn\'t use server rendering. We can\'t do this ' + 'without using server rendering due to cross-browser quirks. ' + 'See ReactDOMServer.renderToString() for server rendering.') : invariant(false) : undefined; if (transaction.useCreateElement) { while (container.lastChild) { container.removeChild(container.lastChild); } container.appendChild(markup); } else { setInnerHTML(container, markup); } }, ownerDocumentContextKey: ownerDocumentContextKey, /** * React ID utilities. */ getReactRootID: getReactRootID, getID: getID, setID: setID, getNode: getNode, getNodeFromInstance: getNodeFromInstance, isValid: isValid, purgeID: purgeID }; ReactPerf.measureMethods(ReactMount, 'ReactMount', { _renderNewRootComponent: '_renderNewRootComponent', _mountImageIntoNode: '_mountImageIntoNode' }); module.exports = ReactMount; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactBrowserEventEmitter * @typechecks static-only */ 'use strict'; var EventConstants = __webpack_require__(36); var EventPluginHub = __webpack_require__(37); var EventPluginRegistry = __webpack_require__(38); var ReactEventEmitterMixin = __webpack_require__(43); var ReactPerf = __webpack_require__(24); var ViewportMetrics = __webpack_require__(44); var assign = __webpack_require__(45); var isEventSupported = __webpack_require__(46); /** * Summary of `ReactBrowserEventEmitter` event handling: * * - Top-level delegation is used to trap most native browser events. This * may only occur in the main thread and is the responsibility of * ReactEventListener, which is injected and can therefore support pluggable * event sources. This is the only work that occurs in the main thread. * * - We normalize and de-duplicate events to account for browser quirks. This * may be done in the worker thread. * * - Forward these native events (with the associated top-level type used to * trap it) to `EventPluginHub`, which in turn will ask plugins if they want * to extract any synthetic events. * * - The `EventPluginHub` will then process each event by annotating them with * "dispatches", a sequence of listeners and IDs that care about that event. * * - The `EventPluginHub` then dispatches the events. * * Overview of React and the event system: * * +------------+ . * | DOM | . * +------------+ . * | . * v . * +------------+ . * | ReactEvent | . * | Listener | . * +------------+ . +-----------+ * | . +--------+|SimpleEvent| * | . | |Plugin | * +-----|------+ . v +-----------+ * | | | . +--------------+ +------------+ * | +-----------.--->|EventPluginHub| | Event | * | | . | | +-----------+ | Propagators| * | ReactEvent | . | | |TapEvent | |------------| * | Emitter | . | |<---+|Plugin | |other plugin| * | | . | | +-----------+ | utilities | * | +-----------.--->| | +------------+ * | | | . +--------------+ * +-----|------+ . ^ +-----------+ * | . | |Enter/Leave| * + . +-------+|Plugin | * +-------------+ . +-----------+ * | application | . * |-------------| . * | | . * | | . * +-------------+ . * . * React Core . General Purpose Event Plugin System */ var alreadyListeningTo = {}; var isMonitoringScrollValue = false; var reactTopListenersCounter = 0; // For events like 'submit' which don't consistently bubble (which we trap at a // lower node than `document`), binding at `document` would cause duplicate // events so we don't include them here var topEventMapping = { topAbort: 'abort', topBlur: 'blur', topCanPlay: 'canplay', topCanPlayThrough: 'canplaythrough', topChange: 'change', topClick: 'click', topCompositionEnd: 'compositionend', topCompositionStart: 'compositionstart', topCompositionUpdate: 'compositionupdate', topContextMenu: 'contextmenu', topCopy: 'copy', topCut: 'cut', topDoubleClick: 'dblclick', topDrag: 'drag', topDragEnd: 'dragend', topDragEnter: 'dragenter', topDragExit: 'dragexit', topDragLeave: 'dragleave', topDragOver: 'dragover', topDragStart: 'dragstart', topDrop: 'drop', topDurationChange: 'durationchange', topEmptied: 'emptied', topEncrypted: 'encrypted', topEnded: 'ended', topError: 'error', topFocus: 'focus', topInput: 'input', topKeyDown: 'keydown', topKeyPress: 'keypress', topKeyUp: 'keyup', topLoadedData: 'loadeddata', topLoadedMetadata: 'loadedmetadata', topLoadStart: 'loadstart', topMouseDown: 'mousedown', topMouseMove: 'mousemove', topMouseOut: 'mouseout', topMouseOver: 'mouseover', topMouseUp: 'mouseup', topPaste: 'paste', topPause: 'pause', topPlay: 'play', topPlaying: 'playing', topProgress: 'progress', topRateChange: 'ratechange', topScroll: 'scroll', topSeeked: 'seeked', topSeeking: 'seeking', topSelectionChange: 'selectionchange', topStalled: 'stalled', topSuspend: 'suspend', topTextInput: 'textInput', topTimeUpdate: 'timeupdate', topTouchCancel: 'touchcancel', topTouchEnd: 'touchend', topTouchMove: 'touchmove', topTouchStart: 'touchstart', topVolumeChange: 'volumechange', topWaiting: 'waiting', topWheel: 'wheel' }; /** * To ensure no conflicts with other potential React instances on the page */ var topListenersIDKey = '_reactListenersID' + String(Math.random()).slice(2); function getListeningForDocument(mountAt) { // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` // directly. if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListeningTo[mountAt[topListenersIDKey]]; } /** * `ReactBrowserEventEmitter` is used to attach top-level event listeners. For * example: * * ReactBrowserEventEmitter.putListener('myID', 'onClick', myFunction); * * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'. * * @internal */ var ReactBrowserEventEmitter = assign({}, ReactEventEmitterMixin, { /** * Injectable event backend */ ReactEventListener: null, injection: { /** * @param {object} ReactEventListener */ injectReactEventListener: function (ReactEventListener) { ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel); ReactBrowserEventEmitter.ReactEventListener = ReactEventListener; } }, /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function (enabled) { if (ReactBrowserEventEmitter.ReactEventListener) { ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled); } }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function () { return !!(ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled()); }, /** * We listen for bubbled touch events on the document object. * * Firefox v8.01 (and possibly others) exhibited strange behavior when * mounting `onmousemove` events at some node that was not the document * element. The symptoms were that if your mouse is not moving over something * contained within that mount point (for example on the background) the * top-level listeners for `onmousemove` won't be called. However, if you * register the `mousemove` on the document object, then it will of course * catch all `mousemove`s. This along with iOS quirks, justifies restricting * top-level listeners to the document object only, at least for these * movement types of events and possibly all events. * * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html * * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but * they bubble to document. * * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {object} contentDocumentHandle Document which owns the container */ listenTo: function (registrationName, contentDocumentHandle) { var mountAt = contentDocumentHandle; var isListening = getListeningForDocument(mountAt); var dependencies = EventPluginRegistry.registrationNameDependencies[registrationName]; var topLevelTypes = EventConstants.topLevelTypes; for (var i = 0; i < dependencies.length; i++) { var dependency = dependencies[i]; if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) { if (dependency === topLevelTypes.topWheel) { if (isEventSupported('wheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'wheel', mountAt); } else if (isEventSupported('mousewheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'mousewheel', mountAt); } else { // Firefox needs to capture a different mouse scroll event. // @see http://www.quirksmode.org/dom/events/tests/scroll.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'DOMMouseScroll', mountAt); } } else if (dependency === topLevelTypes.topScroll) { if (isEventSupported('scroll', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topScroll, 'scroll', mountAt); } else { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topScroll, 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE); } } else if (dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur) { if (isEventSupported('focus', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topFocus, 'focus', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topBlur, 'blur', mountAt); } else if (isEventSupported('focusin')) { // IE has `focusin` and `focusout` events which bubble. // @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topFocus, 'focusin', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topBlur, 'focusout', mountAt); } // to make sure blur and focus event listeners are only attached once isListening[topLevelTypes.topBlur] = true; isListening[topLevelTypes.topFocus] = true; } else if (topEventMapping.hasOwnProperty(dependency)) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt); } isListening[dependency] = true; } } }, trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle); }, trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle); }, /** * Listens to window scroll and resize events. We cache scroll values so that * application code can access them without triggering reflows. * * NOTE: Scroll events do not bubble. * * @see http://www.quirksmode.org/dom/events/scroll.html */ ensureScrollValueMonitoring: function () { if (!isMonitoringScrollValue) { var refresh = ViewportMetrics.refreshScrollValues; ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh); isMonitoringScrollValue = true; } }, eventNameDispatchConfigs: EventPluginHub.eventNameDispatchConfigs, registrationNameModules: EventPluginHub.registrationNameModules, putListener: EventPluginHub.putListener, getListener: EventPluginHub.getListener, deleteListener: EventPluginHub.deleteListener, deleteAllListeners: EventPluginHub.deleteAllListeners }); ReactPerf.measureMethods(ReactBrowserEventEmitter, 'ReactBrowserEventEmitter', { putListener: 'putListener', deleteListener: 'deleteListener' }); module.exports = ReactBrowserEventEmitter; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventConstants */ 'use strict'; var keyMirror = __webpack_require__(23); var PropagationPhases = keyMirror({ bubbled: null, captured: null }); /** * Types of raw signals from the browser caught at the top level. */ var topLevelTypes = keyMirror({ topAbort: null, topBlur: null, topCanPlay: null, topCanPlayThrough: null, topChange: null, topClick: null, topCompositionEnd: null, topCompositionStart: null, topCompositionUpdate: null, topContextMenu: null, topCopy: null, topCut: null, topDoubleClick: null, topDrag: null, topDragEnd: null, topDragEnter: null, topDragExit: null, topDragLeave: null, topDragOver: null, topDragStart: null, topDrop: null, topDurationChange: null, topEmptied: null, topEncrypted: null, topEnded: null, topError: null, topFocus: null, topInput: null, topKeyDown: null, topKeyPress: null, topKeyUp: null, topLoad: null, topLoadedData: null, topLoadedMetadata: null, topLoadStart: null, topMouseDown: null, topMouseMove: null, topMouseOut: null, topMouseOver: null, topMouseUp: null, topPaste: null, topPause: null, topPlay: null, topPlaying: null, topProgress: null, topRateChange: null, topReset: null, topScroll: null, topSeeked: null, topSeeking: null, topSelectionChange: null, topStalled: null, topSubmit: null, topSuspend: null, topTextInput: null, topTimeUpdate: null, topTouchCancel: null, topTouchEnd: null, topTouchMove: null, topTouchStart: null, topVolumeChange: null, topWaiting: null, topWheel: null }); var EventConstants = { topLevelTypes: topLevelTypes, PropagationPhases: PropagationPhases }; module.exports = EventConstants; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginHub */ 'use strict'; var EventPluginRegistry = __webpack_require__(38); var EventPluginUtils = __webpack_require__(39); var ReactErrorUtils = __webpack_require__(40); var accumulateInto = __webpack_require__(41); var forEachAccumulated = __webpack_require__(42); var invariant = __webpack_require__(19); var warning = __webpack_require__(31); /** * Internal store for event listeners */ var listenerBank = {}; /** * Internal queue of events that have accumulated their dispatches and are * waiting to have their dispatches executed. */ var eventQueue = null; /** * Dispatches an event and releases it back into the pool, unless persistent. * * @param {?object} event Synthetic event to be dispatched. * @param {boolean} simulated If the event is simulated (changes exn behavior) * @private */ var executeDispatchesAndRelease = function (event, simulated) { if (event) { EventPluginUtils.executeDispatchesInOrder(event, simulated); if (!event.isPersistent()) { event.constructor.release(event); } } }; var executeDispatchesAndReleaseSimulated = function (e) { return executeDispatchesAndRelease(e, true); }; var executeDispatchesAndReleaseTopLevel = function (e) { return executeDispatchesAndRelease(e, false); }; /** * - `InstanceHandle`: [required] Module that performs logical traversals of DOM * hierarchy given ids of the logical DOM elements involved. */ var InstanceHandle = null; function validateInstanceHandle() { var valid = InstanceHandle && InstanceHandle.traverseTwoPhase && InstanceHandle.traverseEnterLeave; process.env.NODE_ENV !== 'production' ? warning(valid, 'InstanceHandle not injected before use!') : undefined; } /** * This is a unified interface for event plugins to be installed and configured. * * Event plugins can implement the following properties: * * `extractEvents` {function(string, DOMEventTarget, string, object): *} * Required. When a top-level event is fired, this method is expected to * extract synthetic events that will in turn be queued and dispatched. * * `eventTypes` {object} * Optional, plugins that fire events must publish a mapping of registration * names that are used to register listeners. Values of this mapping must * be objects that contain `registrationName` or `phasedRegistrationNames`. * * `executeDispatch` {function(object, function, string)} * Optional, allows plugins to override how an event gets dispatched. By * default, the listener is simply invoked. * * Each plugin that is injected into `EventsPluginHub` is immediately operable. * * @public */ var EventPluginHub = { /** * Methods for injecting dependencies. */ injection: { /** * @param {object} InjectedMount * @public */ injectMount: EventPluginUtils.injection.injectMount, /** * @param {object} InjectedInstanceHandle * @public */ injectInstanceHandle: function (InjectedInstanceHandle) { InstanceHandle = InjectedInstanceHandle; if (process.env.NODE_ENV !== 'production') { validateInstanceHandle(); } }, getInstanceHandle: function () { if (process.env.NODE_ENV !== 'production') { validateInstanceHandle(); } return InstanceHandle; }, /** * @param {array} InjectedEventPluginOrder * @public */ injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder, /** * @param {object} injectedNamesToPlugins Map from names to plugin modules. */ injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName }, eventNameDispatchConfigs: EventPluginRegistry.eventNameDispatchConfigs, registrationNameModules: EventPluginRegistry.registrationNameModules, /** * Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent. * * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {?function} listener The callback to store. */ putListener: function (id, registrationName, listener) { !(typeof listener === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : invariant(false) : undefined; var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {}); bankForRegistrationName[id] = listener; var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.didPutListener) { PluginModule.didPutListener(id, registrationName, listener); } }, /** * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ getListener: function (id, registrationName) { var bankForRegistrationName = listenerBank[registrationName]; return bankForRegistrationName && bankForRegistrationName[id]; }, /** * Deletes a listener from the registration bank. * * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). */ deleteListener: function (id, registrationName) { var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(id, registrationName); } var bankForRegistrationName = listenerBank[registrationName]; // TODO: This should never be null -- when is it? if (bankForRegistrationName) { delete bankForRegistrationName[id]; } }, /** * Deletes all listeners for the DOM element with the supplied ID. * * @param {string} id ID of the DOM element. */ deleteAllListeners: function (id) { for (var registrationName in listenerBank) { if (!listenerBank[registrationName][id]) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(id, registrationName); } delete listenerBank[registrationName][id]; } }, /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. * * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @internal */ extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { var events; var plugins = EventPluginRegistry.plugins; for (var i = 0; i < plugins.length; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget); if (extractedEvents) { events = accumulateInto(events, extractedEvents); } } } return events; }, /** * Enqueues a synthetic event that should be dispatched when * `processEventQueue` is invoked. * * @param {*} events An accumulation of synthetic events. * @internal */ enqueueEvents: function (events) { if (events) { eventQueue = accumulateInto(eventQueue, events); } }, /** * Dispatches all synthetic events on the event queue. * * @internal */ processEventQueue: function (simulated) { // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. var processingEventQueue = eventQueue; eventQueue = null; if (simulated) { forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated); } else { forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); } !!eventQueue ? process.env.NODE_ENV !== 'production' ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing ' + 'an event queue. Support for this has not yet been implemented.') : invariant(false) : undefined; // This would be a good time to rethrow if any of the event handlers threw. ReactErrorUtils.rethrowCaughtError(); }, /** * These are needed for tests only. Do not use! */ __purge: function () { listenerBank = {}; }, __getListenerBank: function () { return listenerBank; } }; module.exports = EventPluginHub; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginRegistry * @typechecks static-only */ 'use strict'; var invariant = __webpack_require__(19); /** * Injectable ordering of event plugins. */ var EventPluginOrder = null; /** * Injectable mapping from names to event plugin modules. */ var namesToPlugins = {}; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ function recomputePluginOrdering() { if (!EventPluginOrder) { // Wait until an `EventPluginOrder` is injected. return; } for (var pluginName in namesToPlugins) { var PluginModule = namesToPlugins[pluginName]; var pluginIndex = EventPluginOrder.indexOf(pluginName); !(pluginIndex > -1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in ' + 'the plugin ordering, `%s`.', pluginName) : invariant(false) : undefined; if (EventPluginRegistry.plugins[pluginIndex]) { continue; } !PluginModule.extractEvents ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `%s` does not.', pluginName) : invariant(false) : undefined; EventPluginRegistry.plugins[pluginIndex] = PluginModule; var publishedEvents = PluginModule.eventTypes; for (var eventName in publishedEvents) { !publishEventForPlugin(publishedEvents[eventName], PluginModule, eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : invariant(false) : undefined; } } } /** * Publishes an event so that it can be dispatched by the supplied plugin. * * @param {object} dispatchConfig Dispatch configuration for the event. * @param {object} PluginModule Plugin publishing the event. * @return {boolean} True if the event was successfully published. * @private */ function publishEventForPlugin(dispatchConfig, PluginModule, eventName) { !!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', eventName) : invariant(false) : undefined; EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { var phasedRegistrationName = phasedRegistrationNames[phaseName]; publishRegistrationName(phasedRegistrationName, PluginModule, eventName); } } return true; } else if (dispatchConfig.registrationName) { publishRegistrationName(dispatchConfig.registrationName, PluginModule, eventName); return true; } return false; } /** * Publishes a registration name that is used to identify dispatched events and * can be used with `EventPluginHub.putListener` to register listeners. * * @param {string} registrationName Registration name to add. * @param {object} PluginModule Plugin publishing the event. * @private */ function publishRegistrationName(registrationName, PluginModule, eventName) { !!EventPluginRegistry.registrationNameModules[registrationName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName) : invariant(false) : undefined; EventPluginRegistry.registrationNameModules[registrationName] = PluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies; } /** * Registers plugins so that they can extract and dispatch events. * * @see {EventPluginHub} */ var EventPluginRegistry = { /** * Ordered list of injected plugins. */ plugins: [], /** * Mapping from event name to dispatch config */ eventNameDispatchConfigs: {}, /** * Mapping from registration name to plugin module */ registrationNameModules: {}, /** * Mapping from registration name to event name */ registrationNameDependencies: {}, /** * Injects an ordering of plugins (by plugin name). This allows the ordering * to be decoupled from injection of the actual plugins so that ordering is * always deterministic regardless of packaging, on-the-fly injection, etc. * * @param {array} InjectedEventPluginOrder * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ injectEventPluginOrder: function (InjectedEventPluginOrder) { !!EventPluginOrder ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than ' + 'once. You are likely trying to load more than one copy of React.') : invariant(false) : undefined; // Clone the ordering so it cannot be dynamically mutated. EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder); recomputePluginOrdering(); }, /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. * * Plugins can be injected as part of page initialization or on-the-fly. * * @param {object} injectedNamesToPlugins Map from names to plugin modules. * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ injectEventPluginsByName: function (injectedNamesToPlugins) { var isOrderingDirty = false; for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } var PluginModule = injectedNamesToPlugins[pluginName]; if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== PluginModule) { !!namesToPlugins[pluginName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins ' + 'using the same name, `%s`.', pluginName) : invariant(false) : undefined; namesToPlugins[pluginName] = PluginModule; isOrderingDirty = true; } } if (isOrderingDirty) { recomputePluginOrdering(); } }, /** * Looks up the plugin for the supplied event. * * @param {object} event A synthetic event. * @return {?object} The plugin that created the supplied event. * @internal */ getPluginModuleForEvent: function (event) { var dispatchConfig = event.dispatchConfig; if (dispatchConfig.registrationName) { return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null; } for (var phase in dispatchConfig.phasedRegistrationNames) { if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[dispatchConfig.phasedRegistrationNames[phase]]; if (PluginModule) { return PluginModule; } } return null; }, /** * Exposed for unit testing. * @private */ _resetEventPlugins: function () { EventPluginOrder = null; for (var pluginName in namesToPlugins) { if (namesToPlugins.hasOwnProperty(pluginName)) { delete namesToPlugins[pluginName]; } } EventPluginRegistry.plugins.length = 0; var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs; for (var eventName in eventNameDispatchConfigs) { if (eventNameDispatchConfigs.hasOwnProperty(eventName)) { delete eventNameDispatchConfigs[eventName]; } } var registrationNameModules = EventPluginRegistry.registrationNameModules; for (var registrationName in registrationNameModules) { if (registrationNameModules.hasOwnProperty(registrationName)) { delete registrationNameModules[registrationName]; } } } }; module.exports = EventPluginRegistry; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginUtils */ 'use strict'; var EventConstants = __webpack_require__(36); var ReactErrorUtils = __webpack_require__(40); var invariant = __webpack_require__(19); var warning = __webpack_require__(31); /** * Injected dependencies: */ /** * - `Mount`: [required] Module that can convert between React dom IDs and * actual node references. */ var injection = { Mount: null, injectMount: function (InjectedMount) { injection.Mount = InjectedMount; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(InjectedMount && InjectedMount.getNode && InjectedMount.getID, 'EventPluginUtils.injection.injectMount(...): Injected Mount ' + 'module is missing getNode or getID.') : undefined; } } }; var topLevelTypes = EventConstants.topLevelTypes; function isEndish(topLevelType) { return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel; } function isMoveish(topLevelType) { return topLevelType === topLevelTypes.topMouseMove || topLevelType === topLevelTypes.topTouchMove; } function isStartish(topLevelType) { return topLevelType === topLevelTypes.topMouseDown || topLevelType === topLevelTypes.topTouchStart; } var validateEventDispatches; if (process.env.NODE_ENV !== 'production') { validateEventDispatches = function (event) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; var listenersIsArr = Array.isArray(dispatchListeners); var idsIsArr = Array.isArray(dispatchIDs); var IDsLen = idsIsArr ? dispatchIDs.length : dispatchIDs ? 1 : 0; var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; process.env.NODE_ENV !== 'production' ? warning(idsIsArr === listenersIsArr && IDsLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : undefined; }; } /** * Dispatch the event to the listener. * @param {SyntheticEvent} event SyntheticEvent to handle * @param {boolean} simulated If the event is simulated (changes exn behavior) * @param {function} listener Application-level callback * @param {string} domID DOM id to pass to the callback. */ function executeDispatch(event, simulated, listener, domID) { var type = event.type || 'unknown-event'; event.currentTarget = injection.Mount.getNode(domID); if (simulated) { ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event, domID); } else { ReactErrorUtils.invokeGuardedCallback(type, listener, event, domID); } event.currentTarget = null; } /** * Standard/simple iteration through an event's collected dispatches. */ function executeDispatchesInOrder(event, simulated) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; if (process.env.NODE_ENV !== 'production') { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and IDs are two parallel arrays that are always in sync. executeDispatch(event, simulated, dispatchListeners[i], dispatchIDs[i]); } } else if (dispatchListeners) { executeDispatch(event, simulated, dispatchListeners, dispatchIDs); } event._dispatchListeners = null; event._dispatchIDs = null; } /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. * * @return {?string} id of the first dispatch execution who's listener returns * true, or null if no listener returned true. */ function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; if (process.env.NODE_ENV !== 'production') { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and IDs are two parallel arrays that are always in sync. if (dispatchListeners[i](event, dispatchIDs[i])) { return dispatchIDs[i]; } } } else if (dispatchListeners) { if (dispatchListeners(event, dispatchIDs)) { return dispatchIDs; } } return null; } /** * @see executeDispatchesInOrderStopAtTrueImpl */ function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchIDs = null; event._dispatchListeners = null; return ret; } /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make * sense for an event with multiple dispatches (bubbled) to keep track of the * return values at each dispatch execution, but it does tend to make sense when * dealing with "direct" dispatches. * * @return {*} The return value of executing the single dispatch. */ function executeDirectDispatch(event) { if (process.env.NODE_ENV !== 'production') { validateEventDispatches(event); } var dispatchListener = event._dispatchListeners; var dispatchID = event._dispatchIDs; !!Array.isArray(dispatchListener) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : invariant(false) : undefined; var res = dispatchListener ? dispatchListener(event, dispatchID) : null; event._dispatchListeners = null; event._dispatchIDs = null; return res; } /** * @param {SyntheticEvent} event * @return {boolean} True iff number of dispatches accumulated is greater than 0. */ function hasDispatches(event) { return !!event._dispatchListeners; } /** * General utilities that are useful in creating custom Event Plugins. */ var EventPluginUtils = { isEndish: isEndish, isMoveish: isMoveish, isStartish: isStartish, executeDirectDispatch: executeDirectDispatch, executeDispatchesInOrder: executeDispatchesInOrder, executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, hasDispatches: hasDispatches, getNode: function (id) { return injection.Mount.getNode(id); }, getID: function (node) { return injection.Mount.getID(node); }, injection: injection }; module.exports = EventPluginUtils; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactErrorUtils * @typechecks */ 'use strict'; var caughtError = null; /** * Call a function while guarding against errors that happens within it. * * @param {?String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} a First argument * @param {*} b Second argument */ function invokeGuardedCallback(name, func, a, b) { try { return func(a, b); } catch (x) { if (caughtError === null) { caughtError = x; } return undefined; } } var ReactErrorUtils = { invokeGuardedCallback: invokeGuardedCallback, /** * Invoked by ReactTestUtils.Simulate so that any errors thrown by the event * handler are sure to be rethrown by rethrowCaughtError. */ invokeGuardedCallbackWithCatch: invokeGuardedCallback, /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ rethrowCaughtError: function () { if (caughtError) { var error = caughtError; caughtError = null; throw error; } } }; if (process.env.NODE_ENV !== 'production') { /** * To help development we can get better devtools integration by simulating a * real browser event. */ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { var fakeNode = document.createElement('react'); ReactErrorUtils.invokeGuardedCallback = function (name, func, a, b) { var boundFunc = func.bind(null, a, b); var evtType = 'react-' + name; fakeNode.addEventListener(evtType, boundFunc, false); var evt = document.createEvent('Event'); evt.initEvent(evtType, false, false); fakeNode.dispatchEvent(evt); fakeNode.removeEventListener(evtType, boundFunc, false); }; } } module.exports = ReactErrorUtils; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule accumulateInto */ 'use strict'; var invariant = __webpack_require__(19); /** * * Accumulates items that must not be null or undefined into the first one. This * is used to conserve memory by avoiding array allocations, and thus sacrifices * API cleanness. Since `current` can be null before being passed in and not * null after this function, make sure to assign it back to `current`: * * `a = accumulateInto(a, b);` * * This API should be sparingly used. Try `accumulate` for something cleaner. * * @return {*|array<*>} An accumulation of items. */ function accumulateInto(current, next) { !(next != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : invariant(false) : undefined; if (current == null) { return next; } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). var currentIsArray = Array.isArray(current); var nextIsArray = Array.isArray(next); if (currentIsArray && nextIsArray) { current.push.apply(current, next); return current; } if (currentIsArray) { current.push(next); return current; } if (nextIsArray) { // A bit too dangerous to mutate `next`. return [current].concat(next); } return [current, next]; } module.exports = accumulateInto; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 42 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule forEachAccumulated */ 'use strict'; /** * @param {array} arr an "accumulation" of items which is either an Array or * a single item. Useful when paired with the `accumulate` module. This is a * simple utility that allows us to reason about a collection of items, but * handling the case when there is exactly one item (and we do not need to * allocate an array). */ var forEachAccumulated = function (arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } }; module.exports = forEachAccumulated; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEventEmitterMixin */ 'use strict'; var EventPluginHub = __webpack_require__(37); function runEventQueueInBatch(events) { EventPluginHub.enqueueEvents(events); EventPluginHub.processEventQueue(false); } var ReactEventEmitterMixin = { /** * Streams a fired top-level event to `EventPluginHub` where plugins have the * opportunity to create `ReactEvent`s to be dispatched. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native environment event. */ handleTopLevel: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { var events = EventPluginHub.extractEvents(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget); runEventQueueInBatch(events); } }; module.exports = ReactEventEmitterMixin; /***/ }, /* 44 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ViewportMetrics */ 'use strict'; var ViewportMetrics = { currentScrollLeft: 0, currentScrollTop: 0, refreshScrollValues: function (scrollPosition) { ViewportMetrics.currentScrollLeft = scrollPosition.x; ViewportMetrics.currentScrollTop = scrollPosition.y; } }; module.exports = ViewportMetrics; /***/ }, /* 45 */ /***/ function(module, exports) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Object.assign */ // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign 'use strict'; function assign(target, sources) { if (target == null) { throw new TypeError('Object.assign target cannot be null or undefined'); } var to = Object(target); var hasOwnProperty = Object.prototype.hasOwnProperty; for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) { var nextSource = arguments[nextIndex]; if (nextSource == null) { continue; } var from = Object(nextSource); // We don't currently support accessors nor proxies. Therefore this // copy cannot throw. If we ever supported this then we must handle // exceptions and side-effects. We don't support symbols so they won't // be transferred. for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } } return to; } module.exports = assign; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isEventSupported */ 'use strict'; var ExecutionEnvironment = __webpack_require__(15); var useHasFeature; if (ExecutionEnvironment.canUseDOM) { useHasFeature = document.implementation && document.implementation.hasFeature && // always returns true in newer browsers as per the standard. // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature document.implementation.hasFeature('', '') !== true; } /** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @param {?boolean} capture Check if the capture phase is supported. * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function isEventSupported(eventNameSuffix, capture) { if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) { return false; } var eventName = 'on' + eventNameSuffix; var isSupported = (eventName in document); if (!isSupported) { var element = document.createElement('div'); element.setAttribute(eventName, 'return;'); isSupported = typeof element[eventName] === 'function'; } if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') { // This is the only way to test support for the `wheel` event in IE9+. isSupported = document.implementation.hasFeature('Events.wheel', '3.0'); } return isSupported; } module.exports = isEventSupported; /***/ }, /* 47 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMFeatureFlags */ 'use strict'; var ReactDOMFeatureFlags = { useCreateElement: false }; module.exports = ReactDOMFeatureFlags; /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElement */ 'use strict'; var ReactCurrentOwner = __webpack_require__(11); var assign = __webpack_require__(45); var canDefineProperty = __webpack_require__(49); // The Symbol used to tag the ReactElement type. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; /** * Base constructor for all React elements. This is only used to make this * work with a dynamic instanceof check. Nothing should live on this prototype. * * @param {*} type * @param {*} key * @param {string|object} ref * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @param {*} owner * @param {*} props * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allow us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; if (process.env.NODE_ENV !== 'production') { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. if (canDefineProperty) { Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); } else { element._store.validated = false; element._self = self; element._source = source; } Object.freeze(element.props); Object.freeze(element); } return element; }; ReactElement.createElement = function (type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; var self = null; var source = null; if (config != null) { ref = config.ref === undefined ? null : config.ref; key = config.key === undefined ? null : '' + config.key; self = config.__self === undefined ? null : config.__self; source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (typeof props[propName] === 'undefined') { props[propName] = defaultProps[propName]; } } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); }; ReactElement.createFactory = function (type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. `<Foo />.type === Foo`. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. // Legacy hook TODO: Warn if this is accessed factory.type = type; return factory; }; ReactElement.cloneAndReplaceKey = function (oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; }; ReactElement.cloneAndReplaceProps = function (oldElement, newProps) { var newElement = ReactElement(oldElement.type, oldElement.key, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, newProps); if (process.env.NODE_ENV !== 'production') { // If the key on the original is valid, then the clone is valid newElement._store.validated = oldElement._store.validated; } return newElement; }; ReactElement.cloneElement = function (element, config, children) { var propName; // Original props are copied var props = assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Self is preserved since the owner is preserved. var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element._source; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (config.ref !== undefined) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (config.key !== undefined) { key = '' + config.key; } // Remaining properties override existing props for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return ReactElement(element.type, key, ref, self, source, owner, props); }; /** * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function (object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; module.exports = ReactElement; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule canDefineProperty */ 'use strict'; var canDefineProperty = false; if (process.env.NODE_ENV !== 'production') { try { Object.defineProperty({}, 'x', { get: function () {} }); canDefineProperty = true; } catch (x) { // IE will fail on defineProperty } } module.exports = canDefineProperty; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 50 */ /***/ function(module, exports) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEmptyComponentRegistry */ 'use strict'; // This registry keeps track of the React IDs of the components that rendered to // `null` (in reality a placeholder such as `noscript`) var nullComponentIDsRegistry = {}; /** * @param {string} id Component's `_rootNodeID`. * @return {boolean} True if the component is rendered to null. */ function isNullComponentID(id) { return !!nullComponentIDsRegistry[id]; } /** * Mark the component as having rendered to null. * @param {string} id Component's `_rootNodeID`. */ function registerNullComponentID(id) { nullComponentIDsRegistry[id] = true; } /** * Unmark the component as having rendered to null: it renders to something now. * @param {string} id Component's `_rootNodeID`. */ function deregisterNullComponentID(id) { delete nullComponentIDsRegistry[id]; } var ReactEmptyComponentRegistry = { isNullComponentID: isNullComponentID, registerNullComponentID: registerNullComponentID, deregisterNullComponentID: deregisterNullComponentID }; module.exports = ReactEmptyComponentRegistry; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInstanceHandles * @typechecks static-only */ 'use strict'; var ReactRootIndex = __webpack_require__(52); var invariant = __webpack_require__(19); var SEPARATOR = '.'; var SEPARATOR_LENGTH = SEPARATOR.length; /** * Maximum depth of traversals before we consider the possibility of a bad ID. */ var MAX_TREE_DEPTH = 10000; /** * Creates a DOM ID prefix to use when mounting React components. * * @param {number} index A unique integer * @return {string} React root ID. * @internal */ function getReactRootIDString(index) { return SEPARATOR + index.toString(36); } /** * Checks if a character in the supplied ID is a separator or the end. * * @param {string} id A React DOM ID. * @param {number} index Index of the character to check. * @return {boolean} True if the character is a separator or end of the ID. * @private */ function isBoundary(id, index) { return id.charAt(index) === SEPARATOR || index === id.length; } /** * Checks if the supplied string is a valid React DOM ID. * * @param {string} id A React DOM ID, maybe. * @return {boolean} True if the string is a valid React DOM ID. * @private */ function isValidID(id) { return id === '' || id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR; } /** * Checks if the first ID is an ancestor of or equal to the second ID. * * @param {string} ancestorID * @param {string} descendantID * @return {boolean} True if `ancestorID` is an ancestor of `descendantID`. * @internal */ function isAncestorIDOf(ancestorID, descendantID) { return descendantID.indexOf(ancestorID) === 0 && isBoundary(descendantID, ancestorID.length); } /** * Gets the parent ID of the supplied React DOM ID, `id`. * * @param {string} id ID of a component. * @return {string} ID of the parent, or an empty string. * @private */ function getParentID(id) { return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : ''; } /** * Gets the next DOM ID on the tree path from the supplied `ancestorID` to the * supplied `destinationID`. If they are equal, the ID is returned. * * @param {string} ancestorID ID of an ancestor node of `destinationID`. * @param {string} destinationID ID of the destination node. * @return {string} Next ID on the path from `ancestorID` to `destinationID`. * @private */ function getNextDescendantID(ancestorID, destinationID) { !(isValidID(ancestorID) && isValidID(destinationID)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNextDescendantID(%s, %s): Received an invalid React DOM ID.', ancestorID, destinationID) : invariant(false) : undefined; !isAncestorIDOf(ancestorID, destinationID) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNextDescendantID(...): React has made an invalid assumption about ' + 'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.', ancestorID, destinationID) : invariant(false) : undefined; if (ancestorID === destinationID) { return ancestorID; } // Skip over the ancestor and the immediate separator. Traverse until we hit // another separator or we reach the end of `destinationID`. var start = ancestorID.length + SEPARATOR_LENGTH; var i; for (i = start; i < destinationID.length; i++) { if (isBoundary(destinationID, i)) { break; } } return destinationID.substr(0, i); } /** * Gets the nearest common ancestor ID of two IDs. * * Using this ID scheme, the nearest common ancestor ID is the longest common * prefix of the two IDs that immediately preceded a "marker" in both strings. * * @param {string} oneID * @param {string} twoID * @return {string} Nearest common ancestor ID, or the empty string if none. * @private */ function getFirstCommonAncestorID(oneID, twoID) { var minLength = Math.min(oneID.length, twoID.length); if (minLength === 0) { return ''; } var lastCommonMarkerIndex = 0; // Use `<=` to traverse until the "EOL" of the shorter string. for (var i = 0; i <= minLength; i++) { if (isBoundary(oneID, i) && isBoundary(twoID, i)) { lastCommonMarkerIndex = i; } else if (oneID.charAt(i) !== twoID.charAt(i)) { break; } } var longestCommonID = oneID.substr(0, lastCommonMarkerIndex); !isValidID(longestCommonID) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s', oneID, twoID, longestCommonID) : invariant(false) : undefined; return longestCommonID; } /** * Traverses the parent path between two IDs (either up or down). The IDs must * not be the same, and there must exist a parent path between them. If the * callback returns `false`, traversal is stopped. * * @param {?string} start ID at which to start traversal. * @param {?string} stop ID at which to end traversal. * @param {function} cb Callback to invoke each ID with. * @param {*} arg Argument to invoke the callback with. * @param {?boolean} skipFirst Whether or not to skip the first node. * @param {?boolean} skipLast Whether or not to skip the last node. * @private */ function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) { start = start || ''; stop = stop || ''; !(start !== stop) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.', start) : invariant(false) : undefined; var traverseUp = isAncestorIDOf(stop, start); !(traverseUp || isAncestorIDOf(start, stop)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' + 'not have a parent path.', start, stop) : invariant(false) : undefined; // Traverse from `start` to `stop` one depth at a time. var depth = 0; var traverse = traverseUp ? getParentID : getNextDescendantID; for (var id = start;; /* until break */id = traverse(id, stop)) { var ret; if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) { ret = cb(id, traverseUp, arg); } if (ret === false || id === stop) { // Only break //after// visiting `stop`. break; } !(depth++ < MAX_TREE_DEPTH) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' + 'traversing the React DOM ID tree. This may be due to malformed IDs: %s', start, stop, id) : invariant(false) : undefined; } } /** * Manages the IDs assigned to DOM representations of React components. This * uses a specific scheme in order to traverse the DOM efficiently (e.g. in * order to simulate events). * * @internal */ var ReactInstanceHandles = { /** * Constructs a React root ID * @return {string} A React root ID. */ createReactRootID: function () { return getReactRootIDString(ReactRootIndex.createReactRootIndex()); }, /** * Constructs a React ID by joining a root ID with a name. * * @param {string} rootID Root ID of a parent component. * @param {string} name A component's name (as flattened children). * @return {string} A React ID. * @internal */ createReactID: function (rootID, name) { return rootID + name; }, /** * Gets the DOM ID of the React component that is the root of the tree that * contains the React component with the supplied DOM ID. * * @param {string} id DOM ID of a React component. * @return {?string} DOM ID of the React component that is the root. * @internal */ getReactRootIDFromNodeID: function (id) { if (id && id.charAt(0) === SEPARATOR && id.length > 1) { var index = id.indexOf(SEPARATOR, 1); return index > -1 ? id.substr(0, index) : id; } return null; }, /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. * * NOTE: Does not invoke the callback on the nearest common ancestor because * nothing "entered" or "left" that element. * * @param {string} leaveID ID being left. * @param {string} enterID ID being entered. * @param {function} cb Callback to invoke on each entered/left ID. * @param {*} upArg Argument to invoke the callback with on left IDs. * @param {*} downArg Argument to invoke the callback with on entered IDs. * @internal */ traverseEnterLeave: function (leaveID, enterID, cb, upArg, downArg) { var ancestorID = getFirstCommonAncestorID(leaveID, enterID); if (ancestorID !== leaveID) { traverseParentPath(leaveID, ancestorID, cb, upArg, false, true); } if (ancestorID !== enterID) { traverseParentPath(ancestorID, enterID, cb, downArg, true, false); } }, /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. * * NOTE: This traversal happens on IDs without touching the DOM. * * @param {string} targetID ID of the target node. * @param {function} cb Callback to invoke. * @param {*} arg Argument to invoke the callback with. * @internal */ traverseTwoPhase: function (targetID, cb, arg) { if (targetID) { traverseParentPath('', targetID, cb, arg, true, false); traverseParentPath(targetID, '', cb, arg, false, true); } }, /** * Same as `traverseTwoPhase` but skips the `targetID`. */ traverseTwoPhaseSkipTarget: function (targetID, cb, arg) { if (targetID) { traverseParentPath('', targetID, cb, arg, true, true); traverseParentPath(targetID, '', cb, arg, true, true); } }, /** * Traverse a node ID, calling the supplied `cb` for each ancestor ID. For * example, passing `.0.$row-0.1` would result in `cb` getting called * with `.0`, `.0.$row-0`, and `.0.$row-0.1`. * * NOTE: This traversal happens on IDs without touching the DOM. * * @param {string} targetID ID of the target node. * @param {function} cb Callback to invoke. * @param {*} arg Argument to invoke the callback with. * @internal */ traverseAncestors: function (targetID, cb, arg) { traverseParentPath('', targetID, cb, arg, true, false); }, getFirstCommonAncestorID: getFirstCommonAncestorID, /** * Exposed for unit testing. * @private */ _getNextDescendantID: getNextDescendantID, isAncestorIDOf: isAncestorIDOf, SEPARATOR: SEPARATOR }; module.exports = ReactInstanceHandles; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 52 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactRootIndex * @typechecks */ 'use strict'; var ReactRootIndexInjection = { /** * @param {function} _createReactRootIndex */ injectCreateReactRootIndex: function (_createReactRootIndex) { ReactRootIndex.createReactRootIndex = _createReactRootIndex; } }; var ReactRootIndex = { createReactRootIndex: null, injection: ReactRootIndexInjection }; module.exports = ReactRootIndex; /***/ }, /* 53 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInstanceMap */ 'use strict'; /** * `ReactInstanceMap` maintains a mapping from a public facing stateful * instance (key) and the internal representation (value). This allows public * methods to accept the user facing instance as an argument and map them back * to internal methods. */ // TODO: Replace this with ES6: var ReactInstanceMap = new Map(); var ReactInstanceMap = { /** * This API should be called `delete` but we'd have to make sure to always * transform these to strings for IE support. When this transform is fully * supported we can rename it. */ remove: function (key) { key._reactInternalInstance = undefined; }, get: function (key) { return key._reactInternalInstance; }, has: function (key) { return key._reactInternalInstance !== undefined; }, set: function (key, value) { key._reactInternalInstance = value; } }; module.exports = ReactInstanceMap; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMarkupChecksum */ 'use strict'; var adler32 = __webpack_require__(55); var TAG_END = /\/?>/; var ReactMarkupChecksum = { CHECKSUM_ATTR_NAME: 'data-react-checksum', /** * @param {string} markup Markup string * @return {string} Markup string with checksum attribute attached */ addChecksumToMarkup: function (markup) { var checksum = adler32(markup); // Add checksum (handle both parent tags and self-closing tags) return markup.replace(TAG_END, ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&'); }, /** * @param {string} markup to use * @param {DOMElement} element root React element * @returns {boolean} whether or not the markup is the same */ canReuseMarkup: function (markup, element) { var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); existingChecksum = existingChecksum && parseInt(existingChecksum, 10); var markupChecksum = adler32(markup); return markupChecksum === existingChecksum; } }; module.exports = ReactMarkupChecksum; /***/ }, /* 55 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule adler32 */ 'use strict'; var MOD = 65521; // adler32 is not cryptographically strong, and is only used to sanity check that // markup generated on the server matches the markup generated on the client. // This implementation (a modified version of the SheetJS version) has been optimized // for our use case, at the expense of conforming to the adler32 specification // for non-ascii inputs. function adler32(data) { var a = 1; var b = 0; var i = 0; var l = data.length; var m = l & ~0x3; while (i < m) { for (; i < Math.min(i + 4096, m); i += 4) { b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3)); } a %= MOD; b %= MOD; } for (; i < l; i++) { b += a += data.charCodeAt(i); } a %= MOD; b %= MOD; return a | b << 16; } module.exports = adler32; /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactReconciler */ 'use strict'; var ReactRef = __webpack_require__(57); /** * Helper to call ReactRef.attachRefs with this composite component, split out * to avoid allocations in the transaction mount-ready queue. */ function attachRefs() { ReactRef.attachRefs(this, this._currentElement); } var ReactReconciler = { /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactComponent} internalInstance * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (internalInstance, rootID, transaction, context) { var markup = internalInstance.mountComponent(rootID, transaction, context); if (internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } return markup; }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function (internalInstance) { ReactRef.detachRefs(internalInstance, internalInstance._currentElement); internalInstance.unmountComponent(); }, /** * Update a component using a new element. * * @param {ReactComponent} internalInstance * @param {ReactElement} nextElement * @param {ReactReconcileTransaction} transaction * @param {object} context * @internal */ receiveComponent: function (internalInstance, nextElement, transaction, context) { var prevElement = internalInstance._currentElement; if (nextElement === prevElement && context === internalInstance._context) { // Since elements are immutable after the owner is rendered, // we can do a cheap identity compare here to determine if this is a // superfluous reconcile. It's possible for state to be mutable but such // change should trigger an update of the owner which would recreate // the element. We explicitly check for the existence of an owner since // it's possible for an element created outside a composite to be // deeply mutated and reused. // TODO: Bailing out early is just a perf optimization right? // TODO: Removing the return statement should affect correctness? return; } var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement); if (refsChanged) { ReactRef.detachRefs(internalInstance, prevElement); } internalInstance.receiveComponent(nextElement, transaction, context); if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } }, /** * Flush any dirty changes in a component. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (internalInstance, transaction) { internalInstance.performUpdateIfNecessary(transaction); } }; module.exports = ReactReconciler; /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactRef */ 'use strict'; var ReactOwner = __webpack_require__(58); var ReactRef = {}; function attachRef(ref, component, owner) { if (typeof ref === 'function') { ref(component.getPublicInstance()); } else { // Legacy ref ReactOwner.addComponentAsRefTo(component, ref, owner); } } function detachRef(ref, component, owner) { if (typeof ref === 'function') { ref(null); } else { // Legacy ref ReactOwner.removeComponentAsRefFrom(component, ref, owner); } } ReactRef.attachRefs = function (instance, element) { if (element === null || element === false) { return; } var ref = element.ref; if (ref != null) { attachRef(ref, instance, element._owner); } }; ReactRef.shouldUpdateRefs = function (prevElement, nextElement) { // If either the owner or a `ref` has changed, make sure the newest owner // has stored a reference to `this`, and the previous owner (if different) // has forgotten the reference to `this`. We use the element instead // of the public this.props because the post processing cannot determine // a ref. The ref conceptually lives on the element. // TODO: Should this even be possible? The owner cannot change because // it's forbidden by shouldUpdateReactComponent. The ref can change // if you swap the keys of but not the refs. Reconsider where this check // is made. It probably belongs where the key checking and // instantiateReactComponent is done. var prevEmpty = prevElement === null || prevElement === false; var nextEmpty = nextElement === null || nextElement === false; return( // This has a few false positives w/r/t empty components. prevEmpty || nextEmpty || nextElement._owner !== prevElement._owner || nextElement.ref !== prevElement.ref ); }; ReactRef.detachRefs = function (instance, element) { if (element === null || element === false) { return; } var ref = element.ref; if (ref != null) { detachRef(ref, instance, element._owner); } }; module.exports = ReactRef; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactOwner */ 'use strict'; var invariant = __webpack_require__(19); /** * ReactOwners are capable of storing references to owned components. * * All components are capable of //being// referenced by owner components, but * only ReactOwner components are capable of //referencing// owned components. * The named reference is known as a "ref". * * Refs are available when mounted and updated during reconciliation. * * var MyComponent = React.createClass({ * render: function() { * return ( * <div onClick={this.handleClick}> * <CustomComponent ref="custom" /> * </div> * ); * }, * handleClick: function() { * this.refs.custom.handleClick(); * }, * componentDidMount: function() { * this.refs.custom.initialize(); * } * }); * * Refs should rarely be used. When refs are used, they should only be done to * control data that is not handled by React's data flow. * * @class ReactOwner */ var ReactOwner = { /** * @param {?object} object * @return {boolean} True if `object` is a valid owner. * @final */ isValidOwner: function (object) { return !!(object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function'); }, /** * Adds a component by ref to an owner component. * * @param {ReactComponent} component Component to reference. * @param {string} ref Name by which to refer to the component. * @param {ReactOwner} owner Component on which to record the ref. * @final * @internal */ addComponentAsRefTo: function (component, ref, owner) { !ReactOwner.isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might ' + 'be adding a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + '(details: https://fb.me/react-refs-must-have-owner).') : invariant(false) : undefined; owner.attachRef(ref, component); }, /** * Removes a component by ref from an owner component. * * @param {ReactComponent} component Component to dereference. * @param {string} ref Name of the ref to remove. * @param {ReactOwner} owner Component on which the ref is recorded. * @final * @internal */ removeComponentAsRefFrom: function (component, ref, owner) { !ReactOwner.isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might ' + 'be removing a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + '(details: https://fb.me/react-refs-must-have-owner).') : invariant(false) : undefined; // Check that `component` is still the current ref because we do not want to // detach the ref if another component stole it. if (owner.getPublicInstance().refs[ref] === component.getPublicInstance()) { owner.detachRef(ref); } } }; module.exports = ReactOwner; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactUpdateQueue */ 'use strict'; var ReactCurrentOwner = __webpack_require__(11); var ReactElement = __webpack_require__(48); var ReactInstanceMap = __webpack_require__(53); var ReactUpdates = __webpack_require__(60); var assign = __webpack_require__(45); var invariant = __webpack_require__(19); var warning = __webpack_require__(31); function enqueueUpdate(internalInstance) { ReactUpdates.enqueueUpdate(internalInstance); } function getInternalInstanceReadyForUpdate(publicInstance, callerName) { var internalInstance = ReactInstanceMap.get(publicInstance); if (!internalInstance) { if (process.env.NODE_ENV !== 'production') { // Only warn when we have a callerName. Otherwise we should be silent. // We're probably calling from enqueueCallback. We don't want to warn // there because we already warned for the corresponding lifecycle method. process.env.NODE_ENV !== 'production' ? warning(!callerName, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, publicInstance.constructor.displayName) : undefined; } return null; } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition ' + '(such as within `render`). Render methods should be a pure function ' + 'of props and state.', callerName) : undefined; } return internalInstance; } /** * ReactUpdateQueue allows for state updates to be scheduled into a later * reconciliation step. */ var ReactUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { if (process.env.NODE_ENV !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : undefined; owner._warnedAboutRefsInRender = true; } } var internalInstance = ReactInstanceMap.get(publicInstance); if (internalInstance) { // During componentWillMount and render this will still be null but after // that will always render to something. At least for now. So we can use // this hack. return !!internalInstance._renderedComponent; } else { return false; } }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @internal */ enqueueCallback: function (publicInstance, callback) { !(typeof callback === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.') : invariant(false) : undefined; var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); // Previously we would throw an error if we didn't have an internal // instance. Since we want to make it a no-op instead, we mirror the same // behavior we have in other enqueue* methods. // We also need to ignore callbacks in componentWillMount. See // enqueueUpdates. if (!internalInstance) { return null; } if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } // TODO: The callback here is ignored when setState is called from // componentWillMount. Either fix it or disallow doing so completely in // favor of getInitialState. Alternatively, we can disallow // componentWillMount during server-side rendering. enqueueUpdate(internalInstance); }, enqueueCallbackInternal: function (internalInstance, callback) { !(typeof callback === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.') : invariant(false) : undefined; if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } enqueueUpdate(internalInstance); }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function (publicInstance) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'forceUpdate'); if (!internalInstance) { return; } internalInstance._pendingForceUpdate = true; enqueueUpdate(internalInstance); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function (publicInstance, completeState) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState'); if (!internalInstance) { return; } internalInstance._pendingStateQueue = [completeState]; internalInstance._pendingReplaceState = true; enqueueUpdate(internalInstance); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function (publicInstance, partialState) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState'); if (!internalInstance) { return; } var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []); queue.push(partialState); enqueueUpdate(internalInstance); }, /** * Sets a subset of the props. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialProps Subset of the next props. * @internal */ enqueueSetProps: function (publicInstance, partialProps) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setProps'); if (!internalInstance) { return; } ReactUpdateQueue.enqueueSetPropsInternal(internalInstance, partialProps); }, enqueueSetPropsInternal: function (internalInstance, partialProps) { var topLevelWrapper = internalInstance._topLevelWrapper; !topLevelWrapper ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setProps(...): You called `setProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.') : invariant(false) : undefined; // Merge with the pending element if it exists, otherwise with existing // element props. var wrapElement = topLevelWrapper._pendingElement || topLevelWrapper._currentElement; var element = wrapElement.props; var props = assign({}, element.props, partialProps); topLevelWrapper._pendingElement = ReactElement.cloneAndReplaceProps(wrapElement, ReactElement.cloneAndReplaceProps(element, props)); enqueueUpdate(topLevelWrapper); }, /** * Replaces all of the props. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} props New props. * @internal */ enqueueReplaceProps: function (publicInstance, props) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceProps'); if (!internalInstance) { return; } ReactUpdateQueue.enqueueReplacePropsInternal(internalInstance, props); }, enqueueReplacePropsInternal: function (internalInstance, props) { var topLevelWrapper = internalInstance._topLevelWrapper; !topLevelWrapper ? process.env.NODE_ENV !== 'production' ? invariant(false, 'replaceProps(...): You called `replaceProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.') : invariant(false) : undefined; // Merge with the pending element if it exists, otherwise with existing // element props. var wrapElement = topLevelWrapper._pendingElement || topLevelWrapper._currentElement; var element = wrapElement.props; topLevelWrapper._pendingElement = ReactElement.cloneAndReplaceProps(wrapElement, ReactElement.cloneAndReplaceProps(element, props)); enqueueUpdate(topLevelWrapper); }, enqueueElementInternal: function (internalInstance, newElement) { internalInstance._pendingElement = newElement; enqueueUpdate(internalInstance); } }; module.exports = ReactUpdateQueue; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactUpdates */ 'use strict'; var CallbackQueue = __webpack_require__(61); var PooledClass = __webpack_require__(62); var ReactPerf = __webpack_require__(24); var ReactReconciler = __webpack_require__(56); var Transaction = __webpack_require__(63); var assign = __webpack_require__(45); var invariant = __webpack_require__(19); var dirtyComponents = []; var asapCallbackQueue = CallbackQueue.getPooled(); var asapEnqueued = false; var batchingStrategy = null; function ensureInjected() { !(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching ' + 'strategy') : invariant(false) : undefined; } var NESTED_UPDATES = { initialize: function () { this.dirtyComponentsLength = dirtyComponents.length; }, close: function () { if (this.dirtyComponentsLength !== dirtyComponents.length) { // Additional updates were enqueued by componentDidUpdate handlers or // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run // these new updates so that if A's componentDidUpdate calls setState on // B, B will update before the callback A's updater provided when calling // setState. dirtyComponents.splice(0, this.dirtyComponentsLength); flushBatchedUpdates(); } else { dirtyComponents.length = 0; } } }; var UPDATE_QUEUEING = { initialize: function () { this.callbackQueue.reset(); }, close: function () { this.callbackQueue.notifyAll(); } }; var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING]; function ReactUpdatesFlushTransaction() { this.reinitializeTransaction(); this.dirtyComponentsLength = null; this.callbackQueue = CallbackQueue.getPooled(); this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* forceHTML */false); } assign(ReactUpdatesFlushTransaction.prototype, Transaction.Mixin, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, destructor: function () { this.dirtyComponentsLength = null; CallbackQueue.release(this.callbackQueue); this.callbackQueue = null; ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction); this.reconcileTransaction = null; }, perform: function (method, scope, a) { // Essentially calls `this.reconcileTransaction.perform(method, scope, a)` // with this transaction's wrappers around it. return Transaction.Mixin.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a); } }); PooledClass.addPoolingTo(ReactUpdatesFlushTransaction); function batchedUpdates(callback, a, b, c, d, e) { ensureInjected(); batchingStrategy.batchedUpdates(callback, a, b, c, d, e); } /** * Array comparator for ReactComponents by mount ordering. * * @param {ReactComponent} c1 first component you're comparing * @param {ReactComponent} c2 second component you're comparing * @return {number} Return value usable by Array.prototype.sort(). */ function mountOrderComparator(c1, c2) { return c1._mountOrder - c2._mountOrder; } function runBatchedUpdates(transaction) { var len = transaction.dirtyComponentsLength; !(len === dirtyComponents.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to ' + 'match dirty-components array length (%s).', len, dirtyComponents.length) : invariant(false) : undefined; // Since reconciling a component higher in the owner hierarchy usually (not // always -- see shouldComponentUpdate()) will reconcile children, reconcile // them before their children by sorting the array. dirtyComponents.sort(mountOrderComparator); for (var i = 0; i < len; i++) { // If a component is unmounted before pending changes apply, it will still // be here, but we assume that it has cleared its _pendingCallbacks and // that performUpdateIfNecessary is a noop. var component = dirtyComponents[i]; // If performUpdateIfNecessary happens to enqueue any new updates, we // shouldn't execute the callbacks until the next render happens, so // stash the callbacks first var callbacks = component._pendingCallbacks; component._pendingCallbacks = null; ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction); if (callbacks) { for (var j = 0; j < callbacks.length; j++) { transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance()); } } } } var flushBatchedUpdates = function () { // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents // array and perform any updates enqueued by mount-ready handlers (i.e., // componentDidUpdate) but we need to check here too in order to catch // updates enqueued by setState callbacks and asap calls. while (dirtyComponents.length || asapEnqueued) { if (dirtyComponents.length) { var transaction = ReactUpdatesFlushTransaction.getPooled(); transaction.perform(runBatchedUpdates, null, transaction); ReactUpdatesFlushTransaction.release(transaction); } if (asapEnqueued) { asapEnqueued = false; var queue = asapCallbackQueue; asapCallbackQueue = CallbackQueue.getPooled(); queue.notifyAll(); CallbackQueue.release(queue); } } }; flushBatchedUpdates = ReactPerf.measure('ReactUpdates', 'flushBatchedUpdates', flushBatchedUpdates); /** * Mark a component as needing a rerender, adding an optional callback to a * list of functions which will be executed once the rerender occurs. */ function enqueueUpdate(component) { ensureInjected(); // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (This is called by each top-level update // function, like setProps, setState, forceUpdate, etc.; creation and // destruction of top-level components is guarded in ReactMount.) if (!batchingStrategy.isBatchingUpdates) { batchingStrategy.batchedUpdates(enqueueUpdate, component); return; } dirtyComponents.push(component); } /** * Enqueue a callback to be run at the end of the current batching cycle. Throws * if no updates are currently being performed. */ function asap(callback, context) { !batchingStrategy.isBatchingUpdates ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context where' + 'updates are not being batched.') : invariant(false) : undefined; asapCallbackQueue.enqueue(callback, context); asapEnqueued = true; } var ReactUpdatesInjection = { injectReconcileTransaction: function (ReconcileTransaction) { !ReconcileTransaction ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : invariant(false) : undefined; ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; }, injectBatchingStrategy: function (_batchingStrategy) { !_batchingStrategy ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : invariant(false) : undefined; !(typeof _batchingStrategy.batchedUpdates === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : invariant(false) : undefined; !(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : invariant(false) : undefined; batchingStrategy = _batchingStrategy; } }; var ReactUpdates = { /** * React references `ReactReconcileTransaction` using this property in order * to allow dependency injection. * * @internal */ ReactReconcileTransaction: null, batchedUpdates: batchedUpdates, enqueueUpdate: enqueueUpdate, flushBatchedUpdates: flushBatchedUpdates, injection: ReactUpdatesInjection, asap: asap }; module.exports = ReactUpdates; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CallbackQueue */ 'use strict'; var PooledClass = __webpack_require__(62); var assign = __webpack_require__(45); var invariant = __webpack_require__(19); /** * A specialized pseudo-event module to help keep track of components waiting to * be notified when their DOM representations are available for use. * * This implements `PooledClass`, so you should never need to instantiate this. * Instead, use `CallbackQueue.getPooled()`. * * @class ReactMountReady * @implements PooledClass * @internal */ function CallbackQueue() { this._callbacks = null; this._contexts = null; } assign(CallbackQueue.prototype, { /** * Enqueues a callback to be invoked when `notifyAll` is invoked. * * @param {function} callback Invoked when `notifyAll` is invoked. * @param {?object} context Context to call `callback` with. * @internal */ enqueue: function (callback, context) { this._callbacks = this._callbacks || []; this._contexts = this._contexts || []; this._callbacks.push(callback); this._contexts.push(context); }, /** * Invokes all enqueued callbacks and clears the queue. This is invoked after * the DOM representation of a component has been created or updated. * * @internal */ notifyAll: function () { var callbacks = this._callbacks; var contexts = this._contexts; if (callbacks) { !(callbacks.length === contexts.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Mismatched list of contexts in callback queue') : invariant(false) : undefined; this._callbacks = null; this._contexts = null; for (var i = 0; i < callbacks.length; i++) { callbacks[i].call(contexts[i]); } callbacks.length = 0; contexts.length = 0; } }, /** * Resets the internal queue. * * @internal */ reset: function () { this._callbacks = null; this._contexts = null; }, /** * `PooledClass` looks for this. */ destructor: function () { this.reset(); } }); PooledClass.addPoolingTo(CallbackQueue); module.exports = CallbackQueue; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule PooledClass */ 'use strict'; var invariant = __webpack_require__(19); /** * Static poolers. Several custom versions for each potential number of * arguments. A completely generic pooler is easy to implement, but would * require accessing the `arguments` object. In each of these, `this` refers to * the Class itself, not an instance. If any others are needed, simply add them * here, or in their own files. */ var oneArgumentPooler = function (copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }; var twoArgumentPooler = function (a1, a2) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2); return instance; } else { return new Klass(a1, a2); } }; var threeArgumentPooler = function (a1, a2, a3) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3); return instance; } else { return new Klass(a1, a2, a3); } }; var fourArgumentPooler = function (a1, a2, a3, a4) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4); return instance; } else { return new Klass(a1, a2, a3, a4); } }; var fiveArgumentPooler = function (a1, a2, a3, a4, a5) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4, a5); return instance; } else { return new Klass(a1, a2, a3, a4, a5); } }; var standardReleaser = function (instance) { var Klass = this; !(instance instanceof Klass) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : invariant(false) : undefined; instance.destructor(); if (Klass.instancePool.length < Klass.poolSize) { Klass.instancePool.push(instance); } }; var DEFAULT_POOL_SIZE = 10; var DEFAULT_POOLER = oneArgumentPooler; /** * Augments `CopyConstructor` to be a poolable class, augmenting only the class * itself (statically) not adding any prototypical fields. Any CopyConstructor * you give this may have a `poolSize` property, and will look for a * prototypical `destructor` on instances (optional). * * @param {Function} CopyConstructor Constructor that can be used to reset. * @param {Function} pooler Customizable pooler. */ var addPoolingTo = function (CopyConstructor, pooler) { var NewKlass = CopyConstructor; NewKlass.instancePool = []; NewKlass.getPooled = pooler || DEFAULT_POOLER; if (!NewKlass.poolSize) { NewKlass.poolSize = DEFAULT_POOL_SIZE; } NewKlass.release = standardReleaser; return NewKlass; }; var PooledClass = { addPoolingTo: addPoolingTo, oneArgumentPooler: oneArgumentPooler, twoArgumentPooler: twoArgumentPooler, threeArgumentPooler: threeArgumentPooler, fourArgumentPooler: fourArgumentPooler, fiveArgumentPooler: fiveArgumentPooler }; module.exports = PooledClass; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Transaction */ 'use strict'; var invariant = __webpack_require__(19); /** * `Transaction` creates a black box that is able to wrap any method such that * certain invariants are maintained before and after the method is invoked * (Even if an exception is thrown while invoking the wrapped method). Whoever * instantiates a transaction can provide enforcers of the invariants at * creation time. The `Transaction` class itself will supply one additional * automatic invariant for you - the invariant that any transaction instance * should not be run while it is already being run. You would typically create a * single instance of a `Transaction` for reuse multiple times, that potentially * is used to wrap several different methods. Wrappers are extremely simple - * they only require implementing two methods. * * <pre> * wrappers (injected at creation time) * + + * | | * +-----------------|--------|--------------+ * | v | | * | +---------------+ | | * | +--| wrapper1 |---|----+ | * | | +---------------+ v | | * | | +-------------+ | | * | | +----| wrapper2 |--------+ | * | | | +-------------+ | | | * | | | | | | * | v v v v | wrapper * | +---+ +---+ +---------+ +---+ +---+ | invariants * perform(anyMethod) | | | | | | | | | | | | maintained * +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|--------> * | | | | | | | | | | | | * | | | | | | | | | | | | * | | | | | | | | | | | | * | +---+ +---+ +---------+ +---+ +---+ | * | initialize close | * +-----------------------------------------+ * </pre> * * Use cases: * - Preserving the input selection ranges before/after reconciliation. * Restoring selection even in the event of an unexpected error. * - Deactivating events while rearranging the DOM, preventing blurs/focuses, * while guaranteeing that afterwards, the event system is reactivated. * - Flushing a queue of collected DOM mutations to the main UI thread after a * reconciliation takes place in a worker thread. * - Invoking any collected `componentDidUpdate` callbacks after rendering new * content. * - (Future use case): Wrapping particular flushes of the `ReactWorker` queue * to preserve the `scrollTop` (an automatic scroll aware DOM). * - (Future use case): Layout calculations before and after DOM updates. * * Transactional plugin API: * - A module that has an `initialize` method that returns any precomputation. * - and a `close` method that accepts the precomputation. `close` is invoked * when the wrapped process is completed, or has failed. * * @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules * that implement `initialize` and `close`. * @return {Transaction} Single transaction for reuse in thread. * * @class Transaction */ var Mixin = { /** * Sets up this instance so that it is prepared for collecting metrics. Does * so such that this setup method may be used on an instance that is already * initialized, in a way that does not consume additional memory upon reuse. * That can be useful if you decide to make your subclass of this mixin a * "PooledClass". */ reinitializeTransaction: function () { this.transactionWrappers = this.getTransactionWrappers(); if (this.wrapperInitData) { this.wrapperInitData.length = 0; } else { this.wrapperInitData = []; } this._isInTransaction = false; }, _isInTransaction: false, /** * @abstract * @return {Array<TransactionWrapper>} Array of transaction wrappers. */ getTransactionWrappers: null, isInTransaction: function () { return !!this._isInTransaction; }, /** * Executes the function within a safety window. Use this for the top level * methods that result in large amounts of computation/mutations that would * need to be safety checked. The optional arguments helps prevent the need * to bind in many cases. * * @param {function} method Member of scope to call. * @param {Object} scope Scope to invoke from. * @param {Object?=} a Argument to pass to the method. * @param {Object?=} b Argument to pass to the method. * @param {Object?=} c Argument to pass to the method. * @param {Object?=} d Argument to pass to the method. * @param {Object?=} e Argument to pass to the method. * @param {Object?=} f Argument to pass to the method. * * @return {*} Return value from `method`. */ perform: function (method, scope, a, b, c, d, e, f) { !!this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there ' + 'is already an outstanding transaction.') : invariant(false) : undefined; var errorThrown; var ret; try { this._isInTransaction = true; // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // one of these calls threw. errorThrown = true; this.initializeAll(0); ret = method.call(scope, a, b, c, d, e, f); errorThrown = false; } finally { try { if (errorThrown) { // If `method` throws, prefer to show that stack trace over any thrown // by invoking `closeAll`. try { this.closeAll(0); } catch (err) {} } else { // Since `method` didn't throw, we don't want to silence the exception // here. this.closeAll(0); } } finally { this._isInTransaction = false; } } return ret; }, initializeAll: function (startIndex) { var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; try { // Catching errors makes debugging more difficult, so we start with the // OBSERVED_ERROR state before overwriting it with the real return value // of initialize -- if it's still set to OBSERVED_ERROR in the finally // block, it means wrapper.initialize threw. this.wrapperInitData[i] = Transaction.OBSERVED_ERROR; this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; } finally { if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) { // The initializer for wrapper i threw an error; initialize the // remaining wrappers but silence any exceptions from them to ensure // that the first error is the one to bubble up. try { this.initializeAll(i + 1); } catch (err) {} } } } }, /** * Invokes each of `this.transactionWrappers.close[i]` functions, passing into * them the respective return values of `this.transactionWrappers.init[i]` * (`close`rs that correspond to initializers that failed will not be * invoked). */ closeAll: function (startIndex) { !this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : invariant(false) : undefined; var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; var initData = this.wrapperInitData[i]; var errorThrown; try { // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // wrapper.close threw. errorThrown = true; if (initData !== Transaction.OBSERVED_ERROR && wrapper.close) { wrapper.close.call(this, initData); } errorThrown = false; } finally { if (errorThrown) { // The closer for wrapper i threw an error; close the remaining // wrappers but silence any exceptions from them to ensure that the // first error is the one to bubble up. try { this.closeAll(i + 1); } catch (e) {} } } } this.wrapperInitData.length = 0; } }; var Transaction = { Mixin: Mixin, /** * Token to look for to determine if an error occurred. */ OBSERVED_ERROR: {} }; module.exports = Transaction; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule emptyObject */ 'use strict'; var emptyObject = {}; if (process.env.NODE_ENV !== 'production') { Object.freeze(emptyObject); } module.exports = emptyObject; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule containsNode * @typechecks */ 'use strict'; var isTextNode = __webpack_require__(66); /*eslint-disable no-bitwise */ /** * Checks if a given DOM node contains or is another DOM node. * * @param {?DOMNode} outerNode Outer DOM node. * @param {?DOMNode} innerNode Inner DOM node. * @return {boolean} True if `outerNode` contains or is `innerNode`. */ function containsNode(_x, _x2) { var _again = true; _function: while (_again) { var outerNode = _x, innerNode = _x2; _again = false; if (!outerNode || !innerNode) { return false; } else if (outerNode === innerNode) { return true; } else if (isTextNode(outerNode)) { return false; } else if (isTextNode(innerNode)) { _x = outerNode; _x2 = innerNode.parentNode; _again = true; continue _function; } else if (outerNode.contains) { return outerNode.contains(innerNode); } else if (outerNode.compareDocumentPosition) { return !!(outerNode.compareDocumentPosition(innerNode) & 16); } else { return false; } } } module.exports = containsNode; /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isTextNode * @typechecks */ 'use strict'; var isNode = __webpack_require__(67); /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM text node. */ function isTextNode(object) { return isNode(object) && object.nodeType == 3; } module.exports = isTextNode; /***/ }, /* 67 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isNode * @typechecks */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM node. */ 'use strict'; function isNode(object) { return !!(object && (typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string')); } module.exports = isNode; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule instantiateReactComponent * @typechecks static-only */ 'use strict'; var ReactCompositeComponent = __webpack_require__(69); var ReactEmptyComponent = __webpack_require__(74); var ReactNativeComponent = __webpack_require__(75); var assign = __webpack_require__(45); var invariant = __webpack_require__(19); var warning = __webpack_require__(31); // To avoid a cyclic dependency, we create the final class in this module var ReactCompositeComponentWrapper = function () {}; assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent.Mixin, { _instantiateReactComponent: instantiateReactComponent }); function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Check if the type reference is a known internal type. I.e. not a user * provided composite type. * * @param {function} type * @return {boolean} Returns true if this is a valid internal type. */ function isInternalComponentType(type) { return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function'; } /** * Given a ReactNode, create an instance that will actually be mounted. * * @param {ReactNode} node * @return {object} A new instance of the element's constructor. * @protected */ function instantiateReactComponent(node) { var instance; if (node === null || node === false) { instance = new ReactEmptyComponent(instantiateReactComponent); } else if (typeof node === 'object') { var element = node; !(element && (typeof element.type === 'function' || typeof element.type === 'string')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) ' + 'or a class/function (for composite components) but got: %s.%s', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : invariant(false) : undefined; // Special case string values if (typeof element.type === 'string') { instance = ReactNativeComponent.createInternalComponent(element); } else if (isInternalComponentType(element.type)) { // This is temporarily available for custom components that are not string // representations. I.e. ART. Once those are updated to use the string // representation, we can drop this code path. instance = new element.type(element); } else { instance = new ReactCompositeComponentWrapper(); } } else if (typeof node === 'string' || typeof node === 'number') { instance = ReactNativeComponent.createInstanceForText(node); } else { true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : invariant(false) : undefined; } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(typeof instance.construct === 'function' && typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : undefined; } // Sets up the instance. This can probably just move into the constructor now. instance.construct(node); // These two fields are used by the DOM and ART diffing algorithms // respectively. Instead of using expandos on components, we should be // storing the state needed by the diffing algorithms elsewhere. instance._mountIndex = 0; instance._mountImage = null; if (process.env.NODE_ENV !== 'production') { instance._isOwnerNecessary = false; instance._warnedAboutRefsInRender = false; } // Internal instances should fully constructed at this point, so they should // not get any new fields added to them at this point. if (process.env.NODE_ENV !== 'production') { if (Object.preventExtensions) { Object.preventExtensions(instance); } } return instance; } module.exports = instantiateReactComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCompositeComponent */ 'use strict'; var ReactComponentEnvironment = __webpack_require__(70); var ReactCurrentOwner = __webpack_require__(11); var ReactElement = __webpack_require__(48); var ReactInstanceMap = __webpack_require__(53); var ReactPerf = __webpack_require__(24); var ReactPropTypeLocations = __webpack_require__(71); var ReactPropTypeLocationNames = __webpack_require__(72); var ReactReconciler = __webpack_require__(56); var ReactUpdateQueue = __webpack_require__(59); var assign = __webpack_require__(45); var emptyObject = __webpack_require__(64); var invariant = __webpack_require__(19); var shouldUpdateReactComponent = __webpack_require__(73); var warning = __webpack_require__(31); function getDeclarationErrorAddendum(component) { var owner = component._currentElement._owner || null; if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } function StatelessComponent(Component) {} StatelessComponent.prototype.render = function () { var Component = ReactInstanceMap.get(this)._currentElement.type; return Component(this.props, this.context, this.updater); }; /** * ------------------ The Life-Cycle of a Composite Component ------------------ * * - constructor: Initialization of state. The instance is now retained. * - componentWillMount * - render * - [children's constructors] * - [children's componentWillMount and render] * - [children's componentDidMount] * - componentDidMount * * Update Phases: * - componentWillReceiveProps (only called if parent updated) * - shouldComponentUpdate * - componentWillUpdate * - render * - [children's constructors or receive props phases] * - componentDidUpdate * * - componentWillUnmount * - [children's componentWillUnmount] * - [children destroyed] * - (destroyed): The instance is now blank, released by React and ready for GC. * * ----------------------------------------------------------------------------- */ /** * An incrementing ID assigned to each component when it is mounted. This is * used to enforce the order in which `ReactUpdates` updates dirty components. * * @private */ var nextMountID = 1; /** * @lends {ReactCompositeComponent.prototype} */ var ReactCompositeComponentMixin = { /** * Base constructor for all composite component. * * @param {ReactElement} element * @final * @internal */ construct: function (element) { this._currentElement = element; this._rootNodeID = null; this._instance = null; // See ReactUpdateQueue this._pendingElement = null; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._renderedComponent = null; this._context = null; this._mountOrder = 0; this._topLevelWrapper = null; // See ReactUpdates and ReactUpdateQueue. this._pendingCallbacks = null; }, /** * Initializes the component, renders markup, and registers event listeners. * * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (rootID, transaction, context) { this._context = context; this._mountOrder = nextMountID++; this._rootNodeID = rootID; var publicProps = this._processProps(this._currentElement.props); var publicContext = this._processContext(context); var Component = this._currentElement.type; // Initialize the public class var inst; var renderedElement; // This is a way to detect if Component is a stateless arrow function // component, which is not newable. It might not be 100% reliable but is // something we can do until we start detecting that Component extends // React.Component. We already assume that typeof Component === 'function'. var canInstantiate = ('prototype' in Component); if (canInstantiate) { if (process.env.NODE_ENV !== 'production') { ReactCurrentOwner.current = this; try { inst = new Component(publicProps, publicContext, ReactUpdateQueue); } finally { ReactCurrentOwner.current = null; } } else { inst = new Component(publicProps, publicContext, ReactUpdateQueue); } } if (!canInstantiate || inst === null || inst === false || ReactElement.isValidElement(inst)) { renderedElement = inst; inst = new StatelessComponent(Component); } if (process.env.NODE_ENV !== 'production') { // This will throw later in _renderValidatedComponent, but add an early // warning now to help debugging if (inst.render == null) { process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`, returned ' + 'null/false from a stateless component, or tried to render an ' + 'element whose type is a function that isn\'t a React component.', Component.displayName || Component.name || 'Component') : undefined; } else { // We support ES6 inheriting from React.Component, the module pattern, // and stateless components, but not ES6 classes that don't extend process.env.NODE_ENV !== 'production' ? warning(Component.prototype && Component.prototype.isReactComponent || !canInstantiate || !(inst instanceof Component), '%s(...): React component classes must extend React.Component.', Component.displayName || Component.name || 'Component') : undefined; } } // These should be set up in the constructor, but as a convenience for // simpler class abstractions, we set them up after the fact. inst.props = publicProps; inst.context = publicContext; inst.refs = emptyObject; inst.updater = ReactUpdateQueue; this._instance = inst; // Store a reference from the instance back to the internal representation ReactInstanceMap.set(inst, this); if (process.env.NODE_ENV !== 'production') { // Since plain JS classes are defined without any special initialization // logic, we can not catch common errors early. Therefore, we have to // catch them here, at initialization time, instead. process.env.NODE_ENV !== 'production' ? warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', this.getName() || 'a component') : undefined; process.env.NODE_ENV !== 'production' ? warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', this.getName() || 'a component') : undefined; process.env.NODE_ENV !== 'production' ? warning(!inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component') : undefined; process.env.NODE_ENV !== 'production' ? warning(!inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component') : undefined; process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentShouldUpdate !== 'function', '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', this.getName() || 'A component') : undefined; process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentDidUnmount !== 'function', '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', this.getName() || 'A component') : undefined; process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component') : undefined; } var initialState = inst.state; if (initialState === undefined) { inst.state = initialState = null; } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; if (inst.componentWillMount) { inst.componentWillMount(); // When mounting, calls to `setState` by `componentWillMount` will set // `this._pendingStateQueue` without triggering a re-render. if (this._pendingStateQueue) { inst.state = this._processPendingState(inst.props, inst.context); } } // If not a stateless component, we now render if (renderedElement === undefined) { renderedElement = this._renderValidatedComponent(); } this._renderedComponent = this._instantiateReactComponent(renderedElement); var markup = ReactReconciler.mountComponent(this._renderedComponent, rootID, transaction, this._processChildContext(context)); if (inst.componentDidMount) { transaction.getReactMountReady().enqueue(inst.componentDidMount, inst); } return markup; }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function () { var inst = this._instance; if (inst.componentWillUnmount) { inst.componentWillUnmount(); } ReactReconciler.unmountComponent(this._renderedComponent); this._renderedComponent = null; this._instance = null; // Reset pending fields // Even if this component is scheduled for another update in ReactUpdates, // it would still be ignored because these fields are reset. this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._pendingCallbacks = null; this._pendingElement = null; // These fields do not really need to be reset since this object is no // longer accessible. this._context = null; this._rootNodeID = null; this._topLevelWrapper = null; // Delete the reference from the instance to this internal representation // which allow the internals to be properly cleaned up even if the user // leaks a reference to the public instance. ReactInstanceMap.remove(inst); // Some existing components rely on inst.props even after they've been // destroyed (in event handlers). // TODO: inst.props = null; // TODO: inst.state = null; // TODO: inst.context = null; }, /** * Filters the context object to only contain keys specified in * `contextTypes` * * @param {object} context * @return {?object} * @private */ _maskContext: function (context) { var maskedContext = null; var Component = this._currentElement.type; var contextTypes = Component.contextTypes; if (!contextTypes) { return emptyObject; } maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } return maskedContext; }, /** * Filters the context object to only contain keys specified in * `contextTypes`, and asserts that they are valid. * * @param {object} context * @return {?object} * @private */ _processContext: function (context) { var maskedContext = this._maskContext(context); if (process.env.NODE_ENV !== 'production') { var Component = this._currentElement.type; if (Component.contextTypes) { this._checkPropTypes(Component.contextTypes, maskedContext, ReactPropTypeLocations.context); } } return maskedContext; }, /** * @param {object} currentContext * @return {object} * @private */ _processChildContext: function (currentContext) { var Component = this._currentElement.type; var inst = this._instance; var childContext = inst.getChildContext && inst.getChildContext(); if (childContext) { !(typeof Component.childContextTypes === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined; if (process.env.NODE_ENV !== 'production') { this._checkPropTypes(Component.childContextTypes, childContext, ReactPropTypeLocations.childContext); } for (var name in childContext) { !(name in Component.childContextTypes) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name) : invariant(false) : undefined; } return assign({}, currentContext, childContext); } return currentContext; }, /** * Processes props by setting default values for unspecified props and * asserting that the props are valid. Does not mutate its argument; returns * a new props object with defaults merged in. * * @param {object} newProps * @return {object} * @private */ _processProps: function (newProps) { if (process.env.NODE_ENV !== 'production') { var Component = this._currentElement.type; if (Component.propTypes) { this._checkPropTypes(Component.propTypes, newProps, ReactPropTypeLocations.prop); } } return newProps; }, /** * Assert that the props are valid * * @param {object} propTypes Map of prop name to a ReactPropType * @param {object} props * @param {string} location e.g. "prop", "context", "child context" * @private */ _checkPropTypes: function (propTypes, props, location) { // TODO: Stop validating prop types here and only use the element // validation. var componentName = this.getName(); for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error; try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. !(typeof propTypes[propName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually ' + 'from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : undefined; error = propTypes[propName](props, propName, componentName, location); } catch (ex) { error = ex; } if (error instanceof Error) { // We may want to extend this logic for similar errors in // top-level render calls, so I'm abstracting it away into // a function to minimize refactoring in the future var addendum = getDeclarationErrorAddendum(this); if (location === ReactPropTypeLocations.prop) { // Preface gives us something to blacklist in warning module process.env.NODE_ENV !== 'production' ? warning(false, 'Failed Composite propType: %s%s', error.message, addendum) : undefined; } else { process.env.NODE_ENV !== 'production' ? warning(false, 'Failed Context Types: %s%s', error.message, addendum) : undefined; } } } } }, receiveComponent: function (nextElement, transaction, nextContext) { var prevElement = this._currentElement; var prevContext = this._context; this._pendingElement = null; this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext); }, /** * If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate` * is set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (transaction) { if (this._pendingElement != null) { ReactReconciler.receiveComponent(this, this._pendingElement || this._currentElement, transaction, this._context); } if (this._pendingStateQueue !== null || this._pendingForceUpdate) { this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context); } }, /** * Perform an update to a mounted component. The componentWillReceiveProps and * shouldComponentUpdate methods are called, then (assuming the update isn't * skipped) the remaining update lifecycle methods are called and the DOM * representation is updated. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevParentElement * @param {ReactElement} nextParentElement * @internal * @overridable */ updateComponent: function (transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) { var inst = this._instance; var nextContext = this._context === nextUnmaskedContext ? inst.context : this._processContext(nextUnmaskedContext); var nextProps; // Distinguish between a props update versus a simple state update if (prevParentElement === nextParentElement) { // Skip checking prop types again -- we don't read inst.props to avoid // warning for DOM component props in this upgrade nextProps = nextParentElement.props; } else { nextProps = this._processProps(nextParentElement.props); // An update here will schedule an update but immediately set // _pendingStateQueue which will ensure that any state updates gets // immediately reconciled instead of waiting for the next batch. if (inst.componentWillReceiveProps) { inst.componentWillReceiveProps(nextProps, nextContext); } } var nextState = this._processPendingState(nextProps, nextContext); var shouldUpdate = this._pendingForceUpdate || !inst.shouldComponentUpdate || inst.shouldComponentUpdate(nextProps, nextState, nextContext); if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(typeof shouldUpdate !== 'undefined', '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent') : undefined; } if (shouldUpdate) { this._pendingForceUpdate = false; // Will set `this.props`, `this.state` and `this.context`. this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext); } else { // If it's determined that a component should not update, we still want // to set props and state but we shortcut the rest of the update. this._currentElement = nextParentElement; this._context = nextUnmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; } }, _processPendingState: function (props, context) { var inst = this._instance; var queue = this._pendingStateQueue; var replace = this._pendingReplaceState; this._pendingReplaceState = false; this._pendingStateQueue = null; if (!queue) { return inst.state; } if (replace && queue.length === 1) { return queue[0]; } var nextState = assign({}, replace ? queue[0] : inst.state); for (var i = replace ? 1 : 0; i < queue.length; i++) { var partial = queue[i]; assign(nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial); } return nextState; }, /** * Merges new props and state, notifies delegate methods of update and * performs update. * * @param {ReactElement} nextElement Next element * @param {object} nextProps Next public object to set as properties. * @param {?object} nextState Next object to set as state. * @param {?object} nextContext Next public object to set as context. * @param {ReactReconcileTransaction} transaction * @param {?object} unmaskedContext * @private */ _performComponentUpdate: function (nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) { var inst = this._instance; var hasComponentDidUpdate = Boolean(inst.componentDidUpdate); var prevProps; var prevState; var prevContext; if (hasComponentDidUpdate) { prevProps = inst.props; prevState = inst.state; prevContext = inst.context; } if (inst.componentWillUpdate) { inst.componentWillUpdate(nextProps, nextState, nextContext); } this._currentElement = nextElement; this._context = unmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; this._updateRenderedComponent(transaction, unmaskedContext); if (hasComponentDidUpdate) { transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst); } }, /** * Call the component's `render` method and update the DOM accordingly. * * @param {ReactReconcileTransaction} transaction * @internal */ _updateRenderedComponent: function (transaction, context) { var prevComponentInstance = this._renderedComponent; var prevRenderedElement = prevComponentInstance._currentElement; var nextRenderedElement = this._renderValidatedComponent(); if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) { ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context)); } else { // These two IDs are actually the same! But nothing should rely on that. var thisID = this._rootNodeID; var prevComponentID = prevComponentInstance._rootNodeID; ReactReconciler.unmountComponent(prevComponentInstance); this._renderedComponent = this._instantiateReactComponent(nextRenderedElement); var nextMarkup = ReactReconciler.mountComponent(this._renderedComponent, thisID, transaction, this._processChildContext(context)); this._replaceNodeWithMarkupByID(prevComponentID, nextMarkup); } }, /** * @protected */ _replaceNodeWithMarkupByID: function (prevComponentID, nextMarkup) { ReactComponentEnvironment.replaceNodeWithMarkupByID(prevComponentID, nextMarkup); }, /** * @protected */ _renderValidatedComponentWithoutOwnerOrContext: function () { var inst = this._instance; var renderedComponent = inst.render(); if (process.env.NODE_ENV !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if (typeof renderedComponent === 'undefined' && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. renderedComponent = null; } } return renderedComponent; }, /** * @private */ _renderValidatedComponent: function () { var renderedComponent; ReactCurrentOwner.current = this; try { renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext(); } finally { ReactCurrentOwner.current = null; } !( // TODO: An `isValidNode` function would probably be more appropriate renderedComponent === null || renderedComponent === false || ReactElement.isValidElement(renderedComponent)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.render(): A valid ReactComponent must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined; return renderedComponent; }, /** * Lazily allocates the refs object and stores `component` as `ref`. * * @param {string} ref Reference name. * @param {component} component Component to store as `ref`. * @final * @private */ attachRef: function (ref, component) { var inst = this.getPublicInstance(); !(inst != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Stateless function components cannot have refs.') : invariant(false) : undefined; var publicComponentInstance = component.getPublicInstance(); if (process.env.NODE_ENV !== 'production') { var componentName = component && component.getName ? component.getName() : 'a component'; process.env.NODE_ENV !== 'production' ? warning(publicComponentInstance != null, 'Stateless function components cannot be given refs ' + '(See ref "%s" in %s created by %s). ' + 'Attempts to access this ref will fail.', ref, componentName, this.getName()) : undefined; } var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs; refs[ref] = publicComponentInstance; }, /** * Detaches a reference name. * * @param {string} ref Name to dereference. * @final * @private */ detachRef: function (ref) { var refs = this.getPublicInstance().refs; delete refs[ref]; }, /** * Get a text description of the component that can be used to identify it * in error messages. * @return {string} The name or null. * @internal */ getName: function () { var type = this._currentElement.type; var constructor = this._instance && this._instance.constructor; return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null; }, /** * Get the publicly accessible representation of this component - i.e. what * is exposed by refs and returned by render. Can be null for stateless * components. * * @return {ReactComponent} the public component instance. * @internal */ getPublicInstance: function () { var inst = this._instance; if (inst instanceof StatelessComponent) { return null; } return inst; }, // Stub _instantiateReactComponent: null }; ReactPerf.measureMethods(ReactCompositeComponentMixin, 'ReactCompositeComponent', { mountComponent: 'mountComponent', updateComponent: 'updateComponent', _renderValidatedComponent: '_renderValidatedComponent' }); var ReactCompositeComponent = { Mixin: ReactCompositeComponentMixin }; module.exports = ReactCompositeComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentEnvironment */ 'use strict'; var invariant = __webpack_require__(19); var injected = false; var ReactComponentEnvironment = { /** * Optionally injectable environment dependent cleanup hook. (server vs. * browser etc). Example: A browser system caches DOM nodes based on component * ID and must remove that cache entry when this instance is unmounted. */ unmountIDFromEnvironment: null, /** * Optionally injectable hook for swapping out mount images in the middle of * the tree. */ replaceNodeWithMarkupByID: null, /** * Optionally injectable hook for processing a queue of child updates. Will * later move into MultiChildComponents. */ processChildrenUpdates: null, injection: { injectEnvironment: function (environment) { !!injected ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactCompositeComponent: injectEnvironment() can only be called once.') : invariant(false) : undefined; ReactComponentEnvironment.unmountIDFromEnvironment = environment.unmountIDFromEnvironment; ReactComponentEnvironment.replaceNodeWithMarkupByID = environment.replaceNodeWithMarkupByID; ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates; injected = true; } } }; module.exports = ReactComponentEnvironment; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypeLocations */ 'use strict'; var keyMirror = __webpack_require__(23); var ReactPropTypeLocations = keyMirror({ prop: null, context: null, childContext: null }); module.exports = ReactPropTypeLocations; /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypeLocationNames */ 'use strict'; var ReactPropTypeLocationNames = {}; if (process.env.NODE_ENV !== 'production') { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 73 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shouldUpdateReactComponent * @typechecks static-only */ 'use strict'; /** * Given a `prevElement` and `nextElement`, determines if the existing * instance should be updated as opposed to being destroyed or replaced by a new * instance. Both arguments are elements. This ensures that this logic can * operate on stateless trees without any backing instance. * * @param {?object} prevElement * @param {?object} nextElement * @return {boolean} True if the existing instance should be updated. * @protected */ function shouldUpdateReactComponent(prevElement, nextElement) { var prevEmpty = prevElement === null || prevElement === false; var nextEmpty = nextElement === null || nextElement === false; if (prevEmpty || nextEmpty) { return prevEmpty === nextEmpty; } var prevType = typeof prevElement; var nextType = typeof nextElement; if (prevType === 'string' || prevType === 'number') { return nextType === 'string' || nextType === 'number'; } else { return nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key; } return false; } module.exports = shouldUpdateReactComponent; /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEmptyComponent */ 'use strict'; var ReactElement = __webpack_require__(48); var ReactEmptyComponentRegistry = __webpack_require__(50); var ReactReconciler = __webpack_require__(56); var assign = __webpack_require__(45); var placeholderElement; var ReactEmptyComponentInjection = { injectEmptyComponent: function (component) { placeholderElement = ReactElement.createElement(component); } }; var ReactEmptyComponent = function (instantiate) { this._currentElement = null; this._rootNodeID = null; this._renderedComponent = instantiate(placeholderElement); }; assign(ReactEmptyComponent.prototype, { construct: function (element) {}, mountComponent: function (rootID, transaction, context) { ReactEmptyComponentRegistry.registerNullComponentID(rootID); this._rootNodeID = rootID; return ReactReconciler.mountComponent(this._renderedComponent, rootID, transaction, context); }, receiveComponent: function () {}, unmountComponent: function (rootID, transaction, context) { ReactReconciler.unmountComponent(this._renderedComponent); ReactEmptyComponentRegistry.deregisterNullComponentID(this._rootNodeID); this._rootNodeID = null; this._renderedComponent = null; } }); ReactEmptyComponent.injection = ReactEmptyComponentInjection; module.exports = ReactEmptyComponent; /***/ }, /* 75 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactNativeComponent */ 'use strict'; var assign = __webpack_require__(45); var invariant = __webpack_require__(19); var autoGenerateWrapperClass = null; var genericComponentClass = null; // This registry keeps track of wrapper classes around native tags. var tagToComponentClass = {}; var textComponentClass = null; var ReactNativeComponentInjection = { // This accepts a class that receives the tag string. This is a catch all // that can render any kind of tag. injectGenericComponentClass: function (componentClass) { genericComponentClass = componentClass; }, // This accepts a text component class that takes the text string to be // rendered as props. injectTextComponentClass: function (componentClass) { textComponentClass = componentClass; }, // This accepts a keyed object with classes as values. Each key represents a // tag. That particular tag will use this class instead of the generic one. injectComponentClasses: function (componentClasses) { assign(tagToComponentClass, componentClasses); } }; /** * Get a composite component wrapper class for a specific tag. * * @param {ReactElement} element The tag for which to get the class. * @return {function} The React class constructor function. */ function getComponentClassForElement(element) { if (typeof element.type === 'function') { return element.type; } var tag = element.type; var componentClass = tagToComponentClass[tag]; if (componentClass == null) { tagToComponentClass[tag] = componentClass = autoGenerateWrapperClass(tag); } return componentClass; } /** * Get a native internal component class for a specific tag. * * @param {ReactElement} element The element to create. * @return {function} The internal class constructor function. */ function createInternalComponent(element) { !genericComponentClass ? process.env.NODE_ENV !== 'production' ? invariant(false, 'There is no registered component for the tag %s', element.type) : invariant(false) : undefined; return new genericComponentClass(element.type, element.props); } /** * @param {ReactText} text * @return {ReactComponent} */ function createInstanceForText(text) { return new textComponentClass(text); } /** * @param {ReactComponent} component * @return {boolean} */ function isTextComponent(component) { return component instanceof textComponentClass; } var ReactNativeComponent = { getComponentClassForElement: getComponentClassForElement, createInternalComponent: createInternalComponent, createInstanceForText: createInstanceForText, isTextComponent: isTextComponent, injection: ReactNativeComponentInjection }; module.exports = ReactNativeComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 76 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule validateDOMNesting */ 'use strict'; var assign = __webpack_require__(45); var emptyFunction = __webpack_require__(21); var warning = __webpack_require__(31); var validateDOMNesting = emptyFunction; if (process.env.NODE_ENV !== 'production') { // This validation code was written based on the HTML5 parsing spec: // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope // // Note: this does not catch all invalid nesting, nor does it try to (as it's // not clear what practical benefit doing so provides); instead, we warn only // for cases where the parser will give a parse tree differing from what React // intended. For example, <b><div></div></b> is invalid but we don't warn // because it still parses correctly; we do warn for other cases like nested // <p> tags where the beginning of the second element implicitly closes the // first, causing a confusing mess. // https://html.spec.whatwg.org/multipage/syntax.html#special var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point // TODO: Distinguish by namespace here -- for <title>, including it here // errs on the side of fewer warnings 'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt']; var emptyAncestorInfo = { parentTag: null, formTag: null, aTagInScope: null, buttonTagInScope: null, nobrTagInScope: null, pTagInButtonScope: null, listItemTagAutoclosing: null, dlItemTagAutoclosing: null }; var updatedAncestorInfo = function (oldInfo, tag, instance) { var ancestorInfo = assign({}, oldInfo || emptyAncestorInfo); var info = { tag: tag, instance: instance }; if (inScopeTags.indexOf(tag) !== -1) { ancestorInfo.aTagInScope = null; ancestorInfo.buttonTagInScope = null; ancestorInfo.nobrTagInScope = null; } if (buttonScopeTags.indexOf(tag) !== -1) { ancestorInfo.pTagInButtonScope = null; } // See rules for 'li', 'dd', 'dt' start tags in // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') { ancestorInfo.listItemTagAutoclosing = null; ancestorInfo.dlItemTagAutoclosing = null; } ancestorInfo.parentTag = info; if (tag === 'form') { ancestorInfo.formTag = info; } if (tag === 'a') { ancestorInfo.aTagInScope = info; } if (tag === 'button') { ancestorInfo.buttonTagInScope = info; } if (tag === 'nobr') { ancestorInfo.nobrTagInScope = info; } if (tag === 'p') { ancestorInfo.pTagInButtonScope = info; } if (tag === 'li') { ancestorInfo.listItemTagAutoclosing = info; } if (tag === 'dd' || tag === 'dt') { ancestorInfo.dlItemTagAutoclosing = info; } return ancestorInfo; }; /** * Returns whether */ var isTagValidWithParent = function (tag, parentTag) { // First, let's check if we're in an unusual parsing mode... switch (parentTag) { // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect case 'select': return tag === 'option' || tag === 'optgroup' || tag === '#text'; case 'optgroup': return tag === 'option' || tag === '#text'; // Strictly speaking, seeing an <option> doesn't mean we're in a <select> // but case 'option': return tag === '#text'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption // No special behavior since these rules fall back to "in body" mode for // all except special table nodes which cause bad parsing behavior anyway. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr case 'tr': return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody case 'tbody': case 'thead': case 'tfoot': return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup case 'colgroup': return tag === 'col' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable case 'table': return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead case 'head': return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element case 'html': return tag === 'head' || tag === 'body'; } // Probably in the "in body" parsing mode, so we outlaw only tag combos // where the parsing rules cause implicit opens or closes to be added. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody switch (tag) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6'; case 'rp': case 'rt': return impliedEndTags.indexOf(parentTag) === -1; case 'caption': case 'col': case 'colgroup': case 'frame': case 'head': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': // These tags are only valid with a few parents that have special child // parsing rules -- if we're down here, then none of those matched and // so we allow it only if we don't know what the parent is, as all other // cases are invalid. return parentTag == null; } return true; }; /** * Returns whether */ var findInvalidAncestorForTag = function (tag, ancestorInfo) { switch (tag) { case 'address': case 'article': case 'aside': case 'blockquote': case 'center': case 'details': case 'dialog': case 'dir': case 'div': case 'dl': case 'fieldset': case 'figcaption': case 'figure': case 'footer': case 'header': case 'hgroup': case 'main': case 'menu': case 'nav': case 'ol': case 'p': case 'section': case 'summary': case 'ul': case 'pre': case 'listing': case 'table': case 'hr': case 'xmp': case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return ancestorInfo.pTagInButtonScope; case 'form': return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope; case 'li': return ancestorInfo.listItemTagAutoclosing; case 'dd': case 'dt': return ancestorInfo.dlItemTagAutoclosing; case 'button': return ancestorInfo.buttonTagInScope; case 'a': // Spec says something about storing a list of markers, but it sounds // equivalent to this check. return ancestorInfo.aTagInScope; case 'nobr': return ancestorInfo.nobrTagInScope; } return null; }; /** * Given a ReactCompositeComponent instance, return a list of its recursive * owners, starting at the root and ending with the instance itself. */ var findOwnerStack = function (instance) { if (!instance) { return []; } var stack = []; /*eslint-disable space-after-keywords */ do { /*eslint-enable space-after-keywords */ stack.push(instance); } while (instance = instance._currentElement._owner); stack.reverse(); return stack; }; var didWarn = {}; validateDOMNesting = function (childTag, childInstance, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.parentTag; var parentTag = parentInfo && parentInfo.tag; var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo; var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo); var problematic = invalidParent || invalidAncestor; if (problematic) { var ancestorTag = problematic.tag; var ancestorInstance = problematic.instance; var childOwner = childInstance && childInstance._currentElement._owner; var ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner; var childOwners = findOwnerStack(childOwner); var ancestorOwners = findOwnerStack(ancestorOwner); var minStackLen = Math.min(childOwners.length, ancestorOwners.length); var i; var deepestCommon = -1; for (i = 0; i < minStackLen; i++) { if (childOwners[i] === ancestorOwners[i]) { deepestCommon = i; } else { break; } } var UNKNOWN = '(unknown)'; var childOwnerNames = childOwners.slice(deepestCommon + 1).map(function (inst) { return inst.getName() || UNKNOWN; }); var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function (inst) { return inst.getName() || UNKNOWN; }); var ownerInfo = [].concat( // If the parent and child instances have a common owner ancestor, start // with that -- otherwise we just start with the parent's owners. deepestCommon !== -1 ? childOwners[deepestCommon].getName() || UNKNOWN : [], ancestorOwnerNames, ancestorTag, // If we're warning about an invalid (non-parent) ancestry, add '...' invalidAncestor ? ['...'] : [], childOwnerNames, childTag).join(' > '); var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + ownerInfo; if (didWarn[warnKey]) { return; } didWarn[warnKey] = true; if (invalidParent) { var info = ''; if (ancestorTag === 'table' && childTag === 'tr') { info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.'; } process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): <%s> cannot appear as a child of <%s>. ' + 'See %s.%s', childTag, ancestorTag, ownerInfo, info) : undefined; } else { process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): <%s> cannot appear as a descendant of ' + '<%s>. See %s.', childTag, ancestorTag, ownerInfo) : undefined; } } }; validateDOMNesting.ancestorInfoContextKey = '__validateDOMNesting_ancestorInfo$' + Math.random().toString(36).slice(2); validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo; // For testing validateDOMNesting.isTagValidInContext = function (tag, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.parentTag; var parentTag = parentInfo && parentInfo.tag; return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo); }; } module.exports = validateDOMNesting; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultInjection */ 'use strict'; var BeforeInputEventPlugin = __webpack_require__(78); var ChangeEventPlugin = __webpack_require__(86); var ClientReactRootIndex = __webpack_require__(89); var DefaultEventPluginOrder = __webpack_require__(90); var EnterLeaveEventPlugin = __webpack_require__(91); var ExecutionEnvironment = __webpack_require__(15); var HTMLDOMPropertyConfig = __webpack_require__(95); var ReactBrowserComponentMixin = __webpack_require__(96); var ReactComponentBrowserEnvironment = __webpack_require__(32); var ReactDefaultBatchingStrategy = __webpack_require__(98); var ReactDOMComponent = __webpack_require__(99); var ReactDOMTextComponent = __webpack_require__(12); var ReactEventListener = __webpack_require__(124); var ReactInjection = __webpack_require__(127); var ReactInstanceHandles = __webpack_require__(51); var ReactMount = __webpack_require__(34); var ReactReconcileTransaction = __webpack_require__(131); var SelectEventPlugin = __webpack_require__(136); var ServerReactRootIndex = __webpack_require__(137); var SimpleEventPlugin = __webpack_require__(138); var SVGDOMPropertyConfig = __webpack_require__(147); var alreadyInjected = false; function inject() { if (alreadyInjected) { // TODO: This is currently true because these injections are shared between // the client and the server package. They should be built independently // and not share any injection state. Then this problem will be solved. return; } alreadyInjected = true; ReactInjection.EventEmitter.injectReactEventListener(ReactEventListener); /** * Inject modules for resolving DOM hierarchy and plugin ordering. */ ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder); ReactInjection.EventPluginHub.injectInstanceHandle(ReactInstanceHandles); ReactInjection.EventPluginHub.injectMount(ReactMount); /** * Some important event plugins included by default (without having to require * them). */ ReactInjection.EventPluginHub.injectEventPluginsByName({ SimpleEventPlugin: SimpleEventPlugin, EnterLeaveEventPlugin: EnterLeaveEventPlugin, ChangeEventPlugin: ChangeEventPlugin, SelectEventPlugin: SelectEventPlugin, BeforeInputEventPlugin: BeforeInputEventPlugin }); ReactInjection.NativeComponent.injectGenericComponentClass(ReactDOMComponent); ReactInjection.NativeComponent.injectTextComponentClass(ReactDOMTextComponent); ReactInjection.Class.injectMixin(ReactBrowserComponentMixin); ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig); ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig); ReactInjection.EmptyComponent.injectEmptyComponent('noscript'); ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction); ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy); ReactInjection.RootIndex.injectCreateReactRootIndex(ExecutionEnvironment.canUseDOM ? ClientReactRootIndex.createReactRootIndex : ServerReactRootIndex.createReactRootIndex); ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment); if (process.env.NODE_ENV !== 'production') { var url = ExecutionEnvironment.canUseDOM && window.location.href || ''; if (/[?&]react_perf\b/.test(url)) { var ReactDefaultPerf = __webpack_require__(148); ReactDefaultPerf.start(); } } } module.exports = { inject: inject }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 78 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015 Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule BeforeInputEventPlugin * @typechecks static-only */ 'use strict'; var EventConstants = __webpack_require__(36); var EventPropagators = __webpack_require__(79); var ExecutionEnvironment = __webpack_require__(15); var FallbackCompositionState = __webpack_require__(80); var SyntheticCompositionEvent = __webpack_require__(82); var SyntheticInputEvent = __webpack_require__(84); var keyOf = __webpack_require__(85); var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space var START_KEYCODE = 229; var canUseCompositionEvent = ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window; var documentMode = null; if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) { documentMode = document.documentMode; } // Webkit offers a very useful `textInput` event that can be used to // directly represent `beforeInput`. The IE `textinput` event is not as // useful, so we don't use it. var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto(); // In IE9+, we have access to composition events, but the data supplied // by the native compositionend event may be incorrect. Japanese ideographic // spaces, for instance (\u3000) are not recorded correctly. var useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11); /** * Opera <= 12 includes TextEvent in window, but does not fire * text input events. Rely on keypress instead. */ function isPresto() { var opera = window.opera; return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12; } var SPACEBAR_CODE = 32; var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); var topLevelTypes = EventConstants.topLevelTypes; // Events and their corresponding property names. var eventTypes = { beforeInput: { phasedRegistrationNames: { bubbled: keyOf({ onBeforeInput: null }), captured: keyOf({ onBeforeInputCapture: null }) }, dependencies: [topLevelTypes.topCompositionEnd, topLevelTypes.topKeyPress, topLevelTypes.topTextInput, topLevelTypes.topPaste] }, compositionEnd: { phasedRegistrationNames: { bubbled: keyOf({ onCompositionEnd: null }), captured: keyOf({ onCompositionEndCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionEnd, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] }, compositionStart: { phasedRegistrationNames: { bubbled: keyOf({ onCompositionStart: null }), captured: keyOf({ onCompositionStartCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionStart, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] }, compositionUpdate: { phasedRegistrationNames: { bubbled: keyOf({ onCompositionUpdate: null }), captured: keyOf({ onCompositionUpdateCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionUpdate, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] } }; // Track whether we've ever handled a keypress on the space key. var hasSpaceKeypress = false; /** * Return whether a native keypress event is assumed to be a command. * This is required because Firefox fires `keypress` events for key commands * (cut, copy, select-all, etc.) even though no character is inserted. */ function isKeypressCommand(nativeEvent) { return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command. !(nativeEvent.ctrlKey && nativeEvent.altKey); } /** * Translate native top level events into event types. * * @param {string} topLevelType * @return {object} */ function getCompositionEventType(topLevelType) { switch (topLevelType) { case topLevelTypes.topCompositionStart: return eventTypes.compositionStart; case topLevelTypes.topCompositionEnd: return eventTypes.compositionEnd; case topLevelTypes.topCompositionUpdate: return eventTypes.compositionUpdate; } } /** * Does our fallback best-guess model think this event signifies that * composition has begun? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionStart(topLevelType, nativeEvent) { return topLevelType === topLevelTypes.topKeyDown && nativeEvent.keyCode === START_KEYCODE; } /** * Does our fallback mode think that this event is the end of composition? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionEnd(topLevelType, nativeEvent) { switch (topLevelType) { case topLevelTypes.topKeyUp: // Command keys insert or clear IME input. return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; case topLevelTypes.topKeyDown: // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return nativeEvent.keyCode !== START_KEYCODE; case topLevelTypes.topKeyPress: case topLevelTypes.topMouseDown: case topLevelTypes.topBlur: // Events are not possible without cancelling IME. return true; default: return false; } } /** * Google Input Tools provides composition data via a CustomEvent, * with the `data` property populated in the `detail` object. If this * is available on the event object, use it. If not, this is a plain * composition event and we have nothing special to extract. * * @param {object} nativeEvent * @return {?string} */ function getDataFromCustomEvent(nativeEvent) { var detail = nativeEvent.detail; if (typeof detail === 'object' && 'data' in detail) { return detail.data; } return null; } // Track the current IME composition fallback object, if any. var currentComposition = null; /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {?object} A SyntheticCompositionEvent. */ function extractCompositionEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { var eventType; var fallbackData; if (canUseCompositionEvent) { eventType = getCompositionEventType(topLevelType); } else if (!currentComposition) { if (isFallbackCompositionStart(topLevelType, nativeEvent)) { eventType = eventTypes.compositionStart; } } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) { eventType = eventTypes.compositionEnd; } if (!eventType) { return null; } if (useFallbackCompositionData) { // The current composition is stored statically and must not be // overwritten while composition continues. if (!currentComposition && eventType === eventTypes.compositionStart) { currentComposition = FallbackCompositionState.getPooled(topLevelTarget); } else if (eventType === eventTypes.compositionEnd) { if (currentComposition) { fallbackData = currentComposition.getData(); } } } var event = SyntheticCompositionEvent.getPooled(eventType, topLevelTargetID, nativeEvent, nativeEventTarget); if (fallbackData) { // Inject data generated from fallback path into the synthetic event. // This matches the property of native CompositionEventInterface. event.data = fallbackData; } else { var customData = getDataFromCustomEvent(nativeEvent); if (customData !== null) { event.data = customData; } } EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The string corresponding to this `beforeInput` event. */ function getNativeBeforeInputChars(topLevelType, nativeEvent) { switch (topLevelType) { case topLevelTypes.topCompositionEnd: return getDataFromCustomEvent(nativeEvent); case topLevelTypes.topKeyPress: /** * If native `textInput` events are available, our goal is to make * use of them. However, there is a special case: the spacebar key. * In Webkit, preventing default on a spacebar `textInput` event * cancels character insertion, but it *also* causes the browser * to fall back to its default spacebar behavior of scrolling the * page. * * Tracking at: * https://code.google.com/p/chromium/issues/detail?id=355103 * * To avoid this issue, use the keypress event as if no `textInput` * event is available. */ var which = nativeEvent.which; if (which !== SPACEBAR_CODE) { return null; } hasSpaceKeypress = true; return SPACEBAR_CHAR; case topLevelTypes.topTextInput: // Record the characters to be added to the DOM. var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled // it at the keypress level and bail immediately. Android Chrome // doesn't give us keycodes, so we need to blacklist it. if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { return null; } return chars; default: // For other native event types, do nothing. return null; } } /** * For browsers that do not provide the `textInput` event, extract the * appropriate string to use for SyntheticInputEvent. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The fallback string for this `beforeInput` event. */ function getFallbackBeforeInputChars(topLevelType, nativeEvent) { // If we are currently composing (IME) and using a fallback to do so, // try to extract the composed characters from the fallback object. if (currentComposition) { if (topLevelType === topLevelTypes.topCompositionEnd || isFallbackCompositionEnd(topLevelType, nativeEvent)) { var chars = currentComposition.getData(); FallbackCompositionState.release(currentComposition); currentComposition = null; return chars; } return null; } switch (topLevelType) { case topLevelTypes.topPaste: // If a paste event occurs after a keypress, throw out the input // chars. Paste events should not lead to BeforeInput events. return null; case topLevelTypes.topKeyPress: /** * As of v27, Firefox may fire keypress events even when no character * will be inserted. A few possibilities: * * - `which` is `0`. Arrow keys, Esc key, etc. * * - `which` is the pressed key code, but no char is available. * Ex: 'AltGr + d` in Polish. There is no modified character for * this key combination and no character is inserted into the * document, but FF fires the keypress for char code `100` anyway. * No `input` event will occur. * * - `which` is the pressed key code, but a command combination is * being used. Ex: `Cmd+C`. No character is inserted, and no * `input` event will occur. */ if (nativeEvent.which && !isKeypressCommand(nativeEvent)) { return String.fromCharCode(nativeEvent.which); } return null; case topLevelTypes.topCompositionEnd: return useFallbackCompositionData ? null : nativeEvent.data; default: return null; } } /** * Extract a SyntheticInputEvent for `beforeInput`, based on either native * `textInput` or fallback behavior. * * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {?object} A SyntheticInputEvent. */ function extractBeforeInputEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { var chars; if (canUseTextInputEvent) { chars = getNativeBeforeInputChars(topLevelType, nativeEvent); } else { chars = getFallbackBeforeInputChars(topLevelType, nativeEvent); } // If no characters are being inserted, no BeforeInput event should // be fired. if (!chars) { return null; } var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, topLevelTargetID, nativeEvent, nativeEventTarget); event.data = chars; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * Create an `onBeforeInput` event to match * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents. * * This event plugin is based on the native `textInput` event * available in Chrome, Safari, Opera, and IE. This event fires after * `onKeyPress` and `onCompositionEnd`, but before `onInput`. * * `beforeInput` is spec'd but not implemented in any browsers, and * the `input` event does not provide any useful information about what has * actually been added, contrary to the spec. Thus, `textInput` is the best * available event to identify the characters that have actually been inserted * into the target node. * * This plugin is also responsible for emitting `composition` events, thus * allowing us to share composition fallback code for both `beforeInput` and * `composition` event types. */ var BeforeInputEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { return [extractCompositionEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget)]; } }; module.exports = BeforeInputEventPlugin; /***/ }, /* 79 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPropagators */ 'use strict'; var EventConstants = __webpack_require__(36); var EventPluginHub = __webpack_require__(37); var warning = __webpack_require__(31); var accumulateInto = __webpack_require__(41); var forEachAccumulated = __webpack_require__(42); var PropagationPhases = EventConstants.PropagationPhases; var getListener = EventPluginHub.getListener; /** * Some event types have a notion of different registration names for different * "phases" of propagation. This finds listeners by a given phase. */ function listenerAtPhase(id, event, propagationPhase) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(id, registrationName); } /** * Tags a `SyntheticEvent` with dispatched listeners. Creating this function * here, allows us to not have to bind or create functions for each event. * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ function accumulateDirectionalDispatches(domID, upwards, event) { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(domID, 'Dispatching id must not be null') : undefined; } var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured; var listener = listenerAtPhase(domID, event, phase); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchIDs = accumulateInto(event._dispatchIDs, domID); } } /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through * each event and perform the traversal for each one. We cannot perform a * single traversal for the entire collection of events because each event may * have a different target. */ function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { EventPluginHub.injection.getInstanceHandle().traverseTwoPhase(event.dispatchMarker, accumulateDirectionalDispatches, event); } } /** * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. */ function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { EventPluginHub.injection.getInstanceHandle().traverseTwoPhaseSkipTarget(event.dispatchMarker, accumulateDirectionalDispatches, event); } } /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ function accumulateDispatches(id, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(id, registrationName); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchIDs = accumulateInto(event._dispatchIDs, id); } } } /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event.dispatchMarker, null, event); } } function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } function accumulateTwoPhaseDispatchesSkipTarget(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget); } function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) { EventPluginHub.injection.getInstanceHandle().traverseEnterLeave(fromID, toID, accumulateDispatches, leave, enter); } function accumulateDirectDispatches(events) { forEachAccumulated(events, accumulateDirectDispatchesSingle); } /** * A small set of propagation patterns, each of which will accept a small amount * of information, and generate a set of "dispatch ready event objects" - which * are sets of events that have already been annotated with a set of dispatched * listener functions/ids. The API is designed this way to discourage these * propagation strategies from actually executing the dispatches, since we * always want to collect the entire set of dispatches before executing event a * single one. * * @constructor EventPropagators */ var EventPropagators = { accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget, accumulateDirectDispatches: accumulateDirectDispatches, accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches }; module.exports = EventPropagators; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FallbackCompositionState * @typechecks static-only */ 'use strict'; var PooledClass = __webpack_require__(62); var assign = __webpack_require__(45); var getTextContentAccessor = __webpack_require__(81); /** * This helper class stores information about text content of a target node, * allowing comparison of content before and after a given event. * * Identify the node where selection currently begins, then observe * both its text content and its current position in the DOM. Since the * browser may natively replace the target node during composition, we can * use its position to find its replacement. * * @param {DOMEventTarget} root */ function FallbackCompositionState(root) { this._root = root; this._startText = this.getText(); this._fallbackText = null; } assign(FallbackCompositionState.prototype, { destructor: function () { this._root = null; this._startText = null; this._fallbackText = null; }, /** * Get current text of input. * * @return {string} */ getText: function () { if ('value' in this._root) { return this._root.value; } return this._root[getTextContentAccessor()]; }, /** * Determine the differing substring between the initially stored * text content and the current content. * * @return {string} */ getData: function () { if (this._fallbackText) { return this._fallbackText; } var start; var startValue = this._startText; var startLength = startValue.length; var end; var endValue = this.getText(); var endLength = endValue.length; for (start = 0; start < startLength; start++) { if (startValue[start] !== endValue[start]) { break; } } var minEnd = startLength - start; for (end = 1; end <= minEnd; end++) { if (startValue[startLength - end] !== endValue[endLength - end]) { break; } } var sliceTail = end > 1 ? 1 - end : undefined; this._fallbackText = endValue.slice(start, sliceTail); return this._fallbackText; } }); PooledClass.addPoolingTo(FallbackCompositionState); module.exports = FallbackCompositionState; /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getTextContentAccessor */ 'use strict'; var ExecutionEnvironment = __webpack_require__(15); var contentKey = null; /** * Gets the key used to access text content on a DOM node. * * @return {?string} Key used to access text content. * @internal */ function getTextContentAccessor() { if (!contentKey && ExecutionEnvironment.canUseDOM) { // Prefer textContent to innerText because many browsers support both but // SVG <text> elements don't support innerText even when <div> does. contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText'; } return contentKey; } module.exports = getTextContentAccessor; /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticCompositionEvent * @typechecks static-only */ 'use strict'; var SyntheticEvent = __webpack_require__(83); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents */ var CompositionEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface); module.exports = SyntheticCompositionEvent; /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticEvent * @typechecks static-only */ 'use strict'; var PooledClass = __webpack_require__(62); var assign = __webpack_require__(45); var emptyFunction = __webpack_require__(21); var warning = __webpack_require__(31); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var EventInterface = { type: null, target: null, // currentTarget is set when dispatching; no use in copying it here currentTarget: emptyFunction.thatReturnsNull, eventPhase: null, bubbles: null, cancelable: null, timeStamp: function (event) { return event.timeStamp || Date.now(); }, defaultPrevented: null, isTrusted: null }; /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. * * These systems should generally use pooling to reduce the frequency of garbage * collection. The system should check `isPersistent` to determine whether the * event should be released into the pool after being dispatched. Users that * need a persisted event should invoke `persist`. * * Synthetic events (and subclasses) implement the DOM Level 3 Events API by * normalizing browser quirks. Subclasses do not necessarily have to implement a * DOM interface; custom application-specific events can also subclass this. * * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. */ function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { this.dispatchConfig = dispatchConfig; this.dispatchMarker = dispatchMarker; this.nativeEvent = nativeEvent; var Interface = this.constructor.Interface; for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } var normalize = Interface[propName]; if (normalize) { this[propName] = normalize(nativeEvent); } else { if (propName === 'target') { this.target = nativeEventTarget; } else { this[propName] = nativeEvent[propName]; } } } var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; if (defaultPrevented) { this.isDefaultPrevented = emptyFunction.thatReturnsTrue; } else { this.isDefaultPrevented = emptyFunction.thatReturnsFalse; } this.isPropagationStopped = emptyFunction.thatReturnsFalse; } assign(SyntheticEvent.prototype, { preventDefault: function () { this.defaultPrevented = true; var event = this.nativeEvent; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(event, 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re calling `preventDefault` on a ' + 'released/nullified synthetic event. This is a no-op. See ' + 'https://fb.me/react-event-pooling for more information.') : undefined; } if (!event) { return; } if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } this.isDefaultPrevented = emptyFunction.thatReturnsTrue; }, stopPropagation: function () { var event = this.nativeEvent; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(event, 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re calling `stopPropagation` on a ' + 'released/nullified synthetic event. This is a no-op. See ' + 'https://fb.me/react-event-pooling for more information.') : undefined; } if (!event) { return; } if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; } this.isPropagationStopped = emptyFunction.thatReturnsTrue; }, /** * We release all dispatched `SyntheticEvent`s after each event loop, adding * them back into the pool. This allows a way to hold onto a reference that * won't be added back into the pool. */ persist: function () { this.isPersistent = emptyFunction.thatReturnsTrue; }, /** * Checks if this event should be released back into the pool. * * @return {boolean} True if this should not be released, false otherwise. */ isPersistent: emptyFunction.thatReturnsFalse, /** * `PooledClass` looks for `destructor` on each instance it releases. */ destructor: function () { var Interface = this.constructor.Interface; for (var propName in Interface) { this[propName] = null; } this.dispatchConfig = null; this.dispatchMarker = null; this.nativeEvent = null; } }); SyntheticEvent.Interface = EventInterface; /** * Helper to reduce boilerplate when creating subclasses. * * @param {function} Class * @param {?object} Interface */ SyntheticEvent.augmentClass = function (Class, Interface) { var Super = this; var prototype = Object.create(Super.prototype); assign(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; Class.Interface = assign({}, Super.Interface, Interface); Class.augmentClass = Super.augmentClass; PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler); }; PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler); module.exports = SyntheticEvent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 84 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticInputEvent * @typechecks static-only */ 'use strict'; var SyntheticEvent = __webpack_require__(83); /** * @interface Event * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105 * /#events-inputevents */ var InputEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface); module.exports = SyntheticInputEvent; /***/ }, /* 85 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule keyOf */ /** * Allows extraction of a minified key. Let's the build system minify keys * without losing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ "use strict"; var keyOf = function (oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ChangeEventPlugin */ 'use strict'; var EventConstants = __webpack_require__(36); var EventPluginHub = __webpack_require__(37); var EventPropagators = __webpack_require__(79); var ExecutionEnvironment = __webpack_require__(15); var ReactUpdates = __webpack_require__(60); var SyntheticEvent = __webpack_require__(83); var getEventTarget = __webpack_require__(87); var isEventSupported = __webpack_require__(46); var isTextInputElement = __webpack_require__(88); var keyOf = __webpack_require__(85); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { change: { phasedRegistrationNames: { bubbled: keyOf({ onChange: null }), captured: keyOf({ onChangeCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topChange, topLevelTypes.topClick, topLevelTypes.topFocus, topLevelTypes.topInput, topLevelTypes.topKeyDown, topLevelTypes.topKeyUp, topLevelTypes.topSelectionChange] } }; /** * For IE shims */ var activeElement = null; var activeElementID = null; var activeElementValue = null; var activeElementValueProp = null; /** * SECTION: handle `change` event */ function shouldUseChangeEvent(elem) { var nodeName = elem.nodeName && elem.nodeName.toLowerCase(); return nodeName === 'select' || nodeName === 'input' && elem.type === 'file'; } var doesChangeEventBubble = false; if (ExecutionEnvironment.canUseDOM) { // See `handleChange` comment below doesChangeEventBubble = isEventSupported('change') && (!('documentMode' in document) || document.documentMode > 8); } function manualDispatchChangeEvent(nativeEvent) { var event = SyntheticEvent.getPooled(eventTypes.change, activeElementID, nativeEvent, getEventTarget(nativeEvent)); EventPropagators.accumulateTwoPhaseDispatches(event); // If change and propertychange bubbled, we'd just bind to it like all the // other events and have it go through ReactBrowserEventEmitter. Since it // doesn't, we manually listen for the events and so we have to enqueue and // process the abstract event manually. // // Batching is necessary here in order to ensure that all event handlers run // before the next rerender (including event handlers attached to ancestor // elements instead of directly on the input). Without this, controlled // components don't work properly in conjunction with event bubbling because // the component is rerendered and the value reverted before all the event // handlers can run. See https://github.com/facebook/react/issues/708. ReactUpdates.batchedUpdates(runEventInBatch, event); } function runEventInBatch(event) { EventPluginHub.enqueueEvents(event); EventPluginHub.processEventQueue(false); } function startWatchingForChangeEventIE8(target, targetID) { activeElement = target; activeElementID = targetID; activeElement.attachEvent('onchange', manualDispatchChangeEvent); } function stopWatchingForChangeEventIE8() { if (!activeElement) { return; } activeElement.detachEvent('onchange', manualDispatchChangeEvent); activeElement = null; activeElementID = null; } function getTargetIDForChangeEvent(topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topChange) { return topLevelTargetID; } } function handleEventsForChangeEventIE8(topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topFocus) { // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForChangeEventIE8(); startWatchingForChangeEventIE8(topLevelTarget, topLevelTargetID); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForChangeEventIE8(); } } /** * SECTION: handle `input` event */ var isInputEventSupported = false; if (ExecutionEnvironment.canUseDOM) { // IE9 claims to support the input event but fails to trigger it when // deleting text, so we ignore its input events isInputEventSupported = isEventSupported('input') && (!('documentMode' in document) || document.documentMode > 9); } /** * (For old IE.) Replacement getter/setter for the `value` property that gets * set on the active element. */ var newValueProp = { get: function () { return activeElementValueProp.get.call(this); }, set: function (val) { // Cast to a string so we can do equality checks. activeElementValue = '' + val; activeElementValueProp.set.call(this, val); } }; /** * (For old IE.) Starts tracking propertychange events on the passed-in element * and override the value property so that we can distinguish user events from * value changes in JS. */ function startWatchingForValueChange(target, targetID) { activeElement = target; activeElementID = targetID; activeElementValue = target.value; activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, 'value'); // Not guarded in a canDefineProperty check: IE8 supports defineProperty only // on DOM elements Object.defineProperty(activeElement, 'value', newValueProp); activeElement.attachEvent('onpropertychange', handlePropertyChange); } /** * (For old IE.) Removes the event listeners from the currently-tracked element, * if any exists. */ function stopWatchingForValueChange() { if (!activeElement) { return; } // delete restores the original property definition delete activeElement.value; activeElement.detachEvent('onpropertychange', handlePropertyChange); activeElement = null; activeElementID = null; activeElementValue = null; activeElementValueProp = null; } /** * (For old IE.) Handles a propertychange event, sending a `change` event if * the value of the active element has changed. */ function handlePropertyChange(nativeEvent) { if (nativeEvent.propertyName !== 'value') { return; } var value = nativeEvent.srcElement.value; if (value === activeElementValue) { return; } activeElementValue = value; manualDispatchChangeEvent(nativeEvent); } /** * If a `change` event should be fired, returns the target's ID. */ function getTargetIDForInputEvent(topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topInput) { // In modern browsers (i.e., not IE8 or IE9), the input event is exactly // what we want so fall through here and trigger an abstract event return topLevelTargetID; } } // For IE8 and IE9. function handleEventsForInputEventIE(topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topFocus) { // In IE8, we can capture almost all .value changes by adding a // propertychange handler and looking for events with propertyName // equal to 'value' // In IE9, propertychange fires for most input events but is buggy and // doesn't fire when text is deleted, but conveniently, selectionchange // appears to fire in all of the remaining cases so we catch those and // forward the event if the value has changed // In either case, we don't want to call the event handler if the value // is changed from JS so we redefine a setter for `.value` that updates // our activeElementValue variable, allowing us to ignore those changes // // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForValueChange(); startWatchingForValueChange(topLevelTarget, topLevelTargetID); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForValueChange(); } } // For IE8 and IE9. function getTargetIDForInputEventIE(topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topSelectionChange || topLevelType === topLevelTypes.topKeyUp || topLevelType === topLevelTypes.topKeyDown) { // On the selectionchange event, the target is just document which isn't // helpful for us so just check activeElement instead. // // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire // propertychange on the first input event after setting `value` from a // script and fires only keydown, keypress, keyup. Catching keyup usually // gets it and catching keydown lets us fire an event for the first // keystroke if user does a key repeat (it'll be a little delayed: right // before the second keystroke). Other input methods (e.g., paste) seem to // fire selectionchange normally. if (activeElement && activeElement.value !== activeElementValue) { activeElementValue = activeElement.value; return activeElementID; } } } /** * SECTION: handle `click` event */ function shouldUseClickEvent(elem) { // Use the `click` event to detect changes to checkbox and radio inputs. // This approach works across all browsers, whereas `change` does not fire // until `blur` in IE8. return elem.nodeName && elem.nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio'); } function getTargetIDForClickEvent(topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topClick) { return topLevelTargetID; } } /** * This plugin creates an `onChange` event that normalizes change events * across form elements. This event fires at a time when it's possible to * change the element's value without seeing a flicker. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - select */ var ChangeEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { var getTargetIDFunc, handleEventFunc; if (shouldUseChangeEvent(topLevelTarget)) { if (doesChangeEventBubble) { getTargetIDFunc = getTargetIDForChangeEvent; } else { handleEventFunc = handleEventsForChangeEventIE8; } } else if (isTextInputElement(topLevelTarget)) { if (isInputEventSupported) { getTargetIDFunc = getTargetIDForInputEvent; } else { getTargetIDFunc = getTargetIDForInputEventIE; handleEventFunc = handleEventsForInputEventIE; } } else if (shouldUseClickEvent(topLevelTarget)) { getTargetIDFunc = getTargetIDForClickEvent; } if (getTargetIDFunc) { var targetID = getTargetIDFunc(topLevelType, topLevelTarget, topLevelTargetID); if (targetID) { var event = SyntheticEvent.getPooled(eventTypes.change, targetID, nativeEvent, nativeEventTarget); event.type = 'change'; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } } if (handleEventFunc) { handleEventFunc(topLevelType, topLevelTarget, topLevelTargetID); } } }; module.exports = ChangeEventPlugin; /***/ }, /* 87 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventTarget * @typechecks static-only */ 'use strict'; /** * Gets the target node from a native browser event by accounting for * inconsistencies in browser DOM APIs. * * @param {object} nativeEvent Native browser event. * @return {DOMEventTarget} Target node. */ function getEventTarget(nativeEvent) { var target = nativeEvent.target || nativeEvent.srcElement || window; // Safari may fire events on text nodes (Node.TEXT_NODE is 3). // @see http://www.quirksmode.org/js/events_properties.html return target.nodeType === 3 ? target.parentNode : target; } module.exports = getEventTarget; /***/ }, /* 88 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isTextInputElement */ 'use strict'; /** * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary */ var supportedInputTypes = { 'color': true, 'date': true, 'datetime': true, 'datetime-local': true, 'email': true, 'month': true, 'number': true, 'password': true, 'range': true, 'search': true, 'tel': true, 'text': true, 'time': true, 'url': true, 'week': true }; function isTextInputElement(elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && (nodeName === 'input' && supportedInputTypes[elem.type] || nodeName === 'textarea'); } module.exports = isTextInputElement; /***/ }, /* 89 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ClientReactRootIndex * @typechecks */ 'use strict'; var nextReactRootIndex = 0; var ClientReactRootIndex = { createReactRootIndex: function () { return nextReactRootIndex++; } }; module.exports = ClientReactRootIndex; /***/ }, /* 90 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DefaultEventPluginOrder */ 'use strict'; var keyOf = __webpack_require__(85); /** * Module that is injectable into `EventPluginHub`, that specifies a * deterministic ordering of `EventPlugin`s. A convenient way to reason about * plugins, without having to package every one of them. This is better than * having plugins be ordered in the same order that they are injected because * that ordering would be influenced by the packaging order. * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that * preventing default on events is convenient in `SimpleEventPlugin` handlers. */ var DefaultEventPluginOrder = [keyOf({ ResponderEventPlugin: null }), keyOf({ SimpleEventPlugin: null }), keyOf({ TapEventPlugin: null }), keyOf({ EnterLeaveEventPlugin: null }), keyOf({ ChangeEventPlugin: null }), keyOf({ SelectEventPlugin: null }), keyOf({ BeforeInputEventPlugin: null })]; module.exports = DefaultEventPluginOrder; /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EnterLeaveEventPlugin * @typechecks static-only */ 'use strict'; var EventConstants = __webpack_require__(36); var EventPropagators = __webpack_require__(79); var SyntheticMouseEvent = __webpack_require__(92); var ReactMount = __webpack_require__(34); var keyOf = __webpack_require__(85); var topLevelTypes = EventConstants.topLevelTypes; var getFirstReactDOM = ReactMount.getFirstReactDOM; var eventTypes = { mouseEnter: { registrationName: keyOf({ onMouseEnter: null }), dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver] }, mouseLeave: { registrationName: keyOf({ onMouseLeave: null }), dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver] } }; var extractedEvents = [null, null]; var EnterLeaveEventPlugin = { eventTypes: eventTypes, /** * For almost every interaction we care about, there will be both a top-level * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that * we do not extract duplicate events. However, moving the mouse into the * browser from outside will not fire a `mouseout` event. In this case, we use * the `mouseover` top-level event. * * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { if (topLevelType === topLevelTypes.topMouseOver && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (topLevelType !== topLevelTypes.topMouseOut && topLevelType !== topLevelTypes.topMouseOver) { // Must not be a mouse in or mouse out - ignoring. return null; } var win; if (topLevelTarget.window === topLevelTarget) { // `topLevelTarget` is probably a window object. win = topLevelTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = topLevelTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from; var to; var fromID = ''; var toID = ''; if (topLevelType === topLevelTypes.topMouseOut) { from = topLevelTarget; fromID = topLevelTargetID; to = getFirstReactDOM(nativeEvent.relatedTarget || nativeEvent.toElement); if (to) { toID = ReactMount.getID(to); } else { to = win; } to = to || win; } else { from = win; to = topLevelTarget; toID = topLevelTargetID; } if (from === to) { // Nothing pertains to our managed components. return null; } var leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, fromID, nativeEvent, nativeEventTarget); leave.type = 'mouseleave'; leave.target = from; leave.relatedTarget = to; var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, toID, nativeEvent, nativeEventTarget); enter.type = 'mouseenter'; enter.target = to; enter.relatedTarget = from; EventPropagators.accumulateEnterLeaveDispatches(leave, enter, fromID, toID); extractedEvents[0] = leave; extractedEvents[1] = enter; return extractedEvents; } }; module.exports = EnterLeaveEventPlugin; /***/ }, /* 92 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticMouseEvent * @typechecks static-only */ 'use strict'; var SyntheticUIEvent = __webpack_require__(93); var ViewportMetrics = __webpack_require__(44); var getEventModifierState = __webpack_require__(94); /** * @interface MouseEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var MouseEventInterface = { screenX: null, screenY: null, clientX: null, clientY: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, getModifierState: getEventModifierState, button: function (event) { // Webkit, Firefox, IE9+ // which: 1 2 3 // button: 0 1 2 (standard) var button = event.button; if ('which' in event) { return button; } // IE<9 // which: undefined // button: 0 0 0 // button: 1 4 2 (onmouseup) return button === 2 ? 2 : button === 4 ? 1 : 0; }, buttons: null, relatedTarget: function (event) { return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement); }, // "Proprietary" Interface. pageX: function (event) { return 'pageX' in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft; }, pageY: function (event) { return 'pageY' in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface); module.exports = SyntheticMouseEvent; /***/ }, /* 93 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticUIEvent * @typechecks static-only */ 'use strict'; var SyntheticEvent = __webpack_require__(83); var getEventTarget = __webpack_require__(87); /** * @interface UIEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var UIEventInterface = { view: function (event) { if (event.view) { return event.view; } var target = getEventTarget(event); if (target != null && target.window === target) { // target is a window object return target; } var doc = target.ownerDocument; // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. if (doc) { return doc.defaultView || doc.parentWindow; } else { return window; } }, detail: function (event) { return event.detail || 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface); module.exports = SyntheticUIEvent; /***/ }, /* 94 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventModifierState * @typechecks static-only */ 'use strict'; /** * Translation from modifier key to the associated property in the event. * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers */ var modifierKeyToProp = { 'Alt': 'altKey', 'Control': 'ctrlKey', 'Meta': 'metaKey', 'Shift': 'shiftKey' }; // IE8 does not implement getModifierState so we simply map it to the only // modifier keys exposed by the event itself, does not support Lock-keys. // Currently, all major browsers except Chrome seems to support Lock-keys. function modifierStateGetter(keyArg) { var syntheticEvent = this; var nativeEvent = syntheticEvent.nativeEvent; if (nativeEvent.getModifierState) { return nativeEvent.getModifierState(keyArg); } var keyProp = modifierKeyToProp[keyArg]; return keyProp ? !!nativeEvent[keyProp] : false; } function getEventModifierState(nativeEvent) { return modifierStateGetter; } module.exports = getEventModifierState; /***/ }, /* 95 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule HTMLDOMPropertyConfig */ 'use strict'; var DOMProperty = __webpack_require__(29); var ExecutionEnvironment = __webpack_require__(15); var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE; var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY; var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE; var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS; var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE; var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE; var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE; var hasSVG; if (ExecutionEnvironment.canUseDOM) { var implementation = document.implementation; hasSVG = implementation && implementation.hasFeature && implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1'); } var HTMLDOMPropertyConfig = { isCustomAttribute: RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/), Properties: { /** * Standard Properties */ accept: null, acceptCharset: null, accessKey: null, action: null, allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, allowTransparency: MUST_USE_ATTRIBUTE, alt: null, async: HAS_BOOLEAN_VALUE, autoComplete: null, // autoFocus is polyfilled/normalized by AutoFocusUtils // autoFocus: HAS_BOOLEAN_VALUE, autoPlay: HAS_BOOLEAN_VALUE, capture: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, cellPadding: null, cellSpacing: null, charSet: MUST_USE_ATTRIBUTE, challenge: MUST_USE_ATTRIBUTE, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, classID: MUST_USE_ATTRIBUTE, // To set className on SVG elements, it's necessary to use .setAttribute; // this works on HTML elements too in all browsers except IE8. Conveniently, // IE8 doesn't support SVG and so we can simply use the attribute in // browsers that support SVG and the property in browsers that don't, // regardless of whether the element is HTML or SVG. className: hasSVG ? MUST_USE_ATTRIBUTE : MUST_USE_PROPERTY, cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, colSpan: null, content: null, contentEditable: null, contextMenu: MUST_USE_ATTRIBUTE, controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, coords: null, crossOrigin: null, data: null, // For `<object />` acts as `src`. dateTime: MUST_USE_ATTRIBUTE, 'default': HAS_BOOLEAN_VALUE, defer: HAS_BOOLEAN_VALUE, dir: null, disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, download: HAS_OVERLOADED_BOOLEAN_VALUE, draggable: null, encType: null, form: MUST_USE_ATTRIBUTE, formAction: MUST_USE_ATTRIBUTE, formEncType: MUST_USE_ATTRIBUTE, formMethod: MUST_USE_ATTRIBUTE, formNoValidate: HAS_BOOLEAN_VALUE, formTarget: MUST_USE_ATTRIBUTE, frameBorder: MUST_USE_ATTRIBUTE, headers: null, height: MUST_USE_ATTRIBUTE, hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, high: null, href: null, hrefLang: null, htmlFor: null, httpEquiv: null, icon: null, id: MUST_USE_PROPERTY, inputMode: MUST_USE_ATTRIBUTE, integrity: null, is: MUST_USE_ATTRIBUTE, keyParams: MUST_USE_ATTRIBUTE, keyType: MUST_USE_ATTRIBUTE, kind: null, label: null, lang: null, list: MUST_USE_ATTRIBUTE, loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, low: null, manifest: MUST_USE_ATTRIBUTE, marginHeight: null, marginWidth: null, max: null, maxLength: MUST_USE_ATTRIBUTE, media: MUST_USE_ATTRIBUTE, mediaGroup: null, method: null, min: null, minLength: MUST_USE_ATTRIBUTE, multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, name: null, nonce: MUST_USE_ATTRIBUTE, noValidate: HAS_BOOLEAN_VALUE, open: HAS_BOOLEAN_VALUE, optimum: null, pattern: null, placeholder: null, poster: null, preload: null, radioGroup: null, readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, rel: null, required: HAS_BOOLEAN_VALUE, reversed: HAS_BOOLEAN_VALUE, role: MUST_USE_ATTRIBUTE, rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, rowSpan: null, sandbox: null, scope: null, scoped: HAS_BOOLEAN_VALUE, scrolling: null, seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, shape: null, size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, sizes: MUST_USE_ATTRIBUTE, span: HAS_POSITIVE_NUMERIC_VALUE, spellCheck: null, src: null, srcDoc: MUST_USE_PROPERTY, srcLang: null, srcSet: MUST_USE_ATTRIBUTE, start: HAS_NUMERIC_VALUE, step: null, style: null, summary: null, tabIndex: null, target: null, title: null, type: null, useMap: null, value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS, width: MUST_USE_ATTRIBUTE, wmode: MUST_USE_ATTRIBUTE, wrap: null, /** * RDFa Properties */ about: MUST_USE_ATTRIBUTE, datatype: MUST_USE_ATTRIBUTE, inlist: MUST_USE_ATTRIBUTE, prefix: MUST_USE_ATTRIBUTE, // property is also supported for OpenGraph in meta tags. property: MUST_USE_ATTRIBUTE, resource: MUST_USE_ATTRIBUTE, 'typeof': MUST_USE_ATTRIBUTE, vocab: MUST_USE_ATTRIBUTE, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autoCapitalize: MUST_USE_ATTRIBUTE, autoCorrect: MUST_USE_ATTRIBUTE, // autoSave allows WebKit/Blink to persist values of input fields on page reloads autoSave: null, // color is for Safari mask-icon link color: null, // itemProp, itemScope, itemType are for // Microdata support. See http://schema.org/docs/gs.html itemProp: MUST_USE_ATTRIBUTE, itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, itemType: MUST_USE_ATTRIBUTE, // itemID and itemRef are for Microdata support as well but // only specified in the the WHATWG spec document. See // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api itemID: MUST_USE_ATTRIBUTE, itemRef: MUST_USE_ATTRIBUTE, // results show looking glass icon and recent searches on input // search fields in WebKit/Blink results: null, // IE-only attribute that specifies security restrictions on an iframe // as an alternative to the sandbox attribute on IE<10 security: MUST_USE_ATTRIBUTE, // IE-only attribute that controls focus behavior unselectable: MUST_USE_ATTRIBUTE }, DOMAttributeNames: { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv' }, DOMPropertyNames: { autoComplete: 'autocomplete', autoFocus: 'autofocus', autoPlay: 'autoplay', autoSave: 'autosave', // `encoding` is equivalent to `enctype`, IE8 lacks an `enctype` setter. // http://www.w3.org/TR/html5/forms.html#dom-fs-encoding encType: 'encoding', hrefLang: 'hreflang', radioGroup: 'radiogroup', spellCheck: 'spellcheck', srcDoc: 'srcdoc', srcSet: 'srcset' } }; module.exports = HTMLDOMPropertyConfig; /***/ }, /* 96 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactBrowserComponentMixin */ 'use strict'; var ReactInstanceMap = __webpack_require__(53); var findDOMNode = __webpack_require__(97); var warning = __webpack_require__(31); var didWarnKey = '_getDOMNodeDidWarn'; var ReactBrowserComponentMixin = { /** * Returns the DOM node rendered by this component. * * @return {DOMElement} The root node of this component. * @final * @protected */ getDOMNode: function () { process.env.NODE_ENV !== 'production' ? warning(this.constructor[didWarnKey], '%s.getDOMNode(...) is deprecated. Please use ' + 'ReactDOM.findDOMNode(instance) instead.', ReactInstanceMap.get(this).getName() || this.tagName || 'Unknown') : undefined; this.constructor[didWarnKey] = true; return findDOMNode(this); } }; module.exports = ReactBrowserComponentMixin; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 97 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule findDOMNode * @typechecks static-only */ 'use strict'; var ReactCurrentOwner = __webpack_require__(11); var ReactInstanceMap = __webpack_require__(53); var ReactMount = __webpack_require__(34); var invariant = __webpack_require__(19); var warning = __webpack_require__(31); /** * Returns the DOM node rendered by this element. * * @param {ReactComponent|DOMElement} componentOrElement * @return {?DOMElement} The root node of this element. */ function findDOMNode(componentOrElement) { if (process.env.NODE_ENV !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing getDOMNode or findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : undefined; owner._warnedAboutRefsInRender = true; } } if (componentOrElement == null) { return null; } if (componentOrElement.nodeType === 1) { return componentOrElement; } if (ReactInstanceMap.has(componentOrElement)) { return ReactMount.getNodeFromInstance(componentOrElement); } !(componentOrElement.render == null || typeof componentOrElement.render !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : invariant(false) : undefined; true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : invariant(false) : undefined; } module.exports = findDOMNode; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 98 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultBatchingStrategy */ 'use strict'; var ReactUpdates = __webpack_require__(60); var Transaction = __webpack_require__(63); var assign = __webpack_require__(45); var emptyFunction = __webpack_require__(21); var RESET_BATCHED_UPDATES = { initialize: emptyFunction, close: function () { ReactDefaultBatchingStrategy.isBatchingUpdates = false; } }; var FLUSH_BATCHED_UPDATES = { initialize: emptyFunction, close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates) }; var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES]; function ReactDefaultBatchingStrategyTransaction() { this.reinitializeTransaction(); } assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction.Mixin, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; } }); var transaction = new ReactDefaultBatchingStrategyTransaction(); var ReactDefaultBatchingStrategy = { isBatchingUpdates: false, /** * Call the provided function in a context within which calls to `setState` * and friends are batched such that components aren't updated unnecessarily. */ batchedUpdates: function (callback, a, b, c, d, e) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { callback(a, b, c, d, e); } else { transaction.perform(callback, null, a, b, c, d, e); } } }; module.exports = ReactDefaultBatchingStrategy; /***/ }, /* 99 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMComponent * @typechecks static-only */ /* global hasOwnProperty:true */ 'use strict'; var AutoFocusUtils = __webpack_require__(100); var CSSPropertyOperations = __webpack_require__(102); var DOMProperty = __webpack_require__(29); var DOMPropertyOperations = __webpack_require__(28); var EventConstants = __webpack_require__(36); var ReactBrowserEventEmitter = __webpack_require__(35); var ReactComponentBrowserEnvironment = __webpack_require__(32); var ReactDOMButton = __webpack_require__(110); var ReactDOMInput = __webpack_require__(111); var ReactDOMOption = __webpack_require__(115); var ReactDOMSelect = __webpack_require__(118); var ReactDOMTextarea = __webpack_require__(119); var ReactMount = __webpack_require__(34); var ReactMultiChild = __webpack_require__(120); var ReactPerf = __webpack_require__(24); var ReactUpdateQueue = __webpack_require__(59); var assign = __webpack_require__(45); var canDefineProperty = __webpack_require__(49); var escapeTextContentForBrowser = __webpack_require__(27); var invariant = __webpack_require__(19); var isEventSupported = __webpack_require__(46); var keyOf = __webpack_require__(85); var setInnerHTML = __webpack_require__(25); var setTextContent = __webpack_require__(26); var shallowEqual = __webpack_require__(123); var validateDOMNesting = __webpack_require__(76); var warning = __webpack_require__(31); var deleteListener = ReactBrowserEventEmitter.deleteListener; var listenTo = ReactBrowserEventEmitter.listenTo; var registrationNameModules = ReactBrowserEventEmitter.registrationNameModules; // For quickly matching children type, to test if can be treated as content. var CONTENT_TYPES = { 'string': true, 'number': true }; var CHILDREN = keyOf({ children: null }); var STYLE = keyOf({ style: null }); var HTML = keyOf({ __html: null }); var ELEMENT_NODE_TYPE = 1; function getDeclarationErrorAddendum(internalInstance) { if (internalInstance) { var owner = internalInstance._currentElement._owner || null; if (owner) { var name = owner.getName(); if (name) { return ' This DOM node was rendered by `' + name + '`.'; } } } return ''; } var legacyPropsDescriptor; if (process.env.NODE_ENV !== 'production') { legacyPropsDescriptor = { props: { enumerable: false, get: function () { var component = this._reactInternalComponent; process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .props of a DOM node; instead, ' + 'recreate the props as `render` did originally or read the DOM ' + 'properties/attributes directly from this node (e.g., ' + 'this.refs.box.className).%s', getDeclarationErrorAddendum(component)) : undefined; return component._currentElement.props; } } }; } function legacyGetDOMNode() { if (process.env.NODE_ENV !== 'production') { var component = this._reactInternalComponent; process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .getDOMNode() of a DOM node; ' + 'instead, use the node directly.%s', getDeclarationErrorAddendum(component)) : undefined; } return this; } function legacyIsMounted() { var component = this._reactInternalComponent; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .isMounted() of a DOM node.%s', getDeclarationErrorAddendum(component)) : undefined; } return !!component; } function legacySetStateEtc() { if (process.env.NODE_ENV !== 'production') { var component = this._reactInternalComponent; process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .setState(), .replaceState(), or ' + '.forceUpdate() of a DOM node. This is a no-op.%s', getDeclarationErrorAddendum(component)) : undefined; } } function legacySetProps(partialProps, callback) { var component = this._reactInternalComponent; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .setProps() of a DOM node. ' + 'Instead, call ReactDOM.render again at the top level.%s', getDeclarationErrorAddendum(component)) : undefined; } if (!component) { return; } ReactUpdateQueue.enqueueSetPropsInternal(component, partialProps); if (callback) { ReactUpdateQueue.enqueueCallbackInternal(component, callback); } } function legacyReplaceProps(partialProps, callback) { var component = this._reactInternalComponent; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .replaceProps() of a DOM node. ' + 'Instead, call ReactDOM.render again at the top level.%s', getDeclarationErrorAddendum(component)) : undefined; } if (!component) { return; } ReactUpdateQueue.enqueueReplacePropsInternal(component, partialProps); if (callback) { ReactUpdateQueue.enqueueCallbackInternal(component, callback); } } function friendlyStringify(obj) { if (typeof obj === 'object') { if (Array.isArray(obj)) { return '[' + obj.map(friendlyStringify).join(', ') + ']'; } else { var pairs = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var keyEscaped = /^[a-z$_][\w$_]*$/i.test(key) ? key : JSON.stringify(key); pairs.push(keyEscaped + ': ' + friendlyStringify(obj[key])); } } return '{' + pairs.join(', ') + '}'; } } else if (typeof obj === 'string') { return JSON.stringify(obj); } else if (typeof obj === 'function') { return '[function object]'; } // Differs from JSON.stringify in that undefined becauses undefined and that // inf and nan don't become null return String(obj); } var styleMutationWarning = {}; function checkAndWarnForMutatedStyle(style1, style2, component) { if (style1 == null || style2 == null) { return; } if (shallowEqual(style1, style2)) { return; } var componentName = component._tag; var owner = component._currentElement._owner; var ownerName; if (owner) { ownerName = owner.getName(); } var hash = ownerName + '|' + componentName; if (styleMutationWarning.hasOwnProperty(hash)) { return; } styleMutationWarning[hash] = true; process.env.NODE_ENV !== 'production' ? warning(false, '`%s` was passed a style object that has previously been mutated. ' + 'Mutating `style` is deprecated. Consider cloning it beforehand. Check ' + 'the `render` %s. Previous style: %s. Mutated style: %s.', componentName, owner ? 'of `' + ownerName + '`' : 'using <' + componentName + '>', friendlyStringify(style1), friendlyStringify(style2)) : undefined; } /** * @param {object} component * @param {?object} props */ function assertValidProps(component, props) { if (!props) { return; } // Note the use of `==` which checks for null or undefined. if (process.env.NODE_ENV !== 'production') { if (voidElementTags[component._tag]) { process.env.NODE_ENV !== 'production' ? warning(props.children == null && props.dangerouslySetInnerHTML == null, '%s is a void element tag and must not have `children` or ' + 'use `props.dangerouslySetInnerHTML`.%s', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : undefined; } } if (props.dangerouslySetInnerHTML != null) { !(props.children == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : invariant(false) : undefined; !(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://fb.me/react-invariant-dangerously-set-inner-html ' + 'for more information.') : invariant(false) : undefined; } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.') : undefined; process.env.NODE_ENV !== 'production' ? warning(!props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.') : undefined; } !(props.style == null || typeof props.style === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The `style` prop expects a mapping from style properties to values, ' + 'not a string. For example, style={{marginRight: spacing + \'em\'}} when ' + 'using JSX.%s', getDeclarationErrorAddendum(component)) : invariant(false) : undefined; } function enqueuePutListener(id, registrationName, listener, transaction) { if (process.env.NODE_ENV !== 'production') { // IE8 has no API for event capturing and the `onScroll` event doesn't // bubble. process.env.NODE_ENV !== 'production' ? warning(registrationName !== 'onScroll' || isEventSupported('scroll', true), 'This browser doesn\'t support the `onScroll` event') : undefined; } var container = ReactMount.findReactContainerForID(id); if (container) { var doc = container.nodeType === ELEMENT_NODE_TYPE ? container.ownerDocument : container; listenTo(registrationName, doc); } transaction.getReactMountReady().enqueue(putListener, { id: id, registrationName: registrationName, listener: listener }); } function putListener() { var listenerToPut = this; ReactBrowserEventEmitter.putListener(listenerToPut.id, listenerToPut.registrationName, listenerToPut.listener); } // There are so many media events, it makes sense to just // maintain a list rather than create a `trapBubbledEvent` for each var mediaEvents = { topAbort: 'abort', topCanPlay: 'canplay', topCanPlayThrough: 'canplaythrough', topDurationChange: 'durationchange', topEmptied: 'emptied', topEncrypted: 'encrypted', topEnded: 'ended', topError: 'error', topLoadedData: 'loadeddata', topLoadedMetadata: 'loadedmetadata', topLoadStart: 'loadstart', topPause: 'pause', topPlay: 'play', topPlaying: 'playing', topProgress: 'progress', topRateChange: 'ratechange', topSeeked: 'seeked', topSeeking: 'seeking', topStalled: 'stalled', topSuspend: 'suspend', topTimeUpdate: 'timeupdate', topVolumeChange: 'volumechange', topWaiting: 'waiting' }; function trapBubbledEventsLocal() { var inst = this; // If a component renders to null or if another component fatals and causes // the state of the tree to be corrupted, `node` here can be null. !inst._rootNodeID ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Must be mounted to trap events') : invariant(false) : undefined; var node = ReactMount.getNode(inst._rootNodeID); !node ? process.env.NODE_ENV !== 'production' ? invariant(false, 'trapBubbledEvent(...): Requires node to be rendered.') : invariant(false) : undefined; switch (inst._tag) { case 'iframe': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)]; break; case 'video': case 'audio': inst._wrapperState.listeners = []; // create listener for each media event for (var event in mediaEvents) { if (mediaEvents.hasOwnProperty(event)) { inst._wrapperState.listeners.push(ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes[event], mediaEvents[event], node)); } } break; case 'img': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)]; break; case 'form': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit', node)]; break; } } function mountReadyInputWrapper() { ReactDOMInput.mountReadyWrapper(this); } function postUpdateSelectWrapper() { ReactDOMSelect.postUpdateWrapper(this); } // For HTML, certain tags should omit their close tag. We keep a whitelist for // those special cased tags. var omittedCloseTags = { 'area': true, 'base': true, 'br': true, 'col': true, 'embed': true, 'hr': true, 'img': true, 'input': true, 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, 'track': true, 'wbr': true }; // NOTE: menuitem's close tag should be omitted, but that causes problems. var newlineEatingTags = { 'listing': true, 'pre': true, 'textarea': true }; // For HTML, certain tags cannot have children. This has the same purpose as // `omittedCloseTags` except that `menuitem` should still have its closing tag. var voidElementTags = assign({ 'menuitem': true }, omittedCloseTags); // We accept any tag to be rendered but since this gets injected into arbitrary // HTML, we want to make sure that it's a safe tag. // http://www.w3.org/TR/REC-xml/#NT-Name var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset var validatedTagCache = {}; var hasOwnProperty = ({}).hasOwnProperty; function validateDangerousTag(tag) { if (!hasOwnProperty.call(validatedTagCache, tag)) { !VALID_TAG_REGEX.test(tag) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Invalid tag: %s', tag) : invariant(false) : undefined; validatedTagCache[tag] = true; } } function processChildContextDev(context, inst) { // Pass down our tag name to child components for validation purposes context = assign({}, context); var info = context[validateDOMNesting.ancestorInfoContextKey]; context[validateDOMNesting.ancestorInfoContextKey] = validateDOMNesting.updatedAncestorInfo(info, inst._tag, inst); return context; } function isCustomComponent(tagName, props) { return tagName.indexOf('-') >= 0 || props.is != null; } /** * Creates a new React class that is idempotent and capable of containing other * React components. It accepts event listeners and DOM properties that are * valid according to `DOMProperty`. * * - Event listeners: `onClick`, `onMouseDown`, etc. * - DOM properties: `className`, `name`, `title`, etc. * * The `style` property functions differently from the DOM API. It accepts an * object mapping of style properties to values. * * @constructor ReactDOMComponent * @extends ReactMultiChild */ function ReactDOMComponent(tag) { validateDangerousTag(tag); this._tag = tag.toLowerCase(); this._renderedChildren = null; this._previousStyle = null; this._previousStyleCopy = null; this._rootNodeID = null; this._wrapperState = null; this._topLevelWrapper = null; this._nodeWithLegacyProperties = null; if (process.env.NODE_ENV !== 'production') { this._unprocessedContextDev = null; this._processedContextDev = null; } } ReactDOMComponent.displayName = 'ReactDOMComponent'; ReactDOMComponent.Mixin = { construct: function (element) { this._currentElement = element; }, /** * Generates root tag markup then recurses. This method has side effects and * is not idempotent. * * @internal * @param {string} rootID The root DOM ID for this node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} context * @return {string} The computed markup. */ mountComponent: function (rootID, transaction, context) { this._rootNodeID = rootID; var props = this._currentElement.props; switch (this._tag) { case 'iframe': case 'img': case 'form': case 'video': case 'audio': this._wrapperState = { listeners: null }; transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'button': props = ReactDOMButton.getNativeProps(this, props, context); break; case 'input': ReactDOMInput.mountWrapper(this, props, context); props = ReactDOMInput.getNativeProps(this, props, context); break; case 'option': ReactDOMOption.mountWrapper(this, props, context); props = ReactDOMOption.getNativeProps(this, props, context); break; case 'select': ReactDOMSelect.mountWrapper(this, props, context); props = ReactDOMSelect.getNativeProps(this, props, context); context = ReactDOMSelect.processChildContext(this, props, context); break; case 'textarea': ReactDOMTextarea.mountWrapper(this, props, context); props = ReactDOMTextarea.getNativeProps(this, props, context); break; } assertValidProps(this, props); if (process.env.NODE_ENV !== 'production') { if (context[validateDOMNesting.ancestorInfoContextKey]) { validateDOMNesting(this._tag, this, context[validateDOMNesting.ancestorInfoContextKey]); } } if (process.env.NODE_ENV !== 'production') { this._unprocessedContextDev = context; this._processedContextDev = processChildContextDev(context, this); context = this._processedContextDev; } var mountImage; if (transaction.useCreateElement) { var ownerDocument = context[ReactMount.ownerDocumentContextKey]; var el = ownerDocument.createElement(this._currentElement.type); DOMPropertyOperations.setAttributeForID(el, this._rootNodeID); // Populate node cache ReactMount.getID(el); this._updateDOMProperties({}, props, transaction, el); this._createInitialChildren(transaction, props, context, el); mountImage = el; } else { var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props); var tagContent = this._createContentMarkup(transaction, props, context); if (!tagContent && omittedCloseTags[this._tag]) { mountImage = tagOpen + '/>'; } else { mountImage = tagOpen + '>' + tagContent + '</' + this._currentElement.type + '>'; } } switch (this._tag) { case 'input': transaction.getReactMountReady().enqueue(mountReadyInputWrapper, this); // falls through case 'button': case 'select': case 'textarea': if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; } return mountImage; }, /** * Creates markup for the open tag and all attributes. * * This method has side effects because events get registered. * * Iterating over object properties is faster than iterating over arrays. * @see http://jsperf.com/obj-vs-arr-iteration * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @return {string} Markup of opening tag. */ _createOpenTagMarkupAndPutListeners: function (transaction, props) { var ret = '<' + this._currentElement.type; for (var propKey in props) { if (!props.hasOwnProperty(propKey)) { continue; } var propValue = props[propKey]; if (propValue == null) { continue; } if (registrationNameModules.hasOwnProperty(propKey)) { if (propValue) { enqueuePutListener(this._rootNodeID, propKey, propValue, transaction); } } else { if (propKey === STYLE) { if (propValue) { if (process.env.NODE_ENV !== 'production') { // See `_updateDOMProperties`. style block this._previousStyle = propValue; } propValue = this._previousStyleCopy = assign({}, props.style); } propValue = CSSPropertyOperations.createMarkupForStyles(propValue); } var markup = null; if (this._tag != null && isCustomComponent(this._tag, props)) { if (propKey !== CHILDREN) { markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue); } } else { markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue); } if (markup) { ret += ' ' + markup; } } } // For static pages, no need to put React ID and checksum. Saves lots of // bytes. if (transaction.renderToStaticMarkup) { return ret; } var markupForID = DOMPropertyOperations.createMarkupForID(this._rootNodeID); return ret + ' ' + markupForID; }, /** * Creates markup for the content between the tags. * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @param {object} context * @return {string} Content markup. */ _createContentMarkup: function (transaction, props, context) { var ret = ''; // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { ret = innerHTML.__html; } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; if (contentToUse != null) { // TODO: Validate that text is allowed as a child of this node ret = escapeTextContentForBrowser(contentToUse); } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); ret = mountImages.join(''); } } if (newlineEatingTags[this._tag] && ret.charAt(0) === '\n') { // text/html ignores the first character in these tags if it's a newline // Prefer to break application/xml over text/html (for now) by adding // a newline specifically to get eaten by the parser. (Alternately for // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first // \r is normalized out by HTMLTextAreaElement#value.) // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre> // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions> // See: <http://www.w3.org/TR/html5/syntax.html#newlines> // See: Parsing of "textarea" "listing" and "pre" elements // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody> return '\n' + ret; } else { return ret; } }, _createInitialChildren: function (transaction, props, context, el) { // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { setInnerHTML(el, innerHTML.__html); } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; if (contentToUse != null) { // TODO: Validate that text is allowed as a child of this node setTextContent(el, contentToUse); } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); for (var i = 0; i < mountImages.length; i++) { el.appendChild(mountImages[i]); } } } }, /** * Receives a next element and updates the component. * * @internal * @param {ReactElement} nextElement * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} context */ receiveComponent: function (nextElement, transaction, context) { var prevElement = this._currentElement; this._currentElement = nextElement; this.updateComponent(transaction, prevElement, nextElement, context); }, /** * Updates a native DOM component after it has already been allocated and * attached to the DOM. Reconciles the root DOM node, then recurses. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevElement * @param {ReactElement} nextElement * @internal * @overridable */ updateComponent: function (transaction, prevElement, nextElement, context) { var lastProps = prevElement.props; var nextProps = this._currentElement.props; switch (this._tag) { case 'button': lastProps = ReactDOMButton.getNativeProps(this, lastProps); nextProps = ReactDOMButton.getNativeProps(this, nextProps); break; case 'input': ReactDOMInput.updateWrapper(this); lastProps = ReactDOMInput.getNativeProps(this, lastProps); nextProps = ReactDOMInput.getNativeProps(this, nextProps); break; case 'option': lastProps = ReactDOMOption.getNativeProps(this, lastProps); nextProps = ReactDOMOption.getNativeProps(this, nextProps); break; case 'select': lastProps = ReactDOMSelect.getNativeProps(this, lastProps); nextProps = ReactDOMSelect.getNativeProps(this, nextProps); break; case 'textarea': ReactDOMTextarea.updateWrapper(this); lastProps = ReactDOMTextarea.getNativeProps(this, lastProps); nextProps = ReactDOMTextarea.getNativeProps(this, nextProps); break; } if (process.env.NODE_ENV !== 'production') { // If the context is reference-equal to the old one, pass down the same // processed object so the update bailout in ReactReconciler behaves // correctly (and identically in dev and prod). See #5005. if (this._unprocessedContextDev !== context) { this._unprocessedContextDev = context; this._processedContextDev = processChildContextDev(context, this); } context = this._processedContextDev; } assertValidProps(this, nextProps); this._updateDOMProperties(lastProps, nextProps, transaction, null); this._updateDOMChildren(lastProps, nextProps, transaction, context); if (!canDefineProperty && this._nodeWithLegacyProperties) { this._nodeWithLegacyProperties.props = nextProps; } if (this._tag === 'select') { // <select> value update needs to occur after <option> children // reconciliation transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this); } }, /** * Reconciles the properties by detecting differences in property values and * updating the DOM as necessary. This function is probably the single most * critical path for performance optimization. * * TODO: Benchmark whether checking for changed values in memory actually * improves performance (especially statically positioned elements). * TODO: Benchmark the effects of putting this at the top since 99% of props * do not change for a given reconciliation. * TODO: Benchmark areas that can be improved with caching. * * @private * @param {object} lastProps * @param {object} nextProps * @param {ReactReconcileTransaction} transaction * @param {?DOMElement} node */ _updateDOMProperties: function (lastProps, nextProps, transaction, node) { var propKey; var styleName; var styleUpdates; for (propKey in lastProps) { if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey)) { continue; } if (propKey === STYLE) { var lastStyle = this._previousStyleCopy; for (styleName in lastStyle) { if (lastStyle.hasOwnProperty(styleName)) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } this._previousStyleCopy = null; } else if (registrationNameModules.hasOwnProperty(propKey)) { if (lastProps[propKey]) { // Only call deleteListener if there was a listener previously or // else willDeleteListener gets called when there wasn't actually a // listener (e.g., onClick={null}) deleteListener(this._rootNodeID, propKey); } } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { if (!node) { node = ReactMount.getNode(this._rootNodeID); } DOMPropertyOperations.deleteValueForProperty(node, propKey); } } for (propKey in nextProps) { var nextProp = nextProps[propKey]; var lastProp = propKey === STYLE ? this._previousStyleCopy : lastProps[propKey]; if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp) { continue; } if (propKey === STYLE) { if (nextProp) { if (process.env.NODE_ENV !== 'production') { checkAndWarnForMutatedStyle(this._previousStyleCopy, this._previousStyle, this); this._previousStyle = nextProp; } nextProp = this._previousStyleCopy = assign({}, nextProp); } else { this._previousStyleCopy = null; } if (lastProp) { // Unset styles on `lastProp` but not on `nextProp`. for (styleName in lastProp) { if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } // Update styles that changed since `lastProp`. for (styleName in nextProp) { if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = nextProp[styleName]; } } } else { // Relies on `updateStylesByID` not mutating `styleUpdates`. styleUpdates = nextProp; } } else if (registrationNameModules.hasOwnProperty(propKey)) { if (nextProp) { enqueuePutListener(this._rootNodeID, propKey, nextProp, transaction); } else if (lastProp) { deleteListener(this._rootNodeID, propKey); } } else if (isCustomComponent(this._tag, nextProps)) { if (!node) { node = ReactMount.getNode(this._rootNodeID); } if (propKey === CHILDREN) { nextProp = null; } DOMPropertyOperations.setValueForAttribute(node, propKey, nextProp); } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { if (!node) { node = ReactMount.getNode(this._rootNodeID); } // If we're updating to null or undefined, we should remove the property // from the DOM node instead of inadvertantly setting to a string. This // brings us in line with the same behavior we have on initial render. if (nextProp != null) { DOMPropertyOperations.setValueForProperty(node, propKey, nextProp); } else { DOMPropertyOperations.deleteValueForProperty(node, propKey); } } } if (styleUpdates) { if (!node) { node = ReactMount.getNode(this._rootNodeID); } CSSPropertyOperations.setValueForStyles(node, styleUpdates); } }, /** * Reconciles the children with the various properties that affect the * children content. * * @param {object} lastProps * @param {object} nextProps * @param {ReactReconcileTransaction} transaction * @param {object} context */ _updateDOMChildren: function (lastProps, nextProps, transaction, context) { var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null; var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null; var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html; var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html; // Note the use of `!=` which checks for null or undefined. var lastChildren = lastContent != null ? null : lastProps.children; var nextChildren = nextContent != null ? null : nextProps.children; // If we're switching from children to content/html or vice versa, remove // the old content var lastHasContentOrHtml = lastContent != null || lastHtml != null; var nextHasContentOrHtml = nextContent != null || nextHtml != null; if (lastChildren != null && nextChildren == null) { this.updateChildren(null, transaction, context); } else if (lastHasContentOrHtml && !nextHasContentOrHtml) { this.updateTextContent(''); } if (nextContent != null) { if (lastContent !== nextContent) { this.updateTextContent('' + nextContent); } } else if (nextHtml != null) { if (lastHtml !== nextHtml) { this.updateMarkup('' + nextHtml); } } else if (nextChildren != null) { this.updateChildren(nextChildren, transaction, context); } }, /** * Destroys all event registrations for this instance. Does not remove from * the DOM. That must be done by the parent. * * @internal */ unmountComponent: function () { switch (this._tag) { case 'iframe': case 'img': case 'form': case 'video': case 'audio': var listeners = this._wrapperState.listeners; if (listeners) { for (var i = 0; i < listeners.length; i++) { listeners[i].remove(); } } break; case 'input': ReactDOMInput.unmountWrapper(this); break; case 'html': case 'head': case 'body': /** * Components like <html> <head> and <body> can't be removed or added * easily in a cross-browser way, however it's valuable to be able to * take advantage of React's reconciliation for styling and <title> * management. So we just document it and throw in dangerous cases. */ true ? process.env.NODE_ENV !== 'production' ? invariant(false, '<%s> tried to unmount. Because of cross-browser quirks it is ' + 'impossible to unmount some top-level components (eg <html>, ' + '<head>, and <body>) reliably and efficiently. To fix this, have a ' + 'single top-level component that never unmounts render these ' + 'elements.', this._tag) : invariant(false) : undefined; break; } this.unmountChildren(); ReactBrowserEventEmitter.deleteAllListeners(this._rootNodeID); ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID); this._rootNodeID = null; this._wrapperState = null; if (this._nodeWithLegacyProperties) { var node = this._nodeWithLegacyProperties; node._reactInternalComponent = null; this._nodeWithLegacyProperties = null; } }, getPublicInstance: function () { if (!this._nodeWithLegacyProperties) { var node = ReactMount.getNode(this._rootNodeID); node._reactInternalComponent = this; node.getDOMNode = legacyGetDOMNode; node.isMounted = legacyIsMounted; node.setState = legacySetStateEtc; node.replaceState = legacySetStateEtc; node.forceUpdate = legacySetStateEtc; node.setProps = legacySetProps; node.replaceProps = legacyReplaceProps; if (process.env.NODE_ENV !== 'production') { if (canDefineProperty) { Object.defineProperties(node, legacyPropsDescriptor); } else { // updateComponent will update this property on subsequent renders node.props = this._currentElement.props; } } else { // updateComponent will update this property on subsequent renders node.props = this._currentElement.props; } this._nodeWithLegacyProperties = node; } return this._nodeWithLegacyProperties; } }; ReactPerf.measureMethods(ReactDOMComponent, 'ReactDOMComponent', { mountComponent: 'mountComponent', updateComponent: 'updateComponent' }); assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin); module.exports = ReactDOMComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 100 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule AutoFocusUtils * @typechecks static-only */ 'use strict'; var ReactMount = __webpack_require__(34); var findDOMNode = __webpack_require__(97); var focusNode = __webpack_require__(101); var Mixin = { componentDidMount: function () { if (this.props.autoFocus) { focusNode(findDOMNode(this)); } } }; var AutoFocusUtils = { Mixin: Mixin, focusDOMComponent: function () { focusNode(ReactMount.getNode(this._rootNodeID)); } }; module.exports = AutoFocusUtils; /***/ }, /* 101 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule focusNode */ 'use strict'; /** * @param {DOMElement} node input/textarea to focus */ function focusNode(node) { // IE8 can throw "Can't move focus to the control because it is invisible, // not enabled, or of a type that does not accept the focus." for all kinds of // reasons that are too expensive and fragile to test. try { node.focus(); } catch (e) {} } module.exports = focusNode; /***/ }, /* 102 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSPropertyOperations * @typechecks static-only */ 'use strict'; var CSSProperty = __webpack_require__(103); var ExecutionEnvironment = __webpack_require__(15); var ReactPerf = __webpack_require__(24); var camelizeStyleName = __webpack_require__(104); var dangerousStyleValue = __webpack_require__(106); var hyphenateStyleName = __webpack_require__(107); var memoizeStringOnly = __webpack_require__(109); var warning = __webpack_require__(31); var processStyleName = memoizeStringOnly(function (styleName) { return hyphenateStyleName(styleName); }); var hasShorthandPropertyBug = false; var styleFloatAccessor = 'cssFloat'; if (ExecutionEnvironment.canUseDOM) { var tempStyle = document.createElement('div').style; try { // IE8 throws "Invalid argument." if resetting shorthand style properties. tempStyle.font = ''; } catch (e) { hasShorthandPropertyBug = true; } // IE8 only supports accessing cssFloat (standard) as styleFloat if (document.documentElement.style.cssFloat === undefined) { styleFloatAccessor = 'styleFloat'; } } if (process.env.NODE_ENV !== 'production') { // 'msTransform' is correct, but the other prefixes should be capitalized var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; // style values shouldn't contain a semicolon var badStyleValueWithSemicolonPattern = /;\s*$/; var warnedStyleNames = {}; var warnedStyleValues = {}; var warnHyphenatedStyleName = function (name) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported style property %s. Did you mean %s?', name, camelizeStyleName(name)) : undefined; }; var warnBadVendoredStyleName = function (name) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1)) : undefined; }; var warnStyleValueWithSemicolon = function (name, value) { if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { return; } warnedStyleValues[value] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Style property values shouldn\'t contain a semicolon. ' + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, '')) : undefined; }; /** * @param {string} name * @param {*} value */ var warnValidStyle = function (name, value) { if (name.indexOf('-') > -1) { warnHyphenatedStyleName(name); } else if (badVendoredStyleNamePattern.test(name)) { warnBadVendoredStyleName(name); } else if (badStyleValueWithSemicolonPattern.test(value)) { warnStyleValueWithSemicolon(name, value); } }; } /** * Operations for dealing with CSS properties. */ var CSSPropertyOperations = { /** * Serializes a mapping of style properties for use as inline styles: * * > createMarkupForStyles({width: '200px', height: 0}) * "width:200px;height:0;" * * Undefined values are ignored so that declarative programming is easier. * The result should be HTML-escaped before insertion into the DOM. * * @param {object} styles * @return {?string} */ createMarkupForStyles: function (styles) { var serialized = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = styles[styleName]; if (process.env.NODE_ENV !== 'production') { warnValidStyle(styleName, styleValue); } if (styleValue != null) { serialized += processStyleName(styleName) + ':'; serialized += dangerousStyleValue(styleName, styleValue) + ';'; } } return serialized || null; }, /** * Sets the value for multiple styles on a node. If a value is specified as * '' (empty string), the corresponding style property will be unset. * * @param {DOMElement} node * @param {object} styles */ setValueForStyles: function (node, styles) { var style = node.style; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } if (process.env.NODE_ENV !== 'production') { warnValidStyle(styleName, styles[styleName]); } var styleValue = dangerousStyleValue(styleName, styles[styleName]); if (styleName === 'float') { styleName = styleFloatAccessor; } if (styleValue) { style[styleName] = styleValue; } else { var expansion = hasShorthandPropertyBug && CSSProperty.shorthandPropertyExpansions[styleName]; if (expansion) { // Shorthand property that IE8 won't like unsetting, so unset each // component to placate it for (var individualStyleName in expansion) { style[individualStyleName] = ''; } } else { style[styleName] = ''; } } } } }; ReactPerf.measureMethods(CSSPropertyOperations, 'CSSPropertyOperations', { setValueForStyles: 'setValueForStyles' }); module.exports = CSSPropertyOperations; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 103 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSProperty */ 'use strict'; /** * CSS properties which accept numbers but are not in units of "px". */ var isUnitlessNumber = { animationIterationCount: true, boxFlex: true, boxFlexGroup: true, boxOrdinalGroup: true, columnCount: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, flexOrder: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, tabSize: true, widows: true, zIndex: true, zoom: true, // SVG-related properties fillOpacity: true, stopOpacity: true, strokeDashoffset: true, strokeOpacity: true, strokeWidth: true }; /** * @param {string} prefix vendor-specific prefix, eg: Webkit * @param {string} key style name, eg: transitionDuration * @return {string} style name prefixed with `prefix`, properly camelCased, eg: * WebkitTransitionDuration */ function prefixKey(prefix, key) { return prefix + key.charAt(0).toUpperCase() + key.substring(1); } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber).forEach(function (prop) { prefixes.forEach(function (prefix) { isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; }); }); /** * Most style properties can be unset by doing .style[prop] = '' but IE8 * doesn't like doing that with shorthand properties so for the properties that * IE8 breaks on, which are listed here, we instead unset each of the * individual properties. See http://bugs.jquery.com/ticket/12385. * The 4-value 'clock' properties like margin, padding, border-width seem to * behave without any problems. Curiously, list-style works too without any * special prodding. */ var shorthandPropertyExpansions = { background: { backgroundAttachment: true, backgroundColor: true, backgroundImage: true, backgroundPositionX: true, backgroundPositionY: true, backgroundRepeat: true }, backgroundPosition: { backgroundPositionX: true, backgroundPositionY: true }, border: { borderWidth: true, borderStyle: true, borderColor: true }, borderBottom: { borderBottomWidth: true, borderBottomStyle: true, borderBottomColor: true }, borderLeft: { borderLeftWidth: true, borderLeftStyle: true, borderLeftColor: true }, borderRight: { borderRightWidth: true, borderRightStyle: true, borderRightColor: true }, borderTop: { borderTopWidth: true, borderTopStyle: true, borderTopColor: true }, font: { fontStyle: true, fontVariant: true, fontWeight: true, fontSize: true, lineHeight: true, fontFamily: true }, outline: { outlineWidth: true, outlineStyle: true, outlineColor: true } }; var CSSProperty = { isUnitlessNumber: isUnitlessNumber, shorthandPropertyExpansions: shorthandPropertyExpansions }; module.exports = CSSProperty; /***/ }, /* 104 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule camelizeStyleName * @typechecks */ 'use strict'; var camelize = __webpack_require__(105); var msPattern = /^-ms-/; /** * Camelcases a hyphenated CSS property name, for example: * * > camelizeStyleName('background-color') * < "backgroundColor" * > camelizeStyleName('-moz-transition') * < "MozTransition" * > camelizeStyleName('-ms-transition') * < "msTransition" * * As Andi Smith suggests * (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix * is converted to lowercase `ms`. * * @param {string} string * @return {string} */ function camelizeStyleName(string) { return camelize(string.replace(msPattern, 'ms-')); } module.exports = camelizeStyleName; /***/ }, /* 105 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule camelize * @typechecks */ "use strict"; var _hyphenPattern = /-(.)/g; /** * Camelcases a hyphenated string, for example: * * > camelize('background-color') * < "backgroundColor" * * @param {string} string * @return {string} */ function camelize(string) { return string.replace(_hyphenPattern, function (_, character) { return character.toUpperCase(); }); } module.exports = camelize; /***/ }, /* 106 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule dangerousStyleValue * @typechecks static-only */ 'use strict'; var CSSProperty = __webpack_require__(103); var isUnitlessNumber = CSSProperty.isUnitlessNumber; /** * Convert a value into the proper css writable value. The style name `name` * should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} name CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(name, value) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = value == null || typeof value === 'boolean' || value === ''; if (isEmpty) { return ''; } var isNonNumeric = isNaN(value); if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) { return '' + value; // cast to string } if (typeof value === 'string') { value = value.trim(); } return value + 'px'; } module.exports = dangerousStyleValue; /***/ }, /* 107 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule hyphenateStyleName * @typechecks */ 'use strict'; var hyphenate = __webpack_require__(108); var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return hyphenate(string).replace(msPattern, '-ms-'); } module.exports = hyphenateStyleName; /***/ }, /* 108 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule hyphenate * @typechecks */ 'use strict'; var _uppercasePattern = /([A-Z])/g; /** * Hyphenates a camelcased string, for example: * * > hyphenate('backgroundColor') * < "background-color" * * For CSS style names, use `hyphenateStyleName` instead which works properly * with all vendor prefixes, including `ms`. * * @param {string} string * @return {string} */ function hyphenate(string) { return string.replace(_uppercasePattern, '-$1').toLowerCase(); } module.exports = hyphenate; /***/ }, /* 109 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule memoizeStringOnly * @typechecks static-only */ 'use strict'; /** * Memoizes the return value of a function that accepts one string argument. * * @param {function} callback * @return {function} */ function memoizeStringOnly(callback) { var cache = {}; return function (string) { if (!cache.hasOwnProperty(string)) { cache[string] = callback.call(this, string); } return cache[string]; }; } module.exports = memoizeStringOnly; /***/ }, /* 110 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMButton */ 'use strict'; var mouseListenerNames = { onClick: true, onDoubleClick: true, onMouseDown: true, onMouseMove: true, onMouseUp: true, onClickCapture: true, onDoubleClickCapture: true, onMouseDownCapture: true, onMouseMoveCapture: true, onMouseUpCapture: true }; /** * Implements a <button> native component that does not receive mouse events * when `disabled` is set. */ var ReactDOMButton = { getNativeProps: function (inst, props, context) { if (!props.disabled) { return props; } // Copy the props, except the mouse listeners var nativeProps = {}; for (var key in props) { if (props.hasOwnProperty(key) && !mouseListenerNames[key]) { nativeProps[key] = props[key]; } } return nativeProps; } }; module.exports = ReactDOMButton; /***/ }, /* 111 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMInput */ 'use strict'; var ReactDOMIDOperations = __webpack_require__(33); var LinkedValueUtils = __webpack_require__(112); var ReactMount = __webpack_require__(34); var ReactUpdates = __webpack_require__(60); var assign = __webpack_require__(45); var invariant = __webpack_require__(19); var instancesByReactID = {}; function forceUpdateIfMounted() { if (this._rootNodeID) { // DOM component is still mounted; update ReactDOMInput.updateWrapper(this); } } /** * Implements an <input> native component that allows setting these optional * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. * * If `checked` or `value` are not supplied (or null/undefined), user actions * that affect the checked state or value will trigger updates to the element. * * If they are supplied (and not null/undefined), the rendered element will not * trigger updates to the element. Instead, the props must change in order for * the rendered element to be updated. * * The rendered element will be initialized as unchecked (or `defaultChecked`) * with an empty value (or `defaultValue`). * * @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html */ var ReactDOMInput = { getNativeProps: function (inst, props, context) { var value = LinkedValueUtils.getValue(props); var checked = LinkedValueUtils.getChecked(props); var nativeProps = assign({}, props, { defaultChecked: undefined, defaultValue: undefined, value: value != null ? value : inst._wrapperState.initialValue, checked: checked != null ? checked : inst._wrapperState.initialChecked, onChange: inst._wrapperState.onChange }); return nativeProps; }, mountWrapper: function (inst, props) { if (process.env.NODE_ENV !== 'production') { LinkedValueUtils.checkPropTypes('input', props, inst._currentElement._owner); } var defaultValue = props.defaultValue; inst._wrapperState = { initialChecked: props.defaultChecked || false, initialValue: defaultValue != null ? defaultValue : null, onChange: _handleChange.bind(inst) }; }, mountReadyWrapper: function (inst) { // Can't be in mountWrapper or else server rendering leaks. instancesByReactID[inst._rootNodeID] = inst; }, unmountWrapper: function (inst) { delete instancesByReactID[inst._rootNodeID]; }, updateWrapper: function (inst) { var props = inst._currentElement.props; // TODO: Shouldn't this be getChecked(props)? var checked = props.checked; if (checked != null) { ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'checked', checked || false); } var value = LinkedValueUtils.getValue(props); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'value', '' + value); } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); // Here we use asap to wait until all updates have propagated, which // is important when using controlled components within layers: // https://github.com/facebook/react/issues/1698 ReactUpdates.asap(forceUpdateIfMounted, this); var name = props.name; if (props.type === 'radio' && name != null) { var rootNode = ReactMount.getNode(this._rootNodeID); var queryRoot = rootNode; while (queryRoot.parentNode) { queryRoot = queryRoot.parentNode; } // If `rootNode.form` was non-null, then we could try `form.elements`, // but that sometimes behaves strangely in IE8. We could also try using // `form.getElementsByName`, but that will only return direct children // and won't include inputs that use the HTML5 `form=` attribute. Since // the input might not even be in a form, let's just use the global // `querySelectorAll` to ensure we don't miss anything. var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]'); for (var i = 0; i < group.length; i++) { var otherNode = group[i]; if (otherNode === rootNode || otherNode.form !== rootNode.form) { continue; } // This will throw if radio buttons rendered by different copies of React // and the same name are rendered into the same form (same as #1939). // That's probably okay; we don't support it just as we don't support // mixing React with non-React. var otherID = ReactMount.getID(otherNode); !otherID ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.') : invariant(false) : undefined; var otherInstance = instancesByReactID[otherID]; !otherInstance ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOMInput: Unknown radio button ID %s.', otherID) : invariant(false) : undefined; // If this is a controlled radio button group, forcing the input that // was previously checked to update will cause it to be come re-checked // as appropriate. ReactUpdates.asap(forceUpdateIfMounted, otherInstance); } } return returnValue; } module.exports = ReactDOMInput; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 112 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule LinkedValueUtils * @typechecks static-only */ 'use strict'; var ReactPropTypes = __webpack_require__(113); var ReactPropTypeLocations = __webpack_require__(71); var invariant = __webpack_require__(19); var warning = __webpack_require__(31); var hasReadOnlyValue = { 'button': true, 'checkbox': true, 'image': true, 'hidden': true, 'radio': true, 'reset': true, 'submit': true }; function _assertSingleLink(inputProps) { !(inputProps.checkedLink == null || inputProps.valueLink == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a valueLink. If you want to use ' + 'checkedLink, you probably don\'t want to use valueLink and vice versa.') : invariant(false) : undefined; } function _assertValueLink(inputProps) { _assertSingleLink(inputProps); !(inputProps.value == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a valueLink and a value or onChange event. If you want ' + 'to use value or onChange, you probably don\'t want to use valueLink.') : invariant(false) : undefined; } function _assertCheckedLink(inputProps) { _assertSingleLink(inputProps); !(inputProps.checked == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a checked property or onChange event. ' + 'If you want to use checked or onChange, you probably don\'t want to ' + 'use checkedLink') : invariant(false) : undefined; } var propTypes = { value: function (props, propName, componentName) { if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, checked: function (props, propName, componentName) { if (!props[propName] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, onChange: ReactPropTypes.func }; var loggedTypeFailures = {}; function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Provide a linked `value` attribute for controlled forms. You should not use * this outside of the ReactDOM controlled form components. */ var LinkedValueUtils = { checkPropTypes: function (tagName, props, owner) { for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error = propTypes[propName](props, propName, tagName, ReactPropTypeLocations.prop); } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var addendum = getDeclarationErrorAddendum(owner); process.env.NODE_ENV !== 'production' ? warning(false, 'Failed form propType: %s%s', error.message, addendum) : undefined; } } }, /** * @param {object} inputProps Props for form component * @return {*} current value of the input either from value prop or link. */ getValue: function (inputProps) { if (inputProps.valueLink) { _assertValueLink(inputProps); return inputProps.valueLink.value; } return inputProps.value; }, /** * @param {object} inputProps Props for form component * @return {*} current checked status of the input either from checked prop * or link. */ getChecked: function (inputProps) { if (inputProps.checkedLink) { _assertCheckedLink(inputProps); return inputProps.checkedLink.value; } return inputProps.checked; }, /** * @param {object} inputProps Props for form component * @param {SyntheticEvent} event change event to handle */ executeOnChange: function (inputProps, event) { if (inputProps.valueLink) { _assertValueLink(inputProps); return inputProps.valueLink.requestChange(event.target.value); } else if (inputProps.checkedLink) { _assertCheckedLink(inputProps); return inputProps.checkedLink.requestChange(event.target.checked); } else if (inputProps.onChange) { return inputProps.onChange.call(undefined, event); } } }; module.exports = LinkedValueUtils; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 113 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypes */ 'use strict'; var ReactElement = __webpack_require__(48); var ReactPropTypeLocationNames = __webpack_require__(72); var emptyFunction = __webpack_require__(21); var getIteratorFn = __webpack_require__(114); /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker }; function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName, location, propFullName) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (props[propName] == null) { var locationName = ReactPropTypeLocationNames[location]; if (isRequired) { return new Error('Required ' + locationName + ' `' + propFullName + '` was not specified in ' + ('`' + componentName + '`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { var locationName = ReactPropTypeLocationNames[location]; // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturns(null)); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!Array.isArray(propValue)) { var locationName = ReactPropTypeLocationNames[location]; var propType = getPropType(propValue); return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']'); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!ReactElement.isValidElement(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var locationName = ReactPropTypeLocationNames[location]; var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { return createChainableTypeChecker(function () { return new Error('Invalid argument supplied to oneOf, expected an instance of array.'); }); } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (propValue === expectedValues[i]) { return null; } } var locationName = ReactPropTypeLocationNames[location]; var valuesString = JSON.stringify(expectedValues); return new Error('Invalid ' + locationName + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { return createChainableTypeChecker(function () { return new Error('Invalid argument supplied to oneOfType, expected an instance of array.'); }); } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName) == null) { return null; } } var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || ReactElement.isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return '<<anonymous>>'; } return propValue.constructor.name; } module.exports = ReactPropTypes; /***/ }, /* 114 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getIteratorFn * @typechecks static-only */ 'use strict'; /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } module.exports = getIteratorFn; /***/ }, /* 115 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMOption */ 'use strict'; var ReactChildren = __webpack_require__(116); var ReactDOMSelect = __webpack_require__(118); var assign = __webpack_require__(45); var warning = __webpack_require__(31); var valueContextKey = ReactDOMSelect.valueContextKey; /** * Implements an <option> native component that warns when `selected` is set. */ var ReactDOMOption = { mountWrapper: function (inst, props, context) { // TODO (yungsters): Remove support for `selected` in <option>. if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.') : undefined; } // Look up whether this option is 'selected' via context var selectValue = context[valueContextKey]; // If context key is null (e.g., no specified value or after initial mount) // or missing (e.g., for <datalist>), we don't change props.selected var selected = null; if (selectValue != null) { selected = false; if (Array.isArray(selectValue)) { // multiple for (var i = 0; i < selectValue.length; i++) { if ('' + selectValue[i] === '' + props.value) { selected = true; break; } } } else { selected = '' + selectValue === '' + props.value; } } inst._wrapperState = { selected: selected }; }, getNativeProps: function (inst, props, context) { var nativeProps = assign({ selected: undefined, children: undefined }, props); // Read state only from initial mount because <select> updates value // manually; we need the initial state only for server rendering if (inst._wrapperState.selected != null) { nativeProps.selected = inst._wrapperState.selected; } var content = ''; // Flatten children and warn if they aren't strings or numbers; // invalid types are ignored. ReactChildren.forEach(props.children, function (child) { if (child == null) { return; } if (typeof child === 'string' || typeof child === 'number') { content += child; } else { process.env.NODE_ENV !== 'production' ? warning(false, 'Only strings and numbers are supported as <option> children.') : undefined; } }); if (content) { nativeProps.children = content; } return nativeProps; } }; module.exports = ReactDOMOption; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 116 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactChildren */ 'use strict'; var PooledClass = __webpack_require__(62); var ReactElement = __webpack_require__(48); var emptyFunction = __webpack_require__(21); var traverseAllChildren = __webpack_require__(117); var twoArgumentPooler = PooledClass.twoArgumentPooler; var fourArgumentPooler = PooledClass.fourArgumentPooler; var userProvidedKeyEscapeRegex = /\/(?!\/)/g; function escapeUserProvidedKey(text) { return ('' + text).replace(userProvidedKeyEscapeRegex, '//'); } /** * PooledClass representing the bookkeeping associated with performing a child * traversal. Allows avoiding binding callbacks. * * @constructor ForEachBookKeeping * @param {!function} forEachFunction Function to perform traversal with. * @param {?*} forEachContext Context to perform context with. */ function ForEachBookKeeping(forEachFunction, forEachContext) { this.func = forEachFunction; this.context = forEachContext; this.count = 0; } ForEachBookKeeping.prototype.destructor = function () { this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler); function forEachSingleChild(bookKeeping, child, name) { var func = bookKeeping.func; var context = bookKeeping.context; func.call(context, child, bookKeeping.count++); } /** * Iterates through children that are typically specified as `props.children`. * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { if (children == null) { return children; } var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext); traverseAllChildren(children, forEachSingleChild, traverseContext); ForEachBookKeeping.release(traverseContext); } /** * PooledClass representing the bookkeeping associated with performing a child * mapping. Allows avoiding binding callbacks. * * @constructor MapBookKeeping * @param {!*} mapResult Object containing the ordered map of results. * @param {!function} mapFunction Function to perform mapping with. * @param {?*} mapContext Context to perform mapping with. */ function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) { this.result = mapResult; this.keyPrefix = keyPrefix; this.func = mapFunction; this.context = mapContext; this.count = 0; } MapBookKeeping.prototype.destructor = function () { this.result = null; this.keyPrefix = null; this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler); function mapSingleChildIntoContext(bookKeeping, child, childKey) { var result = bookKeeping.result; var keyPrefix = bookKeeping.keyPrefix; var func = bookKeeping.func; var context = bookKeeping.context; var mappedChild = func.call(context, child, bookKeeping.count++); if (Array.isArray(mappedChild)) { mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument); } else if (mappedChild != null) { if (ReactElement.isValidElement(mappedChild)) { mappedChild = ReactElement.cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children keyPrefix + (mappedChild !== child ? escapeUserProvidedKey(mappedChild.key || '') + '/' : '') + childKey); } result.push(mappedChild); } } function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) { var escapedPrefix = ''; if (prefix != null) { escapedPrefix = escapeUserProvidedKey(prefix) + '/'; } var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); MapBookKeeping.release(traverseContext); } /** * Maps children that are typically specified as `props.children`. * * The provided mapFunction(child, key, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} func The map function. * @param {*} context Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var result = []; mapIntoWithKeyPrefixInternal(children, result, null, func, context); return result; } function forEachSingleChildDummy(traverseContext, child, name) { return null; } /** * Count the number of children that are typically specified as * `props.children`. * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children, context) { return traverseAllChildren(children, forEachSingleChildDummy, null); } /** * Flatten a children object (typically specified as `props.children`) and * return an array with appropriately re-keyed children. */ function toArray(children) { var result = []; mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument); return result; } var ReactChildren = { forEach: forEachChildren, map: mapChildren, mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal, count: countChildren, toArray: toArray }; module.exports = ReactChildren; /***/ }, /* 117 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule traverseAllChildren */ 'use strict'; var ReactCurrentOwner = __webpack_require__(11); var ReactElement = __webpack_require__(48); var ReactInstanceHandles = __webpack_require__(51); var getIteratorFn = __webpack_require__(114); var invariant = __webpack_require__(19); var warning = __webpack_require__(31); var SEPARATOR = ReactInstanceHandles.SEPARATOR; var SUBSEPARATOR = ':'; /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var userProvidedKeyEscaperLookup = { '=': '=0', '.': '=1', ':': '=2' }; var userProvidedKeyEscapeRegex = /[=.:]/g; var didWarnAboutMaps = false; function userProvidedKeyEscaper(match) { return userProvidedKeyEscaperLookup[match]; } /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { if (component && component.key != null) { // Explicit key return wrapUserProvidedKey(component.key); } // Implicit key determined by the index in the set return index.toString(36); } /** * Escape a component key so that it is safe to use in a reactid. * * @param {*} text Component key to be escaped. * @return {string} An escaped string. */ function escapeUserProvidedKey(text) { return ('' + text).replace(userProvidedKeyEscapeRegex, userProvidedKeyEscaper); } /** * Wrap a `key` value explicitly provided by the user to distinguish it from * implicitly-generated keys generated by a component's index in its parent. * * @param {string} key Value of a user-provided `key` attribute * @return {string} */ function wrapUserProvidedKey(key) { return '$' + escapeUserProvidedKey(key); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } if (children === null || type === 'string' || type === 'number' || ReactElement.isValidElement(children)) { callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { var iteratorFn = getIteratorFn(children); if (iteratorFn) { var iterator = iteratorFn.call(children); var step; if (iteratorFn !== children.entries) { var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.') : undefined; didWarnAboutMaps = true; } // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { child = entry[1]; nextName = nextNamePrefix + wrapUserProvidedKey(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } } } else if (type === 'object') { var addendum = ''; if (process.env.NODE_ENV !== 'production') { addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.'; if (children._isReactElement) { addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.'; } if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { addendum += ' Check the render method of `' + name + '`.'; } } } var childrenString = String(children); true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : invariant(false) : undefined; } } return subtreeCount; } /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', callback, traverseContext); } module.exports = traverseAllChildren; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 118 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMSelect */ 'use strict'; var LinkedValueUtils = __webpack_require__(112); var ReactMount = __webpack_require__(34); var ReactUpdates = __webpack_require__(60); var assign = __webpack_require__(45); var warning = __webpack_require__(31); var valueContextKey = '__ReactDOMSelect_value$' + Math.random().toString(36).slice(2); function updateOptionsIfPendingUpdateAndMounted() { if (this._rootNodeID && this._wrapperState.pendingUpdate) { this._wrapperState.pendingUpdate = false; var props = this._currentElement.props; var value = LinkedValueUtils.getValue(props); if (value != null) { updateOptions(this, Boolean(props.multiple), value); } } } function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } var valuePropNames = ['value', 'defaultValue']; /** * Validation function for `value` and `defaultValue`. * @private */ function checkSelectPropTypes(inst, props) { var owner = inst._currentElement._owner; LinkedValueUtils.checkPropTypes('select', props, owner); for (var i = 0; i < valuePropNames.length; i++) { var propName = valuePropNames[i]; if (props[propName] == null) { continue; } if (props.multiple) { process.env.NODE_ENV !== 'production' ? warning(Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum(owner)) : undefined; } else { process.env.NODE_ENV !== 'production' ? warning(!Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum(owner)) : undefined; } } } /** * @param {ReactDOMComponent} inst * @param {boolean} multiple * @param {*} propValue A stringable (with `multiple`, a list of stringables). * @private */ function updateOptions(inst, multiple, propValue) { var selectedValue, i; var options = ReactMount.getNode(inst._rootNodeID).options; if (multiple) { selectedValue = {}; for (i = 0; i < propValue.length; i++) { selectedValue['' + propValue[i]] = true; } for (i = 0; i < options.length; i++) { var selected = selectedValue.hasOwnProperty(options[i].value); if (options[i].selected !== selected) { options[i].selected = selected; } } } else { // Do not set `select.value` as exact behavior isn't consistent across all // browsers for all cases. selectedValue = '' + propValue; for (i = 0; i < options.length; i++) { if (options[i].value === selectedValue) { options[i].selected = true; return; } } if (options.length) { options[0].selected = true; } } } /** * Implements a <select> native component that allows optionally setting the * props `value` and `defaultValue`. If `multiple` is false, the prop must be a * stringable. If `multiple` is true, the prop must be an array of stringables. * * If `value` is not supplied (or null/undefined), user actions that change the * selected option will trigger updates to the rendered options. * * If it is supplied (and not null/undefined), the rendered options will not * update in response to user actions. Instead, the `value` prop must change in * order for the rendered options to update. * * If `defaultValue` is provided, any options with the supplied values will be * selected. */ var ReactDOMSelect = { valueContextKey: valueContextKey, getNativeProps: function (inst, props, context) { return assign({}, props, { onChange: inst._wrapperState.onChange, value: undefined }); }, mountWrapper: function (inst, props) { if (process.env.NODE_ENV !== 'production') { checkSelectPropTypes(inst, props); } var value = LinkedValueUtils.getValue(props); inst._wrapperState = { pendingUpdate: false, initialValue: value != null ? value : props.defaultValue, onChange: _handleChange.bind(inst), wasMultiple: Boolean(props.multiple) }; }, processChildContext: function (inst, props, context) { // Pass down initial value so initial generated markup has correct // `selected` attributes var childContext = assign({}, context); childContext[valueContextKey] = inst._wrapperState.initialValue; return childContext; }, postUpdateWrapper: function (inst) { var props = inst._currentElement.props; // After the initial mount, we control selected-ness manually so don't pass // the context value down inst._wrapperState.initialValue = undefined; var wasMultiple = inst._wrapperState.wasMultiple; inst._wrapperState.wasMultiple = Boolean(props.multiple); var value = LinkedValueUtils.getValue(props); if (value != null) { inst._wrapperState.pendingUpdate = false; updateOptions(inst, Boolean(props.multiple), value); } else if (wasMultiple !== Boolean(props.multiple)) { // For simplicity, reapply `defaultValue` if `multiple` is toggled. if (props.defaultValue != null) { updateOptions(inst, Boolean(props.multiple), props.defaultValue); } else { // Revert the select back to its default unselected state. updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : ''); } } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); this._wrapperState.pendingUpdate = true; ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this); return returnValue; } module.exports = ReactDOMSelect; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 119 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTextarea */ 'use strict'; var LinkedValueUtils = __webpack_require__(112); var ReactDOMIDOperations = __webpack_require__(33); var ReactUpdates = __webpack_require__(60); var assign = __webpack_require__(45); var invariant = __webpack_require__(19); var warning = __webpack_require__(31); function forceUpdateIfMounted() { if (this._rootNodeID) { // DOM component is still mounted; update ReactDOMTextarea.updateWrapper(this); } } /** * Implements a <textarea> native component that allows setting `value`, and * `defaultValue`. This differs from the traditional DOM API because value is * usually set as PCDATA children. * * If `value` is not supplied (or null/undefined), user actions that affect the * value will trigger updates to the element. * * If `value` is supplied (and not null/undefined), the rendered element will * not trigger updates to the element. Instead, the `value` prop must change in * order for the rendered element to be updated. * * The rendered element will be initialized with an empty value, the prop * `defaultValue` if specified, or the children content (deprecated). */ var ReactDOMTextarea = { getNativeProps: function (inst, props, context) { !(props.dangerouslySetInnerHTML == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : invariant(false) : undefined; // Always set children to the same thing. In IE9, the selection range will // get reset if `textContent` is mutated. var nativeProps = assign({}, props, { defaultValue: undefined, value: undefined, children: inst._wrapperState.initialValue, onChange: inst._wrapperState.onChange }); return nativeProps; }, mountWrapper: function (inst, props) { if (process.env.NODE_ENV !== 'production') { LinkedValueUtils.checkPropTypes('textarea', props, inst._currentElement._owner); } var defaultValue = props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>. var children = props.children; if (children != null) { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.') : undefined; } !(defaultValue == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : invariant(false) : undefined; if (Array.isArray(children)) { !(children.length <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, '<textarea> can only have at most one child.') : invariant(false) : undefined; children = children[0]; } defaultValue = '' + children; } if (defaultValue == null) { defaultValue = ''; } var value = LinkedValueUtils.getValue(props); inst._wrapperState = { // We save the initial value so that `ReactDOMComponent` doesn't update // `textContent` (unnecessary since we update value). // The initial value can be a boolean or object so that's why it's // forced to be a string. initialValue: '' + (value != null ? value : defaultValue), onChange: _handleChange.bind(inst) }; }, updateWrapper: function (inst) { var props = inst._currentElement.props; var value = LinkedValueUtils.getValue(props); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'value', '' + value); } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); ReactUpdates.asap(forceUpdateIfMounted, this); return returnValue; } module.exports = ReactDOMTextarea; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 120 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMultiChild * @typechecks static-only */ 'use strict'; var ReactComponentEnvironment = __webpack_require__(70); var ReactMultiChildUpdateTypes = __webpack_require__(22); var ReactCurrentOwner = __webpack_require__(11); var ReactReconciler = __webpack_require__(56); var ReactChildReconciler = __webpack_require__(121); var flattenChildren = __webpack_require__(122); /** * Updating children of a component may trigger recursive updates. The depth is * used to batch recursive updates to render markup more efficiently. * * @type {number} * @private */ var updateDepth = 0; /** * Queue of update configuration objects. * * Each object has a `type` property that is in `ReactMultiChildUpdateTypes`. * * @type {array<object>} * @private */ var updateQueue = []; /** * Queue of markup to be rendered. * * @type {array<string>} * @private */ var markupQueue = []; /** * Enqueues markup to be rendered and inserted at a supplied index. * * @param {string} parentID ID of the parent component. * @param {string} markup Markup that renders into an element. * @param {number} toIndex Destination index. * @private */ function enqueueInsertMarkup(parentID, markup, toIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.INSERT_MARKUP, markupIndex: markupQueue.push(markup) - 1, content: null, fromIndex: null, toIndex: toIndex }); } /** * Enqueues moving an existing element to another index. * * @param {string} parentID ID of the parent component. * @param {number} fromIndex Source index of the existing element. * @param {number} toIndex Destination index of the element. * @private */ function enqueueMove(parentID, fromIndex, toIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.MOVE_EXISTING, markupIndex: null, content: null, fromIndex: fromIndex, toIndex: toIndex }); } /** * Enqueues removing an element at an index. * * @param {string} parentID ID of the parent component. * @param {number} fromIndex Index of the element to remove. * @private */ function enqueueRemove(parentID, fromIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.REMOVE_NODE, markupIndex: null, content: null, fromIndex: fromIndex, toIndex: null }); } /** * Enqueues setting the markup of a node. * * @param {string} parentID ID of the parent component. * @param {string} markup Markup that renders into an element. * @private */ function enqueueSetMarkup(parentID, markup) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.SET_MARKUP, markupIndex: null, content: markup, fromIndex: null, toIndex: null }); } /** * Enqueues setting the text content. * * @param {string} parentID ID of the parent component. * @param {string} textContent Text content to set. * @private */ function enqueueTextContent(parentID, textContent) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.TEXT_CONTENT, markupIndex: null, content: textContent, fromIndex: null, toIndex: null }); } /** * Processes any enqueued updates. * * @private */ function processQueue() { if (updateQueue.length) { ReactComponentEnvironment.processChildrenUpdates(updateQueue, markupQueue); clearQueue(); } } /** * Clears any enqueued updates. * * @private */ function clearQueue() { updateQueue.length = 0; markupQueue.length = 0; } /** * ReactMultiChild are capable of reconciling multiple children. * * @class ReactMultiChild * @internal */ var ReactMultiChild = { /** * Provides common functionality for components that must reconcile multiple * children. This is used by `ReactDOMComponent` to mount, update, and * unmount child components. * * @lends {ReactMultiChild.prototype} */ Mixin: { _reconcilerInstantiateChildren: function (nestedChildren, transaction, context) { if (process.env.NODE_ENV !== 'production') { if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context); } finally { ReactCurrentOwner.current = null; } } } return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context); }, _reconcilerUpdateChildren: function (prevChildren, nextNestedChildrenElements, transaction, context) { var nextChildren; if (process.env.NODE_ENV !== 'production') { if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; nextChildren = flattenChildren(nextNestedChildrenElements); } finally { ReactCurrentOwner.current = null; } return ReactChildReconciler.updateChildren(prevChildren, nextChildren, transaction, context); } } nextChildren = flattenChildren(nextNestedChildrenElements); return ReactChildReconciler.updateChildren(prevChildren, nextChildren, transaction, context); }, /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildren Nested child maps. * @return {array} An array of mounted representations. * @internal */ mountChildren: function (nestedChildren, transaction, context) { var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context); this._renderedChildren = children; var mountImages = []; var index = 0; for (var name in children) { if (children.hasOwnProperty(name)) { var child = children[name]; // Inlined for performance, see `ReactInstanceHandles.createReactID`. var rootID = this._rootNodeID + name; var mountImage = ReactReconciler.mountComponent(child, rootID, transaction, context); child._mountIndex = index++; mountImages.push(mountImage); } } return mountImages; }, /** * Replaces any rendered children with a text content string. * * @param {string} nextContent String of content. * @internal */ updateTextContent: function (nextContent) { updateDepth++; var errorThrown = true; try { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren); // TODO: The setTextContent operation should be enough for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { this._unmountChild(prevChildren[name]); } } // Set new text content. this.setTextContent(nextContent); errorThrown = false; } finally { updateDepth--; if (!updateDepth) { if (errorThrown) { clearQueue(); } else { processQueue(); } } } }, /** * Replaces any rendered children with a markup string. * * @param {string} nextMarkup String of markup. * @internal */ updateMarkup: function (nextMarkup) { updateDepth++; var errorThrown = true; try { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { this._unmountChildByName(prevChildren[name], name); } } this.setMarkup(nextMarkup); errorThrown = false; } finally { updateDepth--; if (!updateDepth) { if (errorThrown) { clearQueue(); } else { processQueue(); } } } }, /** * Updates the rendered children with new children. * * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @internal */ updateChildren: function (nextNestedChildrenElements, transaction, context) { updateDepth++; var errorThrown = true; try { this._updateChildren(nextNestedChildrenElements, transaction, context); errorThrown = false; } finally { updateDepth--; if (!updateDepth) { if (errorThrown) { clearQueue(); } else { processQueue(); } } } }, /** * Improve performance by isolating this hot code path from the try/catch * block in `updateChildren`. * * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @final * @protected */ _updateChildren: function (nextNestedChildrenElements, transaction, context) { var prevChildren = this._renderedChildren; var nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, transaction, context); this._renderedChildren = nextChildren; if (!nextChildren && !prevChildren) { return; } var name; // `nextIndex` will increment for each child in `nextChildren`, but // `lastIndex` will be the last index visited in `prevChildren`. var lastIndex = 0; var nextIndex = 0; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } var prevChild = prevChildren && prevChildren[name]; var nextChild = nextChildren[name]; if (prevChild === nextChild) { this.moveChild(prevChild, nextIndex, lastIndex); lastIndex = Math.max(prevChild._mountIndex, lastIndex); prevChild._mountIndex = nextIndex; } else { if (prevChild) { // Update `lastIndex` before `_mountIndex` gets unset by unmounting. lastIndex = Math.max(prevChild._mountIndex, lastIndex); this._unmountChild(prevChild); } // The child must be instantiated before it's mounted. this._mountChildByNameAtIndex(nextChild, name, nextIndex, transaction, context); } nextIndex++; } // Remove children that are no longer present. for (name in prevChildren) { if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) { this._unmountChild(prevChildren[name]); } } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @internal */ unmountChildren: function () { var renderedChildren = this._renderedChildren; ReactChildReconciler.unmountChildren(renderedChildren); this._renderedChildren = null; }, /** * Moves a child component to the supplied index. * * @param {ReactComponent} child Component to move. * @param {number} toIndex Destination index of the element. * @param {number} lastIndex Last index visited of the siblings of `child`. * @protected */ moveChild: function (child, toIndex, lastIndex) { // If the index of `child` is less than `lastIndex`, then it needs to // be moved. Otherwise, we do not need to move it because a child will be // inserted or moved before `child`. if (child._mountIndex < lastIndex) { enqueueMove(this._rootNodeID, child._mountIndex, toIndex); } }, /** * Creates a child component. * * @param {ReactComponent} child Component to create. * @param {string} mountImage Markup to insert. * @protected */ createChild: function (child, mountImage) { enqueueInsertMarkup(this._rootNodeID, mountImage, child._mountIndex); }, /** * Removes a child component. * * @param {ReactComponent} child Child to remove. * @protected */ removeChild: function (child) { enqueueRemove(this._rootNodeID, child._mountIndex); }, /** * Sets this text content string. * * @param {string} textContent Text content to set. * @protected */ setTextContent: function (textContent) { enqueueTextContent(this._rootNodeID, textContent); }, /** * Sets this markup string. * * @param {string} markup Markup to set. * @protected */ setMarkup: function (markup) { enqueueSetMarkup(this._rootNodeID, markup); }, /** * Mounts a child with the supplied name. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to mount. * @param {string} name Name of the child. * @param {number} index Index at which to insert the child. * @param {ReactReconcileTransaction} transaction * @private */ _mountChildByNameAtIndex: function (child, name, index, transaction, context) { // Inlined for performance, see `ReactInstanceHandles.createReactID`. var rootID = this._rootNodeID + name; var mountImage = ReactReconciler.mountComponent(child, rootID, transaction, context); child._mountIndex = index; this.createChild(child, mountImage); }, /** * Unmounts a rendered child. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to unmount. * @private */ _unmountChild: function (child) { this.removeChild(child); child._mountIndex = null; } } }; module.exports = ReactMultiChild; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 121 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactChildReconciler * @typechecks static-only */ 'use strict'; var ReactReconciler = __webpack_require__(56); var instantiateReactComponent = __webpack_require__(68); var shouldUpdateReactComponent = __webpack_require__(73); var traverseAllChildren = __webpack_require__(117); var warning = __webpack_require__(31); function instantiateChild(childInstances, child, name) { // We found a component instance. var keyUnique = childInstances[name] === undefined; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name) : undefined; } if (child != null && keyUnique) { childInstances[name] = instantiateReactComponent(child, null); } } /** * ReactChildReconciler provides helpers for initializing or updating a set of * children. Its output is suitable for passing it onto ReactMultiChild which * does diffed reordering and insertion. */ var ReactChildReconciler = { /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildNodes Nested child maps. * @return {?object} A set of child instances. * @internal */ instantiateChildren: function (nestedChildNodes, transaction, context) { if (nestedChildNodes == null) { return null; } var childInstances = {}; traverseAllChildren(nestedChildNodes, instantiateChild, childInstances); return childInstances; }, /** * Updates the rendered children and returns a new set of children. * * @param {?object} prevChildren Previously initialized set of children. * @param {?object} nextChildren Flat child element maps. * @param {ReactReconcileTransaction} transaction * @param {object} context * @return {?object} A new set of child instances. * @internal */ updateChildren: function (prevChildren, nextChildren, transaction, context) { // We currently don't have a way to track moves here but if we use iterators // instead of for..in we can zip the iterators and check if an item has // moved. // TODO: If nothing has changed, return the prevChildren object so that we // can quickly bailout if nothing has changed. if (!nextChildren && !prevChildren) { return null; } var name; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } var prevChild = prevChildren && prevChildren[name]; var prevElement = prevChild && prevChild._currentElement; var nextElement = nextChildren[name]; if (prevChild != null && shouldUpdateReactComponent(prevElement, nextElement)) { ReactReconciler.receiveComponent(prevChild, nextElement, transaction, context); nextChildren[name] = prevChild; } else { if (prevChild) { ReactReconciler.unmountComponent(prevChild, name); } // The child must be instantiated before it's mounted. var nextChildInstance = instantiateReactComponent(nextElement, null); nextChildren[name] = nextChildInstance; } } // Unmount children that are no longer present. for (name in prevChildren) { if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) { ReactReconciler.unmountComponent(prevChildren[name]); } } return nextChildren; }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @param {?object} renderedChildren Previously initialized set of children. * @internal */ unmountChildren: function (renderedChildren) { for (var name in renderedChildren) { if (renderedChildren.hasOwnProperty(name)) { var renderedChild = renderedChildren[name]; ReactReconciler.unmountComponent(renderedChild); } } } }; module.exports = ReactChildReconciler; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 122 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule flattenChildren */ 'use strict'; var traverseAllChildren = __webpack_require__(117); var warning = __webpack_require__(31); /** * @param {function} traverseContext Context passed through traversal. * @param {?ReactComponent} child React child component. * @param {!string} name String name of key path to child. */ function flattenSingleChildIntoContext(traverseContext, child, name) { // We found a component instance. var result = traverseContext; var keyUnique = result[name] === undefined; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name) : undefined; } if (keyUnique && child != null) { result[name] = child; } } /** * Flattens children that are typically specified as `props.children`. Any null * children will not be included in the resulting object. * @return {!object} flattened children keyed by name. */ function flattenChildren(children) { if (children == null) { return children; } var result = {}; traverseAllChildren(children, flattenSingleChildIntoContext, result); return result; } module.exports = flattenChildren; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 123 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shallowEqual * @typechecks * */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ function shallowEqual(objA, objB) { if (objA === objB) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var bHasOwnProperty = hasOwnProperty.bind(objB); for (var i = 0; i < keysA.length; i++) { if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; } module.exports = shallowEqual; /***/ }, /* 124 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEventListener * @typechecks static-only */ 'use strict'; var EventListener = __webpack_require__(125); var ExecutionEnvironment = __webpack_require__(15); var PooledClass = __webpack_require__(62); var ReactInstanceHandles = __webpack_require__(51); var ReactMount = __webpack_require__(34); var ReactUpdates = __webpack_require__(60); var assign = __webpack_require__(45); var getEventTarget = __webpack_require__(87); var getUnboundedScrollPosition = __webpack_require__(126); var DOCUMENT_FRAGMENT_NODE_TYPE = 11; /** * Finds the parent React component of `node`. * * @param {*} node * @return {?DOMEventTarget} Parent container, or `null` if the specified node * is not nested. */ function findParent(node) { // TODO: It may be a good idea to cache this to prevent unnecessary DOM // traversal, but caching is difficult to do correctly without using a // mutation observer to listen for all DOM changes. var nodeID = ReactMount.getID(node); var rootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID); var container = ReactMount.findReactContainerForID(rootID); var parent = ReactMount.getFirstReactDOM(container); return parent; } // Used to store ancestor hierarchy in top level callback function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) { this.topLevelType = topLevelType; this.nativeEvent = nativeEvent; this.ancestors = []; } assign(TopLevelCallbackBookKeeping.prototype, { destructor: function () { this.topLevelType = null; this.nativeEvent = null; this.ancestors.length = 0; } }); PooledClass.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler); function handleTopLevelImpl(bookKeeping) { // TODO: Re-enable event.path handling // // if (bookKeeping.nativeEvent.path && bookKeeping.nativeEvent.path.length > 1) { // // New browsers have a path attribute on native events // handleTopLevelWithPath(bookKeeping); // } else { // // Legacy browsers don't have a path attribute on native events // handleTopLevelWithoutPath(bookKeeping); // } void handleTopLevelWithPath; // temporarily unused handleTopLevelWithoutPath(bookKeeping); } // Legacy browsers don't have a path attribute on native events function handleTopLevelWithoutPath(bookKeeping) { var topLevelTarget = ReactMount.getFirstReactDOM(getEventTarget(bookKeeping.nativeEvent)) || window; // Loop through the hierarchy, in case there's any nested components. // It's important that we build the array of ancestors before calling any // event handlers, because event handlers can modify the DOM, leading to // inconsistencies with ReactMount's node cache. See #1105. var ancestor = topLevelTarget; while (ancestor) { bookKeeping.ancestors.push(ancestor); ancestor = findParent(ancestor); } for (var i = 0; i < bookKeeping.ancestors.length; i++) { topLevelTarget = bookKeeping.ancestors[i]; var topLevelTargetID = ReactMount.getID(topLevelTarget) || ''; ReactEventListener._handleTopLevel(bookKeeping.topLevelType, topLevelTarget, topLevelTargetID, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent)); } } // New browsers have a path attribute on native events function handleTopLevelWithPath(bookKeeping) { var path = bookKeeping.nativeEvent.path; var currentNativeTarget = path[0]; var eventsFired = 0; for (var i = 0; i < path.length; i++) { var currentPathElement = path[i]; if (currentPathElement.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE) { currentNativeTarget = path[i + 1]; } // TODO: slow var reactParent = ReactMount.getFirstReactDOM(currentPathElement); if (reactParent === currentPathElement) { var currentPathElementID = ReactMount.getID(currentPathElement); var newRootID = ReactInstanceHandles.getReactRootIDFromNodeID(currentPathElementID); bookKeeping.ancestors.push(currentPathElement); var topLevelTargetID = ReactMount.getID(currentPathElement) || ''; eventsFired++; ReactEventListener._handleTopLevel(bookKeeping.topLevelType, currentPathElement, topLevelTargetID, bookKeeping.nativeEvent, currentNativeTarget); // Jump to the root of this React render tree while (currentPathElementID !== newRootID) { i++; currentPathElement = path[i]; currentPathElementID = ReactMount.getID(currentPathElement); } } } if (eventsFired === 0) { ReactEventListener._handleTopLevel(bookKeeping.topLevelType, window, '', bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent)); } } function scrollValueMonitor(cb) { var scrollPosition = getUnboundedScrollPosition(window); cb(scrollPosition); } var ReactEventListener = { _enabled: true, _handleTopLevel: null, WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null, setHandleTopLevel: function (handleTopLevel) { ReactEventListener._handleTopLevel = handleTopLevel; }, setEnabled: function (enabled) { ReactEventListener._enabled = !!enabled; }, isEnabled: function () { return ReactEventListener._enabled; }, /** * Traps top-level events by using event bubbling. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} handle Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { var element = handle; if (!element) { return null; } return EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, /** * Traps a top-level event by using event capturing. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} handle Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { var element = handle; if (!element) { return null; } return EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, monitorScrollValue: function (refresh) { var callback = scrollValueMonitor.bind(null, refresh); EventListener.listen(window, 'scroll', callback); }, dispatchEvent: function (topLevelType, nativeEvent) { if (!ReactEventListener._enabled) { return; } var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent); try { // Event queue being processed in the same cycle allows // `preventDefault`. ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping); } finally { TopLevelCallbackBookKeeping.release(bookKeeping); } } }; module.exports = ReactEventListener; /***/ }, /* 125 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule EventListener * @typechecks */ 'use strict'; var emptyFunction = __webpack_require__(21); /** * Upstream version of event listener. Does not take into account specific * nature of platform. */ var EventListener = { /** * Listen to DOM events during the bubble phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ listen: function (target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, false); return { remove: function () { target.removeEventListener(eventType, callback, false); } }; } else if (target.attachEvent) { target.attachEvent('on' + eventType, callback); return { remove: function () { target.detachEvent('on' + eventType, callback); } }; } }, /** * Listen to DOM events during the capture phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ capture: function (target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, true); return { remove: function () { target.removeEventListener(eventType, callback, true); } }; } else { if (process.env.NODE_ENV !== 'production') { console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.'); } return { remove: emptyFunction }; } }, registerDefault: function () {} }; module.exports = EventListener; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 126 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getUnboundedScrollPosition * @typechecks */ 'use strict'; /** * Gets the scroll position of the supplied element or window. * * The return values are unbounded, unlike `getScrollPosition`. This means they * may be negative or exceed the element boundaries (which is possible using * inertial scrolling). * * @param {DOMWindow|DOMElement} scrollable * @return {object} Map with `x` and `y` keys. */ function getUnboundedScrollPosition(scrollable) { if (scrollable === window) { return { x: window.pageXOffset || document.documentElement.scrollLeft, y: window.pageYOffset || document.documentElement.scrollTop }; } return { x: scrollable.scrollLeft, y: scrollable.scrollTop }; } module.exports = getUnboundedScrollPosition; /***/ }, /* 127 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInjection */ 'use strict'; var DOMProperty = __webpack_require__(29); var EventPluginHub = __webpack_require__(37); var ReactComponentEnvironment = __webpack_require__(70); var ReactClass = __webpack_require__(128); var ReactEmptyComponent = __webpack_require__(74); var ReactBrowserEventEmitter = __webpack_require__(35); var ReactNativeComponent = __webpack_require__(75); var ReactPerf = __webpack_require__(24); var ReactRootIndex = __webpack_require__(52); var ReactUpdates = __webpack_require__(60); var ReactInjection = { Component: ReactComponentEnvironment.injection, Class: ReactClass.injection, DOMProperty: DOMProperty.injection, EmptyComponent: ReactEmptyComponent.injection, EventPluginHub: EventPluginHub.injection, EventEmitter: ReactBrowserEventEmitter.injection, NativeComponent: ReactNativeComponent.injection, Perf: ReactPerf.injection, RootIndex: ReactRootIndex.injection, Updates: ReactUpdates.injection }; module.exports = ReactInjection; /***/ }, /* 128 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactClass */ 'use strict'; var ReactComponent = __webpack_require__(129); var ReactElement = __webpack_require__(48); var ReactPropTypeLocations = __webpack_require__(71); var ReactPropTypeLocationNames = __webpack_require__(72); var ReactNoopUpdateQueue = __webpack_require__(130); var assign = __webpack_require__(45); var emptyObject = __webpack_require__(64); var invariant = __webpack_require__(19); var keyMirror = __webpack_require__(23); var keyOf = __webpack_require__(85); var warning = __webpack_require__(31); var MIXINS_KEY = keyOf({ mixins: null }); /** * Policies that describe methods in `ReactClassInterface`. */ var SpecPolicy = keyMirror({ /** * These methods may be defined only once by the class specification or mixin. */ DEFINE_ONCE: null, /** * These methods may be defined by both the class specification and mixins. * Subsequent definitions will be chained. These methods must return void. */ DEFINE_MANY: null, /** * These methods are overriding the base class. */ OVERRIDE_BASE: null, /** * These methods are similar to DEFINE_MANY, except we assume they return * objects. We try to merge the keys of the return values of all the mixed in * functions. If there is a key conflict we throw. */ DEFINE_MANY_MERGED: null }); var injectedMixins = []; var warnedSetProps = false; function warnSetProps() { if (!warnedSetProps) { warnedSetProps = true; process.env.NODE_ENV !== 'production' ? warning(false, 'setProps(...) and replaceProps(...) are deprecated. ' + 'Instead, call render again at the top level.') : undefined; } } /** * Composite components are higher-level components that compose other composite * or native components. * * To create a new type of `ReactClass`, pass a specification of * your new class to `React.createClass`. The only requirement of your class * specification is that you implement a `render` method. * * var MyComponent = React.createClass({ * render: function() { * return <div>Hello World</div>; * } * }); * * The class specification supports a specific protocol of methods that have * special meaning (e.g. `render`). See `ReactClassInterface` for * more the comprehensive protocol. Any other properties and methods in the * class specification will be available on the prototype. * * @interface ReactClassInterface * @internal */ var ReactClassInterface = { /** * An array of Mixin objects to include when defining your component. * * @type {array} * @optional */ mixins: SpecPolicy.DEFINE_MANY, /** * An object containing properties and methods that should be defined on * the component's constructor instead of its prototype (static methods). * * @type {object} * @optional */ statics: SpecPolicy.DEFINE_MANY, /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: SpecPolicy.DEFINE_MANY, // ==== Definition methods ==== /** * Invoked when the component is mounted. Values in the mapping will be set on * `this.props` if that prop is not specified (i.e. using an `in` check). * * This method is invoked before `getInitialState` and therefore cannot rely * on `this.state` or use `this.setState`. * * @return {object} * @optional */ getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED, /** * Invoked once before the component is mounted. The return value will be used * as the initial value of `this.state`. * * getInitialState: function() { * return { * isOn: false, * fooBaz: new BazFoo() * } * } * * @return {object} * @optional */ getInitialState: SpecPolicy.DEFINE_MANY_MERGED, /** * @return {object} * @optional */ getChildContext: SpecPolicy.DEFINE_MANY_MERGED, /** * Uses props from `this.props` and state from `this.state` to render the * structure of the component. * * No guarantees are made about when or how often this method is invoked, so * it must not have side effects. * * render: function() { * var name = this.props.name; * return <div>Hello, {name}!</div>; * } * * @return {ReactComponent} * @nosideeffects * @required */ render: SpecPolicy.DEFINE_ONCE, // ==== Delegate methods ==== /** * Invoked when the component is initially created and about to be mounted. * This may have side effects, but any external subscriptions or data created * by this method must be cleaned up in `componentWillUnmount`. * * @optional */ componentWillMount: SpecPolicy.DEFINE_MANY, /** * Invoked when the component has been mounted and has a DOM representation. * However, there is no guarantee that the DOM node is in the document. * * Use this as an opportunity to operate on the DOM when the component has * been mounted (initialized and rendered) for the first time. * * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidMount: SpecPolicy.DEFINE_MANY, /** * Invoked before the component receives new props. * * Use this as an opportunity to react to a prop transition by updating the * state using `this.setState`. Current props are accessed via `this.props`. * * componentWillReceiveProps: function(nextProps, nextContext) { * this.setState({ * likesIncreasing: nextProps.likeCount > this.props.likeCount * }); * } * * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop * transition may cause a state change, but the opposite is not true. If you * need it, you are probably looking for `componentWillUpdate`. * * @param {object} nextProps * @optional */ componentWillReceiveProps: SpecPolicy.DEFINE_MANY, /** * Invoked while deciding if the component should be updated as a result of * receiving new props, state and/or context. * * Use this as an opportunity to `return false` when you're certain that the * transition to the new props/state/context will not require a component * update. * * shouldComponentUpdate: function(nextProps, nextState, nextContext) { * return !equal(nextProps, this.props) || * !equal(nextState, this.state) || * !equal(nextContext, this.context); * } * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @return {boolean} True if the component should update. * @optional */ shouldComponentUpdate: SpecPolicy.DEFINE_ONCE, /** * Invoked when the component is about to update due to a transition from * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` * and `nextContext`. * * Use this as an opportunity to perform preparation before an update occurs. * * NOTE: You **cannot** use `this.setState()` in this method. * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @param {ReactReconcileTransaction} transaction * @optional */ componentWillUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component's DOM representation has been updated. * * Use this as an opportunity to operate on the DOM when the component has * been updated. * * @param {object} prevProps * @param {?object} prevState * @param {?object} prevContext * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component is about to be removed from its parent and have * its DOM representation destroyed. * * Use this as an opportunity to deallocate any external resources. * * NOTE: There is no `componentDidUnmount` since your component will have been * destroyed by that point. * * @optional */ componentWillUnmount: SpecPolicy.DEFINE_MANY, // ==== Advanced methods ==== /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @internal * @overridable */ updateComponent: SpecPolicy.OVERRIDE_BASE }; /** * Mapping from class specification keys to special processing functions. * * Although these are declared like instance properties in the specification * when defining classes using `React.createClass`, they are actually static * and are accessible on the constructor instead of the prototype. Despite * being static, they must be defined outside of the "statics" key under * which all other static methods are defined. */ var RESERVED_SPEC_KEYS = { displayName: function (Constructor, displayName) { Constructor.displayName = displayName; }, mixins: function (Constructor, mixins) { if (mixins) { for (var i = 0; i < mixins.length; i++) { mixSpecIntoComponent(Constructor, mixins[i]); } } }, childContextTypes: function (Constructor, childContextTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, childContextTypes, ReactPropTypeLocations.childContext); } Constructor.childContextTypes = assign({}, Constructor.childContextTypes, childContextTypes); }, contextTypes: function (Constructor, contextTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, contextTypes, ReactPropTypeLocations.context); } Constructor.contextTypes = assign({}, Constructor.contextTypes, contextTypes); }, /** * Special case getDefaultProps which should move into statics but requires * automatic merging. */ getDefaultProps: function (Constructor, getDefaultProps) { if (Constructor.getDefaultProps) { Constructor.getDefaultProps = createMergedResultFunction(Constructor.getDefaultProps, getDefaultProps); } else { Constructor.getDefaultProps = getDefaultProps; } }, propTypes: function (Constructor, propTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, propTypes, ReactPropTypeLocations.prop); } Constructor.propTypes = assign({}, Constructor.propTypes, propTypes); }, statics: function (Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); }, autobind: function () {} }; // noop function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) { if (typeDef.hasOwnProperty(propName)) { // use a warning instead of an invariant so components // don't show up in prod but not in __DEV__ process.env.NODE_ENV !== 'production' ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : undefined; } } } function validateMethodOverride(proto, name) { var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null; // Disallow overriding of base class methods unless explicitly allowed. if (ReactClassMixin.hasOwnProperty(name)) { !(specPolicy === SpecPolicy.OVERRIDE_BASE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name) : invariant(false) : undefined; } // Disallow defining methods more than once unless explicitly allowed. if (proto.hasOwnProperty(name)) { !(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name) : invariant(false) : undefined; } } /** * Mixin helper which handles policy validation and reserved * specification keys when building React classses. */ function mixSpecIntoComponent(Constructor, spec) { if (!spec) { return; } !(typeof spec !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component class as a mixin. Instead, just use a regular object.') : invariant(false) : undefined; !!ReactElement.isValidElement(spec) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component as a mixin. Instead, just use a regular object.') : invariant(false) : undefined; var proto = Constructor.prototype; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above. continue; } var property = spec[name]; validateMethodOverride(proto, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactClass methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); var isAlreadyDefined = proto.hasOwnProperty(name); var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false; if (shouldAutoBind) { if (!proto.__reactAutoBindMap) { proto.__reactAutoBindMap = {}; } proto.__reactAutoBindMap[name] = property; proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; // These cases should already be caught by validateMethodOverride. !(isReactClassMethod && (specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name) : invariant(false) : undefined; // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === SpecPolicy.DEFINE_MANY) { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if (process.env.NODE_ENV !== 'production') { // Add verbose displayName to the function, which helps when looking // at profiling tools. if (typeof property === 'function' && spec.displayName) { proto[name].displayName = spec.displayName + '_' + name; } } } } } } } function mixStaticSpecIntoComponent(Constructor, statics) { if (!statics) { return; } for (var name in statics) { var property = statics[name]; if (!statics.hasOwnProperty(name)) { continue; } var isReserved = (name in RESERVED_SPEC_KEYS); !!isReserved ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You are attempting to define a reserved ' + 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' + 'as an instance property instead; it will still be accessible on the ' + 'constructor.', name) : invariant(false) : undefined; var isInherited = (name in Constructor); !!isInherited ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name) : invariant(false) : undefined; Constructor[name] = property; } } /** * Merge two objects, but throw if both contain the same key. * * @param {object} one The first object, which is mutated. * @param {object} two The second object * @return {object} one after it has been mutated to contain everything in two. */ function mergeIntoWithNoDuplicateKeys(one, two) { !(one && two && typeof one === 'object' && typeof two === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.') : invariant(false) : undefined; for (var key in two) { if (two.hasOwnProperty(key)) { !(one[key] === undefined) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key) : invariant(false) : undefined; one[key] = two[key]; } } return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } var c = {}; mergeIntoWithNoDuplicateKeys(c, a); mergeIntoWithNoDuplicateKeys(c, b); return c; }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } /** * Binds a method to the component. * * @param {object} component Component whose method is going to be bound. * @param {function} method Method to be bound. * @return {function} The bound method. */ function bindAutoBindMethod(component, method) { var boundMethod = method.bind(component); if (process.env.NODE_ENV !== 'production') { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; /* eslint-disable block-scoped-var, no-undef */ boundMethod.bind = function (newThis) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && newThis !== null) { process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : undefined; } else if (!args.length) { process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName) : undefined; return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; /* eslint-enable */ }; } return boundMethod; } /** * Binds all auto-bound methods in a component. * * @param {object} component Component whose method is going to be bound. */ function bindAutoBindMethods(component) { for (var autoBindKey in component.__reactAutoBindMap) { if (component.__reactAutoBindMap.hasOwnProperty(autoBindKey)) { var method = component.__reactAutoBindMap[autoBindKey]; component[autoBindKey] = bindAutoBindMethod(component, method); } } } /** * Add more to the ReactClass base class. These are all legacy features and * therefore not already part of the modern ReactComponent. */ var ReactClassMixin = { /** * TODO: This will be deprecated because state should always keep a consistent * type signature and the only use case for this, is to avoid that. */ replaceState: function (newState, callback) { this.updater.enqueueReplaceState(this, newState); if (callback) { this.updater.enqueueCallback(this, callback); } }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function () { return this.updater.isMounted(this); }, /** * Sets a subset of the props. * * @param {object} partialProps Subset of the next props. * @param {?function} callback Called after props are updated. * @final * @public * @deprecated */ setProps: function (partialProps, callback) { if (process.env.NODE_ENV !== 'production') { warnSetProps(); } this.updater.enqueueSetProps(this, partialProps); if (callback) { this.updater.enqueueCallback(this, callback); } }, /** * Replace all the props. * * @param {object} newProps Subset of the next props. * @param {?function} callback Called after props are updated. * @final * @public * @deprecated */ replaceProps: function (newProps, callback) { if (process.env.NODE_ENV !== 'production') { warnSetProps(); } this.updater.enqueueReplaceProps(this, newProps); if (callback) { this.updater.enqueueCallback(this, callback); } } }; var ReactClassComponent = function () {}; assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin); /** * Module for creating composite components. * * @class ReactClass */ var ReactClass = { /** * Creates a composite component class given a class specification. * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ createClass: function (spec) { var Constructor = function (props, context, updater) { // This constructor is overridden by mocks. The argument is used // by mocks to assert on what gets mounted. if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : undefined; } // Wire up auto-binding if (this.__reactAutoBindMap) { bindAutoBindMethods(this); } this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; this.state = null; // ReactClasses doesn't have constructors. Instead, they use the // getInitialState and componentWillMount methods for initialization. var initialState = this.getInitialState ? this.getInitialState() : null; if (process.env.NODE_ENV !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if (typeof initialState === 'undefined' && this.getInitialState._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent') : invariant(false) : undefined; this.state = initialState; }; Constructor.prototype = new ReactClassComponent(); Constructor.prototype.constructor = Constructor; injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor)); mixSpecIntoComponent(Constructor, spec); // Initialize the defaultProps property after all mixins have been merged. if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } if (process.env.NODE_ENV !== 'production') { // This is a tag to indicate that the use of these method names is ok, // since it's used with createClass. If it's not, then it's likely a // mistake so we'll warn you to use the static property, property // initializer or constructor respectively. if (Constructor.getDefaultProps) { Constructor.getDefaultProps.isReactClassApproved = {}; } if (Constructor.prototype.getInitialState) { Constructor.prototype.getInitialState.isReactClassApproved = {}; } } !Constructor.prototype.render ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createClass(...): Class specification must implement a `render` method.') : invariant(false) : undefined; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component') : undefined; process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : undefined; } // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactClassInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } return Constructor; }, injection: { injectMixin: function (mixin) { injectedMixins.push(mixin); } } }; module.exports = ReactClass; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 129 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponent */ 'use strict'; var ReactNoopUpdateQueue = __webpack_require__(130); var canDefineProperty = __webpack_require__(49); var emptyObject = __webpack_require__(64); var invariant = __webpack_require__(19); var warning = __webpack_require__(31); /** * Base class helpers for the updating state of a component. */ function ReactComponent(props, context, updater) { this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } ReactComponent.prototype.isReactComponent = {}; /** * Sets a subset of the state. Always use this to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * When a function is provided to setState, it will be called at some point in * the future (not synchronously). It will be called with the up to date * component arguments (state, props, context). These values can be different * from this.* because your function may be called after receiveProps but before * shouldComponentUpdate, and this new state, props, and context will not yet be * assigned to this. * * @param {object|function} partialState Next partial state or function to * produce next partial state to be merged with current state. * @param {?function} callback Called after state is updated. * @final * @protected */ ReactComponent.prototype.setState = function (partialState, callback) { !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.') : invariant(false) : undefined; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().') : undefined; } this.updater.enqueueSetState(this, partialState); if (callback) { this.updater.enqueueCallback(this, callback); } }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ ReactComponent.prototype.forceUpdate = function (callback) { this.updater.enqueueForceUpdate(this); if (callback) { this.updater.enqueueCallback(this, callback); } }; /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ if (process.env.NODE_ENV !== 'production') { var deprecatedAPIs = { getDOMNode: ['getDOMNode', 'Use ReactDOM.findDOMNode(component) instead.'], isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], replaceProps: ['replaceProps', 'Instead, call render again at the top level.'], replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'], setProps: ['setProps', 'Instead, call render again at the top level.'] }; var defineDeprecationWarning = function (methodName, info) { if (canDefineProperty) { Object.defineProperty(ReactComponent.prototype, methodName, { get: function () { process.env.NODE_ENV !== 'production' ? warning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]) : undefined; return undefined; } }); } }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } module.exports = ReactComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 130 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactNoopUpdateQueue */ 'use strict'; var warning = __webpack_require__(31); function warnTDZ(publicInstance, callerName) { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, publicInstance.constructor && publicInstance.constructor.displayName || '') : undefined; } } /** * This is the abstract API for an update queue. */ var ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { return false; }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @internal */ enqueueCallback: function (publicInstance, callback) {}, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function (publicInstance) { warnTDZ(publicInstance, 'forceUpdate'); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function (publicInstance, completeState) { warnTDZ(publicInstance, 'replaceState'); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function (publicInstance, partialState) { warnTDZ(publicInstance, 'setState'); }, /** * Sets a subset of the props. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialProps Subset of the next props. * @internal */ enqueueSetProps: function (publicInstance, partialProps) { warnTDZ(publicInstance, 'setProps'); }, /** * Replaces all of the props. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} props New props. * @internal */ enqueueReplaceProps: function (publicInstance, props) { warnTDZ(publicInstance, 'replaceProps'); } }; module.exports = ReactNoopUpdateQueue; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 131 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactReconcileTransaction * @typechecks static-only */ 'use strict'; var CallbackQueue = __webpack_require__(61); var PooledClass = __webpack_require__(62); var ReactBrowserEventEmitter = __webpack_require__(35); var ReactDOMFeatureFlags = __webpack_require__(47); var ReactInputSelection = __webpack_require__(132); var Transaction = __webpack_require__(63); var assign = __webpack_require__(45); /** * Ensures that, when possible, the selection range (currently selected text * input) is not disturbed by performing the transaction. */ var SELECTION_RESTORATION = { /** * @return {Selection} Selection information. */ initialize: ReactInputSelection.getSelectionInformation, /** * @param {Selection} sel Selection information returned from `initialize`. */ close: ReactInputSelection.restoreSelection }; /** * Suppresses events (blur/focus) that could be inadvertently dispatched due to * high level DOM manipulations (like temporarily removing a text input from the * DOM). */ var EVENT_SUPPRESSION = { /** * @return {boolean} The enabled status of `ReactBrowserEventEmitter` before * the reconciliation. */ initialize: function () { var currentlyEnabled = ReactBrowserEventEmitter.isEnabled(); ReactBrowserEventEmitter.setEnabled(false); return currentlyEnabled; }, /** * @param {boolean} previouslyEnabled Enabled status of * `ReactBrowserEventEmitter` before the reconciliation occurred. `close` * restores the previous value. */ close: function (previouslyEnabled) { ReactBrowserEventEmitter.setEnabled(previouslyEnabled); } }; /** * Provides a queue for collecting `componentDidMount` and * `componentDidUpdate` callbacks during the the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function () { this.reactMountReady.reset(); }, /** * After DOM is flushed, invoke all registered `onDOMReady` callbacks. */ close: function () { this.reactMountReady.notifyAll(); } }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING]; /** * Currently: * - The order that these are listed in the transaction is critical: * - Suppresses events. * - Restores selection range. * * Future: * - Restore document/overflow scroll positions that were unintentionally * modified via DOM insertions above the top viewport boundary. * - Implement/integrate with customized constraint based layout system and keep * track of which dimensions must be remeasured. * * @class ReactReconcileTransaction */ function ReactReconcileTransaction(forceHTML) { this.reinitializeTransaction(); // Only server-side rendering really needs this option (see // `ReactServerRendering`), but server-side uses // `ReactServerRenderingTransaction` instead. This option is here so that it's // accessible and defaults to false when `ReactDOMComponent` and // `ReactTextComponent` checks it in `mountComponent`.` this.renderToStaticMarkup = false; this.reactMountReady = CallbackQueue.getPooled(null); this.useCreateElement = !forceHTML && ReactDOMFeatureFlags.useCreateElement; } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array<object>} List of operation wrap procedures. * TODO: convert to array<TransactionWrapper> */ getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function () { return this.reactMountReady; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function () { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; } }; assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin); PooledClass.addPoolingTo(ReactReconcileTransaction); module.exports = ReactReconcileTransaction; /***/ }, /* 132 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInputSelection */ 'use strict'; var ReactDOMSelection = __webpack_require__(133); var containsNode = __webpack_require__(65); var focusNode = __webpack_require__(101); var getActiveElement = __webpack_require__(135); function isInDocument(node) { return containsNode(document.documentElement, node); } /** * @ReactInputSelection: React input selection module. Based on Selection.js, * but modified to be suitable for react and has a couple of bug fixes (doesn't * assume buttons have range selections allowed). * Input selection module for React. */ var ReactInputSelection = { hasSelectionCapabilities: function (elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true'); }, getSelectionInformation: function () { var focusedElem = getActiveElement(); return { focusedElem: focusedElem, selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null }; }, /** * @restoreSelection: If any selection information was potentially lost, * restore it. This is useful when performing operations that could remove dom * nodes and place them back in, resulting in focus being lost. */ restoreSelection: function (priorSelectionInformation) { var curFocusedElem = getActiveElement(); var priorFocusedElem = priorSelectionInformation.focusedElem; var priorSelectionRange = priorSelectionInformation.selectionRange; if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) { ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange); } focusNode(priorFocusedElem); } }, /** * @getSelection: Gets the selection bounds of a focused textarea, input or * contentEditable node. * -@input: Look up selection bounds of this input * -@return {start: selectionStart, end: selectionEnd} */ getSelection: function (input) { var selection; if ('selectionStart' in input) { // Modern browser with input or textarea. selection = { start: input.selectionStart, end: input.selectionEnd }; } else if (document.selection && (input.nodeName && input.nodeName.toLowerCase() === 'input')) { // IE8 input. var range = document.selection.createRange(); // There can only be one selection per document in IE, so it must // be in our element. if (range.parentElement() === input) { selection = { start: -range.moveStart('character', -input.value.length), end: -range.moveEnd('character', -input.value.length) }; } } else { // Content editable or old IE textarea. selection = ReactDOMSelection.getOffsets(input); } return selection || { start: 0, end: 0 }; }, /** * @setSelection: Sets the selection bounds of a textarea or input and focuses * the input. * -@input Set selection bounds of this input or textarea * -@offsets Object of same form that is returned from get* */ setSelection: function (input, offsets) { var start = offsets.start; var end = offsets.end; if (typeof end === 'undefined') { end = start; } if ('selectionStart' in input) { input.selectionStart = start; input.selectionEnd = Math.min(end, input.value.length); } else if (document.selection && (input.nodeName && input.nodeName.toLowerCase() === 'input')) { var range = input.createTextRange(); range.collapse(true); range.moveStart('character', start); range.moveEnd('character', end - start); range.select(); } else { ReactDOMSelection.setOffsets(input, offsets); } } }; module.exports = ReactInputSelection; /***/ }, /* 133 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMSelection */ 'use strict'; var ExecutionEnvironment = __webpack_require__(15); var getNodeForCharacterOffset = __webpack_require__(134); var getTextContentAccessor = __webpack_require__(81); /** * While `isCollapsed` is available on the Selection object and `collapsed` * is available on the Range object, IE11 sometimes gets them wrong. * If the anchor/focus nodes and offsets are the same, the range is collapsed. */ function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) { return anchorNode === focusNode && anchorOffset === focusOffset; } /** * Get the appropriate anchor and focus node/offset pairs for IE. * * The catch here is that IE's selection API doesn't provide information * about whether the selection is forward or backward, so we have to * behave as though it's always forward. * * IE text differs from modern selection in that it behaves as though * block elements end with a new line. This means character offsets will * differ between the two APIs. * * @param {DOMElement} node * @return {object} */ function getIEOffsets(node) { var selection = document.selection; var selectedRange = selection.createRange(); var selectedLength = selectedRange.text.length; // Duplicate selection so we can move range without breaking user selection. var fromStart = selectedRange.duplicate(); fromStart.moveToElementText(node); fromStart.setEndPoint('EndToStart', selectedRange); var startOffset = fromStart.text.length; var endOffset = startOffset + selectedLength; return { start: startOffset, end: endOffset }; } /** * @param {DOMElement} node * @return {?object} */ function getModernOffsets(node) { var selection = window.getSelection && window.getSelection(); if (!selection || selection.rangeCount === 0) { return null; } var anchorNode = selection.anchorNode; var anchorOffset = selection.anchorOffset; var focusNode = selection.focusNode; var focusOffset = selection.focusOffset; var currentRange = selection.getRangeAt(0); // In Firefox, range.startContainer and range.endContainer can be "anonymous // divs", e.g. the up/down buttons on an <input type="number">. Anonymous // divs do not seem to expose properties, triggering a "Permission denied // error" if any of its properties are accessed. The only seemingly possible // way to avoid erroring is to access a property that typically works for // non-anonymous divs and catch any error that may otherwise arise. See // https://bugzilla.mozilla.org/show_bug.cgi?id=208427 try { /* eslint-disable no-unused-expressions */ currentRange.startContainer.nodeType; currentRange.endContainer.nodeType; /* eslint-enable no-unused-expressions */ } catch (e) { return null; } // If the node and offset values are the same, the selection is collapsed. // `Selection.isCollapsed` is available natively, but IE sometimes gets // this value wrong. var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset); var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length; var tempRange = currentRange.cloneRange(); tempRange.selectNodeContents(node); tempRange.setEnd(currentRange.startContainer, currentRange.startOffset); var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset); var start = isTempRangeCollapsed ? 0 : tempRange.toString().length; var end = start + rangeLength; // Detect whether the selection is backward. var detectionRange = document.createRange(); detectionRange.setStart(anchorNode, anchorOffset); detectionRange.setEnd(focusNode, focusOffset); var isBackward = detectionRange.collapsed; return { start: isBackward ? end : start, end: isBackward ? start : end }; } /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setIEOffsets(node, offsets) { var range = document.selection.createRange().duplicate(); var start, end; if (typeof offsets.end === 'undefined') { start = offsets.start; end = start; } else if (offsets.start > offsets.end) { start = offsets.end; end = offsets.start; } else { start = offsets.start; end = offsets.end; } range.moveToElementText(node); range.moveStart('character', start); range.setEndPoint('EndToStart', range); range.moveEnd('character', end - start); range.select(); } /** * In modern non-IE browsers, we can support both forward and backward * selections. * * Note: IE10+ supports the Selection object, but it does not support * the `extend` method, which means that even in modern IE, it's not possible * to programatically create a backward selection. Thus, for all IE * versions, we use the old IE API to create our selections. * * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setModernOffsets(node, offsets) { if (!window.getSelection) { return; } var selection = window.getSelection(); var length = node[getTextContentAccessor()].length; var start = Math.min(offsets.start, length); var end = typeof offsets.end === 'undefined' ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method. // Flip backward selections, so we can set with a single range. if (!selection.extend && start > end) { var temp = end; end = start; start = temp; } var startMarker = getNodeForCharacterOffset(node, start); var endMarker = getNodeForCharacterOffset(node, end); if (startMarker && endMarker) { var range = document.createRange(); range.setStart(startMarker.node, startMarker.offset); selection.removeAllRanges(); if (start > end) { selection.addRange(range); selection.extend(endMarker.node, endMarker.offset); } else { range.setEnd(endMarker.node, endMarker.offset); selection.addRange(range); } } } var useIEOffsets = ExecutionEnvironment.canUseDOM && 'selection' in document && !('getSelection' in window); var ReactDOMSelection = { /** * @param {DOMElement} node */ getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets, /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets }; module.exports = ReactDOMSelection; /***/ }, /* 134 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getNodeForCharacterOffset */ 'use strict'; /** * Given any node return the first leaf node without children. * * @param {DOMElement|DOMTextNode} node * @return {DOMElement|DOMTextNode} */ function getLeafNode(node) { while (node && node.firstChild) { node = node.firstChild; } return node; } /** * Get the next sibling within a container. This will walk up the * DOM if a node's siblings have been exhausted. * * @param {DOMElement|DOMTextNode} node * @return {?DOMElement|DOMTextNode} */ function getSiblingNode(node) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parentNode; } } /** * Get object describing the nodes which contain characters at offset. * * @param {DOMElement|DOMTextNode} root * @param {number} offset * @return {?object} */ function getNodeForCharacterOffset(root, offset) { var node = getLeafNode(root); var nodeStart = 0; var nodeEnd = 0; while (node) { if (node.nodeType === 3) { nodeEnd = nodeStart + node.textContent.length; if (nodeStart <= offset && nodeEnd >= offset) { return { node: node, offset: offset - nodeStart }; } nodeStart = nodeEnd; } node = getLeafNode(getSiblingNode(node)); } } module.exports = getNodeForCharacterOffset; /***/ }, /* 135 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getActiveElement * @typechecks */ /* eslint-disable fb-www/typeof-undefined */ /** * Same as document.activeElement but wraps in a try-catch block. In IE it is * not safe to call document.activeElement if there is nothing focused. * * The activeElement will be null only if the document or document body is not * yet defined. */ 'use strict'; function getActiveElement() /*?DOMElement*/{ if (typeof document === 'undefined') { return null; } try { return document.activeElement || document.body; } catch (e) { return document.body; } } module.exports = getActiveElement; /***/ }, /* 136 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SelectEventPlugin */ 'use strict'; var EventConstants = __webpack_require__(36); var EventPropagators = __webpack_require__(79); var ExecutionEnvironment = __webpack_require__(15); var ReactInputSelection = __webpack_require__(132); var SyntheticEvent = __webpack_require__(83); var getActiveElement = __webpack_require__(135); var isTextInputElement = __webpack_require__(88); var keyOf = __webpack_require__(85); var shallowEqual = __webpack_require__(123); var topLevelTypes = EventConstants.topLevelTypes; var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11; var eventTypes = { select: { phasedRegistrationNames: { bubbled: keyOf({ onSelect: null }), captured: keyOf({ onSelectCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange] } }; var activeElement = null; var activeElementID = null; var lastSelection = null; var mouseDown = false; // Track whether a listener exists for this plugin. If none exist, we do // not extract events. var hasListener = false; var ON_SELECT_KEY = keyOf({ onSelect: null }); /** * Get an object which is a unique representation of the current selection. * * The return value will not be consistent across nodes or browsers, but * two identical selections on the same node will return identical objects. * * @param {DOMElement} node * @return {object} */ function getSelection(node) { if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) { return { start: node.selectionStart, end: node.selectionEnd }; } else if (window.getSelection) { var selection = window.getSelection(); return { anchorNode: selection.anchorNode, anchorOffset: selection.anchorOffset, focusNode: selection.focusNode, focusOffset: selection.focusOffset }; } else if (document.selection) { var range = document.selection.createRange(); return { parentElement: range.parentElement(), text: range.text, top: range.boundingTop, left: range.boundingLeft }; } } /** * Poll selection to see whether it's changed. * * @param {object} nativeEvent * @return {?SyntheticEvent} */ function constructSelectEvent(nativeEvent, nativeEventTarget) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. if (mouseDown || activeElement == null || activeElement !== getActiveElement()) { return null; } // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementID, nativeEvent, nativeEventTarget); syntheticEvent.type = 'select'; syntheticEvent.target = activeElement; EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent); return syntheticEvent; } return null; } /** * This plugin creates an `onSelect` event that normalizes select events * across form elements. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - contentEditable * * This differs from native browser implementations in the following ways: * - Fires on contentEditable fields as well as inputs. * - Fires for collapsed selection. * - Fires after user input. */ var SelectEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { if (!hasListener) { return null; } switch (topLevelType) { // Track the input node that has focus. case topLevelTypes.topFocus: if (isTextInputElement(topLevelTarget) || topLevelTarget.contentEditable === 'true') { activeElement = topLevelTarget; activeElementID = topLevelTargetID; lastSelection = null; } break; case topLevelTypes.topBlur: activeElement = null; activeElementID = null; lastSelection = null; break; // Don't fire the event while the user is dragging. This matches the // semantics of the native select event. case topLevelTypes.topMouseDown: mouseDown = true; break; case topLevelTypes.topContextMenu: case topLevelTypes.topMouseUp: mouseDown = false; return constructSelectEvent(nativeEvent, nativeEventTarget); // Chrome and IE fire non-standard event when selection is changed (and // sometimes when it hasn't). IE's event fires out of order with respect // to key and input events on deletion, so we discard it. // // Firefox doesn't support selectionchange, so check selection status // after each key entry. The selection changes after keydown and before // keyup, but we check on keydown as well in the case of holding down a // key, when multiple keydown events are fired but only one keyup is. // This is also our approach for IE handling, for the reason above. case topLevelTypes.topSelectionChange: if (skipSelectionChangeEvent) { break; } // falls through case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: return constructSelectEvent(nativeEvent, nativeEventTarget); } return null; }, didPutListener: function (id, registrationName, listener) { if (registrationName === ON_SELECT_KEY) { hasListener = true; } } }; module.exports = SelectEventPlugin; /***/ }, /* 137 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ServerReactRootIndex * @typechecks */ 'use strict'; /** * Size of the reactRoot ID space. We generate random numbers for React root * IDs and if there's a collision the events and DOM update system will * get confused. In the future we need a way to generate GUIDs but for * now this will work on a smaller scale. */ var GLOBAL_MOUNT_POINT_MAX = Math.pow(2, 53); var ServerReactRootIndex = { createReactRootIndex: function () { return Math.ceil(Math.random() * GLOBAL_MOUNT_POINT_MAX); } }; module.exports = ServerReactRootIndex; /***/ }, /* 138 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SimpleEventPlugin */ 'use strict'; var EventConstants = __webpack_require__(36); var EventListener = __webpack_require__(125); var EventPropagators = __webpack_require__(79); var ReactMount = __webpack_require__(34); var SyntheticClipboardEvent = __webpack_require__(139); var SyntheticEvent = __webpack_require__(83); var SyntheticFocusEvent = __webpack_require__(140); var SyntheticKeyboardEvent = __webpack_require__(141); var SyntheticMouseEvent = __webpack_require__(92); var SyntheticDragEvent = __webpack_require__(144); var SyntheticTouchEvent = __webpack_require__(145); var SyntheticUIEvent = __webpack_require__(93); var SyntheticWheelEvent = __webpack_require__(146); var emptyFunction = __webpack_require__(21); var getEventCharCode = __webpack_require__(142); var invariant = __webpack_require__(19); var keyOf = __webpack_require__(85); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { abort: { phasedRegistrationNames: { bubbled: keyOf({ onAbort: true }), captured: keyOf({ onAbortCapture: true }) } }, blur: { phasedRegistrationNames: { bubbled: keyOf({ onBlur: true }), captured: keyOf({ onBlurCapture: true }) } }, canPlay: { phasedRegistrationNames: { bubbled: keyOf({ onCanPlay: true }), captured: keyOf({ onCanPlayCapture: true }) } }, canPlayThrough: { phasedRegistrationNames: { bubbled: keyOf({ onCanPlayThrough: true }), captured: keyOf({ onCanPlayThroughCapture: true }) } }, click: { phasedRegistrationNames: { bubbled: keyOf({ onClick: true }), captured: keyOf({ onClickCapture: true }) } }, contextMenu: { phasedRegistrationNames: { bubbled: keyOf({ onContextMenu: true }), captured: keyOf({ onContextMenuCapture: true }) } }, copy: { phasedRegistrationNames: { bubbled: keyOf({ onCopy: true }), captured: keyOf({ onCopyCapture: true }) } }, cut: { phasedRegistrationNames: { bubbled: keyOf({ onCut: true }), captured: keyOf({ onCutCapture: true }) } }, doubleClick: { phasedRegistrationNames: { bubbled: keyOf({ onDoubleClick: true }), captured: keyOf({ onDoubleClickCapture: true }) } }, drag: { phasedRegistrationNames: { bubbled: keyOf({ onDrag: true }), captured: keyOf({ onDragCapture: true }) } }, dragEnd: { phasedRegistrationNames: { bubbled: keyOf({ onDragEnd: true }), captured: keyOf({ onDragEndCapture: true }) } }, dragEnter: { phasedRegistrationNames: { bubbled: keyOf({ onDragEnter: true }), captured: keyOf({ onDragEnterCapture: true }) } }, dragExit: { phasedRegistrationNames: { bubbled: keyOf({ onDragExit: true }), captured: keyOf({ onDragExitCapture: true }) } }, dragLeave: { phasedRegistrationNames: { bubbled: keyOf({ onDragLeave: true }), captured: keyOf({ onDragLeaveCapture: true }) } }, dragOver: { phasedRegistrationNames: { bubbled: keyOf({ onDragOver: true }), captured: keyOf({ onDragOverCapture: true }) } }, dragStart: { phasedRegistrationNames: { bubbled: keyOf({ onDragStart: true }), captured: keyOf({ onDragStartCapture: true }) } }, drop: { phasedRegistrationNames: { bubbled: keyOf({ onDrop: true }), captured: keyOf({ onDropCapture: true }) } }, durationChange: { phasedRegistrationNames: { bubbled: keyOf({ onDurationChange: true }), captured: keyOf({ onDurationChangeCapture: true }) } }, emptied: { phasedRegistrationNames: { bubbled: keyOf({ onEmptied: true }), captured: keyOf({ onEmptiedCapture: true }) } }, encrypted: { phasedRegistrationNames: { bubbled: keyOf({ onEncrypted: true }), captured: keyOf({ onEncryptedCapture: true }) } }, ended: { phasedRegistrationNames: { bubbled: keyOf({ onEnded: true }), captured: keyOf({ onEndedCapture: true }) } }, error: { phasedRegistrationNames: { bubbled: keyOf({ onError: true }), captured: keyOf({ onErrorCapture: true }) } }, focus: { phasedRegistrationNames: { bubbled: keyOf({ onFocus: true }), captured: keyOf({ onFocusCapture: true }) } }, input: { phasedRegistrationNames: { bubbled: keyOf({ onInput: true }), captured: keyOf({ onInputCapture: true }) } }, keyDown: { phasedRegistrationNames: { bubbled: keyOf({ onKeyDown: true }), captured: keyOf({ onKeyDownCapture: true }) } }, keyPress: { phasedRegistrationNames: { bubbled: keyOf({ onKeyPress: true }), captured: keyOf({ onKeyPressCapture: true }) } }, keyUp: { phasedRegistrationNames: { bubbled: keyOf({ onKeyUp: true }), captured: keyOf({ onKeyUpCapture: true }) } }, load: { phasedRegistrationNames: { bubbled: keyOf({ onLoad: true }), captured: keyOf({ onLoadCapture: true }) } }, loadedData: { phasedRegistrationNames: { bubbled: keyOf({ onLoadedData: true }), captured: keyOf({ onLoadedDataCapture: true }) } }, loadedMetadata: { phasedRegistrationNames: { bubbled: keyOf({ onLoadedMetadata: true }), captured: keyOf({ onLoadedMetadataCapture: true }) } }, loadStart: { phasedRegistrationNames: { bubbled: keyOf({ onLoadStart: true }), captured: keyOf({ onLoadStartCapture: true }) } }, // Note: We do not allow listening to mouseOver events. Instead, use the // onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`. mouseDown: { phasedRegistrationNames: { bubbled: keyOf({ onMouseDown: true }), captured: keyOf({ onMouseDownCapture: true }) } }, mouseMove: { phasedRegistrationNames: { bubbled: keyOf({ onMouseMove: true }), captured: keyOf({ onMouseMoveCapture: true }) } }, mouseOut: { phasedRegistrationNames: { bubbled: keyOf({ onMouseOut: true }), captured: keyOf({ onMouseOutCapture: true }) } }, mouseOver: { phasedRegistrationNames: { bubbled: keyOf({ onMouseOver: true }), captured: keyOf({ onMouseOverCapture: true }) } }, mouseUp: { phasedRegistrationNames: { bubbled: keyOf({ onMouseUp: true }), captured: keyOf({ onMouseUpCapture: true }) } }, paste: { phasedRegistrationNames: { bubbled: keyOf({ onPaste: true }), captured: keyOf({ onPasteCapture: true }) } }, pause: { phasedRegistrationNames: { bubbled: keyOf({ onPause: true }), captured: keyOf({ onPauseCapture: true }) } }, play: { phasedRegistrationNames: { bubbled: keyOf({ onPlay: true }), captured: keyOf({ onPlayCapture: true }) } }, playing: { phasedRegistrationNames: { bubbled: keyOf({ onPlaying: true }), captured: keyOf({ onPlayingCapture: true }) } }, progress: { phasedRegistrationNames: { bubbled: keyOf({ onProgress: true }), captured: keyOf({ onProgressCapture: true }) } }, rateChange: { phasedRegistrationNames: { bubbled: keyOf({ onRateChange: true }), captured: keyOf({ onRateChangeCapture: true }) } }, reset: { phasedRegistrationNames: { bubbled: keyOf({ onReset: true }), captured: keyOf({ onResetCapture: true }) } }, scroll: { phasedRegistrationNames: { bubbled: keyOf({ onScroll: true }), captured: keyOf({ onScrollCapture: true }) } }, seeked: { phasedRegistrationNames: { bubbled: keyOf({ onSeeked: true }), captured: keyOf({ onSeekedCapture: true }) } }, seeking: { phasedRegistrationNames: { bubbled: keyOf({ onSeeking: true }), captured: keyOf({ onSeekingCapture: true }) } }, stalled: { phasedRegistrationNames: { bubbled: keyOf({ onStalled: true }), captured: keyOf({ onStalledCapture: true }) } }, submit: { phasedRegistrationNames: { bubbled: keyOf({ onSubmit: true }), captured: keyOf({ onSubmitCapture: true }) } }, suspend: { phasedRegistrationNames: { bubbled: keyOf({ onSuspend: true }), captured: keyOf({ onSuspendCapture: true }) } }, timeUpdate: { phasedRegistrationNames: { bubbled: keyOf({ onTimeUpdate: true }), captured: keyOf({ onTimeUpdateCapture: true }) } }, touchCancel: { phasedRegistrationNames: { bubbled: keyOf({ onTouchCancel: true }), captured: keyOf({ onTouchCancelCapture: true }) } }, touchEnd: { phasedRegistrationNames: { bubbled: keyOf({ onTouchEnd: true }), captured: keyOf({ onTouchEndCapture: true }) } }, touchMove: { phasedRegistrationNames: { bubbled: keyOf({ onTouchMove: true }), captured: keyOf({ onTouchMoveCapture: true }) } }, touchStart: { phasedRegistrationNames: { bubbled: keyOf({ onTouchStart: true }), captured: keyOf({ onTouchStartCapture: true }) } }, volumeChange: { phasedRegistrationNames: { bubbled: keyOf({ onVolumeChange: true }), captured: keyOf({ onVolumeChangeCapture: true }) } }, waiting: { phasedRegistrationNames: { bubbled: keyOf({ onWaiting: true }), captured: keyOf({ onWaitingCapture: true }) } }, wheel: { phasedRegistrationNames: { bubbled: keyOf({ onWheel: true }), captured: keyOf({ onWheelCapture: true }) } } }; var topLevelEventsToDispatchConfig = { topAbort: eventTypes.abort, topBlur: eventTypes.blur, topCanPlay: eventTypes.canPlay, topCanPlayThrough: eventTypes.canPlayThrough, topClick: eventTypes.click, topContextMenu: eventTypes.contextMenu, topCopy: eventTypes.copy, topCut: eventTypes.cut, topDoubleClick: eventTypes.doubleClick, topDrag: eventTypes.drag, topDragEnd: eventTypes.dragEnd, topDragEnter: eventTypes.dragEnter, topDragExit: eventTypes.dragExit, topDragLeave: eventTypes.dragLeave, topDragOver: eventTypes.dragOver, topDragStart: eventTypes.dragStart, topDrop: eventTypes.drop, topDurationChange: eventTypes.durationChange, topEmptied: eventTypes.emptied, topEncrypted: eventTypes.encrypted, topEnded: eventTypes.ended, topError: eventTypes.error, topFocus: eventTypes.focus, topInput: eventTypes.input, topKeyDown: eventTypes.keyDown, topKeyPress: eventTypes.keyPress, topKeyUp: eventTypes.keyUp, topLoad: eventTypes.load, topLoadedData: eventTypes.loadedData, topLoadedMetadata: eventTypes.loadedMetadata, topLoadStart: eventTypes.loadStart, topMouseDown: eventTypes.mouseDown, topMouseMove: eventTypes.mouseMove, topMouseOut: eventTypes.mouseOut, topMouseOver: eventTypes.mouseOver, topMouseUp: eventTypes.mouseUp, topPaste: eventTypes.paste, topPause: eventTypes.pause, topPlay: eventTypes.play, topPlaying: eventTypes.playing, topProgress: eventTypes.progress, topRateChange: eventTypes.rateChange, topReset: eventTypes.reset, topScroll: eventTypes.scroll, topSeeked: eventTypes.seeked, topSeeking: eventTypes.seeking, topStalled: eventTypes.stalled, topSubmit: eventTypes.submit, topSuspend: eventTypes.suspend, topTimeUpdate: eventTypes.timeUpdate, topTouchCancel: eventTypes.touchCancel, topTouchEnd: eventTypes.touchEnd, topTouchMove: eventTypes.touchMove, topTouchStart: eventTypes.touchStart, topVolumeChange: eventTypes.volumeChange, topWaiting: eventTypes.waiting, topWheel: eventTypes.wheel }; for (var type in topLevelEventsToDispatchConfig) { topLevelEventsToDispatchConfig[type].dependencies = [type]; } var ON_CLICK_KEY = keyOf({ onClick: null }); var onClickListeners = {}; var SimpleEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType]; if (!dispatchConfig) { return null; } var EventConstructor; switch (topLevelType) { case topLevelTypes.topAbort: case topLevelTypes.topCanPlay: case topLevelTypes.topCanPlayThrough: case topLevelTypes.topDurationChange: case topLevelTypes.topEmptied: case topLevelTypes.topEncrypted: case topLevelTypes.topEnded: case topLevelTypes.topError: case topLevelTypes.topInput: case topLevelTypes.topLoad: case topLevelTypes.topLoadedData: case topLevelTypes.topLoadedMetadata: case topLevelTypes.topLoadStart: case topLevelTypes.topPause: case topLevelTypes.topPlay: case topLevelTypes.topPlaying: case topLevelTypes.topProgress: case topLevelTypes.topRateChange: case topLevelTypes.topReset: case topLevelTypes.topSeeked: case topLevelTypes.topSeeking: case topLevelTypes.topStalled: case topLevelTypes.topSubmit: case topLevelTypes.topSuspend: case topLevelTypes.topTimeUpdate: case topLevelTypes.topVolumeChange: case topLevelTypes.topWaiting: // HTML Events // @see http://www.w3.org/TR/html5/index.html#events-0 EventConstructor = SyntheticEvent; break; case topLevelTypes.topKeyPress: // FireFox creates a keypress event for function keys too. This removes // the unwanted keypress events. Enter is however both printable and // non-printable. One would expect Tab to be as well (but it isn't). if (getEventCharCode(nativeEvent) === 0) { return null; } /* falls through */ case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: EventConstructor = SyntheticKeyboardEvent; break; case topLevelTypes.topBlur: case topLevelTypes.topFocus: EventConstructor = SyntheticFocusEvent; break; case topLevelTypes.topClick: // Firefox creates a click event on right mouse clicks. This removes the // unwanted click events. if (nativeEvent.button === 2) { return null; } /* falls through */ case topLevelTypes.topContextMenu: case topLevelTypes.topDoubleClick: case topLevelTypes.topMouseDown: case topLevelTypes.topMouseMove: case topLevelTypes.topMouseOut: case topLevelTypes.topMouseOver: case topLevelTypes.topMouseUp: EventConstructor = SyntheticMouseEvent; break; case topLevelTypes.topDrag: case topLevelTypes.topDragEnd: case topLevelTypes.topDragEnter: case topLevelTypes.topDragExit: case topLevelTypes.topDragLeave: case topLevelTypes.topDragOver: case topLevelTypes.topDragStart: case topLevelTypes.topDrop: EventConstructor = SyntheticDragEvent; break; case topLevelTypes.topTouchCancel: case topLevelTypes.topTouchEnd: case topLevelTypes.topTouchMove: case topLevelTypes.topTouchStart: EventConstructor = SyntheticTouchEvent; break; case topLevelTypes.topScroll: EventConstructor = SyntheticUIEvent; break; case topLevelTypes.topWheel: EventConstructor = SyntheticWheelEvent; break; case topLevelTypes.topCopy: case topLevelTypes.topCut: case topLevelTypes.topPaste: EventConstructor = SyntheticClipboardEvent; break; } !EventConstructor ? process.env.NODE_ENV !== 'production' ? invariant(false, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType) : invariant(false) : undefined; var event = EventConstructor.getPooled(dispatchConfig, topLevelTargetID, nativeEvent, nativeEventTarget); EventPropagators.accumulateTwoPhaseDispatches(event); return event; }, didPutListener: function (id, registrationName, listener) { // Mobile Safari does not fire properly bubble click events on // non-interactive elements, which means delegated click listeners do not // fire. The workaround for this bug involves attaching an empty click // listener on the target node. if (registrationName === ON_CLICK_KEY) { var node = ReactMount.getNode(id); if (!onClickListeners[id]) { onClickListeners[id] = EventListener.listen(node, 'click', emptyFunction); } } }, willDeleteListener: function (id, registrationName) { if (registrationName === ON_CLICK_KEY) { onClickListeners[id].remove(); delete onClickListeners[id]; } } }; module.exports = SimpleEventPlugin; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 139 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticClipboardEvent * @typechecks static-only */ 'use strict'; var SyntheticEvent = __webpack_require__(83); /** * @interface Event * @see http://www.w3.org/TR/clipboard-apis/ */ var ClipboardEventInterface = { clipboardData: function (event) { return 'clipboardData' in event ? event.clipboardData : window.clipboardData; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface); module.exports = SyntheticClipboardEvent; /***/ }, /* 140 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticFocusEvent * @typechecks static-only */ 'use strict'; var SyntheticUIEvent = __webpack_require__(93); /** * @interface FocusEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var FocusEventInterface = { relatedTarget: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface); module.exports = SyntheticFocusEvent; /***/ }, /* 141 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticKeyboardEvent * @typechecks static-only */ 'use strict'; var SyntheticUIEvent = __webpack_require__(93); var getEventCharCode = __webpack_require__(142); var getEventKey = __webpack_require__(143); var getEventModifierState = __webpack_require__(94); /** * @interface KeyboardEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var KeyboardEventInterface = { key: getEventKey, location: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, repeat: null, locale: null, getModifierState: getEventModifierState, // Legacy Interface charCode: function (event) { // `charCode` is the result of a KeyPress event and represents the value of // the actual printable character. // KeyPress is deprecated, but its replacement is not yet final and not // implemented in any major browser. Only KeyPress has charCode. if (event.type === 'keypress') { return getEventCharCode(event); } return 0; }, keyCode: function (event) { // `keyCode` is the result of a KeyDown/Up event and represents the value of // physical keyboard key. // The actual meaning of the value depends on the users' keyboard layout // which cannot be detected. Assuming that it is a US keyboard layout // provides a surprisingly accurate mapping for US and European users. // Due to this, it is left to the user to implement at this time. if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; }, which: function (event) { // `which` is an alias for either `keyCode` or `charCode` depending on the // type of the event. if (event.type === 'keypress') { return getEventCharCode(event); } if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface); module.exports = SyntheticKeyboardEvent; /***/ }, /* 142 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventCharCode * @typechecks static-only */ 'use strict'; /** * `charCode` represents the actual "character code" and is safe to use with * `String.fromCharCode`. As such, only keys that correspond to printable * characters produce a valid `charCode`, the only exception to this is Enter. * The Tab-key is considered non-printable and does not have a `charCode`, * presumably because it does not produce a tab-character in browsers. * * @param {object} nativeEvent Native browser event. * @return {number} Normalized `charCode` property. */ function getEventCharCode(nativeEvent) { var charCode; var keyCode = nativeEvent.keyCode; if ('charCode' in nativeEvent) { charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`. if (charCode === 0 && keyCode === 13) { charCode = 13; } } else { // IE8 does not implement `charCode`, but `keyCode` has the correct value. charCode = keyCode; } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. // Must not discard the (non-)printable Enter-key. if (charCode >= 32 || charCode === 13) { return charCode; } return 0; } module.exports = getEventCharCode; /***/ }, /* 143 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventKey * @typechecks static-only */ 'use strict'; var getEventCharCode = __webpack_require__(142); /** * Normalization of deprecated HTML5 `key` values * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var normalizeKey = { 'Esc': 'Escape', 'Spacebar': ' ', 'Left': 'ArrowLeft', 'Up': 'ArrowUp', 'Right': 'ArrowRight', 'Down': 'ArrowDown', 'Del': 'Delete', 'Win': 'OS', 'Menu': 'ContextMenu', 'Apps': 'ContextMenu', 'Scroll': 'ScrollLock', 'MozPrintableKey': 'Unidentified' }; /** * Translation from legacy `keyCode` to HTML5 `key` * Only special keys supported, all others depend on keyboard layout or browser * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var translateToKey = { 8: 'Backspace', 9: 'Tab', 12: 'Clear', 13: 'Enter', 16: 'Shift', 17: 'Control', 18: 'Alt', 19: 'Pause', 20: 'CapsLock', 27: 'Escape', 32: ' ', 33: 'PageUp', 34: 'PageDown', 35: 'End', 36: 'Home', 37: 'ArrowLeft', 38: 'ArrowUp', 39: 'ArrowRight', 40: 'ArrowDown', 45: 'Insert', 46: 'Delete', 112: 'F1', 113: 'F2', 114: 'F3', 115: 'F4', 116: 'F5', 117: 'F6', 118: 'F7', 119: 'F8', 120: 'F9', 121: 'F10', 122: 'F11', 123: 'F12', 144: 'NumLock', 145: 'ScrollLock', 224: 'Meta' }; /** * @param {object} nativeEvent Native browser event. * @return {string} Normalized `key` property. */ function getEventKey(nativeEvent) { if (nativeEvent.key) { // Normalize inconsistent values reported by browsers due to // implementations of a working draft specification. // FireFox implements `key` but returns `MozPrintableKey` for all // printable characters (normalized to `Unidentified`), ignore it. var key = normalizeKey[nativeEvent.key] || nativeEvent.key; if (key !== 'Unidentified') { return key; } } // Browser does not implement `key`, polyfill as much of it as we can. if (nativeEvent.type === 'keypress') { var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can // thus be captured by `keypress`, no other non-printable key should. return charCode === 13 ? 'Enter' : String.fromCharCode(charCode); } if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') { // While user keyboard layout determines the actual meaning of each // `keyCode` value, almost all function keys have a universal value. return translateToKey[nativeEvent.keyCode] || 'Unidentified'; } return ''; } module.exports = getEventKey; /***/ }, /* 144 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticDragEvent * @typechecks static-only */ 'use strict'; var SyntheticMouseEvent = __webpack_require__(92); /** * @interface DragEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var DragEventInterface = { dataTransfer: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface); module.exports = SyntheticDragEvent; /***/ }, /* 145 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticTouchEvent * @typechecks static-only */ 'use strict'; var SyntheticUIEvent = __webpack_require__(93); var getEventModifierState = __webpack_require__(94); /** * @interface TouchEvent * @see http://www.w3.org/TR/touch-events/ */ var TouchEventInterface = { touches: null, targetTouches: null, changedTouches: null, altKey: null, metaKey: null, ctrlKey: null, shiftKey: null, getModifierState: getEventModifierState }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface); module.exports = SyntheticTouchEvent; /***/ }, /* 146 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticWheelEvent * @typechecks static-only */ 'use strict'; var SyntheticMouseEvent = __webpack_require__(92); /** * @interface WheelEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var WheelEventInterface = { deltaX: function (event) { return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). 'wheelDeltaX' in event ? -event.wheelDeltaX : 0; }, deltaY: function (event) { return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). 'wheelDelta' in event ? -event.wheelDelta : 0; }, deltaZ: null, // Browsers without "deltaMode" is reporting in raw wheel delta where one // notch on the scroll is always +/- 120, roughly equivalent to pixels. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. deltaMode: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticMouseEvent} */ function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface); module.exports = SyntheticWheelEvent; /***/ }, /* 147 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SVGDOMPropertyConfig */ 'use strict'; var DOMProperty = __webpack_require__(29); var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE; var NS = { xlink: 'http://www.w3.org/1999/xlink', xml: 'http://www.w3.org/XML/1998/namespace' }; var SVGDOMPropertyConfig = { Properties: { clipPath: MUST_USE_ATTRIBUTE, cx: MUST_USE_ATTRIBUTE, cy: MUST_USE_ATTRIBUTE, d: MUST_USE_ATTRIBUTE, dx: MUST_USE_ATTRIBUTE, dy: MUST_USE_ATTRIBUTE, fill: MUST_USE_ATTRIBUTE, fillOpacity: MUST_USE_ATTRIBUTE, fontFamily: MUST_USE_ATTRIBUTE, fontSize: MUST_USE_ATTRIBUTE, fx: MUST_USE_ATTRIBUTE, fy: MUST_USE_ATTRIBUTE, gradientTransform: MUST_USE_ATTRIBUTE, gradientUnits: MUST_USE_ATTRIBUTE, markerEnd: MUST_USE_ATTRIBUTE, markerMid: MUST_USE_ATTRIBUTE, markerStart: MUST_USE_ATTRIBUTE, offset: MUST_USE_ATTRIBUTE, opacity: MUST_USE_ATTRIBUTE, patternContentUnits: MUST_USE_ATTRIBUTE, patternUnits: MUST_USE_ATTRIBUTE, points: MUST_USE_ATTRIBUTE, preserveAspectRatio: MUST_USE_ATTRIBUTE, r: MUST_USE_ATTRIBUTE, rx: MUST_USE_ATTRIBUTE, ry: MUST_USE_ATTRIBUTE, spreadMethod: MUST_USE_ATTRIBUTE, stopColor: MUST_USE_ATTRIBUTE, stopOpacity: MUST_USE_ATTRIBUTE, stroke: MUST_USE_ATTRIBUTE, strokeDasharray: MUST_USE_ATTRIBUTE, strokeLinecap: MUST_USE_ATTRIBUTE, strokeOpacity: MUST_USE_ATTRIBUTE, strokeWidth: MUST_USE_ATTRIBUTE, textAnchor: MUST_USE_ATTRIBUTE, transform: MUST_USE_ATTRIBUTE, version: MUST_USE_ATTRIBUTE, viewBox: MUST_USE_ATTRIBUTE, x1: MUST_USE_ATTRIBUTE, x2: MUST_USE_ATTRIBUTE, x: MUST_USE_ATTRIBUTE, xlinkActuate: MUST_USE_ATTRIBUTE, xlinkArcrole: MUST_USE_ATTRIBUTE, xlinkHref: MUST_USE_ATTRIBUTE, xlinkRole: MUST_USE_ATTRIBUTE, xlinkShow: MUST_USE_ATTRIBUTE, xlinkTitle: MUST_USE_ATTRIBUTE, xlinkType: MUST_USE_ATTRIBUTE, xmlBase: MUST_USE_ATTRIBUTE, xmlLang: MUST_USE_ATTRIBUTE, xmlSpace: MUST_USE_ATTRIBUTE, y1: MUST_USE_ATTRIBUTE, y2: MUST_USE_ATTRIBUTE, y: MUST_USE_ATTRIBUTE }, DOMAttributeNamespaces: { xlinkActuate: NS.xlink, xlinkArcrole: NS.xlink, xlinkHref: NS.xlink, xlinkRole: NS.xlink, xlinkShow: NS.xlink, xlinkTitle: NS.xlink, xlinkType: NS.xlink, xmlBase: NS.xml, xmlLang: NS.xml, xmlSpace: NS.xml }, DOMAttributeNames: { clipPath: 'clip-path', fillOpacity: 'fill-opacity', fontFamily: 'font-family', fontSize: 'font-size', gradientTransform: 'gradientTransform', gradientUnits: 'gradientUnits', markerEnd: 'marker-end', markerMid: 'marker-mid', markerStart: 'marker-start', patternContentUnits: 'patternContentUnits', patternUnits: 'patternUnits', preserveAspectRatio: 'preserveAspectRatio', spreadMethod: 'spreadMethod', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strokeDasharray: 'stroke-dasharray', strokeLinecap: 'stroke-linecap', strokeOpacity: 'stroke-opacity', strokeWidth: 'stroke-width', textAnchor: 'text-anchor', viewBox: 'viewBox', xlinkActuate: 'xlink:actuate', xlinkArcrole: 'xlink:arcrole', xlinkHref: 'xlink:href', xlinkRole: 'xlink:role', xlinkShow: 'xlink:show', xlinkTitle: 'xlink:title', xlinkType: 'xlink:type', xmlBase: 'xml:base', xmlLang: 'xml:lang', xmlSpace: 'xml:space' } }; module.exports = SVGDOMPropertyConfig; /***/ }, /* 148 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultPerf * @typechecks static-only */ 'use strict'; var DOMProperty = __webpack_require__(29); var ReactDefaultPerfAnalysis = __webpack_require__(149); var ReactMount = __webpack_require__(34); var ReactPerf = __webpack_require__(24); var performanceNow = __webpack_require__(150); function roundFloat(val) { return Math.floor(val * 100) / 100; } function addValue(obj, key, val) { obj[key] = (obj[key] || 0) + val; } var ReactDefaultPerf = { _allMeasurements: [], // last item in the list is the current one _mountStack: [0], _injected: false, start: function () { if (!ReactDefaultPerf._injected) { ReactPerf.injection.injectMeasure(ReactDefaultPerf.measure); } ReactDefaultPerf._allMeasurements.length = 0; ReactPerf.enableMeasure = true; }, stop: function () { ReactPerf.enableMeasure = false; }, getLastMeasurements: function () { return ReactDefaultPerf._allMeasurements; }, printExclusive: function (measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getExclusiveSummary(measurements); console.table(summary.map(function (item) { return { 'Component class name': item.componentName, 'Total inclusive time (ms)': roundFloat(item.inclusive), 'Exclusive mount time (ms)': roundFloat(item.exclusive), 'Exclusive render time (ms)': roundFloat(item.render), 'Mount time per instance (ms)': roundFloat(item.exclusive / item.count), 'Render time per instance (ms)': roundFloat(item.render / item.count), 'Instances': item.count }; })); // TODO: ReactDefaultPerfAnalysis.getTotalTime() does not return the correct // number. }, printInclusive: function (measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements); console.table(summary.map(function (item) { return { 'Owner > component': item.componentName, 'Inclusive time (ms)': roundFloat(item.time), 'Instances': item.count }; })); console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms'); }, getMeasurementsSummaryMap: function (measurements) { var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements, true); return summary.map(function (item) { return { 'Owner > component': item.componentName, 'Wasted time (ms)': item.time, 'Instances': item.count }; }); }, printWasted: function (measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; console.table(ReactDefaultPerf.getMeasurementsSummaryMap(measurements)); console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms'); }, printDOM: function (measurements) { measurements = measurements || ReactDefaultPerf._allMeasurements; var summary = ReactDefaultPerfAnalysis.getDOMSummary(measurements); console.table(summary.map(function (item) { var result = {}; result[DOMProperty.ID_ATTRIBUTE_NAME] = item.id; result.type = item.type; result.args = JSON.stringify(item.args); return result; })); console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms'); }, _recordWrite: function (id, fnName, totalTime, args) { // TODO: totalTime isn't that useful since it doesn't count paints/reflows var writes = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1].writes; writes[id] = writes[id] || []; writes[id].push({ type: fnName, time: totalTime, args: args }); }, measure: function (moduleName, fnName, func) { return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var totalTime; var rv; var start; if (fnName === '_renderNewRootComponent' || fnName === 'flushBatchedUpdates') { // A "measurement" is a set of metrics recorded for each flush. We want // to group the metrics for a given flush together so we can look at the // components that rendered and the DOM operations that actually // happened to determine the amount of "wasted work" performed. ReactDefaultPerf._allMeasurements.push({ exclusive: {}, inclusive: {}, render: {}, counts: {}, writes: {}, displayNames: {}, totalTime: 0, created: {} }); start = performanceNow(); rv = func.apply(this, args); ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1].totalTime = performanceNow() - start; return rv; } else if (fnName === '_mountImageIntoNode' || moduleName === 'ReactBrowserEventEmitter' || moduleName === 'ReactDOMIDOperations' || moduleName === 'CSSPropertyOperations' || moduleName === 'DOMChildrenOperations' || moduleName === 'DOMPropertyOperations') { start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; if (fnName === '_mountImageIntoNode') { var mountID = ReactMount.getID(args[1]); ReactDefaultPerf._recordWrite(mountID, fnName, totalTime, args[0]); } else if (fnName === 'dangerouslyProcessChildrenUpdates') { // special format args[0].forEach(function (update) { var writeArgs = {}; if (update.fromIndex !== null) { writeArgs.fromIndex = update.fromIndex; } if (update.toIndex !== null) { writeArgs.toIndex = update.toIndex; } if (update.textContent !== null) { writeArgs.textContent = update.textContent; } if (update.markupIndex !== null) { writeArgs.markup = args[1][update.markupIndex]; } ReactDefaultPerf._recordWrite(update.parentID, update.type, totalTime, writeArgs); }); } else { // basic format var id = args[0]; if (typeof id === 'object') { id = ReactMount.getID(args[0]); } ReactDefaultPerf._recordWrite(id, fnName, totalTime, Array.prototype.slice.call(args, 1)); } return rv; } else if (moduleName === 'ReactCompositeComponent' && (fnName === 'mountComponent' || fnName === 'updateComponent' || // TODO: receiveComponent()? fnName === '_renderValidatedComponent')) { if (this._currentElement.type === ReactMount.TopLevelWrapper) { return func.apply(this, args); } var rootNodeID = fnName === 'mountComponent' ? args[0] : this._rootNodeID; var isRender = fnName === '_renderValidatedComponent'; var isMount = fnName === 'mountComponent'; var mountStack = ReactDefaultPerf._mountStack; var entry = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1]; if (isRender) { addValue(entry.counts, rootNodeID, 1); } else if (isMount) { entry.created[rootNodeID] = true; mountStack.push(0); } start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; if (isRender) { addValue(entry.render, rootNodeID, totalTime); } else if (isMount) { var subMountTime = mountStack.pop(); mountStack[mountStack.length - 1] += totalTime; addValue(entry.exclusive, rootNodeID, totalTime - subMountTime); addValue(entry.inclusive, rootNodeID, totalTime); } else { addValue(entry.inclusive, rootNodeID, totalTime); } entry.displayNames[rootNodeID] = { current: this.getName(), owner: this._currentElement._owner ? this._currentElement._owner.getName() : '<root>' }; return rv; } else { return func.apply(this, args); } }; } }; module.exports = ReactDefaultPerf; /***/ }, /* 149 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultPerfAnalysis */ 'use strict'; var assign = __webpack_require__(45); // Don't try to save users less than 1.2ms (a number I made up) var DONT_CARE_THRESHOLD = 1.2; var DOM_OPERATION_TYPES = { '_mountImageIntoNode': 'set innerHTML', INSERT_MARKUP: 'set innerHTML', MOVE_EXISTING: 'move', REMOVE_NODE: 'remove', SET_MARKUP: 'set innerHTML', TEXT_CONTENT: 'set textContent', 'setValueForProperty': 'update attribute', 'setValueForAttribute': 'update attribute', 'deleteValueForProperty': 'remove attribute', 'setValueForStyles': 'update styles', 'replaceNodeWithMarkup': 'replace', 'updateTextContent': 'set textContent' }; function getTotalTime(measurements) { // TODO: return number of DOM ops? could be misleading. // TODO: measure dropped frames after reconcile? // TODO: log total time of each reconcile and the top-level component // class that triggered it. var totalTime = 0; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; totalTime += measurement.totalTime; } return totalTime; } function getDOMSummary(measurements) { var items = []; measurements.forEach(function (measurement) { Object.keys(measurement.writes).forEach(function (id) { measurement.writes[id].forEach(function (write) { items.push({ id: id, type: DOM_OPERATION_TYPES[write.type] || write.type, args: write.args }); }); }); }); return items; } function getExclusiveSummary(measurements) { var candidates = {}; var displayName; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var allIDs = assign({}, measurement.exclusive, measurement.inclusive); for (var id in allIDs) { displayName = measurement.displayNames[id].current; candidates[displayName] = candidates[displayName] || { componentName: displayName, inclusive: 0, exclusive: 0, render: 0, count: 0 }; if (measurement.render[id]) { candidates[displayName].render += measurement.render[id]; } if (measurement.exclusive[id]) { candidates[displayName].exclusive += measurement.exclusive[id]; } if (measurement.inclusive[id]) { candidates[displayName].inclusive += measurement.inclusive[id]; } if (measurement.counts[id]) { candidates[displayName].count += measurement.counts[id]; } } } // Now make a sorted array with the results. var arr = []; for (displayName in candidates) { if (candidates[displayName].exclusive >= DONT_CARE_THRESHOLD) { arr.push(candidates[displayName]); } } arr.sort(function (a, b) { return b.exclusive - a.exclusive; }); return arr; } function getInclusiveSummary(measurements, onlyClean) { var candidates = {}; var inclusiveKey; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var allIDs = assign({}, measurement.exclusive, measurement.inclusive); var cleanComponents; if (onlyClean) { cleanComponents = getUnchangedComponents(measurement); } for (var id in allIDs) { if (onlyClean && !cleanComponents[id]) { continue; } var displayName = measurement.displayNames[id]; // Inclusive time is not useful for many components without knowing where // they are instantiated. So we aggregate inclusive time with both the // owner and current displayName as the key. inclusiveKey = displayName.owner + ' > ' + displayName.current; candidates[inclusiveKey] = candidates[inclusiveKey] || { componentName: inclusiveKey, time: 0, count: 0 }; if (measurement.inclusive[id]) { candidates[inclusiveKey].time += measurement.inclusive[id]; } if (measurement.counts[id]) { candidates[inclusiveKey].count += measurement.counts[id]; } } } // Now make a sorted array with the results. var arr = []; for (inclusiveKey in candidates) { if (candidates[inclusiveKey].time >= DONT_CARE_THRESHOLD) { arr.push(candidates[inclusiveKey]); } } arr.sort(function (a, b) { return b.time - a.time; }); return arr; } function getUnchangedComponents(measurement) { // For a given reconcile, look at which components did not actually // render anything to the DOM and return a mapping of their ID to // the amount of time it took to render the entire subtree. var cleanComponents = {}; var dirtyLeafIDs = Object.keys(measurement.writes); var allIDs = assign({}, measurement.exclusive, measurement.inclusive); for (var id in allIDs) { var isDirty = false; // For each component that rendered, see if a component that triggered // a DOM op is in its subtree. for (var i = 0; i < dirtyLeafIDs.length; i++) { if (dirtyLeafIDs[i].indexOf(id) === 0) { isDirty = true; break; } } // check if component newly created if (measurement.created[id]) { isDirty = true; } if (!isDirty && measurement.counts[id] > 0) { cleanComponents[id] = true; } } return cleanComponents; } var ReactDefaultPerfAnalysis = { getExclusiveSummary: getExclusiveSummary, getInclusiveSummary: getInclusiveSummary, getDOMSummary: getDOMSummary, getTotalTime: getTotalTime }; module.exports = ReactDefaultPerfAnalysis; /***/ }, /* 150 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule performanceNow * @typechecks */ 'use strict'; var performance = __webpack_require__(151); var performanceNow; /** * Detect if we can use `window.performance.now()` and gracefully fallback to * `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now * because of Facebook's testing infrastructure. */ if (performance.now) { performanceNow = function () { return performance.now(); }; } else { performanceNow = function () { return Date.now(); }; } module.exports = performanceNow; /***/ }, /* 151 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule performance * @typechecks */ 'use strict'; var ExecutionEnvironment = __webpack_require__(15); var performance; if (ExecutionEnvironment.canUseDOM) { performance = window.performance || window.msPerformance || window.webkitPerformance; } module.exports = performance || {}; /***/ }, /* 152 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactVersion */ 'use strict'; module.exports = '0.14.7'; /***/ }, /* 153 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule renderSubtreeIntoContainer */ 'use strict'; var ReactMount = __webpack_require__(34); module.exports = ReactMount.renderSubtreeIntoContainer; /***/ }, /* 154 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMServer */ 'use strict'; var ReactDefaultInjection = __webpack_require__(77); var ReactServerRendering = __webpack_require__(155); var ReactVersion = __webpack_require__(152); ReactDefaultInjection.inject(); var ReactDOMServer = { renderToString: ReactServerRendering.renderToString, renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup, version: ReactVersion }; module.exports = ReactDOMServer; /***/ }, /* 155 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks static-only * @providesModule ReactServerRendering */ 'use strict'; var ReactDefaultBatchingStrategy = __webpack_require__(98); var ReactElement = __webpack_require__(48); var ReactInstanceHandles = __webpack_require__(51); var ReactMarkupChecksum = __webpack_require__(54); var ReactServerBatchingStrategy = __webpack_require__(156); var ReactServerRenderingTransaction = __webpack_require__(157); var ReactUpdates = __webpack_require__(60); var emptyObject = __webpack_require__(64); var instantiateReactComponent = __webpack_require__(68); var invariant = __webpack_require__(19); /** * @param {ReactElement} element * @return {string} the HTML markup */ function renderToString(element) { !ReactElement.isValidElement(element) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'renderToString(): You must pass a valid ReactElement.') : invariant(false) : undefined; var transaction; try { ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy); var id = ReactInstanceHandles.createReactRootID(); transaction = ReactServerRenderingTransaction.getPooled(false); return transaction.perform(function () { var componentInstance = instantiateReactComponent(element, null); var markup = componentInstance.mountComponent(id, transaction, emptyObject); return ReactMarkupChecksum.addChecksumToMarkup(markup); }, null); } finally { ReactServerRenderingTransaction.release(transaction); // Revert to the DOM batching strategy since these two renderers // currently share these stateful modules. ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy); } } /** * @param {ReactElement} element * @return {string} the HTML markup, without the extra React ID and checksum * (for generating static pages) */ function renderToStaticMarkup(element) { !ReactElement.isValidElement(element) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'renderToStaticMarkup(): You must pass a valid ReactElement.') : invariant(false) : undefined; var transaction; try { ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy); var id = ReactInstanceHandles.createReactRootID(); transaction = ReactServerRenderingTransaction.getPooled(true); return transaction.perform(function () { var componentInstance = instantiateReactComponent(element, null); return componentInstance.mountComponent(id, transaction, emptyObject); }, null); } finally { ReactServerRenderingTransaction.release(transaction); // Revert to the DOM batching strategy since these two renderers // currently share these stateful modules. ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy); } } module.exports = { renderToString: renderToString, renderToStaticMarkup: renderToStaticMarkup }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 156 */ /***/ function(module, exports) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactServerBatchingStrategy * @typechecks */ 'use strict'; var ReactServerBatchingStrategy = { isBatchingUpdates: false, batchedUpdates: function (callback) { // Don't do anything here. During the server rendering we don't want to // schedule any updates. We will simply ignore them. } }; module.exports = ReactServerBatchingStrategy; /***/ }, /* 157 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactServerRenderingTransaction * @typechecks */ 'use strict'; var PooledClass = __webpack_require__(62); var CallbackQueue = __webpack_require__(61); var Transaction = __webpack_require__(63); var assign = __webpack_require__(45); var emptyFunction = __webpack_require__(21); /** * Provides a `CallbackQueue` queue for collecting `onDOMReady` callbacks * during the performing of the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function () { this.reactMountReady.reset(); }, close: emptyFunction }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [ON_DOM_READY_QUEUEING]; /** * @class ReactServerRenderingTransaction * @param {boolean} renderToStaticMarkup */ function ReactServerRenderingTransaction(renderToStaticMarkup) { this.reinitializeTransaction(); this.renderToStaticMarkup = renderToStaticMarkup; this.reactMountReady = CallbackQueue.getPooled(null); this.useCreateElement = false; } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array} Empty list of operation wrap procedures. */ getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function () { return this.reactMountReady; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function () { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; } }; assign(ReactServerRenderingTransaction.prototype, Transaction.Mixin, Mixin); PooledClass.addPoolingTo(ReactServerRenderingTransaction); module.exports = ReactServerRenderingTransaction; /***/ }, /* 158 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactIsomorphic */ 'use strict'; var ReactChildren = __webpack_require__(116); var ReactComponent = __webpack_require__(129); var ReactClass = __webpack_require__(128); var ReactDOMFactories = __webpack_require__(159); var ReactElement = __webpack_require__(48); var ReactElementValidator = __webpack_require__(160); var ReactPropTypes = __webpack_require__(113); var ReactVersion = __webpack_require__(152); var assign = __webpack_require__(45); var onlyChild = __webpack_require__(162); var createElement = ReactElement.createElement; var createFactory = ReactElement.createFactory; var cloneElement = ReactElement.cloneElement; if (process.env.NODE_ENV !== 'production') { createElement = ReactElementValidator.createElement; createFactory = ReactElementValidator.createFactory; cloneElement = ReactElementValidator.cloneElement; } var React = { // Modern Children: { map: ReactChildren.map, forEach: ReactChildren.forEach, count: ReactChildren.count, toArray: ReactChildren.toArray, only: onlyChild }, Component: ReactComponent, createElement: createElement, cloneElement: cloneElement, isValidElement: ReactElement.isValidElement, // Classic PropTypes: ReactPropTypes, createClass: ReactClass.createClass, createFactory: createFactory, createMixin: function (mixin) { // Currently a noop. Will be used to validate and trace mixins. return mixin; }, // This looks DOM specific but these are actually isomorphic helpers // since they are just generating DOM strings. DOM: ReactDOMFactories, version: ReactVersion, // Hook for JSX spread, don't use this for anything else. __spread: assign }; module.exports = React; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 159 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMFactories * @typechecks static-only */ 'use strict'; var ReactElement = __webpack_require__(48); var ReactElementValidator = __webpack_require__(160); var mapObject = __webpack_require__(161); /** * Create a factory that creates HTML tag elements. * * @param {string} tag Tag name (e.g. `div`). * @private */ function createDOMFactory(tag) { if (process.env.NODE_ENV !== 'production') { return ReactElementValidator.createFactory(tag); } return ReactElement.createFactory(tag); } /** * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes. * This is also accessible via `React.DOM`. * * @public */ var ReactDOMFactories = mapObject({ a: 'a', abbr: 'abbr', address: 'address', area: 'area', article: 'article', aside: 'aside', audio: 'audio', b: 'b', base: 'base', bdi: 'bdi', bdo: 'bdo', big: 'big', blockquote: 'blockquote', body: 'body', br: 'br', button: 'button', canvas: 'canvas', caption: 'caption', cite: 'cite', code: 'code', col: 'col', colgroup: 'colgroup', data: 'data', datalist: 'datalist', dd: 'dd', del: 'del', details: 'details', dfn: 'dfn', dialog: 'dialog', div: 'div', dl: 'dl', dt: 'dt', em: 'em', embed: 'embed', fieldset: 'fieldset', figcaption: 'figcaption', figure: 'figure', footer: 'footer', form: 'form', h1: 'h1', h2: 'h2', h3: 'h3', h4: 'h4', h5: 'h5', h6: 'h6', head: 'head', header: 'header', hgroup: 'hgroup', hr: 'hr', html: 'html', i: 'i', iframe: 'iframe', img: 'img', input: 'input', ins: 'ins', kbd: 'kbd', keygen: 'keygen', label: 'label', legend: 'legend', li: 'li', link: 'link', main: 'main', map: 'map', mark: 'mark', menu: 'menu', menuitem: 'menuitem', meta: 'meta', meter: 'meter', nav: 'nav', noscript: 'noscript', object: 'object', ol: 'ol', optgroup: 'optgroup', option: 'option', output: 'output', p: 'p', param: 'param', picture: 'picture', pre: 'pre', progress: 'progress', q: 'q', rp: 'rp', rt: 'rt', ruby: 'ruby', s: 's', samp: 'samp', script: 'script', section: 'section', select: 'select', small: 'small', source: 'source', span: 'span', strong: 'strong', style: 'style', sub: 'sub', summary: 'summary', sup: 'sup', table: 'table', tbody: 'tbody', td: 'td', textarea: 'textarea', tfoot: 'tfoot', th: 'th', thead: 'thead', time: 'time', title: 'title', tr: 'tr', track: 'track', u: 'u', ul: 'ul', 'var': 'var', video: 'video', wbr: 'wbr', // SVG circle: 'circle', clipPath: 'clipPath', defs: 'defs', ellipse: 'ellipse', g: 'g', image: 'image', line: 'line', linearGradient: 'linearGradient', mask: 'mask', path: 'path', pattern: 'pattern', polygon: 'polygon', polyline: 'polyline', radialGradient: 'radialGradient', rect: 'rect', stop: 'stop', svg: 'svg', text: 'text', tspan: 'tspan' }, createDOMFactory); module.exports = ReactDOMFactories; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 160 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElementValidator */ /** * ReactElementValidator provides a wrapper around a element factory * which validates the props passed to the element. This is intended to be * used only in DEV and could be replaced by a static type checker for languages * that support it. */ 'use strict'; var ReactElement = __webpack_require__(48); var ReactPropTypeLocations = __webpack_require__(71); var ReactPropTypeLocationNames = __webpack_require__(72); var ReactCurrentOwner = __webpack_require__(11); var canDefineProperty = __webpack_require__(49); var getIteratorFn = __webpack_require__(114); var invariant = __webpack_require__(19); var warning = __webpack_require__(31); function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; var loggedTypeFailures = {}; /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var addenda = getAddendaForKeyUse('uniqueKey', element, parentType); if (addenda === null) { // we already showed the warning return; } process.env.NODE_ENV !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s%s', addenda.parentOrOwner || '', addenda.childOwner || '', addenda.url || '') : undefined; } /** * Shared warning and monitoring code for the key warnings. * * @internal * @param {string} messageType A key used for de-duping warnings. * @param {ReactElement} element Component that requires a key. * @param {*} parentType element's parent's type. * @returns {?object} A set of addenda to use in the warning message, or null * if the warning has already been shown before (and shouldn't be shown again). */ function getAddendaForKeyUse(messageType, element, parentType) { var addendum = getDeclarationErrorAddendum(); if (!addendum) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { addendum = ' Check the top-level render call using <' + parentName + '>.'; } } var memoizer = ownerHasKeyUseWarning[messageType] || (ownerHasKeyUseWarning[messageType] = {}); if (memoizer[addendum]) { return null; } memoizer[addendum] = true; var addenda = { parentOrOwner: addendum, url: ' See https://fb.me/react-warning-keys for more information.', childOwner: null }; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. if (element && element._owner && element._owner !== ReactCurrentOwner.current) { // Give the component that originally created this child. addenda.childOwner = ' It was passed a child from ' + element._owner.getName() + '.'; } return addenda; } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { if (typeof node !== 'object') { return; } if (Array.isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (ReactElement.isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (ReactElement.isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); // Entry iterators provide implicit keys. if (iteratorFn) { if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (ReactElement.isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } /** * Assert that the props are valid * * @param {string} componentName Name of the component for error messages. * @param {object} propTypes Map of prop name to a ReactPropType * @param {object} props * @param {string} location e.g. "prop", "context", "child context" * @private */ function checkPropTypes(componentName, propTypes, props, location) { for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. !(typeof propTypes[propName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : undefined; error = propTypes[propName](props, propName, componentName, location); } catch (ex) { error = ex; } process.env.NODE_ENV !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], propName, typeof error) : undefined; if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var addendum = getDeclarationErrorAddendum(); process.env.NODE_ENV !== 'production' ? warning(false, 'Failed propType: %s%s', error.message, addendum) : undefined; } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { var componentClass = element.type; if (typeof componentClass !== 'function') { return; } var name = componentClass.displayName || componentClass.name; if (componentClass.propTypes) { checkPropTypes(name, componentClass.propTypes, element.props, ReactPropTypeLocations.prop); } if (typeof componentClass.getDefaultProps === 'function') { process.env.NODE_ENV !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : undefined; } } var ReactElementValidator = { createElement: function (type, props, children) { var validType = typeof type === 'string' || typeof type === 'function'; // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. process.env.NODE_ENV !== 'production' ? warning(validType, 'React.createElement: type should not be null, undefined, boolean, or ' + 'number. It should be a string (for DOM elements) or a ReactClass ' + '(for composite components).%s', getDeclarationErrorAddendum()) : undefined; var element = ReactElement.createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } } validatePropTypes(element); return element; }, createFactory: function (type) { var validatedFactory = ReactElementValidator.createElement.bind(null, type); // Legacy hook TODO: Warn if this is accessed validatedFactory.type = type; if (process.env.NODE_ENV !== 'production') { if (canDefineProperty) { Object.defineProperty(validatedFactory, 'type', { enumerable: false, get: function () { process.env.NODE_ENV !== 'production' ? warning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.') : undefined; Object.defineProperty(this, 'type', { value: type }); return type; } }); } } return validatedFactory; }, cloneElement: function (element, props, children) { var newElement = ReactElement.cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } }; module.exports = ReactElementValidator; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 161 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule mapObject */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Executes the provided `callback` once for each enumerable own property in the * object and constructs a new object from the results. The `callback` is * invoked with three arguments: * * - the property value * - the property name * - the object being traversed * * Properties that are added after the call to `mapObject` will not be visited * by `callback`. If the values of existing properties are changed, the value * passed to `callback` will be the value at the time `mapObject` visits them. * Properties that are deleted before being visited are not visited. * * @grep function objectMap() * @grep function objMap() * * @param {?object} object * @param {function} callback * @param {*} context * @return {?object} */ function mapObject(object, callback, context) { if (!object) { return null; } var result = {}; for (var name in object) { if (hasOwnProperty.call(object, name)) { result[name] = callback.call(context, object[name], name, object); } } return result; } module.exports = mapObject; /***/ }, /* 162 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule onlyChild */ 'use strict'; var ReactElement = __webpack_require__(48); var invariant = __webpack_require__(19); /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. The current implementation of this * function assumes that a single child gets passed without a wrapper, but the * purpose of this helper function is to abstract away the particular structure * of children. * * @param {?object} children Child collection structure. * @return {ReactComponent} The first and only `ReactComponent` contained in the * structure. */ function onlyChild(children) { !ReactElement.isValidElement(children) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'onlyChild must be passed a children with exactly one child.') : invariant(false) : undefined; return children; } module.exports = onlyChild; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 163 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule deprecated */ 'use strict'; var assign = __webpack_require__(45); var warning = __webpack_require__(31); /** * This will log a single deprecation notice per function and forward the call * on to the new API. * * @param {string} fnName The name of the function * @param {string} newModule The module that fn will exist in * @param {string} newPackage The module that fn will exist in * @param {*} ctx The context this forwarded call should run in * @param {function} fn The function to forward on to * @return {function} The function that will warn once and then call fn */ function deprecated(fnName, newModule, newPackage, ctx, fn) { var warned = false; if (process.env.NODE_ENV !== 'production') { var newFn = function () { process.env.NODE_ENV !== 'production' ? warning(warned, // Require examples in this string must be split to prevent React's // build tools from mistaking them for real requires. // Otherwise the build tools will attempt to build a '%s' module. 'React.%s is deprecated. Please use %s.%s from require' + '(\'%s\') ' + 'instead.', fnName, newModule, fnName, newPackage) : undefined; warned = true; return fn.apply(ctx, arguments); }; // We need to make sure all properties of the original fn are copied over. // In particular, this is needed to support PropTypes return assign(newFn, fn); } return fn; } module.exports = deprecated; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7))) /***/ }, /* 164 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin module.exports = {"handle":"react-ios-switch-Switch-handle","input":"react-ios-switch-Switch-input","offState":"react-ios-switch-Switch-offState","switch":"react-ios-switch-Switch-switch","switch--disabled":"react-ios-switch-Switch-switch--disabled"}; /***/ } /******/ ]) }); ;
Practicas/TicTac2/componentes/Game.js
tonkyfiero/React_Ejercicios
/* *Importacion de Modulos */ import React from 'react'; import Tablero from './Tablero.js'; export default class Game extends React.Component{ constructor(props){ super(props); this.state={ arreglo:Array(9).fill(null), siguienteLugar:0, isXNext:true } } handleClick(i){ alert(i); /*Matriz de matrices*/ //let historia=this.state.historia.slice(0,this.state.siguienteLugar+1); let arr=this.state.arreglo; //let current =historia[historia.length-1]; //let squares=current.squared.slice(); arr[i]=this.state.isXNext?'X':'O'; if (arr[i]) { return; } this.setState({ arreglo:arr, isXNext: ! this.state.isXNext }); } render(){ //const currentSquare=this.state.historia[this.state.siguienteLugar]; return( <div> <Tablero square={this.state.arreglo} onMouse={(i)=>this.handleClick(i)} /> </div> ) } } function calcularGanador(square) { let decision=[ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6] ]; for (let i = 0; i <decision.length; i++){ const[a,b,c]=decision[i]; if (square[a] && square[a]===square[b] && square[a] ===square[c]) { return square[a]; } } return null; }
ajax/libs/rxjs/2.3.14/rx.lite.compat.js
paleozogt/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise // Detect if promise exists }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()), defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFn(/x/)) { isFn = function(value) { return typeof value == 'function' && toString.call(value) == '[object Function]'; }; } return isFn; }()); // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; Rx.iterator = $iterator$; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `-0` vs. `+0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; var result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Utilities if (!Function.prototype.bind) { Function.prototype.bind = function (that) { var target = this, args = slice.call(arguments, 1); var bound = function () { if (this instanceof bound) { function F() { } F.prototype = target.prototype; var self = new F(); var result = target.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) { return result; } return self; } else { return target.apply(that, args.concat(slice.call(arguments))); } }; return bound; }; } if (!Array.prototype.forEach) { Array.prototype.forEach = function (callback, thisArg) { var T, k; if (this == null) { throw new TypeError(" this is null or not defined"); } var O = Object(this); var len = O.length >>> 0; if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } if (arguments.length > 1) { T = thisArg; } k = 0; while (k < len) { var kValue; if (k in O) { kValue = O[k]; callback.call(T, kValue, k, O); } k++; } }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { result[i] = fun.call(thisp, self[i], i, object); } } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function (predicate) { var results = [], item, t = new Object(this); for (var i = 0, len = t.length >>> 0; i < len; i++) { item = t[i]; if (i in t && predicate.call(arguments[1], item, i, t)) { results.push(item); } } return results; }; } if (!Array.isArray) { Array.isArray = function (arg) { return {}.toString.call(arg) == arrayClass; }; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(searchElement) { var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n !== n) { n = 0; } else if (n !== 0 && n != Infinity && n !== -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; } // Collections function IndexedItem(id, value) { this.id = id; this.value = value; } IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); c === 0 && (c = this.id - other.id); return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { +index || (index = 0); if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () { function BooleanDisposable () { this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } old && old.dispose(); }; return BooleanDisposable; }()); var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); 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 = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return !queue; }; currentScheduler.ensureTrampoline = function (action) { if (!queue) { this.schedule(action); } else { action(); } }; return currentScheduler; }()); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); var scheduleMethod, clearMethod = noop; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if ('WScript' in this) { localSetTimeout = function (fn, time) { WScript.Sleep(time); fn(); }; } else if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else { throw new Error('No concurrency detected!'); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('','*'); root.onmessage = oldHandler; return isAsync; } // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return localSetTimeout(action, 0); }; clearMethod = localClearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = localSetTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { localClearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var notification = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (e) { var notification = new Notification('E'); notification.exception = e; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem; try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableOf = Enumerable.of = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler, thisArg) { return new AnonymousObserver(function (x) { return handler.call(thisArg, notificationCreateOnNext(x)); }, function (e) { return handler.call(thisArg, notificationCreateOnError(e)); }, function () { return handler.call(thisArg, notificationCreateOnCompleted()); }); }; /** * 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) { 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 (err) { var self = this; this.queue.push(function () { self.observer.onError(err); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** * Creates a list from an observable sequence. * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { var self = this; return new AnonymousObservable(function(observer) { var arr = []; return self.subscribe( arr.push.bind(arr), observer.onError.bind(observer), function () { observer.onNext(arr); observer.onCompleted(); }); }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; var maxSafeInteger = Math.pow(2, 53) - 1; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function isIterable(o) { return o[$iterator$] !== undefined; } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } function isCallable(f) { return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function'; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isCallable(mapFn)) { throw new Error('mapFn when provided must be a function'); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var list = Object(iterable), objIsIterable = isIterable(list), len = objIsIterable ? 0 : toLength(list), it = objIsIterable ? list[$iterator$]() : null, i = 0; return scheduler.scheduleRecursive(function (self) { if (i < len || objIsIterable) { var result; if (objIsIterable) { var next; try { next = it.next(); } catch (e) { observer.onError(e); return; } if (next.done) { observer.onCompleted(); return; } result = next.value; } else { result = !!list.charAt ? list.charAt(i) : list[i]; } if (mapFn && isCallable(mapFn)) { try { result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i); } catch (e) { observer.onError(e); return; } } observer.onNext(result); i++; self(); } else { observer.onCompleted(); } }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0, len = array.length; return scheduler.scheduleRecursive(function (self) { if (count < len) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return observableFromArray(args); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ var observableOf = Observable.ofWithScheduler = function (scheduler) { var len = arguments.length - 1, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } return observableFromArray(args, scheduler); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just', and 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwError' for browsers <IE9. * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = Observable.throwError = function (exception, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } isPromise(result) && (result = observableFromPromise(result)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable.catchError = Observable['catch'] = function () { return enumerableOf(argsOrArray(arguments, 0)).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { return enumerableOf(argsOrArray(arguments, 0)).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = []; function subscribe(xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support isPromise(xs) && (xs = observableFromPromise(xs)); subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(subscription); if (q.length > 0) { subscribe(q.shift()); } else { activeCount--; isStopped && activeCount === 0 && observer.onCompleted(); } })); } group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; activeCount === 0 && observer.onCompleted(); })); return group; }); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * * @example * 1 - merged = Rx.Observable.merge(xs, ys, zs); * 2 - merged = Rx.Observable.merge([xs, ys, zs]); * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (arguments[0].now) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableFromArray(sources, scheduler).mergeObservable(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeObservable = observableProto.mergeAll = function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(innerSubscription); isStopped && group.length === 1 && observer.onCompleted(); })); }, observer.onError.bind(observer), function () { isStopped = true; group.length === 1 && observer.onCompleted(); })); return group; }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && observer.onNext(left); }, observer.onError.bind(observer), function () { isOpen && observer.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe( function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe( function (x) { latest === id && observer.onNext(x); }, function (e) { latest === id && observer.onError(e); }, function () { if (latest === id) { hasLatest = false; isStopped && observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = sources[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { return new AnonymousObservable(this.subscribe.bind(this)); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { if (onError) { try { onError(err); } catch (e) { observer.onError(e); } } observer.onError(err); }, function () { if (onCompleted) { try { onCompleted(); } catch (e) { observer.onError(e); } } observer.onCompleted(); }); }); }; /** * Invokes an action for each element in the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onNext Action to invoke for each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { return this.tap(arguments.length === 2 ? function (x) { onNext.call(thisArg, x); } : onNext); }; /** * Invokes an action upon exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { return this.tap(noop, arguments.length === 2 ? function (e) { onError.call(thisArg, e); } : onError); }; /** * Invokes an action upon graceful termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { return this.tap(noop, null, arguments.length === 2 ? function () { onCompleted.call(thisArg); } : onCompleted); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { !hasValue && hasSeed && observer.onNext(seed); observer.onCompleted(); } ); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && observer.onNext(q.shift()); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableOf([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { while(q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); }); }); }; function concatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i, source); isPromise(result) && (result = observableFromPromise(result)); (Array.isArray(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (typeof selector === 'function' && typeof resultSelector === 'function') { return this.concatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (Array.isArray(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }); } return typeof selector === 'function' ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} prop The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (prop) { return this.map(function (x) { return x[prop]; }); }; function flatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i, source); isPromise(result) && (result = observableFromPromise(result)); (Array.isArray(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).mergeObservable(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (typeof selector === 'function' && typeof resultSelector === 'function') { return this.flatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (Array.isArray(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }, thisArg); } return typeof selector === 'function' ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var source = this; return new AnonymousObservable(function (observer) { var remaining = count; return source.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } running && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new RangeError(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining-- > 0) { observer.onNext(x); remaining === 0 && observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, observable); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = observableProto.filter = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (e) { observer.onError(e); return; } shouldRun && observer.onNext(value); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, context, selector) { return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { function handler(e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return; } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, context, selector) { return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { function handler(err) { if (err) { observer.onError(err); return; } var results = slice.call(arguments, 1); if (selector) { try { results = selector(results); } catch (e) { observer.onError(e); return; } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; function fixEvent(event) { var stopPropagation = function () { this.cancelBubble = true; }; var preventDefault = function () { this.bubbledKeyCode = this.keyCode; if (this.ctrlKey) { try { this.keyCode = 0; } catch (e) { } } this.defaultPrevented = true; this.returnValue = false; this.modified = true; }; event || (event = root.event); if (!event.target) { event.target = event.target || event.srcElement; if (event.type == 'mouseover') { event.relatedTarget = event.fromElement; } if (event.type == 'mouseout') { event.relatedTarget = event.toElement; } // Adding stopPropogation and preventDefault to IE if (!event.stopPropagation){ event.stopPropagation = stopPropagation; event.preventDefault = preventDefault; } // Normalize key events switch(event.type){ case 'keypress': var c = ('charCode' in event ? event.charCode : event.keyCode); if (c == 10) { c = 0; event.keyCode = 13; } else if (c == 13 || c == 27) { c = 0; } else if (c == 3) { c = 99; } event.charCode = c; event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : ''; break; } } return event; } function createListener (element, name, handler) { // Standards compliant if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } if (element.attachEvent) { // IE Specific var innerHandler = function (event) { handler(fixEvent(event)); }; element.attachEvent('on' + name, innerHandler); return disposableCreate(function () { element.detachEvent('on' + name, innerHandler); }); } // Level 1 DOM Events element['on' + name] = handler; return disposableCreate(function () { element['on' + name] = null; }); } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList if (Object.prototype.toString.call(el) === '[object NodeList]') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } /** * Configuration option to determine whether to use native events only */ Rx.config.useNativeEvents = false; // Check for Angular/jQuery/Zepto support var jq = !!root.angular && !!angular.element ? angular.element : (!!root.jQuery ? root.jQuery : ( !!root.Zepto ? root.Zepto : null)); // Check for ember var ember = !!root.Ember && typeof root.Ember.addListener === 'function'; // Check for Backbone.Marionette. Note if using AMD add Marionette as a dependency of rxjs // for proper loading order! var marionette = !!root.Backbone && !!root.Backbone.Marionette; /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { // Node.js specific if (element.addListener) { return fromEventPattern( function (h) { element.addListener(eventName, h); }, function (h) { element.removeListener(eventName, h); }, selector); } // Use only if non-native events are allowed if (!Rx.config.useNativeEvents) { if (marionette) { return fromEventPattern( function (h) { element.on(eventName, h); }, function (h) { element.off(eventName, h); }, selector); } if (ember) { return fromEventPattern( function (h) { Ember.addListener(element, eventName, h); }, function (h) { Ember.removeListener(element, eventName, h); }, selector); } if (jq) { var $elem = jq(element); return fromEventPattern( function (h) { $elem.on(eventName, h); }, function (h) { $elem.off(eventName, h); }, selector); } } return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { observer.onError(err); return; } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return observableDefer(function () { var subject = new Rx.AsyncSubject(); promise.then( function (value) { if (!subject.isDisposed) { subject.onNext(value); subject.onCompleted(); } }, subject.onError.bind(subject)); return subject; }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new 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()); }) : 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. * * @example * var res = source.share(); * * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish().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. * * @example * var res = source.shareValue(42); * * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, window, scheduler) { return selector && 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, subject.subscribe.bind(subject)); } ConnectableObservable.prototype.refCount = function () { var connectableSubscription, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect = ++count === 1, subscription = source.subscribe(observer); shouldConnect && (connectableSubscription = source.connect()); return function () { subscription.dispose(); --count === 0 && connectableSubscription.dispose(); }; }); }; return ConnectableObservable; }(Observable)); function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { return new AnonymousObservable(function (observer) { var count = 0, d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { if (p > 0) { var now = scheduler.now(); d = d + p; d <= now && (d = now + p); } observer.onNext(count++); self(d); }); }); } function observableTimerTimeSpan(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { return dueTime === period ? new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }) : observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * @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); }); } function observableDelayDate(source, dueTime, scheduler) { return observableDefer(function () { return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); }); } /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * 1 - res = Rx.Observable.delay(new Date()); * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); * * 3 - res = Rx.Observable.delay(5000); * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return dueTime instanceof Date ? observableDelayDate(this, dueTime.getTime(), scheduler) : observableDelayTimeSpan(this, dueTime, scheduler); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * * @example * 1 - res = source.throttle(5000); // 5 seconds * 2 - res = source.throttle(5000, scheduler); * * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The throttled sequence. */ observableProto.throttle = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); 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); }); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.map(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } atEnd && observer.onCompleted(); } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = function (intervalOrSampler, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return typeof intervalOrSampler === 'number' ? sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * @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); }); }; var PausableObservable = (function (_super) { inherits(PausableObservable, _super); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } _super.call(this, subscribe); } PausableObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (observer) { var n = 2, hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(n); function next(x, i) { values[i] = x var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone) { observer.onCompleted(); } } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, observer.onError.bind(observer), function () { isDone = true; observer.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, observer.onError.bind(observer)) ); }); } var PausableBufferedObservable = (function (_super) { inherits(PausableBufferedObservable, _super); function subscribe(observer) { var q = [], previousShouldFire; var subscription = combineLatestSource( this.source, this.pauser.distinctUntilChanged().startWith(false), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) { previousShouldFire = results.shouldFire; // change in shouldFire if (results.shouldFire) { while (q.length > 0) { observer.onNext(q.shift()); } } } else { previousShouldFire = results.shouldFire; // new data if (results.shouldFire) { observer.onNext(results.data); } else { q.push(results.data); } } }, function (err) { // Empty buffer before sending error while (q.length > 0) { observer.onNext(q.shift()); } observer.onError(err); }, function () { // Empty buffer before sending completion while (q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); } ); return subscription; } function PausableBufferedObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } _super.call(this, subscribe); } PausableBufferedObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.controlled = function (enableQueue) { if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue); }; var ControlledObservable = (function (_super) { inherits(ControlledObservable, _super); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue) { _super.call(this, subscribe); this.subject = new ControlledSubject(enableQueue); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { if (numberOfItems == null) { numberOfItems = -1; } return this.subject.request(numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = Rx.ControlledSubject = (function (_super) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, _super); function ControlledSubject(enableQueue) { if (enableQueue == null) { enableQueue = true; } _super.call(this, subscribe); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; this.controlledDisposable = disposableEmpty; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { checkDisposed.call(this); this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) { this.subject.onCompleted(); } }, onError: function (error) { checkDisposed.call(this); this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) { this.subject.onError(error); } }, onNext: function (value) { checkDisposed.call(this); var hasRequested = false; if (this.requestedCount === 0) { if (this.enableQueue) { this.queue.push(value); } } else { if (this.requestedCount !== -1) { if (this.requestedCount-- === 0) { this.disposeCurrentRequest(); } } hasRequested = true; } if (hasRequested) { this.subject.onNext(value); } }, _processRequest: function (numberOfItems) { if (this.enableQueue) { //console.log('queue length', this.queue.length); while (this.queue.length >= numberOfItems && numberOfItems > 0) { //console.log('number of items', numberOfItems); this.subject.onNext(this.queue.shift()); numberOfItems--; } if (this.queue.length !== 0) { return { numberOfItems: numberOfItems, returnValue: true }; } else { return { numberOfItems: numberOfItems, returnValue: false }; } } if (this.hasFailed) { this.subject.onError(this.error); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } else if (this.hasCompleted) { this.subject.onCompleted(); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { checkDisposed.call(this); this.disposeCurrentRequest(); var self = this, r = this._processRequest(number); number = r.numberOfItems; if (!r.returnValue) { this.requestedCount = number; this.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); return this.requestedDisposable } else { return disposableEmpty; } }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; }, dispose: function () { this.isDisposed = true; this.error = null; this.subject.dispose(); this.requestedDisposable.dispose(); } }); return ControlledSubject; }(Observable)); /** * Executes a transducer to transform the observable sequence * @param {Transducer} transducer A transducer to execute * @returns {Observable} An Observable sequence containing the results from the transducer. */ observableProto.transduce = function(transducer) { var source = this; function transformForObserver(observer) { return { init: function() { return observer; }, step: function(obs, input) { return obs.onNext(input); }, result: function(obs) { return obs.onCompleted(); } }; } return new AnonymousObservable(function(observer) { var xform = transducer(transformForObserver(observer)); return source.subscribe( function(v) { try { xform.step(observer, v); } catch (e) { observer.onError(e); } }, observer.onError.bind(observer), function() { xform.result(observer); } ); }); }; var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } return typeof subscriber === 'function' ? disposableCreate(subscriber) : disposableEmpty; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var setDisposable = function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }; var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(setDisposable); } else { setDisposable(); } return autoDetachObserver; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (__super__) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } this.value = value; this.hasValue = true; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, this.observable.subscribe.bind(this.observable)); } addProperties(AnonymousSubject.prototype, Observer, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (exception) { this.observer.onError(exception); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } var ex = this.exception; if (ex) { observer.onError(ex); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, __super__); /** * @constructor * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { __super__.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.exception = null; } addProperties(BehaviorSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; this.exception = error; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { 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); var n = this.q.length; for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { n++; so.onError(this.error); } else if (this.isStopped) { n++; so.onCompleted(); } so.ensureActive(n); return subscription; } inherits(ReplaySubject, __super__); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; __super__.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, _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)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } }.call(this));
ajax/libs/yui/3.9.1/scrollview-base/scrollview-base-debug.js
gaearon/cdnjs
YUI.add('scrollview-base', function (Y, NAME) { /** * The scrollview-base module provides a basic ScrollView Widget, without scrollbar indicators * * @module scrollview * @submodule scrollview-base */ // Local vars var getClassName = Y.ClassNameManager.getClassName, DOCUMENT = Y.config.doc, IE = Y.UA.ie, NATIVE_TRANSITIONS = Y.Transition.useNative, vendorPrefix = Y.Transition._VENDOR_PREFIX, // Todo: This is a private property, and alternative approaches should be investigated SCROLLVIEW = 'scrollview', CLASS_NAMES = { vertical: getClassName(SCROLLVIEW, 'vert'), horizontal: getClassName(SCROLLVIEW, 'horiz') }, EV_SCROLL_END = 'scrollEnd', FLICK = 'flick', DRAG = 'drag', MOUSEWHEEL = 'mousewheel', UI = 'ui', TOP = 'top', LEFT = 'left', PX = 'px', AXIS = 'axis', SCROLL_Y = 'scrollY', SCROLL_X = 'scrollX', BOUNCE = 'bounce', DISABLED = 'disabled', DECELERATION = 'deceleration', DIM_X = 'x', DIM_Y = 'y', BOUNDING_BOX = 'boundingBox', CONTENT_BOX = 'contentBox', GESTURE_MOVE = 'gesturemove', START = 'start', END = 'end', EMPTY = '', ZERO = '0s', SNAP_DURATION = 'snapDuration', SNAP_EASING = 'snapEasing', EASING = 'easing', FRAME_DURATION = 'frameDuration', BOUNCE_RANGE = 'bounceRange', _constrain = function (val, min, max) { return Math.min(Math.max(val, min), max); }; /** * ScrollView provides a scrollable widget, supporting flick gestures, * across both touch and mouse based devices. * * @class ScrollView * @param config {Object} Object literal with initial attribute values * @extends Widget * @constructor */ function ScrollView() { ScrollView.superclass.constructor.apply(this, arguments); } Y.ScrollView = Y.extend(ScrollView, Y.Widget, { // *** Y.ScrollView prototype /** * Flag driving whether or not we should try and force H/W acceleration when transforming. Currently enabled by default for Webkit. * Used by the _transform method. * * @property _forceHWTransforms * @type boolean * @protected */ _forceHWTransforms: Y.UA.webkit ? true : false, /** * <p>Used to control whether or not ScrollView's internal * gesturemovestart, gesturemove and gesturemoveend * event listeners should preventDefault. The value is an * object, with "start", "move" and "end" properties used to * specify which events should preventDefault and which shouldn't:</p> * * <pre> * { * start: false, * move: true, * end: false * } * </pre> * * <p>The default values are set up in order to prevent panning, * on touch devices, while allowing click listeners on elements inside * the ScrollView to be notified as expected.</p> * * @property _prevent * @type Object * @protected */ _prevent: { start: false, move: true, end: false }, /** * Contains the distance (postive or negative) in pixels by which * the scrollview was last scrolled. This is useful when setting up * click listeners on the scrollview content, which on mouse based * devices are always fired, even after a drag/flick. * * <p>Touch based devices don't currently fire a click event, * if the finger has been moved (beyond a threshold) so this * check isn't required, if working in a purely touch based environment</p> * * @property lastScrolledAmt * @type Number * @public * @default 0 */ lastScrolledAmt: 0, /** * Internal state, defines the minimum amount that the scrollview can be scrolled along the X axis * * @property _minScrollX * @type number * @protected */ _minScrollX: null, /** * Internal state, defines the maximum amount that the scrollview can be scrolled along the X axis * * @property _maxScrollX * @type number * @protected */ _maxScrollX: null, /** * Internal state, defines the minimum amount that the scrollview can be scrolled along the Y axis * * @property _minScrollY * @type number * @protected */ _minScrollY: null, /** * Internal state, defines the maximum amount that the scrollview can be scrolled along the Y axis * * @property _maxScrollY * @type number * @protected */ _maxScrollY: null, /** * Designated initializer * * @method initializer * @param {config} Configuration object for the plugin */ initializer: function () { var sv = this; // Cache these values, since they aren't going to change. sv._bb = sv.get(BOUNDING_BOX); sv._cb = sv.get(CONTENT_BOX); // Cache some attributes sv._cAxis = sv.get(AXIS); sv._cBounce = sv.get(BOUNCE); sv._cBounceRange = sv.get(BOUNCE_RANGE); sv._cDeceleration = sv.get(DECELERATION); sv._cFrameDuration = sv.get(FRAME_DURATION); }, /** * bindUI implementation * * Hooks up events for the widget * @method bindUI */ bindUI: function () { var sv = this; // Bind interaction listers sv._bindFlick(sv.get(FLICK)); sv._bindDrag(sv.get(DRAG)); sv._bindMousewheel(true); // Bind change events sv._bindAttrs(); // IE SELECT HACK. See if we can do this non-natively and in the gesture for a future release. if (IE) { sv._fixIESelect(sv._bb, sv._cb); } // Set any deprecated static properties if (ScrollView.SNAP_DURATION) { sv.set(SNAP_DURATION, ScrollView.SNAP_DURATION); } if (ScrollView.SNAP_EASING) { sv.set(SNAP_EASING, ScrollView.SNAP_EASING); } if (ScrollView.EASING) { sv.set(EASING, ScrollView.EASING); } if (ScrollView.FRAME_STEP) { sv.set(FRAME_DURATION, ScrollView.FRAME_STEP); } if (ScrollView.BOUNCE_RANGE) { sv.set(BOUNCE_RANGE, ScrollView.BOUNCE_RANGE); } // Recalculate dimension properties // TODO: This should be throttled. // Y.one(WINDOW).after('resize', sv._afterDimChange, sv); }, /** * Bind event listeners * * @method _bindAttrs * @private */ _bindAttrs: function () { var sv = this, scrollChangeHandler = sv._afterScrollChange, dimChangeHandler = sv._afterDimChange; // Bind any change event listeners sv.after({ 'scrollEnd': sv._afterScrollEnd, 'disabledChange': sv._afterDisabledChange, 'flickChange': sv._afterFlickChange, 'dragChange': sv._afterDragChange, 'axisChange': sv._afterAxisChange, 'scrollYChange': scrollChangeHandler, 'scrollXChange': scrollChangeHandler, 'heightChange': dimChangeHandler, 'widthChange': dimChangeHandler }); }, /** * Bind (or unbind) gesture move listeners required for drag support * * @method _bindDrag * @param drag {boolean} If true, the method binds listener to enable * drag (gesturemovestart). If false, the method unbinds gesturemove * listeners for drag support. * @private */ _bindDrag: function (drag) { var sv = this, bb = sv._bb; // Unbind any previous 'drag' listeners bb.detach(DRAG + '|*'); if (drag) { bb.on(DRAG + '|' + GESTURE_MOVE + START, Y.bind(sv._onGestureMoveStart, sv)); } }, /** * Bind (or unbind) flick listeners. * * @method _bindFlick * @param flick {Object|boolean} If truthy, the method binds listeners for * flick support. If false, the method unbinds flick listeners. * @private */ _bindFlick: function (flick) { var sv = this, bb = sv._bb; // Unbind any previous 'flick' listeners bb.detach(FLICK + '|*'); if (flick) { bb.on(FLICK + '|' + FLICK, Y.bind(sv._flick, sv), flick); // Rebind Drag, becuase _onGestureMoveEnd always has to fire -after- _flick sv._bindDrag(sv.get(DRAG)); } }, /** * Bind (or unbind) mousewheel listeners. * * @method _bindMousewheel * @param mousewheel {Object|boolean} If truthy, the method binds listeners for * mousewheel support. If false, the method unbinds mousewheel listeners. * @private */ _bindMousewheel: function (mousewheel) { var sv = this, bb = sv._bb; // Unbind any previous 'mousewheel' listeners // TODO: This doesn't actually appear to work properly. Fix. #2532743 bb.detach(MOUSEWHEEL + '|*'); // Only enable for vertical scrollviews if (mousewheel) { // Bound to document, because that's where mousewheel events fire off of. Y.one(DOCUMENT).on(MOUSEWHEEL, Y.bind(sv._mousewheel, sv)); } }, /** * syncUI implementation. * * Update the scroll position, based on the current value of scrollX/scrollY. * * @method syncUI */ syncUI: function () { var sv = this, scrollDims = sv._getScrollDims(), width = scrollDims.offsetWidth, height = scrollDims.offsetHeight, scrollWidth = scrollDims.scrollWidth, scrollHeight = scrollDims.scrollHeight; // If the axis is undefined, auto-calculate it if (sv._cAxis === undefined) { // This should only ever be run once (for now). // In the future SV might post-load axis changes sv._cAxis = { x: (scrollWidth > width), y: (scrollHeight > height) }; sv._set(AXIS, sv._cAxis); } // get text direction on or inherited by scrollview node sv.rtl = (sv._cb.getComputedStyle('direction') === 'rtl'); // Cache the disabled value sv._cDisabled = sv.get(DISABLED); // Run this to set initial values sv._uiDimensionsChange(); // If we're out-of-bounds, snap back. if (sv._isOutOfBounds()) { sv._snapBack(); } }, /** * Utility method to obtain widget dimensions * * @method _getScrollDims * @return {Object} The offsetWidth, offsetHeight, scrollWidth and * scrollHeight as an array: [offsetWidth, offsetHeight, scrollWidth, * scrollHeight] * @private */ _getScrollDims: function () { var sv = this, cb = sv._cb, bb = sv._bb, TRANS = ScrollView._TRANSITION, // Ideally using CSSMatrix - don't think we have it normalized yet though. // origX = (new WebKitCSSMatrix(cb.getComputedStyle("transform"))).e, // origY = (new WebKitCSSMatrix(cb.getComputedStyle("transform"))).f, origX = sv.get(SCROLL_X), origY = sv.get(SCROLL_Y), origHWTransform, dims; // TODO: Is this OK? Just in case it's called 'during' a transition. if (NATIVE_TRANSITIONS) { cb.setStyle(TRANS.DURATION, ZERO); cb.setStyle(TRANS.PROPERTY, EMPTY); } origHWTransform = sv._forceHWTransforms; sv._forceHWTransforms = false; // the z translation was causing issues with picking up accurate scrollWidths in Chrome/Mac. sv._moveTo(cb, 0, 0); dims = { 'offsetWidth': bb.get('offsetWidth'), 'offsetHeight': bb.get('offsetHeight'), 'scrollWidth': bb.get('scrollWidth'), 'scrollHeight': bb.get('scrollHeight') }; sv._moveTo(cb, -(origX), -(origY)); sv._forceHWTransforms = origHWTransform; return dims; }, /** * This method gets invoked whenever the height or width attributes change, * allowing us to determine which scrolling axes need to be enabled. * * @method _uiDimensionsChange * @protected */ _uiDimensionsChange: function () { var sv = this, bb = sv._bb, scrollDims = sv._getScrollDims(), width = scrollDims.offsetWidth, height = scrollDims.offsetHeight, scrollWidth = scrollDims.scrollWidth, scrollHeight = scrollDims.scrollHeight, rtl = sv.rtl, svAxis = sv._cAxis, minScrollX = (rtl ? Math.min(0, -(scrollWidth - width)) : 0), maxScrollX = (rtl ? 0 : Math.max(0, scrollWidth - width)), minScrollY = 0, maxScrollY = Math.max(0, scrollHeight - height); if (svAxis && svAxis.x) { bb.addClass(CLASS_NAMES.horizontal); } if (svAxis && svAxis.y) { bb.addClass(CLASS_NAMES.vertical); } sv._setBounds({ minScrollX: minScrollX, maxScrollX: maxScrollX, minScrollY: minScrollY, maxScrollY: maxScrollY }); }, /** * Set the bounding dimensions of the ScrollView * * @method _setBounds * @protected * @param bounds {Object} [duration] ms of the scroll animation. (default is 0) * @param {Number} [bounds.minScrollX] The minimum scroll X value * @param {Number} [bounds.maxScrollX] The maximum scroll X value * @param {Number} [bounds.minScrollY] The minimum scroll Y value * @param {Number} [bounds.maxScrollY] The maximum scroll Y value */ _setBounds: function (bounds) { var sv = this; // TODO: Do a check to log if the bounds are invalid sv._minScrollX = bounds.minScrollX; sv._maxScrollX = bounds.maxScrollX; sv._minScrollY = bounds.minScrollY; sv._maxScrollY = bounds.maxScrollY; }, /** * Get the bounding dimensions of the ScrollView * * @method _getBounds * @protected */ _getBounds: function () { var sv = this; return { minScrollX: sv._minScrollX, maxScrollX: sv._maxScrollX, minScrollY: sv._minScrollY, maxScrollY: sv._maxScrollY }; }, /** * Scroll the element to a given xy coordinate * * @method scrollTo * @param x {Number} The x-position to scroll to. (null for no movement) * @param y {Number} The y-position to scroll to. (null for no movement) * @param {Number} [duration] ms of the scroll animation. (default is 0) * @param {String} [easing] An easing equation if duration is set. (default is `easing` attribute) * @param {String} [node] The node to transform. Setting this can be useful in * dual-axis paginated instances. (default is the instance's contentBox) */ scrollTo: function (x, y, duration, easing, node) { // Check to see if widget is disabled if (this._cDisabled) { return; } var sv = this, cb = sv._cb, TRANS = ScrollView._TRANSITION, callback = Y.bind(sv._onTransEnd, sv), // @Todo : cache this newX = 0, newY = 0, transition = {}, transform; // default the optional arguments duration = duration || 0; easing = easing || sv.get(EASING); // @TODO: Cache this node = node || cb; if (x !== null) { sv.set(SCROLL_X, x, {src:UI}); newX = -(x); } if (y !== null) { sv.set(SCROLL_Y, y, {src:UI}); newY = -(y); } transform = sv._transform(newX, newY); if (NATIVE_TRANSITIONS) { // ANDROID WORKAROUND - try and stop existing transition, before kicking off new one. node.setStyle(TRANS.DURATION, ZERO).setStyle(TRANS.PROPERTY, EMPTY); } // Move if (duration === 0) { if (NATIVE_TRANSITIONS) { node.setStyle('transform', transform); } else { // TODO: If both set, batch them in the same update // Update: Nope, setStyles() just loops through each property and applies it. if (x !== null) { node.setStyle(LEFT, newX + PX); } if (y !== null) { node.setStyle(TOP, newY + PX); } } } // Animate else { transition.easing = easing; transition.duration = duration / 1000; if (NATIVE_TRANSITIONS) { transition.transform = transform; } else { transition.left = newX + PX; transition.top = newY + PX; } node.transition(transition, callback); } }, /** * Utility method, to create the translate transform string with the * x, y translation amounts provided. * * @method _transform * @param {Number} x Number of pixels to translate along the x axis * @param {Number} y Number of pixels to translate along the y axis * @private */ _transform: function (x, y) { // TODO: Would we be better off using a Matrix for this? var prop = 'translate(' + x + 'px, ' + y + 'px)'; if (this._forceHWTransforms) { prop += ' translateZ(0)'; } return prop; }, /** * Utility method, to move the given element to the given xy position * * @method _moveTo * @param node {Node} The node to move * @param x {Number} The x-position to move to * @param y {Number} The y-position to move to * @private */ _moveTo : function(node, x, y) { if (NATIVE_TRANSITIONS) { node.setStyle('transform', this._transform(x, y)); } else { node.setStyle(LEFT, x + PX); node.setStyle(TOP, y + PX); } }, /** * Content box transition callback * * @method _onTransEnd * @param {Event.Facade} e The event facade * @private */ _onTransEnd: function () { var sv = this; // If for some reason we're OOB, snapback if (sv._isOutOfBounds()) { sv._snapBack(); } else { /** * Notification event fired at the end of a scroll transition * * @event scrollEnd * @param e {EventFacade} The default event facade. */ sv.fire(EV_SCROLL_END); } }, /** * gesturemovestart event handler * * @method _onGestureMoveStart * @param e {Event.Facade} The gesturemovestart event facade * @private */ _onGestureMoveStart: function (e) { if (this._cDisabled) { return false; } var sv = this, bb = sv._bb, currentX = sv.get(SCROLL_X), currentY = sv.get(SCROLL_Y), clientX = e.clientX, clientY = e.clientY; if (sv._prevent.start) { e.preventDefault(); } // if a flick animation is in progress, cancel it if (sv._flickAnim) { sv._cancelFlick(); sv._onTransEnd(); } // Reset lastScrolledAmt sv.lastScrolledAmt = 0; // Stores data for this gesture cycle. Cleaned up later sv._gesture = { // Will hold the axis value axis: null, // The current attribute values startX: currentX, startY: currentY, // The X/Y coordinates where the event began startClientX: clientX, startClientY: clientY, // The X/Y coordinates where the event will end endClientX: null, endClientY: null, // The current delta of the event deltaX: null, deltaY: null, // Will be populated for flicks flick: null, // Create some listeners for the rest of the gesture cycle onGestureMove: bb.on(DRAG + '|' + GESTURE_MOVE, Y.bind(sv._onGestureMove, sv)), // @TODO: Don't bind gestureMoveEnd if it's a Flick? onGestureMoveEnd: bb.on(DRAG + '|' + GESTURE_MOVE + END, Y.bind(sv._onGestureMoveEnd, sv)) }; }, /** * gesturemove event handler * * @method _onGestureMove * @param e {Event.Facade} The gesturemove event facade * @private */ _onGestureMove: function (e) { var sv = this, gesture = sv._gesture, svAxis = sv._cAxis, svAxisX = svAxis.x, svAxisY = svAxis.y, startX = gesture.startX, startY = gesture.startY, startClientX = gesture.startClientX, startClientY = gesture.startClientY, clientX = e.clientX, clientY = e.clientY; if (sv._prevent.move) { e.preventDefault(); } gesture.deltaX = startClientX - clientX; gesture.deltaY = startClientY - clientY; // Determine if this is a vertical or horizontal movement // @TODO: This is crude, but it works. Investigate more intelligent ways to detect intent if (gesture.axis === null) { gesture.axis = (Math.abs(gesture.deltaX) > Math.abs(gesture.deltaY)) ? DIM_X : DIM_Y; } // Move X or Y. @TODO: Move both if dualaxis. if (gesture.axis === DIM_X && svAxisX) { sv.set(SCROLL_X, startX + gesture.deltaX); } else if (gesture.axis === DIM_Y && svAxisY) { sv.set(SCROLL_Y, startY + gesture.deltaY); } }, /** * gesturemoveend event handler * * @method _onGestureMoveEnd * @param e {Event.Facade} The gesturemoveend event facade * @private */ _onGestureMoveEnd: function (e) { var sv = this, gesture = sv._gesture, flick = gesture.flick, clientX = e.clientX, clientY = e.clientY, isOOB; if (sv._prevent.end) { e.preventDefault(); } // Store the end X/Y coordinates gesture.endClientX = clientX; gesture.endClientY = clientY; // Cleanup the event handlers gesture.onGestureMove.detach(); gesture.onGestureMoveEnd.detach(); // If this wasn't a flick, wrap up the gesture cycle if (!flick) { // @TODO: Be more intelligent about this. Look at the Flick attribute to see // if it is safe to assume _flick did or didn't fire. // Then, the order _flick and _onGestureMoveEnd fire doesn't matter? // If there was movement (_onGestureMove fired) if (gesture.deltaX !== null && gesture.deltaY !== null) { isOOB = sv._isOutOfBounds(); // If we're out-out-bounds, then snapback if (isOOB) { sv._snapBack(); } // Inbounds else { // Fire scrollEnd unless this is a paginated instance and the gesture axis is the same as paginator's // Not totally confident this is ideal to access a plugin's properties from a host, @TODO revisit if (!sv.pages || (sv.pages && !sv.pages.get(AXIS)[gesture.axis])) { sv._onTransEnd(); } } } } }, /** * Execute a flick at the end of a scroll action * * @method _flick * @param e {Event.Facade} The Flick event facade * @private */ _flick: function (e) { if (this._cDisabled) { return false; } var sv = this, svAxis = sv._cAxis, flick = e.flick, flickAxis = flick.axis, flickVelocity = flick.velocity, axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y, startPosition = sv.get(axisAttr); // Sometimes flick is enabled, but drag is disabled if (sv._gesture) { sv._gesture.flick = flick; } // Prevent unneccesary firing of _flickFrame if we can't scroll on the flick axis if (svAxis[flickAxis]) { sv._flickFrame(flickVelocity, flickAxis, startPosition); } }, /** * Execute a single frame in the flick animation * * @method _flickFrame * @param velocity {Number} The velocity of this animated frame * @param flickAxis {String} The axis on which to animate * @param startPosition {Number} The starting X/Y point to flick from * @protected */ _flickFrame: function (velocity, flickAxis, startPosition) { var sv = this, axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y, bounds = sv._getBounds(), // Localize cached values bounce = sv._cBounce, bounceRange = sv._cBounceRange, deceleration = sv._cDeceleration, frameDuration = sv._cFrameDuration, // Calculate newVelocity = velocity * deceleration, newPosition = startPosition - (frameDuration * newVelocity), // Some convinience conditions min = flickAxis === DIM_X ? bounds.minScrollX : bounds.minScrollY, max = flickAxis === DIM_X ? bounds.maxScrollX : bounds.maxScrollY, belowMin = (newPosition < min), belowMax = (newPosition < max), aboveMin = (newPosition > min), aboveMax = (newPosition > max), belowMinRange = (newPosition < (min - bounceRange)), withinMinRange = (belowMin && (newPosition > (min - bounceRange))), withinMaxRange = (aboveMax && (newPosition < (max + bounceRange))), aboveMaxRange = (newPosition > (max + bounceRange)), tooSlow; // If we're within the range but outside min/max, dampen the velocity if (withinMinRange || withinMaxRange) { newVelocity *= bounce; } // Is the velocity too slow to bother? tooSlow = (Math.abs(newVelocity).toFixed(4) < 0.015); // If the velocity is too slow or we're outside the range if (tooSlow || belowMinRange || aboveMaxRange) { // Cancel and delete sv._flickAnim if (sv._flickAnim) { sv._cancelFlick(); } // If we're inside the scroll area, just end if (aboveMin && belowMax) { sv._onTransEnd(); } // We're outside the scroll area, so we need to snap back else { sv._snapBack(); } } // Otherwise, animate to the next frame else { // @TODO: maybe use requestAnimationFrame instead sv._flickAnim = Y.later(frameDuration, sv, '_flickFrame', [newVelocity, flickAxis, newPosition]); sv.set(axisAttr, newPosition); } }, _cancelFlick: function () { var sv = this; if (sv._flickAnim) { // Cancel the flick (if it exists) sv._flickAnim.cancel(); // Also delete it, otherwise _onGestureMoveStart will think we're still flicking delete sv._flickAnim; } }, /** * Handle mousewheel events on the widget * * @method _mousewheel * @param e {Event.Facade} The mousewheel event facade * @private */ _mousewheel: function (e) { var sv = this, scrollY = sv.get(SCROLL_Y), bounds = sv._getBounds(), bb = sv._bb, scrollOffset = 10, // 10px isForward = (e.wheelDelta > 0), scrollToY = scrollY - ((isForward ? 1 : -1) * scrollOffset); scrollToY = _constrain(scrollToY, bounds.minScrollY, bounds.maxScrollY); // Because Mousewheel events fire off 'document', every ScrollView widget will react // to any mousewheel anywhere on the page. This check will ensure that the mouse is currently // over this specific ScrollView. Also, only allow mousewheel scrolling on Y-axis, // becuase otherwise the 'prevent' will block page scrolling. if (bb.contains(e.target) && sv._cAxis[DIM_Y]) { // Reset lastScrolledAmt sv.lastScrolledAmt = 0; // Jump to the new offset sv.set(SCROLL_Y, scrollToY); // if we have scrollbars plugin, update & set the flash timer on the scrollbar // @TODO: This probably shouldn't be in this module if (sv.scrollbars) { // @TODO: The scrollbars should handle this themselves sv.scrollbars._update(); sv.scrollbars.flash(); // or just this // sv.scrollbars._hostDimensionsChange(); } // Fire the 'scrollEnd' event sv._onTransEnd(); // prevent browser default behavior on mouse scroll e.preventDefault(); } }, /** * Checks to see the current scrollX/scrollY position beyond the min/max boundary * * @method _isOutOfBounds * @param x {Number} [optional] The X position to check * @param y {Number} [optional] The Y position to check * @return {boolen} Whether the current X/Y position is out of bounds (true) or not (false) * @private */ _isOutOfBounds: function (x, y) { var sv = this, svAxis = sv._cAxis, svAxisX = svAxis.x, svAxisY = svAxis.y, currentX = x || sv.get(SCROLL_X), currentY = y || sv.get(SCROLL_Y), bounds = sv._getBounds(), minX = bounds.minScrollX, minY = bounds.minScrollY, maxX = bounds.maxScrollX, maxY = bounds.maxScrollY; return (svAxisX && (currentX < minX || currentX > maxX)) || (svAxisY && (currentY < minY || currentY > maxY)); }, /** * Bounces back * @TODO: Should be more generalized and support both X and Y detection * * @method _snapBack * @private */ _snapBack: function () { var sv = this, currentX = sv.get(SCROLL_X), currentY = sv.get(SCROLL_Y), bounds = sv._getBounds(), minX = bounds.minScrollX, minY = bounds.minScrollY, maxX = bounds.maxScrollX, maxY = bounds.maxScrollY, newY = _constrain(currentY, minY, maxY), newX = _constrain(currentX, minX, maxX), duration = sv.get(SNAP_DURATION), easing = sv.get(SNAP_EASING); if (newX !== currentX) { sv.set(SCROLL_X, newX, {duration:duration, easing:easing}); } else if (newY !== currentY) { sv.set(SCROLL_Y, newY, {duration:duration, easing:easing}); } else { sv._onTransEnd(); } }, /** * After listener for changes to the scrollX or scrollY attribute * * @method _afterScrollChange * @param e {Event.Facade} The event facade * @protected */ _afterScrollChange: function (e) { if (e.src === ScrollView.UI_SRC) { return false; } var sv = this, duration = e.duration, easing = e.easing, val = e.newVal, scrollToArgs = []; // Set the scrolled value sv.lastScrolledAmt = sv.lastScrolledAmt + (e.newVal - e.prevVal); // Generate the array of args to pass to scrollTo() if (e.attrName === SCROLL_X) { scrollToArgs.push(val); scrollToArgs.push(sv.get(SCROLL_Y)); } else { scrollToArgs.push(sv.get(SCROLL_X)); scrollToArgs.push(val); } scrollToArgs.push(duration); scrollToArgs.push(easing); sv.scrollTo.apply(sv, scrollToArgs); }, /** * After listener for changes to the flick attribute * * @method _afterFlickChange * @param e {Event.Facade} The event facade * @protected */ _afterFlickChange: function (e) { this._bindFlick(e.newVal); }, /** * After listener for changes to the disabled attribute * * @method _afterDisabledChange * @param e {Event.Facade} The event facade * @protected */ _afterDisabledChange: function (e) { // Cache for performance - we check during move this._cDisabled = e.newVal; }, /** * After listener for the axis attribute * * @method _afterAxisChange * @param e {Event.Facade} The event facade * @protected */ _afterAxisChange: function (e) { this._cAxis = e.newVal; }, /** * After listener for changes to the drag attribute * * @method _afterDragChange * @param e {Event.Facade} The event facade * @protected */ _afterDragChange: function (e) { this._bindDrag(e.newVal); }, /** * After listener for the height or width attribute * * @method _afterDimChange * @param e {Event.Facade} The event facade * @protected */ _afterDimChange: function () { this._uiDimensionsChange(); }, /** * After listener for scrollEnd, for cleanup * * @method _afterScrollEnd * @param e {Event.Facade} The event facade * @protected */ _afterScrollEnd: function () { var sv = this; if (sv._flickAnim) { sv._cancelFlick(); } // Ideally this should be removed, but doing so causing some JS errors with fast swiping // because _gesture is being deleted after the previous one has been overwritten // delete sv._gesture; // TODO: Move to sv.prevGesture? }, /** * Setter for 'axis' attribute * * @method _axisSetter * @param val {Mixed} A string ('x', 'y', 'xy') to specify which axis/axes to allow scrolling on * @param name {String} The attribute name * @return {Object} An object to specify scrollability on the x & y axes * * @protected */ _axisSetter: function (val) { // Turn a string into an axis object if (Y.Lang.isString(val)) { return { x: val.match(/x/i) ? true : false, y: val.match(/y/i) ? true : false }; } }, /** * The scrollX, scrollY setter implementation * * @method _setScroll * @private * @param {Number} val * @param {String} dim * * @return {Number} The value */ _setScroll : function(val) { // Just ensure the widget is not disabled if (this._cDisabled) { val = Y.Attribute.INVALID_VALUE; } return val; }, /** * Setter for the scrollX attribute * * @method _setScrollX * @param val {Number} The new scrollX value * @return {Number} The normalized value * @protected */ _setScrollX: function(val) { return this._setScroll(val, DIM_X); }, /** * Setter for the scrollY ATTR * * @method _setScrollY * @param val {Number} The new scrollY value * @return {Number} The normalized value * @protected */ _setScrollY: function(val) { return this._setScroll(val, DIM_Y); } // End prototype properties }, { // Static properties /** * The identity of the widget. * * @property NAME * @type String * @default 'scrollview' * @readOnly * @protected * @static */ NAME: 'scrollview', /** * Static property used to define the default attribute configuration of * the Widget. * * @property ATTRS * @type {Object} * @protected * @static */ ATTRS: { /** * Specifies ability to scroll on x, y, or x and y axis/axes. * * @attribute axis * @type String */ axis: { setter: '_axisSetter', writeOnce: 'initOnly' }, /** * The current scroll position in the x-axis * * @attribute scrollX * @type Number * @default 0 */ scrollX: { value: 0, setter: '_setScrollX' }, /** * The current scroll position in the y-axis * * @attribute scrollY * @type Number * @default 0 */ scrollY: { value: 0, setter: '_setScrollY' }, /** * Drag coefficent for inertial scrolling. The closer to 1 this * value is, the less friction during scrolling. * * @attribute deceleration * @default 0.93 */ deceleration: { value: 0.93 }, /** * Drag coefficient for intertial scrolling at the upper * and lower boundaries of the scrollview. Set to 0 to * disable "rubber-banding". * * @attribute bounce * @type Number * @default 0.1 */ bounce: { value: 0.1 }, /** * The minimum distance and/or velocity which define a flick. Can be set to false, * to disable flick support (note: drag support is enabled/disabled separately) * * @attribute flick * @type Object * @default Object with properties minDistance = 10, minVelocity = 0.3. */ flick: { value: { minDistance: 10, minVelocity: 0.3 } }, /** * Enable/Disable dragging the ScrollView content (note: flick support is enabled/disabled separately) * @attribute drag * @type boolean * @default true */ drag: { value: true }, /** * The default duration to use when animating the bounce snap back. * * @attribute snapDuration * @type Number * @default 400 */ snapDuration: { value: 400 }, /** * The default easing to use when animating the bounce snap back. * * @attribute snapEasing * @type String * @default 'ease-out' */ snapEasing: { value: 'ease-out' }, /** * The default easing used when animating the flick * * @attribute easing * @type String * @default 'cubic-bezier(0, 0.1, 0, 1.0)' */ easing: { value: 'cubic-bezier(0, 0.1, 0, 1.0)' }, /** * The interval (ms) used when animating the flick for JS-timer animations * * @attribute frameDuration * @type Number * @default 15 */ frameDuration: { value: 15 }, /** * The default bounce distance in pixels * * @attribute bounceRange * @type Number * @default 150 */ bounceRange: { value: 150 } }, /** * List of class names used in the scrollview's DOM * * @property CLASS_NAMES * @type Object * @static */ CLASS_NAMES: CLASS_NAMES, /** * Flag used to source property changes initiated from the DOM * * @property UI_SRC * @type String * @static * @default 'ui' */ UI_SRC: UI, /** * Object map of style property names used to set transition properties. * Defaults to the vendor prefix established by the Transition module. * The configured property names are `_TRANSITION.DURATION` (e.g. "WebkitTransitionDuration") and * `_TRANSITION.PROPERTY (e.g. "WebkitTransitionProperty"). * * @property _TRANSITION * @private */ _TRANSITION: { DURATION: (vendorPrefix ? vendorPrefix + 'TransitionDuration' : 'transitionDuration'), PROPERTY: (vendorPrefix ? vendorPrefix + 'TransitionProperty' : 'transitionProperty') }, /** * The default bounce distance in pixels * * @property BOUNCE_RANGE * @type Number * @static * @default false * @deprecated (in 3.7.0) */ BOUNCE_RANGE: false, /** * The interval (ms) used when animating the flick * * @property FRAME_STEP * @type Number * @static * @default false * @deprecated (in 3.7.0) */ FRAME_STEP: false, /** * The default easing used when animating the flick * * @property EASING * @type String * @static * @default false * @deprecated (in 3.7.0) */ EASING: false, /** * The default easing to use when animating the bounce snap back. * * @property SNAP_EASING * @type String * @static * @default false * @deprecated (in 3.7.0) */ SNAP_EASING: false, /** * The default duration to use when animating the bounce snap back. * * @property SNAP_DURATION * @type Number * @static * @default false * @deprecated (in 3.7.0) */ SNAP_DURATION: false // End static properties }); }, '@VERSION@', {"requires": ["widget", "event-gestures", "event-mousewheel", "transition"], "skinnable": true});
app/lib/bootstrap.js
toddmoore/SmartSparrowTest
import React from 'react'; import { Application } from './app.jsx!'; React.render(React.createElement(Application), document.querySelector('body'));
admin/client/App/index.js
naustudio/keystone
/** * This is the main entry file, which we compile the main JS bundle from. It * only contains the client side routing setup. */ // Needed for ES6 generators (redux-saga) to work import 'babel-polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, browserHistory, IndexRoute } from 'react-router'; import { Provider } from 'react-redux'; import { syncHistoryWithStore } from 'react-router-redux'; import App from './App'; import Home from './screens/Home'; import Item from './screens/Item'; import List from './screens/List'; import store from './store'; // Sync the browser history to the Redux store const history = syncHistoryWithStore(browserHistory, store); // Initialise Keystone.User list import { listsByKey } from '../utils/lists'; Keystone.User = listsByKey[Keystone.userList]; ReactDOM.render( <Provider store={store}> <Router history={history}> <Route path={Keystone.adminPath} component={App}> <IndexRoute component={Home} /> <Route path=":listId" component={List} /> <Route path=":listId/:itemId" component={Item} /> </Route> </Router> </Provider>, document.getElementById('react-root') );
src/components/FieldItem.js
puneetbhakar/almabaseReact
import React from 'react' import {SortableElement} from 'react-sortable-hoc'; const FieldItem = SortableElement((props)=>{ let nofields = false console.log('fieldItem') if(props.fieldItem==="No Fields Exist"){ nofields = true } return ( <div className={`fieldItem ${nofields ? 'noFields' : ''}`}> <div className="fieldText" >{props.fieldItem}</div> <i className={`fa fa-times fieldDelete ${nofields ? 'hide' : ''}`} onClick={()=>{props.handleFieldDelete(props.keyValue, props.fieldkey)}}/> </div> ) }) export default (FieldItem)
app/components/Toggle/index.js
gihrig/react-boilerplate
/** * * LocaleToggle * */ import React from 'react'; import Select from './Select'; import ToggleOption from '../ToggleOption'; function Toggle(props) { let content = (<option>--</option>); // If we have items, render them if (props.values) { content = props.values.map((value) => ( <ToggleOption key={value} value={value} message={props.messages[value]} /> )); } return ( <Select value={props.value} onChange={props.onToggle}> {content} </Select> ); } Toggle.propTypes = { onToggle: React.PropTypes.func, values: React.PropTypes.array, value: React.PropTypes.string, messages: React.PropTypes.object, }; export default Toggle;
index.ios.js
ericnograles/gainsville
'use strict'; import React, { AppRegistry } from 'react-native'; import Main from './src/containers/Main/Main'; AppRegistry.registerComponent('gainsville', () => Main);
internals/templates/app.js
7ruth/PadStats2
/** * app.js * * This is the entry file for the application, only setup and boilerplate * code. */ // Needed for redux-saga es6 generator support import 'babel-polyfill'; // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { applyRouterMiddleware, Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import { useScroll } from 'react-router-scroll'; import 'sanitize.css/sanitize.css'; // Import root app import App from 'containers/App'; // Import selector for `syncHistoryWithStore` import { makeSelectLocationState } from 'containers/App/selectors'; // Import Language Provider import LanguageProvider from 'containers/LanguageProvider'; // Load the favicon, the manifest.json file and the .htaccess file /* eslint-disable import/no-unresolved, import/extensions */ import '!file-loader?name=[name].[ext]!./favicon.ico'; import '!file-loader?name=[name].[ext]!./manifest.json'; import 'file-loader?name=[name].[ext]!./.htaccess'; /* eslint-enable import/no-unresolved, import/extensions */ import configureStore from './store'; // Import i18n messages import { translationMessages } from './i18n'; // Import CSS reset and Global Styles import './global-styles'; // Import root routes import createRoutes from './routes'; // Create redux store with history // this uses the singleton browserHistory provided by react-router // Optionally, this could be changed to leverage a created history // e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();` const initialState = {}; const store = configureStore(initialState, browserHistory); // Sync history and store, as the react-router-redux reducer // is under the non-default key ("routing"), selectLocationState // must be provided for resolving how to retrieve the "route" in the state const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: makeSelectLocationState(), }); // Set up the router, wrapping all Routes in the App component const rootRoute = { component: App, childRoutes: createRoutes(store), }; const render = (messages) => { ReactDOM.render( <Provider store={store}> <LanguageProvider messages={messages}> <Router history={history} routes={rootRoute} render={ // Scroll to top when going to a new page, imitating default browser // behaviour applyRouterMiddleware(useScroll()) } /> </LanguageProvider> </Provider>, document.getElementById('app') ); }; // Hot reloadable translation json files if (module.hot) { // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept('./i18n', () => { render(translationMessages); }); } // Chunked polyfill for browsers without Intl support if (!window.Intl) { (new Promise((resolve) => { resolve(import('intl')); })) .then(() => Promise.all([ import('intl/locale-data/jsonp/en.js'), ])) .then(() => render(translationMessages)) .catch((err) => { throw err; }); } else { render(translationMessages); } // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed if (process.env.NODE_ENV === 'production') { require('offline-plugin/runtime').install(); // eslint-disable-line global-require }
src/encoded/static/components/static-pages/placeholders/SlideCarousel.js
hms-dbmi/fourfront
'use strict'; import React from 'react'; import PropTypes from 'prop-types'; import _ from 'underscore'; import Carousel from 'nuka-carousel'; export class SlideCarousel extends React.PureComponent { static defaultProps = { 'fileLocation' : "/static/img/Metadata_structure_slides/", 'carouselProps' : { 'cellSpacing' : 20, 'speed' : 700, 'cellAlign' : 'center', 'slideWidth' : 1, 'slideHeight' : '540px', 'dragging' : false, 'easing' : 'easeLinear', 'transitionMode' : 'fade', 'renderBottomCenterControls' : null } }; render(){ var { fileLocation, carouselProps } = this.props, style = { 'width' : 720, 'height' : 540 }, slides = [ "Slide01.png", "Slide02.png", "Slide03.png", "Slide04.png", "Slide05.png", "Slide06.png", "Slide07.png", "Slide08.png", "Slide09.png", "Slide10.png", "Slide11.png", "Slide12.png", "Slide13.png", "Slide14.png", "Slide15.png", "Slide16.png" ]; return ( <Carousel {...carouselProps}> { _.map(slides, function(filename){ var src = fileLocation + filename; return ( <div className="text-center" key={filename}> <img {...{ src, style }} alt={filename} /> </div> ); }) } </Carousel> ); } }
config/project.config.js
vio-lets/Larkyo-Client
/* eslint key-spacing:0 spaced-comment:0 */ const path = require('path') const debug = require('debug')('app:config:project') const argv = require('yargs').argv const ip = require('ip') debug('Creating default configuration.') // ======================================================== // Default Configuration // ======================================================== const config = { env : process.env.NODE_ENV || 'development', // ---------------------------------- // Project Structure // ---------------------------------- path_base : path.resolve(__dirname, '..'), dir_client : 'src', dir_dist : 'dist', dir_public : 'public', dir_test : 'tests', // ---------------------------------- // Server Configuration // ---------------------------------- server_host : ip.address(), // use string 'localhost' to prevent exposure on local network server_port : process.env.PORT || 3000, // ---------------------------------- // Compiler Configuration // ---------------------------------- compiler_babel : { cacheDirectory : true, plugins : ['transform-runtime'], presets : ['es2015', 'react', 'stage-0'] }, compiler_devtool : 'source-map', compiler_hash_type : 'hash', compiler_fail_on_warning : false, compiler_quiet : false, compiler_public_path : '/', compiler_stats : { chunks : false, chunkModules : false, colors : true }, compiler_vendors : [ 'react', 'react-redux', 'react-router', 'redux' ], // ---------------------------------- // Test Configuration // ---------------------------------- coverage_reporters : [ { type : 'text-summary' }, { type : 'lcov', dir : 'coverage' } ] } /************************************************ ------------------------------------------------- All Internal Configuration Below Edit at Your Own Risk ------------------------------------------------- ************************************************/ // ------------------------------------ // Environment // ------------------------------------ // N.B.: globals added here must _also_ be added to .eslintrc config.globals = { 'process.env' : { 'NODE_ENV' : JSON.stringify(config.env) }, 'NODE_ENV' : config.env, '__DEV__' : config.env === 'development', '__PROD__' : config.env === 'production', '__TEST__' : config.env === 'test', '__COVERAGE__' : !argv.watch && config.env === 'test', '__BASENAME__' : JSON.stringify(process.env.BASENAME || '') } // ------------------------------------ // Validate Vendor Dependencies // ------------------------------------ const pkg = require('../package.json') config.compiler_vendors = config.compiler_vendors .filter((dep) => { if (pkg.dependencies[dep]) return true debug( `Package "${dep}" was not found as an npm dependency in package.json; ` + `it won't be included in the webpack vendor bundle. Consider removing it from \`compiler_vendors\` in ~/config/index.js` ) }) // ------------------------------------ // Utilities // ------------------------------------ function base () { const args = [config.path_base].concat([].slice.call(arguments)) return path.resolve.apply(path, args) } config.paths = { base : base, client : base.bind(null, config.dir_client), public : base.bind(null, config.dir_public), dist : base.bind(null, config.dir_dist) } // ======================================================== // Environment Configuration // ======================================================== debug(`Looking for environment overrides for NODE_ENV "${config.env}".`) const environments = require('./environments.config') const overrides = environments[config.env] if (overrides) { debug('Found overrides, applying to default configuration.') Object.assign(config, overrides(config)) } else { debug('No environment overrides found, defaults will be used.') } module.exports = config
src/components/devices/Form.js
cristianszwarc/react_crud_localStorage
import React from 'react'; import { Component } from 'react'; import { reduxForm, initialize } from 'redux-form'; import validation from './validation'; // scenes is a silly trick to avoid routes, check the file to see it how works import {SceneLink} from '../Scenes'; class DeviceForm extends Component { render() { const { fields: {title, port}, item, itemFetching, handleSubmit, submitting, error } = this.props; if (itemFetching) { return ( <div className="alert alert-warning" role="alert"> Loading... </div> ); } if (!item) { return ( <div className="alert alert-danger" role="alert"> Failed to load </div> ); } return ( <fieldset disabled={this.props.submitting}> <form onSubmit={handleSubmit(this.props.save)}> <div className="form-group"> <label>Title ({item.title})</label> <input className="form-control" type="text" placeholder="Title" {...title}/> {title.touched && title.error && <div className="help-block">{title.error}</div>} </div> <div className="form-group"> <label>Port</label> <input className="form-control" type="text" placeholder="port" {...port}/> {port.touched && port.error && <div className="help-block">{port.error}</div>} </div> {error && <div className="help-block">{error}</div>} <button className="btn btn-default btn-success" type="submit"> Save </button> &nbsp; {/* two white spaces (one because the nbsp and another beacuse this comment) */} <SceneLink className="btn btn-default" param="list" onClick={this.props.navigate}> Cancel </SceneLink> </form> </fieldset> ); } } DeviceForm = reduxForm({ form: 'newDeviceForm', fields: ['title', 'port', '_id'], validate: validation }, state => ({ // mapStateToProps initialValues: state.devices.item // will pull state into form's initialValues }) )(DeviceForm); export default DeviceForm;
blueocean-material-icons/src/js/components/svg-icons/maps/restaurant.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const MapsRestaurant = (props) => ( <SvgIcon {...props}> <path d="M11 9H9V2H7v7H5V2H3v7c0 2.12 1.66 3.84 3.75 3.97V22h2.5v-9.03C11.34 12.84 13 11.12 13 9V2h-2v7zm5-3v8h2.5v8H21V2c-2.76 0-5 2.24-5 4z"/> </SvgIcon> ); MapsRestaurant.displayName = 'MapsRestaurant'; MapsRestaurant.muiName = 'SvgIcon'; export default MapsRestaurant;
src/index.js
karim88/karim88.github.io
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; ReactDOM.hydrate(<App />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: http://bit.ly/CRA-PWA serviceWorker.unregister();
tests/components/Application.spec.js
hack-duke/hackduke-portal
import React from 'react' import Application from 'components/Application' import NavMenu from 'redux/containers/NavMenuContainer' import Participant from 'components/Participant' import Typeform from 'components/Participant' import classes from 'components/Application/Application.scss' import { shallow } from 'enzyme' describe('(Component) Application', () => { let _props, _spies, _wrapper beforeEach(() => { _spies = {} _props = { participant: { 'person': {'first_name': 'George', 'email': 'george.smith@gmail.com'}, 'role': { "event_id": 13, "team_id": null, "status": "accepted", "graduation_year": 2018, "over_eighteen": 1, "attending": null, "major": "Computer Science", "school": "North Carolina State University", "dietary_restrictions": [ "None" ], "website": null, "resume": null, "github": "www.github.com", "travel": null, "portfolio": null, "skills": [], "custom": [ "Q: Why do you want to attend Ideate?", "asdasd", "Q: Tell us about your design experience.", "asdasd" ] } } }, _wrapper = shallow(<Application {..._props} />) }) it('renders a Participant', () => { expect(_wrapper.find(Participant)).to.have.length(1) }) it('renders a Typeform', () => { expect(_wrapper.find(Typeform)).to.have.length(1) }) it('doesn\'t render Participant or Typeform when participant is null', () => { _wrapper.setProps({participant: null}) expect(_wrapper.find(Typeform)).to.have.length(0) expect(_wrapper.find(Participant)).to.have.length(0) }) })
actor-apps/app-web/src/app/components/modals/create-group/ContactItem.react.js
VikingDen/actor-platform
import React from 'react'; import AvatarItem from 'components/common/AvatarItem.react'; class ContactItem extends React.Component { static propTypes = { contact: React.PropTypes.object, onToggle: React.PropTypes.func } constructor(props) { super(props); this.onToggle = this.onToggle.bind(this); this.state = { isSelected: false }; } onToggle() { const isSelected = !this.state.isSelected; this.setState({ isSelected: isSelected }); this.props.onToggle(this.props.contact, isSelected); } render() { let contact = this.props.contact; let icon; if (this.state.isSelected) { icon = 'check_box'; } else { icon = 'check_box_outline_blank'; } return ( <li className="contacts__list__item row"> <AvatarItem image={contact.avatar} placeholder={contact.placeholder} size="small" title={contact.name}/> <div className="col-xs"> <span className="title"> {contact.name} </span> </div> <div className="controls"> <a className="material-icons" onClick={this.onToggle}>{icon}</a> </div> </li> ); } } export default ContactItem;
files/babel/5.8.8/browser-polyfill.js
akkumar/jsdelivr
(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){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; function drainQueue() { if (draining) { return; } draining = true; var currentQueue; var len = queue.length; while(len) { currentQueue = queue; queue = []; var i = -1; while (++i < len) { currentQueue[i](); } len = queue.length; } draining = false; } process.nextTick = function (fun) { queue.push(fun); if (!draining) { setTimeout(drainQueue, 0); } }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.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'); }; process.umask = function() { return 0; }; },{}],2:[function(require,module,exports){ (function (global){ "use strict"; require("core-js/shim"); require("regenerator/runtime"); if (global._babelPolyfill) { throw new Error("only one instance of babel/polyfill is allowed"); } global._babelPolyfill = true; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"core-js/shim":91,"regenerator/runtime":92}],3:[function(require,module,exports){ // false -> Array#indexOf // true -> Array#includes var $ = require('./$'); module.exports = function(IS_INCLUDES){ return function($this, el, fromIndex){ var O = $.toObject($this) , length = $.toLength(O.length) , index = $.toIndex(fromIndex, length) , value; if(IS_INCLUDES && el != el)while(length > index){ value = O[index++]; if(value != value)return true; } else for(;length > index; index++)if(IS_INCLUDES || index in O){ if(O[index] === el)return IS_INCLUDES || index; } return !IS_INCLUDES && -1; }; }; },{"./$":24}],4:[function(require,module,exports){ // 0 -> Array#forEach // 1 -> Array#map // 2 -> Array#filter // 3 -> Array#some // 4 -> Array#every // 5 -> Array#find // 6 -> Array#findIndex var $ = require('./$') , ctx = require('./$.ctx'); module.exports = function(TYPE){ var IS_MAP = TYPE == 1 , IS_FILTER = TYPE == 2 , IS_SOME = TYPE == 3 , IS_EVERY = TYPE == 4 , IS_FIND_INDEX = TYPE == 6 , NO_HOLES = TYPE == 5 || IS_FIND_INDEX; return function($this, callbackfn, that){ var O = Object($.assertDefined($this)) , self = $.ES5Object(O) , f = ctx(callbackfn, that, 3) , length = $.toLength(self.length) , index = 0 , result = IS_MAP ? Array(length) : IS_FILTER ? [] : undefined , val, res; for(;length > index; index++)if(NO_HOLES || index in self){ val = self[index]; res = f(val, index, O); if(TYPE){ if(IS_MAP)result[index] = res; // map else if(res)switch(TYPE){ case 3: return true; // some case 5: return val; // find case 6: return index; // findIndex case 2: result.push(val); // filter } else if(IS_EVERY)return false; // every } } return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; }; }; },{"./$":24,"./$.ctx":12}],5:[function(require,module,exports){ var $ = require('./$'); function assert(condition, msg1, msg2){ if(!condition)throw TypeError(msg2 ? msg1 + msg2 : msg1); } assert.def = $.assertDefined; assert.fn = function(it){ if(!$.isFunction(it))throw TypeError(it + ' is not a function!'); return it; }; assert.obj = function(it){ if(!$.isObject(it))throw TypeError(it + ' is not an object!'); return it; }; assert.inst = function(it, Constructor, name){ if(!(it instanceof Constructor))throw TypeError(name + ": use the 'new' operator!"); return it; }; module.exports = assert; },{"./$":24}],6:[function(require,module,exports){ var $ = require('./$') , enumKeys = require('./$.enum-keys'); // 19.1.2.1 Object.assign(target, source, ...) /* eslint-disable no-unused-vars */ module.exports = Object.assign || function assign(target, source){ /* eslint-enable no-unused-vars */ var T = Object($.assertDefined(target)) , l = arguments.length , i = 1; while(l > i){ var S = $.ES5Object(arguments[i++]) , keys = enumKeys(S) , length = keys.length , j = 0 , key; while(length > j)T[key = keys[j++]] = S[key]; } return T; }; },{"./$":24,"./$.enum-keys":15}],7:[function(require,module,exports){ var $ = require('./$') , TAG = require('./$.wks')('toStringTag') , toString = {}.toString; function cof(it){ return toString.call(it).slice(8, -1); } cof.classof = function(it){ var O, T; return it == undefined ? it === undefined ? 'Undefined' : 'Null' : typeof (T = (O = Object(it))[TAG]) == 'string' ? T : cof(O); }; cof.set = function(it, tag, stat){ if(it && !$.has(it = stat ? it : it.prototype, TAG))$.hide(it, TAG, tag); }; module.exports = cof; },{"./$":24,"./$.wks":42}],8:[function(require,module,exports){ 'use strict'; var $ = require('./$') , ctx = require('./$.ctx') , safe = require('./$.uid').safe , assert = require('./$.assert') , forOf = require('./$.for-of') , step = require('./$.iter').step , $has = $.has , set = $.set , isObject = $.isObject , hide = $.hide , isExtensible = Object.isExtensible || isObject , ID = safe('id') , O1 = safe('O1') , LAST = safe('last') , FIRST = safe('first') , ITER = safe('iter') , SIZE = $.DESC ? safe('size') : 'size' , id = 0; function fastKey(it, create){ // return primitive with prefix if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if(!$has(it, ID)){ // can't set id to frozen object if(!isExtensible(it))return 'F'; // not necessary to add id if(!create)return 'E'; // add missing object id hide(it, ID, ++id); // return object id with prefix } return 'O' + it[ID]; } function getEntry(that, key){ // fast case var index = fastKey(key), entry; if(index !== 'F')return that[O1][index]; // frozen object case for(entry = that[FIRST]; entry; entry = entry.n){ if(entry.k == key)return entry; } } module.exports = { getConstructor: function(wrapper, NAME, IS_MAP, ADDER){ var C = wrapper(function(that, iterable){ assert.inst(that, C, NAME); set(that, O1, $.create(null)); set(that, SIZE, 0); set(that, LAST, undefined); set(that, FIRST, undefined); if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); }); require('./$.mix')(C.prototype, { // 23.1.3.1 Map.prototype.clear() // 23.2.3.2 Set.prototype.clear() clear: function clear(){ for(var that = this, data = that[O1], entry = that[FIRST]; entry; entry = entry.n){ entry.r = true; if(entry.p)entry.p = entry.p.n = undefined; delete data[entry.i]; } that[FIRST] = that[LAST] = undefined; that[SIZE] = 0; }, // 23.1.3.3 Map.prototype.delete(key) // 23.2.3.4 Set.prototype.delete(value) 'delete': function(key){ var that = this , entry = getEntry(that, key); if(entry){ var next = entry.n , prev = entry.p; delete that[O1][entry.i]; entry.r = true; if(prev)prev.n = next; if(next)next.p = prev; if(that[FIRST] == entry)that[FIRST] = next; if(that[LAST] == entry)that[LAST] = prev; that[SIZE]--; } return !!entry; }, // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) forEach: function forEach(callbackfn /*, that = undefined */){ var f = ctx(callbackfn, arguments[1], 3) , entry; while(entry = entry ? entry.n : this[FIRST]){ f(entry.v, entry.k, this); // revert to the last existing entry while(entry && entry.r)entry = entry.p; } }, // 23.1.3.7 Map.prototype.has(key) // 23.2.3.7 Set.prototype.has(value) has: function has(key){ return !!getEntry(this, key); } }); if($.DESC)$.setDesc(C.prototype, 'size', { get: function(){ return assert.def(this[SIZE]); } }); return C; }, def: function(that, key, value){ var entry = getEntry(that, key) , prev, index; // change existing entry if(entry){ entry.v = value; // create new entry } else { that[LAST] = entry = { i: index = fastKey(key, true), // <- index k: key, // <- key v: value, // <- value p: prev = that[LAST], // <- previous entry n: undefined, // <- next entry r: false // <- removed }; if(!that[FIRST])that[FIRST] = entry; if(prev)prev.n = entry; that[SIZE]++; // add to index if(index !== 'F')that[O1][index] = entry; } return that; }, getEntry: getEntry, // add .keys, .values, .entries, [@@iterator] // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 setIter: function(C, NAME, IS_MAP){ require('./$.iter-define')(C, NAME, function(iterated, kind){ set(this, ITER, {o: iterated, k: kind}); }, function(){ var iter = this[ITER] , kind = iter.k , entry = iter.l; // revert to the last existing entry while(entry && entry.r)entry = entry.p; // get next entry if(!iter.o || !(iter.l = entry = entry ? entry.n : iter.o[FIRST])){ // or finish the iteration iter.o = undefined; return step(1); } // return step by kind if(kind == 'keys' )return step(0, entry.k); if(kind == 'values')return step(0, entry.v); return step(0, [entry.k, entry.v]); }, IS_MAP ? 'entries' : 'values' , !IS_MAP, true); } }; },{"./$":24,"./$.assert":5,"./$.ctx":12,"./$.for-of":16,"./$.iter":23,"./$.iter-define":21,"./$.mix":26,"./$.uid":40}],9:[function(require,module,exports){ // https://github.com/DavidBruant/Map-Set.prototype.toJSON var $def = require('./$.def') , forOf = require('./$.for-of'); module.exports = function(NAME){ $def($def.P, NAME, { toJSON: function toJSON(){ var arr = []; forOf(this, false, arr.push, arr); return arr; } }); }; },{"./$.def":13,"./$.for-of":16}],10:[function(require,module,exports){ 'use strict'; var $ = require('./$') , safe = require('./$.uid').safe , assert = require('./$.assert') , forOf = require('./$.for-of') , $has = $.has , isObject = $.isObject , hide = $.hide , isExtensible = Object.isExtensible || isObject , id = 0 , ID = safe('id') , WEAK = safe('weak') , LEAK = safe('leak') , method = require('./$.array-methods') , find = method(5) , findIndex = method(6); function findFrozen(store, key){ return find(store.array, function(it){ return it[0] === key; }); } // fallback for frozen keys function leakStore(that){ return that[LEAK] || hide(that, LEAK, { array: [], get: function(key){ var entry = findFrozen(this, key); if(entry)return entry[1]; }, has: function(key){ return !!findFrozen(this, key); }, set: function(key, value){ var entry = findFrozen(this, key); if(entry)entry[1] = value; else this.array.push([key, value]); }, 'delete': function(key){ var index = findIndex(this.array, function(it){ return it[0] === key; }); if(~index)this.array.splice(index, 1); return !!~index; } })[LEAK]; } module.exports = { getConstructor: function(wrapper, NAME, IS_MAP, ADDER){ var C = wrapper(function(that, iterable){ $.set(assert.inst(that, C, NAME), ID, id++); if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); }); require('./$.mix')(C.prototype, { // 23.3.3.2 WeakMap.prototype.delete(key) // 23.4.3.3 WeakSet.prototype.delete(value) 'delete': function(key){ if(!isObject(key))return false; if(!isExtensible(key))return leakStore(this)['delete'](key); return $has(key, WEAK) && $has(key[WEAK], this[ID]) && delete key[WEAK][this[ID]]; }, // 23.3.3.4 WeakMap.prototype.has(key) // 23.4.3.4 WeakSet.prototype.has(value) has: function has(key){ if(!isObject(key))return false; if(!isExtensible(key))return leakStore(this).has(key); return $has(key, WEAK) && $has(key[WEAK], this[ID]); } }); return C; }, def: function(that, key, value){ if(!isExtensible(assert.obj(key))){ leakStore(that).set(key, value); } else { $has(key, WEAK) || hide(key, WEAK, {}); key[WEAK][that[ID]] = value; } return that; }, leakStore: leakStore, WEAK: WEAK, ID: ID }; },{"./$":24,"./$.array-methods":4,"./$.assert":5,"./$.for-of":16,"./$.mix":26,"./$.uid":40}],11:[function(require,module,exports){ 'use strict'; var $ = require('./$') , $def = require('./$.def') , BUGGY = require('./$.iter').BUGGY , forOf = require('./$.for-of') , species = require('./$.species') , assertInstance = require('./$.assert').inst; module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){ var Base = $.g[NAME] , C = Base , ADDER = IS_MAP ? 'set' : 'add' , proto = C && C.prototype , O = {}; function fixMethod(KEY){ var fn = proto[KEY]; require('./$.redef')(proto, KEY, KEY == 'delete' ? function(a){ return fn.call(this, a === 0 ? 0 : a); } : KEY == 'has' ? function has(a){ return fn.call(this, a === 0 ? 0 : a); } : KEY == 'get' ? function get(a){ return fn.call(this, a === 0 ? 0 : a); } : KEY == 'add' ? function add(a){ fn.call(this, a === 0 ? 0 : a); return this; } : function set(a, b){ fn.call(this, a === 0 ? 0 : a, b); return this; } ); } if(!$.isFunction(C) || !(IS_WEAK || !BUGGY && proto.forEach && proto.entries)){ // create collection constructor C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); require('./$.mix')(C.prototype, methods); } else { var inst = new C , chain = inst[ADDER](IS_WEAK ? {} : -0, 1) , buggyZero; // wrap for init collections from iterable if(!require('./$.iter-detect')(function(iter){ new C(iter); })){ // eslint-disable-line no-new C = wrapper(function(target, iterable){ assertInstance(target, C, NAME); var that = new Base; if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); return that; }); C.prototype = proto; proto.constructor = C; } IS_WEAK || inst.forEach(function(val, key){ buggyZero = 1 / key === -Infinity; }); // fix converting -0 key to +0 if(buggyZero){ fixMethod('delete'); fixMethod('has'); IS_MAP && fixMethod('get'); } // + fix .add & .set for chaining if(buggyZero || chain !== inst)fixMethod(ADDER); } require('./$.cof').set(C, NAME); O[NAME] = C; $def($def.G + $def.W + $def.F * (C != Base), O); species(C); species($.core[NAME]); // for wrapper if(!IS_WEAK)common.setIter(C, NAME, IS_MAP); return C; }; },{"./$":24,"./$.assert":5,"./$.cof":7,"./$.def":13,"./$.for-of":16,"./$.iter":23,"./$.iter-detect":22,"./$.mix":26,"./$.redef":29,"./$.species":34}],12:[function(require,module,exports){ // Optional / simple context binding var assertFunction = require('./$.assert').fn; module.exports = function(fn, that, length){ assertFunction(fn); if(~length && that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); }; case 2: return function(a, b){ return fn.call(that, a, b); }; case 3: return function(a, b, c){ return fn.call(that, a, b, c); }; } return function(/* ...args */){ return fn.apply(that, arguments); }; }; },{"./$.assert":5}],13:[function(require,module,exports){ var $ = require('./$') , global = $.g , core = $.core , isFunction = $.isFunction , $redef = require('./$.redef'); function ctx(fn, that){ return function(){ return fn.apply(that, arguments); }; } global.core = core; // type bitmap $def.F = 1; // forced $def.G = 2; // global $def.S = 4; // static $def.P = 8; // proto $def.B = 16; // bind $def.W = 32; // wrap function $def(type, name, source){ var key, own, out, exp , isGlobal = type & $def.G , isProto = type & $def.P , target = isGlobal ? global : type & $def.S ? global[name] : (global[name] || {}).prototype , exports = isGlobal ? core : core[name] || (core[name] = {}); if(isGlobal)source = name; for(key in source){ // contains in native own = !(type & $def.F) && target && key in target; // export native or passed out = (own ? target : source)[key]; // bind timers to global for call from export context if(type & $def.B && own)exp = ctx(out, global); else exp = isProto && isFunction(out) ? ctx(Function.call, out) : out; // extend global if(target && !own)$redef(target, key, out); // export if(exports[key] != out)$.hide(exports, key, exp); if(isProto)(exports.prototype || (exports.prototype = {}))[key] = out; } } module.exports = $def; },{"./$":24,"./$.redef":29}],14:[function(require,module,exports){ var $ = require('./$') , document = $.g.document , isObject = $.isObject // in old IE typeof document.createElement is 'object' , is = isObject(document) && isObject(document.createElement); module.exports = function(it){ return is ? document.createElement(it) : {}; }; },{"./$":24}],15:[function(require,module,exports){ var $ = require('./$'); module.exports = function(it){ var keys = $.getKeys(it) , getDesc = $.getDesc , getSymbols = $.getSymbols; if(getSymbols)$.each.call(getSymbols(it), function(key){ if(getDesc(it, key).enumerable)keys.push(key); }); return keys; }; },{"./$":24}],16:[function(require,module,exports){ var ctx = require('./$.ctx') , get = require('./$.iter').get , call = require('./$.iter-call'); module.exports = function(iterable, entries, fn, that){ var iterator = get(iterable) , f = ctx(fn, that, entries ? 2 : 1) , step; while(!(step = iterator.next()).done){ if(call(iterator, f, step.value, entries) === false){ return call.close(iterator); } } }; },{"./$.ctx":12,"./$.iter":23,"./$.iter-call":20}],17:[function(require,module,exports){ module.exports = function($){ $.FW = true; $.path = $.g; return $; }; },{}],18:[function(require,module,exports){ // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var $ = require('./$') , toString = {}.toString , getNames = $.getNames; var windowNames = typeof window == 'object' && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : []; function getWindowNames(it){ try { return getNames(it); } catch(e){ return windowNames.slice(); } } module.exports.get = function getOwnPropertyNames(it){ if(windowNames && toString.call(it) == '[object Window]')return getWindowNames(it); return getNames($.toObject(it)); }; },{"./$":24}],19:[function(require,module,exports){ // Fast apply // http://jsperf.lnkit.com/fast-apply/5 module.exports = function(fn, args, that){ var un = that === undefined; switch(args.length){ case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); case 5: return un ? fn(args[0], args[1], args[2], args[3], args[4]) : fn.call(that, args[0], args[1], args[2], args[3], args[4]); } return fn.apply(that, args); }; },{}],20:[function(require,module,exports){ var assertObject = require('./$.assert').obj; function close(iterator){ var ret = iterator['return']; if(ret !== undefined)assertObject(ret.call(iterator)); } function call(iterator, fn, value, entries){ try { return entries ? fn(assertObject(value)[0], value[1]) : fn(value); } catch(e){ close(iterator); throw e; } } call.close = close; module.exports = call; },{"./$.assert":5}],21:[function(require,module,exports){ var $def = require('./$.def') , $redef = require('./$.redef') , $ = require('./$') , cof = require('./$.cof') , $iter = require('./$.iter') , SYMBOL_ITERATOR = require('./$.wks')('iterator') , FF_ITERATOR = '@@iterator' , KEYS = 'keys' , VALUES = 'values' , Iterators = $iter.Iterators; module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCE){ $iter.create(Constructor, NAME, next); function createMethod(kind){ function $$(that){ return new Constructor(that, kind); } switch(kind){ case KEYS: return function keys(){ return $$(this); }; case VALUES: return function values(){ return $$(this); }; } return function entries(){ return $$(this); }; } var TAG = NAME + ' Iterator' , proto = Base.prototype , _native = proto[SYMBOL_ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] , _default = _native || createMethod(DEFAULT) , methods, key; // Fix native if(_native){ var IteratorPrototype = $.getProto(_default.call(new Base)); // Set @@toStringTag to native iterators cof.set(IteratorPrototype, TAG, true); // FF fix if($.FW && $.has(proto, FF_ITERATOR))$iter.set(IteratorPrototype, $.that); } // Define iterator if($.FW || FORCE)$iter.set(proto, _default); // Plug for library Iterators[NAME] = _default; Iterators[TAG] = $.that; if(DEFAULT){ methods = { keys: IS_SET ? _default : createMethod(KEYS), values: DEFAULT == VALUES ? _default : createMethod(VALUES), entries: DEFAULT != VALUES ? _default : createMethod('entries') }; if(FORCE)for(key in methods){ if(!(key in proto))$redef(proto, key, methods[key]); } else $def($def.P + $def.F * $iter.BUGGY, NAME, methods); } }; },{"./$":24,"./$.cof":7,"./$.def":13,"./$.iter":23,"./$.redef":29,"./$.wks":42}],22:[function(require,module,exports){ var SYMBOL_ITERATOR = require('./$.wks')('iterator') , SAFE_CLOSING = false; try { var riter = [7][SYMBOL_ITERATOR](); riter['return'] = function(){ SAFE_CLOSING = true; }; Array.from(riter, function(){ throw 2; }); } catch(e){ /* empty */ } module.exports = function(exec){ if(!SAFE_CLOSING)return false; var safe = false; try { var arr = [7] , iter = arr[SYMBOL_ITERATOR](); iter.next = function(){ safe = true; }; arr[SYMBOL_ITERATOR] = function(){ return iter; }; exec(arr); } catch(e){ /* empty */ } return safe; }; },{"./$.wks":42}],23:[function(require,module,exports){ 'use strict'; var $ = require('./$') , cof = require('./$.cof') , classof = cof.classof , assert = require('./$.assert') , assertObject = assert.obj , SYMBOL_ITERATOR = require('./$.wks')('iterator') , FF_ITERATOR = '@@iterator' , Iterators = require('./$.shared')('iterators') , IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() setIterator(IteratorPrototype, $.that); function setIterator(O, value){ $.hide(O, SYMBOL_ITERATOR, value); // Add iterator for FF iterator protocol if(FF_ITERATOR in [])$.hide(O, FF_ITERATOR, value); } module.exports = { // Safari has buggy iterators w/o `next` BUGGY: 'keys' in [] && !('next' in [].keys()), Iterators: Iterators, step: function(done, value){ return {value: value, done: !!done}; }, is: function(it){ var O = Object(it) , Symbol = $.g.Symbol; return (Symbol && Symbol.iterator || FF_ITERATOR) in O || SYMBOL_ITERATOR in O || $.has(Iterators, classof(O)); }, get: function(it){ var Symbol = $.g.Symbol , getIter; if(it != undefined){ getIter = it[Symbol && Symbol.iterator || FF_ITERATOR] || it[SYMBOL_ITERATOR] || Iterators[classof(it)]; } assert($.isFunction(getIter), it, ' is not iterable!'); return assertObject(getIter.call(it)); }, set: setIterator, create: function(Constructor, NAME, next, proto){ Constructor.prototype = $.create(proto || IteratorPrototype, {next: $.desc(1, next)}); cof.set(Constructor, NAME + ' Iterator'); } }; },{"./$":24,"./$.assert":5,"./$.cof":7,"./$.shared":33,"./$.wks":42}],24:[function(require,module,exports){ 'use strict'; var global = typeof self != 'undefined' ? self : Function('return this')() , core = {} , defineProperty = Object.defineProperty , hasOwnProperty = {}.hasOwnProperty , ceil = Math.ceil , floor = Math.floor , max = Math.max , min = Math.min; // The engine works fine with descriptors? Thank's IE8 for his funny defineProperty. var DESC = !!function(){ try { return defineProperty({}, 'a', {get: function(){ return 2; }}).a == 2; } catch(e){ /* empty */ } }(); var hide = createDefiner(1); // 7.1.4 ToInteger function toInteger(it){ return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); } function desc(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value }; } function simpleSet(object, key, value){ object[key] = value; return object; } function createDefiner(bitmap){ return DESC ? function(object, key, value){ return $.setDesc(object, key, desc(bitmap, value)); } : simpleSet; } function isObject(it){ return it !== null && (typeof it == 'object' || typeof it == 'function'); } function isFunction(it){ return typeof it == 'function'; } function assertDefined(it){ if(it == undefined)throw TypeError("Can't call method on " + it); return it; } var $ = module.exports = require('./$.fw')({ g: global, core: core, html: global.document && document.documentElement, // http://jsperf.com/core-js-isobject isObject: isObject, isFunction: isFunction, that: function(){ return this; }, // 7.1.4 ToInteger toInteger: toInteger, // 7.1.15 ToLength toLength: function(it){ return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }, toIndex: function(index, length){ index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }, has: function(it, key){ return hasOwnProperty.call(it, key); }, create: Object.create, getProto: Object.getPrototypeOf, DESC: DESC, desc: desc, getDesc: Object.getOwnPropertyDescriptor, setDesc: defineProperty, setDescs: Object.defineProperties, getKeys: Object.keys, getNames: Object.getOwnPropertyNames, getSymbols: Object.getOwnPropertySymbols, assertDefined: assertDefined, // Dummy, fix for not array-like ES3 string in es5 module ES5Object: Object, toObject: function(it){ return $.ES5Object(assertDefined(it)); }, hide: hide, def: createDefiner(0), set: global.Symbol ? simpleSet : hide, each: [].forEach }); /* eslint-disable no-undef */ if(typeof __e != 'undefined')__e = core; if(typeof __g != 'undefined')__g = global; },{"./$.fw":17}],25:[function(require,module,exports){ var $ = require('./$'); module.exports = function(object, el){ var O = $.toObject(object) , keys = $.getKeys(O) , length = keys.length , index = 0 , key; while(length > index)if(O[key = keys[index++]] === el)return key; }; },{"./$":24}],26:[function(require,module,exports){ var $redef = require('./$.redef'); module.exports = function(target, src){ for(var key in src)$redef(target, key, src[key]); return target; }; },{"./$.redef":29}],27:[function(require,module,exports){ var $ = require('./$') , assertObject = require('./$.assert').obj; module.exports = function ownKeys(it){ assertObject(it); var keys = $.getNames(it) , getSymbols = $.getSymbols; return getSymbols ? keys.concat(getSymbols(it)) : keys; }; },{"./$":24,"./$.assert":5}],28:[function(require,module,exports){ 'use strict'; var $ = require('./$') , invoke = require('./$.invoke') , assertFunction = require('./$.assert').fn; module.exports = function(/* ...pargs */){ var fn = assertFunction(this) , length = arguments.length , pargs = Array(length) , i = 0 , _ = $.path._ , holder = false; while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true; return function(/* ...args */){ var that = this , _length = arguments.length , j = 0, k = 0, args; if(!holder && !_length)return invoke(fn, pargs, that); args = pargs.slice(); if(holder)for(;length > j; j++)if(args[j] === _)args[j] = arguments[k++]; while(_length > k)args.push(arguments[k++]); return invoke(fn, args, that); }; }; },{"./$":24,"./$.assert":5,"./$.invoke":19}],29:[function(require,module,exports){ var $ = require('./$') , tpl = String({}.hasOwnProperty) , SRC = require('./$.uid').safe('src') , _toString = Function.toString; function $redef(O, key, val, safe){ if($.isFunction(val)){ var base = O[key]; $.hide(val, SRC, base ? String(base) : tpl.replace(/hasOwnProperty/, String(key))); if(!('name' in val))val.name = key; } if(O === $.g){ O[key] = val; } else { if(!safe)delete O[key]; $.hide(O, key, val); } } // add fake Function#toString for correct work wrapped methods / constructors // with methods similar to LoDash isNative $redef(Function.prototype, 'toString', function toString(){ return $.has(this, SRC) ? this[SRC] : _toString.call(this); }); $.core.inspectSource = function(it){ return _toString.call(it); }; module.exports = $redef; },{"./$":24,"./$.uid":40}],30:[function(require,module,exports){ 'use strict'; module.exports = function(regExp, replace, isStatic){ var replacer = replace === Object(replace) ? function(part){ return replace[part]; } : replace; return function(it){ return String(isStatic ? it : this).replace(regExp, replacer); }; }; },{}],31:[function(require,module,exports){ module.exports = Object.is || function is(x, y){ return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; }; },{}],32:[function(require,module,exports){ // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var $ = require('./$') , assert = require('./$.assert'); function check(O, proto){ assert.obj(O); assert(proto === null || $.isObject(proto), proto, ": can't set as prototype!"); } module.exports = { set: Object.setPrototypeOf || ('__proto__' in {} // eslint-disable-line ? function(buggy, set){ try { set = require('./$.ctx')(Function.call, $.getDesc(Object.prototype, '__proto__').set, 2); set({}, []); } catch(e){ buggy = true; } return function setPrototypeOf(O, proto){ check(O, proto); if(buggy)O.__proto__ = proto; else set(O, proto); return O; }; }() : undefined), check: check }; },{"./$":24,"./$.assert":5,"./$.ctx":12}],33:[function(require,module,exports){ var $ = require('./$') , SHARED = '__core-js_shared__' , store = $.g[SHARED] || ($.g[SHARED] = {}); module.exports = function(key){ return store[key] || (store[key] = {}); }; },{"./$":24}],34:[function(require,module,exports){ var $ = require('./$') , SPECIES = require('./$.wks')('species'); module.exports = function(C){ if($.DESC && !(SPECIES in C))$.setDesc(C, SPECIES, { configurable: true, get: $.that }); }; },{"./$":24,"./$.wks":42}],35:[function(require,module,exports){ // true -> String#at // false -> String#codePointAt var $ = require('./$'); module.exports = function(TO_STRING){ return function(that, pos){ var s = String($.assertDefined(that)) , i = $.toInteger(pos) , l = s.length , a, b; if(i < 0 || i >= l)return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; },{"./$":24}],36:[function(require,module,exports){ // http://wiki.ecmascript.org/doku.php?id=strawman:string_padding var $ = require('./$') , repeat = require('./$.string-repeat'); module.exports = function(that, minLength, fillChar, left){ // 1. Let O be CheckObjectCoercible(this value). // 2. Let S be ToString(O). var S = String($.assertDefined(that)); // 4. If intMinLength is undefined, return S. if(minLength === undefined)return S; // 4. Let intMinLength be ToInteger(minLength). var intMinLength = $.toInteger(minLength); // 5. Let fillLen be the number of characters in S minus intMinLength. var fillLen = intMinLength - S.length; // 6. If fillLen < 0, then throw a RangeError exception. // 7. If fillLen is +∞, then throw a RangeError exception. if(fillLen < 0 || fillLen === Infinity){ throw new RangeError('Cannot satisfy string length ' + minLength + ' for string: ' + S); } // 8. Let sFillStr be the string represented by fillStr. // 9. If sFillStr is undefined, let sFillStr be a space character. var sFillStr = fillChar === undefined ? ' ' : String(fillChar); // 10. Let sFillVal be a String made of sFillStr, repeated until fillLen is met. var sFillVal = repeat.call(sFillStr, Math.ceil(fillLen / sFillStr.length)); // truncate if we overflowed if(sFillVal.length > fillLen)sFillVal = left ? sFillVal.slice(sFillVal.length - fillLen) : sFillVal.slice(0, fillLen); // 11. Return a string made from sFillVal, followed by S. // 11. Return a String made from S, followed by sFillVal. return left ? sFillVal.concat(S) : S.concat(sFillVal); }; },{"./$":24,"./$.string-repeat":37}],37:[function(require,module,exports){ 'use strict'; var $ = require('./$'); module.exports = function repeat(count){ var str = String($.assertDefined(this)) , res = '' , n = $.toInteger(count); if(n < 0 || n == Infinity)throw RangeError("Count can't be negative"); for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str; return res; }; },{"./$":24}],38:[function(require,module,exports){ 'use strict'; var $ = require('./$') , ctx = require('./$.ctx') , cof = require('./$.cof') , invoke = require('./$.invoke') , cel = require('./$.dom-create') , global = $.g , isFunction = $.isFunction , html = $.html , process = global.process , setTask = global.setImmediate , clearTask = global.clearImmediate , MessageChannel = global.MessageChannel , counter = 0 , queue = {} , ONREADYSTATECHANGE = 'onreadystatechange' , defer, channel, port; function run(){ var id = +this; if($.has(queue, id)){ var fn = queue[id]; delete queue[id]; fn(); } } function listner(event){ run.call(event.data); } // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if(!isFunction(setTask) || !isFunction(clearTask)){ setTask = function(fn){ var args = [], i = 1; while(arguments.length > i)args.push(arguments[i++]); queue[++counter] = function(){ invoke(isFunction(fn) ? fn : Function(fn), args); }; defer(counter); return counter; }; clearTask = function(id){ delete queue[id]; }; // Node.js 0.8- if(cof(process) == 'process'){ defer = function(id){ process.nextTick(ctx(run, id, 1)); }; // Modern browsers, skip implementation for WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is object } else if(global.addEventListener && isFunction(global.postMessage) && !global.importScripts){ defer = function(id){ global.postMessage(id, '*'); }; global.addEventListener('message', listner, false); // WebWorkers } else if(isFunction(MessageChannel)){ channel = new MessageChannel; port = channel.port2; channel.port1.onmessage = listner; defer = ctx(port.postMessage, port, 1); // IE8- } else if(ONREADYSTATECHANGE in cel('script')){ defer = function(id){ html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){ html.removeChild(this); run.call(id); }; }; // Rest old browsers } else { defer = function(id){ setTimeout(ctx(run, id, 1), 0); }; } } module.exports = { set: setTask, clear: clearTask }; },{"./$":24,"./$.cof":7,"./$.ctx":12,"./$.dom-create":14,"./$.invoke":19}],39:[function(require,module,exports){ module.exports = function(exec){ try { exec(); return false; } catch(e){ return true; } }; },{}],40:[function(require,module,exports){ var sid = 0; function uid(key){ return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++sid + Math.random()).toString(36)); } uid.safe = require('./$').g.Symbol || uid; module.exports = uid; },{"./$":24}],41:[function(require,module,exports){ // 22.1.3.31 Array.prototype[@@unscopables] var UNSCOPABLES = require('./$.wks')('unscopables'); if(!(UNSCOPABLES in []))require('./$').hide(Array.prototype, UNSCOPABLES, {}); module.exports = function(key){ [][UNSCOPABLES][key] = true; }; },{"./$":24,"./$.wks":42}],42:[function(require,module,exports){ var global = require('./$').g , store = require('./$.shared')('wks'); module.exports = function(name){ return store[name] || (store[name] = global.Symbol && global.Symbol[name] || require('./$.uid').safe('Symbol.' + name)); }; },{"./$":24,"./$.shared":33,"./$.uid":40}],43:[function(require,module,exports){ var $ = require('./$') , cel = require('./$.dom-create') , cof = require('./$.cof') , $def = require('./$.def') , invoke = require('./$.invoke') , arrayMethod = require('./$.array-methods') , IE_PROTO = require('./$.uid').safe('__proto__') , assert = require('./$.assert') , assertObject = assert.obj , ObjectProto = Object.prototype , html = $.html , A = [] , _slice = A.slice , _join = A.join , classof = cof.classof , has = $.has , defineProperty = $.setDesc , getOwnDescriptor = $.getDesc , defineProperties = $.setDescs , isFunction = $.isFunction , isObject = $.isObject , toObject = $.toObject , toLength = $.toLength , toIndex = $.toIndex , IE8_DOM_DEFINE = false , $indexOf = require('./$.array-includes')(false) , $forEach = arrayMethod(0) , $map = arrayMethod(1) , $filter = arrayMethod(2) , $some = arrayMethod(3) , $every = arrayMethod(4); if(!$.DESC){ try { IE8_DOM_DEFINE = defineProperty(cel('div'), 'x', {get: function(){ return 8; }} ).x == 8; } catch(e){ /* empty */ } $.setDesc = function(O, P, Attributes){ if(IE8_DOM_DEFINE)try { return defineProperty(O, P, Attributes); } catch(e){ /* empty */ } if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); if('value' in Attributes)assertObject(O)[P] = Attributes.value; return O; }; $.getDesc = function(O, P){ if(IE8_DOM_DEFINE)try { return getOwnDescriptor(O, P); } catch(e){ /* empty */ } if(has(O, P))return $.desc(!ObjectProto.propertyIsEnumerable.call(O, P), O[P]); }; $.setDescs = defineProperties = function(O, Properties){ assertObject(O); var keys = $.getKeys(Properties) , length = keys.length , i = 0 , P; while(length > i)$.setDesc(O, P = keys[i++], Properties[P]); return O; }; } $def($def.S + $def.F * !$.DESC, 'Object', { // 19.1.2.6 / 15.2.3.3 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $.getDesc, // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) defineProperty: $.setDesc, // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) defineProperties: defineProperties }); // IE 8- don't enum bug keys var keys1 = ('constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,' + 'toLocaleString,toString,valueOf').split(',') // Additional keys for getOwnPropertyNames , keys2 = keys1.concat('length', 'prototype') , keysLen1 = keys1.length; // Create object with `null` prototype: use iframe Object with cleared prototype var createDict = function(){ // Thrash, waste and sodomy: IE GC bug var iframe = cel('iframe') , i = keysLen1 , gt = '>' , iframeDocument; iframe.style.display = 'none'; html.appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write('<script>document.F=Object</script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict.prototype[keys1[i]]; return createDict(); }; function createGetKeys(names, length){ return function(object){ var O = toObject(object) , i = 0 , result = [] , key; for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(length > i)if(has(O, key = names[i++])){ ~$indexOf(result, key) || result.push(key); } return result; }; } function Empty(){} $def($def.S, 'Object', { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) getPrototypeOf: $.getProto = $.getProto || function(O){ O = Object(assert.def(O)); if(has(O, IE_PROTO))return O[IE_PROTO]; if(isFunction(O.constructor) && O instanceof O.constructor){ return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }, // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) getOwnPropertyNames: $.getNames = $.getNames || createGetKeys(keys2, keys2.length, true), // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) create: $.create = $.create || function(O, /*?*/Properties){ var result; if(O !== null){ Empty.prototype = assertObject(O); result = new Empty(); Empty.prototype = null; // add "__proto__" for Object.getPrototypeOf shim result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : defineProperties(result, Properties); }, // 19.1.2.14 / 15.2.3.14 Object.keys(O) keys: $.getKeys = $.getKeys || createGetKeys(keys1, keysLen1, false), // 19.1.2.17 / 15.2.3.8 Object.seal(O) seal: function seal(it){ return it; // <- cap }, // 19.1.2.5 / 15.2.3.9 Object.freeze(O) freeze: function freeze(it){ return it; // <- cap }, // 19.1.2.15 / 15.2.3.10 Object.preventExtensions(O) preventExtensions: function preventExtensions(it){ return it; // <- cap }, // 19.1.2.13 / 15.2.3.11 Object.isSealed(O) isSealed: function isSealed(it){ return !isObject(it); // <- cap }, // 19.1.2.12 / 15.2.3.12 Object.isFrozen(O) isFrozen: function isFrozen(it){ return !isObject(it); // <- cap }, // 19.1.2.11 / 15.2.3.13 Object.isExtensible(O) isExtensible: function isExtensible(it){ return isObject(it); // <- cap } }); // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) $def($def.P, 'Function', { bind: function(that /*, args... */){ var fn = assert.fn(this) , partArgs = _slice.call(arguments, 1); function bound(/* args... */){ var args = partArgs.concat(_slice.call(arguments)) , constr = this instanceof bound , ctx = constr ? $.create(fn.prototype) : that , result = invoke(fn, args, ctx); return constr ? ctx : result; } if(fn.prototype)bound.prototype = fn.prototype; return bound; } }); // Fix for not array-like ES3 string and DOM objects if(!(0 in Object('z') && 'z'[0] == 'z')){ $.ES5Object = function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; } var buggySlice = true; try { if(html)_slice.call(html); buggySlice = false; } catch(e){ /* empty */ } $def($def.P + $def.F * buggySlice, 'Array', { slice: function slice(begin, end){ var len = toLength(this.length) , klass = cof(this); end = end === undefined ? len : end; if(klass == 'Array')return _slice.call(this, begin, end); var start = toIndex(begin, len) , upTo = toIndex(end, len) , size = toLength(upTo - start) , cloned = Array(size) , i = 0; for(; i < size; i++)cloned[i] = klass == 'String' ? this.charAt(start + i) : this[start + i]; return cloned; } }); $def($def.P + $def.F * ($.ES5Object != Object), 'Array', { join: function join(){ return _join.apply($.ES5Object(this), arguments); } }); // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) $def($def.S, 'Array', { isArray: function(arg){ return cof(arg) == 'Array'; } }); function createArrayReduce(isRight){ return function(callbackfn, memo){ assert.fn(callbackfn); var O = toObject(this) , length = toLength(O.length) , index = isRight ? length - 1 : 0 , i = isRight ? -1 : 1; if(arguments.length < 2)for(;;){ if(index in O){ memo = O[index]; index += i; break; } index += i; assert(isRight ? index >= 0 : length > index, 'Reduce of empty array with no initial value'); } for(;isRight ? index >= 0 : length > index; index += i)if(index in O){ memo = callbackfn(memo, O[index], index, this); } return memo; }; } $def($def.P, 'Array', { // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) forEach: $.each = $.each || function forEach(callbackfn/*, that = undefined */){ return $forEach(this, callbackfn, arguments[1]); }, // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) map: function map(callbackfn/*, that = undefined */){ return $map(this, callbackfn, arguments[1]); }, // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) filter: function filter(callbackfn/*, that = undefined */){ return $filter(this, callbackfn, arguments[1]); }, // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) some: function some(callbackfn/*, that = undefined */){ return $some(this, callbackfn, arguments[1]); }, // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) every: function every(callbackfn/*, that = undefined */){ return $every(this, callbackfn, arguments[1]); }, // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) reduce: createArrayReduce(false), // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) reduceRight: createArrayReduce(true), // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) indexOf: function indexOf(el /*, fromIndex = 0 */){ return $indexOf(this, el, arguments[1]); }, // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) lastIndexOf: function(el, fromIndex /* = @[*-1] */){ var O = toObject(this) , length = toLength(O.length) , index = length - 1; if(arguments.length > 1)index = Math.min(index, $.toInteger(fromIndex)); if(index < 0)index = toLength(length + index); for(;index >= 0; index--)if(index in O)if(O[index] === el)return index; return -1; } }); // 21.1.3.25 / 15.5.4.20 String.prototype.trim() $def($def.P, 'String', {trim: require('./$.replacer')(/^\s*([\s\S]*\S)?\s*$/, '$1')}); // 20.3.3.1 / 15.9.4.4 Date.now() $def($def.S, 'Date', {now: function(){ return +new Date; }}); function lz(num){ return num > 9 ? num : '0' + num; } // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() // PhantomJS and old webkit had a broken Date implementation. var date = new Date(-5e13 - 1) , brokenDate = !(date.toISOString && date.toISOString() == '0385-07-25T07:06:39.999Z' && require('./$.throws')(function(){ new Date(NaN).toISOString(); })); $def($def.P + $def.F * brokenDate, 'Date', {toISOString: function(){ if(!isFinite(this))throw RangeError('Invalid time value'); var d = this , y = d.getUTCFullYear() , m = d.getUTCMilliseconds() , s = y < 0 ? '-' : y > 9999 ? '+' : ''; return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) + '-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) + 'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) + ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z'; }}); if(classof(function(){ return arguments; }()) == 'Object')cof.classof = function(it){ var tag = classof(it); return tag == 'Object' && isFunction(it.callee) ? 'Arguments' : tag; }; },{"./$":24,"./$.array-includes":3,"./$.array-methods":4,"./$.assert":5,"./$.cof":7,"./$.def":13,"./$.dom-create":14,"./$.invoke":19,"./$.replacer":30,"./$.throws":39,"./$.uid":40}],44:[function(require,module,exports){ 'use strict'; var $ = require('./$') , $def = require('./$.def') , toIndex = $.toIndex; $def($def.P, 'Array', { // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) copyWithin: function copyWithin(target/* = 0 */, start /* = 0, end = @length */){ var O = Object($.assertDefined(this)) , len = $.toLength(O.length) , to = toIndex(target, len) , from = toIndex(start, len) , end = arguments[2] , fin = end === undefined ? len : toIndex(end, len) , count = Math.min(fin - from, len - to) , inc = 1; if(from < to && to < from + count){ inc = -1; from = from + count - 1; to = to + count - 1; } while(count-- > 0){ if(from in O)O[to] = O[from]; else delete O[to]; to += inc; from += inc; } return O; } }); require('./$.unscope')('copyWithin'); },{"./$":24,"./$.def":13,"./$.unscope":41}],45:[function(require,module,exports){ 'use strict'; var $ = require('./$') , $def = require('./$.def') , toIndex = $.toIndex; $def($def.P, 'Array', { // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) fill: function fill(value /*, start = 0, end = @length */){ var O = Object($.assertDefined(this)) , length = $.toLength(O.length) , index = toIndex(arguments[1], length) , end = arguments[2] , endPos = end === undefined ? length : toIndex(end, length); while(endPos > index)O[index++] = value; return O; } }); require('./$.unscope')('fill'); },{"./$":24,"./$.def":13,"./$.unscope":41}],46:[function(require,module,exports){ 'use strict'; // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) var KEY = 'findIndex' , $def = require('./$.def') , forced = true , $find = require('./$.array-methods')(6); // Shouldn't skip holes if(KEY in [])Array(1)[KEY](function(){ forced = false; }); $def($def.P + $def.F * forced, 'Array', { findIndex: function findIndex(callbackfn/*, that = undefined */){ return $find(this, callbackfn, arguments[1]); } }); require('./$.unscope')(KEY); },{"./$.array-methods":4,"./$.def":13,"./$.unscope":41}],47:[function(require,module,exports){ 'use strict'; // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) var KEY = 'find' , $def = require('./$.def') , forced = true , $find = require('./$.array-methods')(5); // Shouldn't skip holes if(KEY in [])Array(1)[KEY](function(){ forced = false; }); $def($def.P + $def.F * forced, 'Array', { find: function find(callbackfn/*, that = undefined */){ return $find(this, callbackfn, arguments[1]); } }); require('./$.unscope')(KEY); },{"./$.array-methods":4,"./$.def":13,"./$.unscope":41}],48:[function(require,module,exports){ var $ = require('./$') , ctx = require('./$.ctx') , $def = require('./$.def') , $iter = require('./$.iter') , call = require('./$.iter-call'); $def($def.S + $def.F * !require('./$.iter-detect')(function(iter){ Array.from(iter); }), 'Array', { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ var O = Object($.assertDefined(arrayLike)) , mapfn = arguments[1] , mapping = mapfn !== undefined , f = mapping ? ctx(mapfn, arguments[2], 2) : undefined , index = 0 , length, result, step, iterator; if($iter.is(O)){ iterator = $iter.get(O); // strange IE quirks mode bug -> use typeof instead of isFunction result = new (typeof this == 'function' ? this : Array); for(; !(step = iterator.next()).done; index++){ result[index] = mapping ? call(iterator, f, [step.value, index], true) : step.value; } } else { // strange IE quirks mode bug -> use typeof instead of isFunction result = new (typeof this == 'function' ? this : Array)(length = $.toLength(O.length)); for(; length > index; index++){ result[index] = mapping ? f(O[index], index) : O[index]; } } result.length = index; return result; } }); },{"./$":24,"./$.ctx":12,"./$.def":13,"./$.iter":23,"./$.iter-call":20,"./$.iter-detect":22}],49:[function(require,module,exports){ var $ = require('./$') , setUnscope = require('./$.unscope') , ITER = require('./$.uid').safe('iter') , $iter = require('./$.iter') , step = $iter.step , Iterators = $iter.Iterators; // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() require('./$.iter-define')(Array, 'Array', function(iterated, kind){ $.set(this, ITER, {o: $.toObject(iterated), i: 0, k: kind}); // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var iter = this[ITER] , O = iter.o , kind = iter.k , index = iter.i++; if(!O || index >= O.length){ iter.o = undefined; return step(1); } if(kind == 'keys' )return step(0, index); if(kind == 'values')return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; setUnscope('keys'); setUnscope('values'); setUnscope('entries'); },{"./$":24,"./$.iter":23,"./$.iter-define":21,"./$.uid":40,"./$.unscope":41}],50:[function(require,module,exports){ var $def = require('./$.def'); $def($def.S, 'Array', { // 22.1.2.3 Array.of( ...items) of: function of(/* ...args */){ var index = 0 , length = arguments.length // strange IE quirks mode bug -> use typeof instead of isFunction , result = new (typeof this == 'function' ? this : Array)(length); while(length > index)result[index] = arguments[index++]; result.length = length; return result; } }); },{"./$.def":13}],51:[function(require,module,exports){ require('./$.species')(Array); },{"./$.species":34}],52:[function(require,module,exports){ var $ = require('./$') , HAS_INSTANCE = require('./$.wks')('hasInstance') , FunctionProto = Function.prototype; // 19.2.3.6 Function.prototype[@@hasInstance](V) if(!(HAS_INSTANCE in FunctionProto))$.setDesc(FunctionProto, HAS_INSTANCE, {value: function(O){ if(!$.isFunction(this) || !$.isObject(O))return false; if(!$.isObject(this.prototype))return O instanceof this; // for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this: while(O = $.getProto(O))if(this.prototype === O)return true; return false; }}); },{"./$":24,"./$.wks":42}],53:[function(require,module,exports){ 'use strict'; var $ = require('./$') , NAME = 'name' , setDesc = $.setDesc , FunctionProto = Function.prototype; // 19.2.4.2 name NAME in FunctionProto || $.FW && $.DESC && setDesc(FunctionProto, NAME, { configurable: true, get: function(){ var match = String(this).match(/^\s*function ([^ (]*)/) , name = match ? match[1] : ''; $.has(this, NAME) || setDesc(this, NAME, $.desc(5, name)); return name; }, set: function(value){ $.has(this, NAME) || setDesc(this, NAME, $.desc(0, value)); } }); },{"./$":24}],54:[function(require,module,exports){ 'use strict'; var strong = require('./$.collection-strong'); // 23.1 Map Objects require('./$.collection')('Map', function(get){ return function Map(){ return get(this, arguments[0]); }; }, { // 23.1.3.6 Map.prototype.get(key) get: function get(key){ var entry = strong.getEntry(this, key); return entry && entry.v; }, // 23.1.3.9 Map.prototype.set(key, value) set: function set(key, value){ return strong.def(this, key === 0 ? 0 : key, value); } }, strong, true); },{"./$.collection":11,"./$.collection-strong":8}],55:[function(require,module,exports){ var Infinity = 1 / 0 , $def = require('./$.def') , E = Math.E , pow = Math.pow , abs = Math.abs , exp = Math.exp , log = Math.log , sqrt = Math.sqrt , ceil = Math.ceil , floor = Math.floor , EPSILON = pow(2, -52) , EPSILON32 = pow(2, -23) , MAX32 = pow(2, 127) * (2 - EPSILON32) , MIN32 = pow(2, -126); function roundTiesToEven(n){ return n + 1 / EPSILON - 1 / EPSILON; } // 20.2.2.28 Math.sign(x) function sign(x){ return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; } // 20.2.2.5 Math.asinh(x) function asinh(x){ return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : log(x + sqrt(x * x + 1)); } // 20.2.2.14 Math.expm1(x) function expm1(x){ return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : exp(x) - 1; } $def($def.S, 'Math', { // 20.2.2.3 Math.acosh(x) acosh: function acosh(x){ return (x = +x) < 1 ? NaN : isFinite(x) ? log(x / E + sqrt(x + 1) * sqrt(x - 1) / E) + 1 : x; }, // 20.2.2.5 Math.asinh(x) asinh: asinh, // 20.2.2.7 Math.atanh(x) atanh: function atanh(x){ return (x = +x) == 0 ? x : log((1 + x) / (1 - x)) / 2; }, // 20.2.2.9 Math.cbrt(x) cbrt: function cbrt(x){ return sign(x = +x) * pow(abs(x), 1 / 3); }, // 20.2.2.11 Math.clz32(x) clz32: function clz32(x){ return (x >>>= 0) ? 31 - floor(log(x + 0.5) * Math.LOG2E) : 32; }, // 20.2.2.12 Math.cosh(x) cosh: function cosh(x){ return (exp(x = +x) + exp(-x)) / 2; }, // 20.2.2.14 Math.expm1(x) expm1: expm1, // 20.2.2.16 Math.fround(x) fround: function fround(x){ var $abs = abs(x) , $sign = sign(x) , a, result; if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32; a = (1 + EPSILON32 / EPSILON) * $abs; result = a - (a - $abs); if(result > MAX32 || result != result)return $sign * Infinity; return $sign * result; }, // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars var sum = 0 , i = 0 , len = arguments.length , larg = 0 , arg, div; while(i < len){ arg = abs(arguments[i++]); if(larg < arg){ div = larg / arg; sum = sum * div * div + 1; larg = arg; } else if(arg > 0){ div = arg / larg; sum += div * div; } else sum += arg; } return larg === Infinity ? Infinity : larg * sqrt(sum); }, // 20.2.2.18 Math.imul(x, y) imul: function imul(x, y){ var UInt16 = 0xffff , xn = +x , yn = +y , xl = UInt16 & xn , yl = UInt16 & yn; return 0 | xl * yl + ((UInt16 & xn >>> 16) * yl + xl * (UInt16 & yn >>> 16) << 16 >>> 0); }, // 20.2.2.20 Math.log1p(x) log1p: function log1p(x){ return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : log(1 + x); }, // 20.2.2.21 Math.log10(x) log10: function log10(x){ return log(x) / Math.LN10; }, // 20.2.2.22 Math.log2(x) log2: function log2(x){ return log(x) / Math.LN2; }, // 20.2.2.28 Math.sign(x) sign: sign, // 20.2.2.30 Math.sinh(x) sinh: function sinh(x){ return abs(x = +x) < 1 ? (expm1(x) - expm1(-x)) / 2 : (exp(x - 1) - exp(-x - 1)) * (E / 2); }, // 20.2.2.33 Math.tanh(x) tanh: function tanh(x){ var a = expm1(x = +x) , b = expm1(-x); return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); }, // 20.2.2.34 Math.trunc(x) trunc: function trunc(it){ return (it > 0 ? floor : ceil)(it); } }); },{"./$.def":13}],56:[function(require,module,exports){ 'use strict'; var $ = require('./$') , isObject = $.isObject , isFunction = $.isFunction , NUMBER = 'Number' , $Number = $.g[NUMBER] , Base = $Number , proto = $Number.prototype; function toPrimitive(it){ var fn, val; if(isFunction(fn = it.valueOf) && !isObject(val = fn.call(it)))return val; if(isFunction(fn = it.toString) && !isObject(val = fn.call(it)))return val; throw TypeError("Can't convert object to number"); } function toNumber(it){ if(isObject(it))it = toPrimitive(it); if(typeof it == 'string' && it.length > 2 && it.charCodeAt(0) == 48){ var binary = false; switch(it.charCodeAt(1)){ case 66 : case 98 : binary = true; case 79 : case 111 : return parseInt(it.slice(2), binary ? 2 : 8); } } return +it; } if($.FW && !($Number('0o1') && $Number('0b1'))){ $Number = function Number(it){ return this instanceof $Number ? new Base(toNumber(it)) : toNumber(it); }; $.each.call($.DESC ? $.getNames(Base) : ( // ES3: 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + // ES6 (in case, if modules with ES6 Number statics required before): 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger' ).split(','), function(key){ if($.has(Base, key) && !$.has($Number, key)){ $.setDesc($Number, key, $.getDesc(Base, key)); } } ); $Number.prototype = proto; proto.constructor = $Number; require('./$.redef')($.g, NUMBER, $Number); } },{"./$":24,"./$.redef":29}],57:[function(require,module,exports){ var $ = require('./$') , $def = require('./$.def') , abs = Math.abs , floor = Math.floor , _isFinite = $.g.isFinite , MAX_SAFE_INTEGER = 0x1fffffffffffff; // pow(2, 53) - 1 == 9007199254740991; function isInteger(it){ return !$.isObject(it) && _isFinite(it) && floor(it) === it; } $def($def.S, 'Number', { // 20.1.2.1 Number.EPSILON EPSILON: Math.pow(2, -52), // 20.1.2.2 Number.isFinite(number) isFinite: function isFinite(it){ return typeof it == 'number' && _isFinite(it); }, // 20.1.2.3 Number.isInteger(number) isInteger: isInteger, // 20.1.2.4 Number.isNaN(number) isNaN: function isNaN(number){ return number != number; }, // 20.1.2.5 Number.isSafeInteger(number) isSafeInteger: function isSafeInteger(number){ return isInteger(number) && abs(number) <= MAX_SAFE_INTEGER; }, // 20.1.2.6 Number.MAX_SAFE_INTEGER MAX_SAFE_INTEGER: MAX_SAFE_INTEGER, // 20.1.2.10 Number.MIN_SAFE_INTEGER MIN_SAFE_INTEGER: -MAX_SAFE_INTEGER, // 20.1.2.12 Number.parseFloat(string) parseFloat: parseFloat, // 20.1.2.13 Number.parseInt(string, radix) parseInt: parseInt }); },{"./$":24,"./$.def":13}],58:[function(require,module,exports){ // 19.1.3.1 Object.assign(target, source) var $def = require('./$.def'); $def($def.S, 'Object', {assign: require('./$.assign')}); },{"./$.assign":6,"./$.def":13}],59:[function(require,module,exports){ // 19.1.3.10 Object.is(value1, value2) var $def = require('./$.def'); $def($def.S, 'Object', { is: require('./$.same') }); },{"./$.def":13,"./$.same":31}],60:[function(require,module,exports){ // 19.1.3.19 Object.setPrototypeOf(O, proto) var $def = require('./$.def'); $def($def.S, 'Object', {setPrototypeOf: require('./$.set-proto').set}); },{"./$.def":13,"./$.set-proto":32}],61:[function(require,module,exports){ var $ = require('./$') , $def = require('./$.def') , isObject = $.isObject , toObject = $.toObject; $.each.call(('freeze,seal,preventExtensions,isFrozen,isSealed,isExtensible,' + 'getOwnPropertyDescriptor,getPrototypeOf,keys,getOwnPropertyNames').split(',') , function(KEY, ID){ var fn = ($.core.Object || {})[KEY] || Object[KEY] , forced = 0 , method = {}; method[KEY] = ID == 0 ? function freeze(it){ return isObject(it) ? fn(it) : it; } : ID == 1 ? function seal(it){ return isObject(it) ? fn(it) : it; } : ID == 2 ? function preventExtensions(it){ return isObject(it) ? fn(it) : it; } : ID == 3 ? function isFrozen(it){ return isObject(it) ? fn(it) : true; } : ID == 4 ? function isSealed(it){ return isObject(it) ? fn(it) : true; } : ID == 5 ? function isExtensible(it){ return isObject(it) ? fn(it) : false; } : ID == 6 ? function getOwnPropertyDescriptor(it, key){ return fn(toObject(it), key); } : ID == 7 ? function getPrototypeOf(it){ return fn(Object($.assertDefined(it))); } : ID == 8 ? function keys(it){ return fn(toObject(it)); } : require('./$.get-names').get; try { fn('z'); } catch(e){ forced = 1; } $def($def.S + $def.F * forced, 'Object', method); }); },{"./$":24,"./$.def":13,"./$.get-names":18}],62:[function(require,module,exports){ 'use strict'; // 19.1.3.6 Object.prototype.toString() var cof = require('./$.cof') , tmp = {}; tmp[require('./$.wks')('toStringTag')] = 'z'; if(require('./$').FW && cof(tmp) != 'z'){ require('./$.redef')(Object.prototype, 'toString', function toString(){ return '[object ' + cof.classof(this) + ']'; }, true); } },{"./$":24,"./$.cof":7,"./$.redef":29,"./$.wks":42}],63:[function(require,module,exports){ 'use strict'; var $ = require('./$') , ctx = require('./$.ctx') , cof = require('./$.cof') , $def = require('./$.def') , assert = require('./$.assert') , forOf = require('./$.for-of') , setProto = require('./$.set-proto').set , same = require('./$.same') , species = require('./$.species') , SPECIES = require('./$.wks')('species') , RECORD = require('./$.uid').safe('record') , PROMISE = 'Promise' , global = $.g , process = global.process , isNode = cof(process) == 'process' , asap = process && process.nextTick || require('./$.task').set , P = global[PROMISE] , isFunction = $.isFunction , isObject = $.isObject , assertFunction = assert.fn , assertObject = assert.obj , Wrapper; function testResolve(sub){ var test = new P(function(){}); if(sub)test.constructor = Object; return P.resolve(test) === test; } var useNative = function(){ var works = false; function P2(x){ var self = new P(x); setProto(self, P2.prototype); return self; } try { works = isFunction(P) && isFunction(P.resolve) && testResolve(); setProto(P2, P); P2.prototype = $.create(P.prototype, {constructor: {value: P2}}); // actual Firefox has broken subclass support, test that if(!(P2.resolve(5).then(function(){}) instanceof P2)){ works = false; } // actual V8 bug, https://code.google.com/p/v8/issues/detail?id=4162 if(works && $.DESC){ var thenableThenGotten = false; P.resolve($.setDesc({}, 'then', { get: function(){ thenableThenGotten = true; } })); works = thenableThenGotten; } } catch(e){ works = false; } return works; }(); // helpers function isPromise(it){ return isObject(it) && (useNative ? cof.classof(it) == 'Promise' : RECORD in it); } function sameConstructor(a, b){ // library wrapper special case if(!$.FW && a === P && b === Wrapper)return true; return same(a, b); } function getConstructor(C){ var S = assertObject(C)[SPECIES]; return S != undefined ? S : C; } function isThenable(it){ var then; if(isObject(it))then = it.then; return isFunction(then) ? then : false; } function notify(record){ var chain = record.c; // strange IE + webpack dev server bug - use .call(global) if(chain.length)asap.call(global, function(){ var value = record.v , ok = record.s == 1 , i = 0; function run(react){ var cb = ok ? react.ok : react.fail , ret, then; try { if(cb){ if(!ok)record.h = true; ret = cb === true ? value : cb(value); if(ret === react.P){ react.rej(TypeError('Promise-chain cycle')); } else if(then = isThenable(ret)){ then.call(ret, react.res, react.rej); } else react.res(ret); } else react.rej(value); } catch(err){ react.rej(err); } } while(chain.length > i)run(chain[i++]); // variable length - can't use forEach chain.length = 0; }); } function isUnhandled(promise){ var record = promise[RECORD] , chain = record.a || record.c , i = 0 , react; if(record.h)return false; while(chain.length > i){ react = chain[i++]; if(react.fail || !isUnhandled(react.P))return false; } return true; } function $reject(value){ var record = this , promise; if(record.d)return; record.d = true; record = record.r || record; // unwrap record.v = value; record.s = 2; record.a = record.c.slice(); setTimeout(function(){ // strange IE + webpack dev server bug - use .call(global) asap.call(global, function(){ if(isUnhandled(promise = record.p)){ if(isNode){ process.emit('unhandledRejection', value, promise); } else if(global.console && console.error){ console.error('Unhandled promise rejection', value); } } record.a = undefined; }); }, 1); notify(record); } function $resolve(value){ var record = this , then; if(record.d)return; record.d = true; record = record.r || record; // unwrap try { if(then = isThenable(value)){ // strange IE + webpack dev server bug - use .call(global) asap.call(global, function(){ var wrapper = {r: record, d: false}; // wrap try { then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } catch(e){ $reject.call(wrapper, e); } }); } else { record.v = value; record.s = 1; notify(record); } } catch(e){ $reject.call({r: record, d: false}, e); // wrap } } // constructor polyfill if(!useNative){ // 25.4.3.1 Promise(executor) P = function Promise(executor){ assertFunction(executor); var record = { p: assert.inst(this, P, PROMISE), // <- promise c: [], // <- awaiting reactions a: undefined, // <- checked in isUnhandled reactions s: 0, // <- state d: false, // <- done v: undefined, // <- value h: false // <- handled rejection }; $.hide(this, RECORD, record); try { executor(ctx($resolve, record, 1), ctx($reject, record, 1)); } catch(err){ $reject.call(record, err); } }; require('./$.mix')(P.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected){ var S = assertObject(assertObject(this).constructor)[SPECIES]; var react = { ok: isFunction(onFulfilled) ? onFulfilled : true, fail: isFunction(onRejected) ? onRejected : false }; var promise = react.P = new (S != undefined ? S : P)(function(res, rej){ react.res = assertFunction(res); react.rej = assertFunction(rej); }); var record = this[RECORD]; record.c.push(react); if(record.a)record.a.push(react); if(record.s)notify(record); return promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function(onRejected){ return this.then(undefined, onRejected); } }); } // export $def($def.G + $def.W + $def.F * !useNative, {Promise: P}); cof.set(P, PROMISE); species(P); species(Wrapper = $.core[PROMISE]); // statics $def($def.S + $def.F * !useNative, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r){ return new (getConstructor(this))(function(res, rej){ rej(r); }); } }); $def($def.S + $def.F * (!useNative || testResolve(true)), PROMISE, { // 25.4.4.6 Promise.resolve(x) resolve: function resolve(x){ return isPromise(x) && sameConstructor(x.constructor, this) ? x : new this(function(res){ res(x); }); } }); $def($def.S + $def.F * !(useNative && require('./$.iter-detect')(function(iter){ P.all(iter)['catch'](function(){}); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable){ var C = getConstructor(this) , values = []; return new C(function(res, rej){ forOf(iterable, false, values.push, values); var remaining = values.length , results = Array(remaining); if(remaining)$.each.call(values, function(promise, index){ C.resolve(promise).then(function(value){ results[index] = value; --remaining || res(results); }, rej); }); else res(results); }); }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable){ var C = getConstructor(this); return new C(function(res, rej){ forOf(iterable, false, function(promise){ C.resolve(promise).then(res, rej); }); }); } }); },{"./$":24,"./$.assert":5,"./$.cof":7,"./$.ctx":12,"./$.def":13,"./$.for-of":16,"./$.iter-detect":22,"./$.mix":26,"./$.same":31,"./$.set-proto":32,"./$.species":34,"./$.task":38,"./$.uid":40,"./$.wks":42}],64:[function(require,module,exports){ var $ = require('./$') , $def = require('./$.def') , setProto = require('./$.set-proto') , $iter = require('./$.iter') , ITERATOR = require('./$.wks')('iterator') , ITER = require('./$.uid').safe('iter') , step = $iter.step , assert = require('./$.assert') , isObject = $.isObject , getProto = $.getProto , $Reflect = $.g.Reflect , _apply = Function.apply , assertObject = assert.obj , _isExtensible = Object.isExtensible || isObject , _preventExtensions = Object.preventExtensions // IE TP has broken Reflect.enumerate , buggyEnumerate = !($Reflect && $Reflect.enumerate && ITERATOR in $Reflect.enumerate({})); function Enumerate(iterated){ $.set(this, ITER, {o: iterated, k: undefined, i: 0}); } $iter.create(Enumerate, 'Object', function(){ var iter = this[ITER] , keys = iter.k , key; if(keys == undefined){ iter.k = keys = []; for(key in iter.o)keys.push(key); } do { if(iter.i >= keys.length)return step(1); } while(!((key = keys[iter.i++]) in iter.o)); return step(0, key); }); var reflect = { // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) apply: function apply(target, thisArgument, argumentsList){ return _apply.call(target, thisArgument, argumentsList); }, // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) construct: function construct(target, argumentsList /*, newTarget*/){ var proto = assert.fn(arguments.length < 3 ? target : arguments[2]).prototype , instance = $.create(isObject(proto) ? proto : Object.prototype) , result = _apply.call(target, instance, argumentsList); return isObject(result) ? result : instance; }, // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) defineProperty: function defineProperty(target, propertyKey, attributes){ assertObject(target); try { $.setDesc(target, propertyKey, attributes); return true; } catch(e){ return false; } }, // 26.1.4 Reflect.deleteProperty(target, propertyKey) deleteProperty: function deleteProperty(target, propertyKey){ var desc = $.getDesc(assertObject(target), propertyKey); return desc && !desc.configurable ? false : delete target[propertyKey]; }, // 26.1.6 Reflect.get(target, propertyKey [, receiver]) get: function get(target, propertyKey/*, receiver*/){ var receiver = arguments.length < 3 ? target : arguments[2] , desc = $.getDesc(assertObject(target), propertyKey), proto; if(desc)return $.has(desc, 'value') ? desc.value : desc.get === undefined ? undefined : desc.get.call(receiver); return isObject(proto = getProto(target)) ? get(proto, propertyKey, receiver) : undefined; }, // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){ return $.getDesc(assertObject(target), propertyKey); }, // 26.1.8 Reflect.getPrototypeOf(target) getPrototypeOf: function getPrototypeOf(target){ return getProto(assertObject(target)); }, // 26.1.9 Reflect.has(target, propertyKey) has: function has(target, propertyKey){ return propertyKey in target; }, // 26.1.10 Reflect.isExtensible(target) isExtensible: function isExtensible(target){ return _isExtensible(assertObject(target)); }, // 26.1.11 Reflect.ownKeys(target) ownKeys: require('./$.own-keys'), // 26.1.12 Reflect.preventExtensions(target) preventExtensions: function preventExtensions(target){ assertObject(target); try { if(_preventExtensions)_preventExtensions(target); return true; } catch(e){ return false; } }, // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) set: function set(target, propertyKey, V/*, receiver*/){ var receiver = arguments.length < 4 ? target : arguments[3] , ownDesc = $.getDesc(assertObject(target), propertyKey) , existingDescriptor, proto; if(!ownDesc){ if(isObject(proto = getProto(target))){ return set(proto, propertyKey, V, receiver); } ownDesc = $.desc(0); } if($.has(ownDesc, 'value')){ if(ownDesc.writable === false || !isObject(receiver))return false; existingDescriptor = $.getDesc(receiver, propertyKey) || $.desc(0); existingDescriptor.value = V; $.setDesc(receiver, propertyKey, existingDescriptor); return true; } return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true); } }; // 26.1.14 Reflect.setPrototypeOf(target, proto) if(setProto)reflect.setPrototypeOf = function setPrototypeOf(target, proto){ setProto.check(target, proto); try { setProto.set(target, proto); return true; } catch(e){ return false; } }; $def($def.G, {Reflect: {}}); $def($def.S + $def.F * buggyEnumerate, 'Reflect', { // 26.1.5 Reflect.enumerate(target) enumerate: function enumerate(target){ return new Enumerate(assertObject(target)); } }); $def($def.S, 'Reflect', reflect); },{"./$":24,"./$.assert":5,"./$.def":13,"./$.iter":23,"./$.own-keys":27,"./$.set-proto":32,"./$.uid":40,"./$.wks":42}],65:[function(require,module,exports){ var $ = require('./$') , cof = require('./$.cof') , $RegExp = $.g.RegExp , Base = $RegExp , proto = $RegExp.prototype , re = /a/g // "new" creates a new object , CORRECT_NEW = new $RegExp(re) !== re // RegExp allows a regex with flags as the pattern , ALLOWS_RE_WITH_FLAGS = function(){ try { return $RegExp(re, 'i') == '/a/i'; } catch(e){ /* empty */ } }(); if($.FW && $.DESC){ if(!CORRECT_NEW || !ALLOWS_RE_WITH_FLAGS){ $RegExp = function RegExp(pattern, flags){ var patternIsRegExp = cof(pattern) == 'RegExp' , flagsIsUndefined = flags === undefined; if(!(this instanceof $RegExp) && patternIsRegExp && flagsIsUndefined)return pattern; return CORRECT_NEW ? new Base(patternIsRegExp && !flagsIsUndefined ? pattern.source : pattern, flags) : new Base(patternIsRegExp ? pattern.source : pattern , patternIsRegExp && flagsIsUndefined ? pattern.flags : flags); }; $.each.call($.getNames(Base), function(key){ key in $RegExp || $.setDesc($RegExp, key, { configurable: true, get: function(){ return Base[key]; }, set: function(it){ Base[key] = it; } }); }); proto.constructor = $RegExp; $RegExp.prototype = proto; require('./$.redef')($.g, 'RegExp', $RegExp); } // 21.2.5.3 get RegExp.prototype.flags() if(/./g.flags != 'g')$.setDesc(proto, 'flags', { configurable: true, get: require('./$.replacer')(/^.*\/(\w*)$/, '$1') }); } require('./$.species')($RegExp); },{"./$":24,"./$.cof":7,"./$.redef":29,"./$.replacer":30,"./$.species":34}],66:[function(require,module,exports){ 'use strict'; var strong = require('./$.collection-strong'); // 23.2 Set Objects require('./$.collection')('Set', function(get){ return function Set(){ return get(this, arguments[0]); }; }, { // 23.2.3.1 Set.prototype.add(value) add: function add(value){ return strong.def(this, value = value === 0 ? 0 : value, value); } }, strong); },{"./$.collection":11,"./$.collection-strong":8}],67:[function(require,module,exports){ 'use strict'; var $def = require('./$.def') , $at = require('./$.string-at')(false); $def($def.P, 'String', { // 21.1.3.3 String.prototype.codePointAt(pos) codePointAt: function codePointAt(pos){ return $at(this, pos); } }); },{"./$.def":13,"./$.string-at":35}],68:[function(require,module,exports){ 'use strict'; var $ = require('./$') , cof = require('./$.cof') , $def = require('./$.def') , toLength = $.toLength; // should throw error on regex $def($def.P + $def.F * !require('./$.throws')(function(){ 'q'.endsWith(/./); }), 'String', { // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) endsWith: function endsWith(searchString /*, endPosition = @length */){ if(cof(searchString) == 'RegExp')throw TypeError(); var that = String($.assertDefined(this)) , endPosition = arguments[1] , len = toLength(that.length) , end = endPosition === undefined ? len : Math.min(toLength(endPosition), len); searchString += ''; return that.slice(end - searchString.length, end) === searchString; } }); },{"./$":24,"./$.cof":7,"./$.def":13,"./$.throws":39}],69:[function(require,module,exports){ var $def = require('./$.def') , toIndex = require('./$').toIndex , fromCharCode = String.fromCharCode , $fromCodePoint = String.fromCodePoint; // length should be 1, old FF problem $def($def.S + $def.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', { // 21.1.2.2 String.fromCodePoint(...codePoints) fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars var res = [] , len = arguments.length , i = 0 , code; while(len > i){ code = +arguments[i++]; if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point'); res.push(code < 0x10000 ? fromCharCode(code) : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) ); } return res.join(''); } }); },{"./$":24,"./$.def":13}],70:[function(require,module,exports){ 'use strict'; var $ = require('./$') , cof = require('./$.cof') , $def = require('./$.def'); $def($def.P, 'String', { // 21.1.3.7 String.prototype.includes(searchString, position = 0) includes: function includes(searchString /*, position = 0 */){ if(cof(searchString) == 'RegExp')throw TypeError(); return !!~String($.assertDefined(this)).indexOf(searchString, arguments[1]); } }); },{"./$":24,"./$.cof":7,"./$.def":13}],71:[function(require,module,exports){ var set = require('./$').set , $at = require('./$.string-at')(true) , ITER = require('./$.uid').safe('iter') , $iter = require('./$.iter') , step = $iter.step; // 21.1.3.27 String.prototype[@@iterator]() require('./$.iter-define')(String, 'String', function(iterated){ set(this, ITER, {o: String(iterated), i: 0}); // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function(){ var iter = this[ITER] , O = iter.o , index = iter.i , point; if(index >= O.length)return step(1); point = $at(O, index); iter.i += point.length; return step(0, point); }); },{"./$":24,"./$.iter":23,"./$.iter-define":21,"./$.string-at":35,"./$.uid":40}],72:[function(require,module,exports){ var $ = require('./$') , $def = require('./$.def'); $def($def.S, 'String', { // 21.1.2.4 String.raw(callSite, ...substitutions) raw: function raw(callSite){ var tpl = $.toObject(callSite.raw) , len = $.toLength(tpl.length) , sln = arguments.length , res = [] , i = 0; while(len > i){ res.push(String(tpl[i++])); if(i < sln)res.push(String(arguments[i])); } return res.join(''); } }); },{"./$":24,"./$.def":13}],73:[function(require,module,exports){ var $def = require('./$.def'); $def($def.P, 'String', { // 21.1.3.13 String.prototype.repeat(count) repeat: require('./$.string-repeat') }); },{"./$.def":13,"./$.string-repeat":37}],74:[function(require,module,exports){ 'use strict'; var $ = require('./$') , cof = require('./$.cof') , $def = require('./$.def'); // should throw error on regex $def($def.P + $def.F * !require('./$.throws')(function(){ 'q'.startsWith(/./); }), 'String', { // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) startsWith: function startsWith(searchString /*, position = 0 */){ if(cof(searchString) == 'RegExp')throw TypeError(); var that = String($.assertDefined(this)) , index = $.toLength(Math.min(arguments[1], that.length)); searchString += ''; return that.slice(index, index + searchString.length) === searchString; } }); },{"./$":24,"./$.cof":7,"./$.def":13,"./$.throws":39}],75:[function(require,module,exports){ 'use strict'; // ECMAScript 6 symbols shim var $ = require('./$') , setTag = require('./$.cof').set , uid = require('./$.uid') , shared = require('./$.shared') , $def = require('./$.def') , $redef = require('./$.redef') , keyOf = require('./$.keyof') , enumKeys = require('./$.enum-keys') , assertObject = require('./$.assert').obj , ObjectProto = Object.prototype , DESC = $.DESC , has = $.has , $create = $.create , getDesc = $.getDesc , setDesc = $.setDesc , desc = $.desc , $names = require('./$.get-names') , getNames = $names.get , toObject = $.toObject , $Symbol = $.g.Symbol , setter = false , TAG = uid('tag') , HIDDEN = uid('hidden') , _propertyIsEnumerable = {}.propertyIsEnumerable , SymbolRegistry = shared('symbol-registry') , AllSymbols = shared('symbols') , useNative = $.isFunction($Symbol); var setSymbolDesc = DESC ? function(){ // fallback for old Android try { return $create(setDesc({}, HIDDEN, { get: function(){ return setDesc(this, HIDDEN, {value: false})[HIDDEN]; } }))[HIDDEN] || setDesc; } catch(e){ return function(it, key, D){ var protoDesc = getDesc(ObjectProto, key); if(protoDesc)delete ObjectProto[key]; setDesc(it, key, D); if(protoDesc && it !== ObjectProto)setDesc(ObjectProto, key, protoDesc); }; } }() : setDesc; function wrap(tag){ var sym = AllSymbols[tag] = $.set($create($Symbol.prototype), TAG, tag); DESC && setter && setSymbolDesc(ObjectProto, tag, { configurable: true, set: function(value){ if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false; setSymbolDesc(this, tag, desc(1, value)); } }); return sym; } function defineProperty(it, key, D){ if(D && has(AllSymbols, key)){ if(!D.enumerable){ if(!has(it, HIDDEN))setDesc(it, HIDDEN, desc(1, {})); it[HIDDEN][key] = true; } else { if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; D = $create(D, {enumerable: desc(0, false)}); } return setSymbolDesc(it, key, D); } return setDesc(it, key, D); } function defineProperties(it, P){ assertObject(it); var keys = enumKeys(P = toObject(P)) , i = 0 , l = keys.length , key; while(l > i)defineProperty(it, key = keys[i++], P[key]); return it; } function create(it, P){ return P === undefined ? $create(it) : defineProperties($create(it), P); } function propertyIsEnumerable(key){ var E = _propertyIsEnumerable.call(this, key); return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; } function getOwnPropertyDescriptor(it, key){ var D = getDesc(it = toObject(it), key); if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; return D; } function getOwnPropertyNames(it){ var names = getNames(toObject(it)) , result = [] , i = 0 , key; while(names.length > i)if(!has(AllSymbols, key = names[i++]) && key != HIDDEN)result.push(key); return result; } function getOwnPropertySymbols(it){ var names = getNames(toObject(it)) , result = [] , i = 0 , key; while(names.length > i)if(has(AllSymbols, key = names[i++]))result.push(AllSymbols[key]); return result; } // 19.4.1.1 Symbol([description]) if(!useNative){ $Symbol = function Symbol(){ if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor'); return wrap(uid(arguments[0])); }; $redef($Symbol.prototype, 'toString', function(){ return this[TAG]; }); $.create = create; $.setDesc = defineProperty; $.getDesc = getOwnPropertyDescriptor; $.setDescs = defineProperties; $.getNames = $names.get = getOwnPropertyNames; $.getSymbols = getOwnPropertySymbols; if($.DESC && $.FW)$redef(ObjectProto, 'propertyIsEnumerable', propertyIsEnumerable, true); } var symbolStatics = { // 19.4.2.1 Symbol.for(key) 'for': function(key){ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = $Symbol(key); }, // 19.4.2.5 Symbol.keyFor(sym) keyFor: function keyFor(key){ return keyOf(SymbolRegistry, key); }, useSetter: function(){ setter = true; }, useSimple: function(){ setter = false; } }; // 19.4.2.2 Symbol.hasInstance // 19.4.2.3 Symbol.isConcatSpreadable // 19.4.2.4 Symbol.iterator // 19.4.2.6 Symbol.match // 19.4.2.8 Symbol.replace // 19.4.2.9 Symbol.search // 19.4.2.10 Symbol.species // 19.4.2.11 Symbol.split // 19.4.2.12 Symbol.toPrimitive // 19.4.2.13 Symbol.toStringTag // 19.4.2.14 Symbol.unscopables $.each.call(( 'hasInstance,isConcatSpreadable,iterator,match,replace,search,' + 'species,split,toPrimitive,toStringTag,unscopables' ).split(','), function(it){ var sym = require('./$.wks')(it); symbolStatics[it] = useNative ? sym : wrap(sym); } ); setter = true; $def($def.G + $def.W, {Symbol: $Symbol}); $def($def.S, 'Symbol', symbolStatics); $def($def.S + $def.F * !useNative, 'Object', { // 19.1.2.2 Object.create(O [, Properties]) create: create, // 19.1.2.4 Object.defineProperty(O, P, Attributes) defineProperty: defineProperty, // 19.1.2.3 Object.defineProperties(O, Properties) defineProperties: defineProperties, // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: getOwnPropertyDescriptor, // 19.1.2.7 Object.getOwnPropertyNames(O) getOwnPropertyNames: getOwnPropertyNames, // 19.1.2.8 Object.getOwnPropertySymbols(O) getOwnPropertySymbols: getOwnPropertySymbols }); // 19.4.3.5 Symbol.prototype[@@toStringTag] setTag($Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] setTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setTag($.g.JSON, 'JSON', true); },{"./$":24,"./$.assert":5,"./$.cof":7,"./$.def":13,"./$.enum-keys":15,"./$.get-names":18,"./$.keyof":25,"./$.redef":29,"./$.shared":33,"./$.uid":40,"./$.wks":42}],76:[function(require,module,exports){ 'use strict'; var $ = require('./$') , weak = require('./$.collection-weak') , leakStore = weak.leakStore , ID = weak.ID , WEAK = weak.WEAK , has = $.has , isObject = $.isObject , isExtensible = Object.isExtensible || isObject , tmp = {}; // 23.3 WeakMap Objects var $WeakMap = require('./$.collection')('WeakMap', function(get){ return function WeakMap(){ return get(this, arguments[0]); }; }, { // 23.3.3.3 WeakMap.prototype.get(key) get: function get(key){ if(isObject(key)){ if(!isExtensible(key))return leakStore(this).get(key); if(has(key, WEAK))return key[WEAK][this[ID]]; } }, // 23.3.3.5 WeakMap.prototype.set(key, value) set: function set(key, value){ return weak.def(this, key, value); } }, weak, true, true); // IE11 WeakMap frozen keys fix if(new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){ $.each.call(['delete', 'has', 'get', 'set'], function(key){ var proto = $WeakMap.prototype , method = proto[key]; require('./$.redef')(proto, key, function(a, b){ // store frozen objects on leaky map if(isObject(a) && !isExtensible(a)){ var result = leakStore(this)[key](a, b); return key == 'set' ? this : result; // store all the rest on native weakmap } return method.call(this, a, b); }); }); } },{"./$":24,"./$.collection":11,"./$.collection-weak":10,"./$.redef":29}],77:[function(require,module,exports){ 'use strict'; var weak = require('./$.collection-weak'); // 23.4 WeakSet Objects require('./$.collection')('WeakSet', function(get){ return function WeakSet(){ return get(this, arguments[0]); }; }, { // 23.4.3.1 WeakSet.prototype.add(value) add: function add(value){ return weak.def(this, value, true); } }, weak, false, true); },{"./$.collection":11,"./$.collection-weak":10}],78:[function(require,module,exports){ 'use strict'; var $def = require('./$.def') , $includes = require('./$.array-includes')(true); $def($def.P, 'Array', { // https://github.com/domenic/Array.prototype.includes includes: function includes(el /*, fromIndex = 0 */){ return $includes(this, el, arguments[1]); } }); require('./$.unscope')('includes'); },{"./$.array-includes":3,"./$.def":13,"./$.unscope":41}],79:[function(require,module,exports){ // https://github.com/DavidBruant/Map-Set.prototype.toJSON require('./$.collection-to-json')('Map'); },{"./$.collection-to-json":9}],80:[function(require,module,exports){ // https://gist.github.com/WebReflection/9353781 var $ = require('./$') , $def = require('./$.def') , ownKeys = require('./$.own-keys'); $def($def.S, 'Object', { getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){ var O = $.toObject(object) , result = {}; $.each.call(ownKeys(O), function(key){ $.setDesc(result, key, $.desc(0, $.getDesc(O, key))); }); return result; } }); },{"./$":24,"./$.def":13,"./$.own-keys":27}],81:[function(require,module,exports){ // http://goo.gl/XkBrjD var $ = require('./$') , $def = require('./$.def'); function createObjectToArray(isEntries){ return function(object){ var O = $.toObject(object) , keys = $.getKeys(O) , length = keys.length , i = 0 , result = Array(length) , key; if(isEntries)while(length > i)result[i] = [key = keys[i++], O[key]]; else while(length > i)result[i] = O[keys[i++]]; return result; }; } $def($def.S, 'Object', { values: createObjectToArray(false), entries: createObjectToArray(true) }); },{"./$":24,"./$.def":13}],82:[function(require,module,exports){ // https://github.com/benjamingr/RexExp.escape var $def = require('./$.def'); $def($def.S, 'RegExp', { escape: require('./$.replacer')(/[\\^$*+?.()|[\]{}]/g, '\\$&', true) }); },{"./$.def":13,"./$.replacer":30}],83:[function(require,module,exports){ // https://github.com/DavidBruant/Map-Set.prototype.toJSON require('./$.collection-to-json')('Set'); },{"./$.collection-to-json":9}],84:[function(require,module,exports){ // https://github.com/mathiasbynens/String.prototype.at 'use strict'; var $def = require('./$.def') , $at = require('./$.string-at')(true); $def($def.P, 'String', { at: function at(pos){ return $at(this, pos); } }); },{"./$.def":13,"./$.string-at":35}],85:[function(require,module,exports){ 'use strict'; var $def = require('./$.def') , $pad = require('./$.string-pad'); $def($def.P, 'String', { lpad: function lpad(n){ return $pad(this, n, arguments[1], true); } }); },{"./$.def":13,"./$.string-pad":36}],86:[function(require,module,exports){ 'use strict'; var $def = require('./$.def') , $pad = require('./$.string-pad'); $def($def.P, 'String', { rpad: function rpad(n){ return $pad(this, n, arguments[1], false); } }); },{"./$.def":13,"./$.string-pad":36}],87:[function(require,module,exports){ // JavaScript 1.6 / Strawman array statics shim var $ = require('./$') , $def = require('./$.def') , $Array = $.core.Array || Array , statics = {}; function setStatics(keys, length){ $.each.call(keys.split(','), function(key){ if(length == undefined && key in $Array)statics[key] = $Array[key]; else if(key in [])statics[key] = require('./$.ctx')(Function.call, [][key], length); }); } setStatics('pop,reverse,shift,keys,values,entries', 1); setStatics('indexOf,every,some,forEach,map,filter,find,findIndex,includes', 3); setStatics('join,slice,concat,push,splice,unshift,sort,lastIndexOf,' + 'reduce,reduceRight,copyWithin,fill,turn'); $def($def.S, 'Array', statics); },{"./$":24,"./$.ctx":12,"./$.def":13}],88:[function(require,module,exports){ require('./es6.array.iterator'); var $ = require('./$') , Iterators = require('./$.iter').Iterators , ITERATOR = require('./$.wks')('iterator') , ArrayValues = Iterators.Array , NL = $.g.NodeList , HTC = $.g.HTMLCollection , NLProto = NL && NL.prototype , HTCProto = HTC && HTC.prototype; if($.FW){ if(NL && !(ITERATOR in NLProto))$.hide(NLProto, ITERATOR, ArrayValues); if(HTC && !(ITERATOR in HTCProto))$.hide(HTCProto, ITERATOR, ArrayValues); } Iterators.NodeList = Iterators.HTMLCollection = ArrayValues; },{"./$":24,"./$.iter":23,"./$.wks":42,"./es6.array.iterator":49}],89:[function(require,module,exports){ var $def = require('./$.def') , $task = require('./$.task'); $def($def.G + $def.B, { setImmediate: $task.set, clearImmediate: $task.clear }); },{"./$.def":13,"./$.task":38}],90:[function(require,module,exports){ // ie9- setTimeout & setInterval additional parameters fix var $ = require('./$') , $def = require('./$.def') , invoke = require('./$.invoke') , partial = require('./$.partial') , navigator = $.g.navigator , MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check function wrap(set){ return MSIE ? function(fn, time /*, ...args */){ return set(invoke( partial, [].slice.call(arguments, 2), $.isFunction(fn) ? fn : Function(fn) ), time); } : set; } $def($def.G + $def.B + $def.F * MSIE, { setTimeout: wrap($.g.setTimeout), setInterval: wrap($.g.setInterval) }); },{"./$":24,"./$.def":13,"./$.invoke":19,"./$.partial":28}],91:[function(require,module,exports){ require('./modules/es5'); require('./modules/es6.symbol'); require('./modules/es6.object.assign'); require('./modules/es6.object.is'); require('./modules/es6.object.set-prototype-of'); require('./modules/es6.object.to-string'); require('./modules/es6.object.statics-accept-primitives'); require('./modules/es6.function.name'); require('./modules/es6.function.has-instance'); require('./modules/es6.number.constructor'); require('./modules/es6.number.statics'); require('./modules/es6.math'); require('./modules/es6.string.from-code-point'); require('./modules/es6.string.raw'); require('./modules/es6.string.iterator'); require('./modules/es6.string.code-point-at'); require('./modules/es6.string.ends-with'); require('./modules/es6.string.includes'); require('./modules/es6.string.repeat'); require('./modules/es6.string.starts-with'); require('./modules/es6.array.from'); require('./modules/es6.array.of'); require('./modules/es6.array.iterator'); require('./modules/es6.array.species'); require('./modules/es6.array.copy-within'); require('./modules/es6.array.fill'); require('./modules/es6.array.find'); require('./modules/es6.array.find-index'); require('./modules/es6.regexp'); require('./modules/es6.promise'); require('./modules/es6.map'); require('./modules/es6.set'); require('./modules/es6.weak-map'); require('./modules/es6.weak-set'); require('./modules/es6.reflect'); require('./modules/es7.array.includes'); require('./modules/es7.string.at'); require('./modules/es7.string.lpad'); require('./modules/es7.string.rpad'); require('./modules/es7.regexp.escape'); require('./modules/es7.object.get-own-property-descriptors'); require('./modules/es7.object.to-array'); require('./modules/es7.map.to-json'); require('./modules/es7.set.to-json'); require('./modules/js.array.statics'); require('./modules/web.timers'); require('./modules/web.immediate'); require('./modules/web.dom.iterable'); module.exports = require('./modules/$').core; },{"./modules/$":24,"./modules/es5":43,"./modules/es6.array.copy-within":44,"./modules/es6.array.fill":45,"./modules/es6.array.find":47,"./modules/es6.array.find-index":46,"./modules/es6.array.from":48,"./modules/es6.array.iterator":49,"./modules/es6.array.of":50,"./modules/es6.array.species":51,"./modules/es6.function.has-instance":52,"./modules/es6.function.name":53,"./modules/es6.map":54,"./modules/es6.math":55,"./modules/es6.number.constructor":56,"./modules/es6.number.statics":57,"./modules/es6.object.assign":58,"./modules/es6.object.is":59,"./modules/es6.object.set-prototype-of":60,"./modules/es6.object.statics-accept-primitives":61,"./modules/es6.object.to-string":62,"./modules/es6.promise":63,"./modules/es6.reflect":64,"./modules/es6.regexp":65,"./modules/es6.set":66,"./modules/es6.string.code-point-at":67,"./modules/es6.string.ends-with":68,"./modules/es6.string.from-code-point":69,"./modules/es6.string.includes":70,"./modules/es6.string.iterator":71,"./modules/es6.string.raw":72,"./modules/es6.string.repeat":73,"./modules/es6.string.starts-with":74,"./modules/es6.symbol":75,"./modules/es6.weak-map":76,"./modules/es6.weak-set":77,"./modules/es7.array.includes":78,"./modules/es7.map.to-json":79,"./modules/es7.object.get-own-property-descriptors":80,"./modules/es7.object.to-array":81,"./modules/es7.regexp.escape":82,"./modules/es7.set.to-json":83,"./modules/es7.string.at":84,"./modules/es7.string.lpad":85,"./modules/es7.string.rpad":86,"./modules/js.array.statics":87,"./modules/web.dom.iterable":88,"./modules/web.immediate":89,"./modules/web.timers":90}],92:[function(require,module,exports){ (function (process,global){ /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * https://raw.github.com/facebook/regenerator/master/LICENSE file. An * additional grant of patent rights can be found in the PATENTS file in * the same directory. */ !(function(global) { "use strict"; var hasOwn = Object.prototype.hasOwnProperty; var undefined; // More compressible than void 0. var iteratorSymbol = typeof Symbol === "function" && Symbol.iterator || "@@iterator"; var inModule = typeof module === "object"; var runtime = global.regeneratorRuntime; if (runtime) { if (inModule) { // If regeneratorRuntime is defined globally and we're in a module, // make the exports object identical to regeneratorRuntime. module.exports = runtime; } // Don't bother evaluating the rest of this file if the runtime was // already defined globally. return; } // Define the runtime globally (as expected by generated code) as either // module.exports (if we're in a module) or a new, empty object. runtime = global.regeneratorRuntime = inModule ? module.exports : {}; function wrap(innerFn, outerFn, self, tryLocsList) { // If outerFn provided, then outerFn.prototype instanceof Generator. var generator = Object.create((outerFn || Generator).prototype); generator._invoke = makeInvokeMethod( innerFn, self || null, new Context(tryLocsList || []) ); return generator; } runtime.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion // record like context.tryEntries[i].completion. This interface could // have been (and was previously) designed to take a closure to be // invoked without arguments, but in all the cases we care about we // already have an existing method we want to call, so there's no need // to create a new function object. We can even get away with assuming // the method takes exactly one argument, since that happens to be true // in every case, so we don't have to touch the arguments object. The // only additional allocation required is the completion record, which // has a stable shape and so hopefully should be cheap to allocate. function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedYield = "suspendedYield"; var GenStateExecuting = "executing"; var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as // breaking out of the dispatch switch statement. var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and // .constructor.prototype properties for functions that return Generator // objects. For full spec compliance, you may wish to configure your // minifier not to mangle the names of these two functions. function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype; GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; GeneratorFunctionPrototype.constructor = GeneratorFunction; GeneratorFunction.displayName = "GeneratorFunction"; // Helper for defining the .next, .throw, and .return methods of the // Iterator interface in terms of a single ._invoke method. function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function(method) { prototype[method] = function(arg) { return this._invoke(method, arg); }; }); } runtime.isGeneratorFunction = function(genFun) { var ctor = typeof genFun === "function" && genFun.constructor; return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can // do is to check its .name property. (ctor.displayName || ctor.name) === "GeneratorFunction" : false; }; runtime.mark = function(genFun) { genFun.__proto__ = GeneratorFunctionPrototype; genFun.prototype = Object.create(Gp); return genFun; }; // Within the body of any async function, `await x` is transformed to // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test // `value instanceof AwaitArgument` to determine if the yielded value is // meant to be awaited. Some may consider the name of this method too // cutesy, but they are curmudgeons. runtime.awrap = function(arg) { return new AwaitArgument(arg); }; function AwaitArgument(arg) { this.arg = arg; } function AsyncIterator(generator) { // This invoke function is written in a style that assumes some // calling function (or Promise) will handle exceptions. function invoke(method, arg) { var result = generator[method](arg); var value = result.value; return value instanceof AwaitArgument ? Promise.resolve(value.arg).then(invokeNext, invokeThrow) : Promise.resolve(value).then(function(unwrapped) { // When a yielded Promise is resolved, its final value becomes // the .value of the Promise<{value,done}> result for the // current iteration. If the Promise is rejected, however, the // result for this iteration will be rejected with the same // reason. Note that rejections of yielded Promises are not // thrown back into the generator function, as is the case // when an awaited Promise is rejected. This difference in // behavior between yield and await is important, because it // allows the consumer to decide what to do with the yielded // rejection (swallow it and continue, manually .throw it back // into the generator, abandon iteration, whatever). With // await, by contrast, there is no opportunity to examine the // rejection reason outside the generator function, so the // only option is to throw it from the await expression, and // let the generator function handle the exception. result.value = unwrapped; return result; }); } if (typeof process === "object" && process.domain) { invoke = process.domain.bind(invoke); } var invokeNext = invoke.bind(generator, "next"); var invokeThrow = invoke.bind(generator, "throw"); var invokeReturn = invoke.bind(generator, "return"); var previousPromise; function enqueue(method, arg) { var enqueueResult = // If enqueue has been called before, then we want to wait until // all previous Promises have been resolved before calling invoke, // so that results are always delivered in the correct order. If // enqueue has not been called before, then it is important to // call invoke immediately, without waiting on a callback to fire, // so that the async generator function has the opportunity to do // any necessary setup in a predictable way. This predictability // is why the Promise constructor synchronously invokes its // executor callback, and why async functions synchronously // execute code before the first await. Since we implement simple // async functions in terms of async generators, it is especially // important to get this right, even though it requires care. previousPromise ? previousPromise.then(function() { return invoke(method, arg); }) : new Promise(function(resolve) { resolve(invoke(method, arg)); }); // Avoid propagating enqueueResult failures to Promises returned by // later invocations of the iterator. previousPromise = enqueueResult["catch"](function(ignored){}); return enqueueResult; } // Define the unified helper method that is used to implement .next, // .throw, and .return (see defineIteratorMethods). this._invoke = enqueue; } defineIteratorMethods(AsyncIterator.prototype); // Note that simple async functions are implemented on top of // AsyncIterator objects; they just return a Promise for the value of // the final result produced by the iterator. runtime.async = function(innerFn, outerFn, self, tryLocsList) { var iter = new AsyncIterator( wrap(innerFn, outerFn, self, tryLocsList) ); return runtime.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. : iter.next().then(function(result) { return result.done ? result.value : iter.next(); }); }; function makeInvokeMethod(innerFn, self, context) { var state = GenStateSuspendedStart; return function invoke(method, arg) { if (state === GenStateExecuting) { throw new Error("Generator is already running"); } if (state === GenStateCompleted) { if (method === "throw") { throw arg; } // Be forgiving, per 25.3.3.3.3 of the spec: // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume return doneResult(); } while (true) { var delegate = context.delegate; if (delegate) { if (method === "return" || (method === "throw" && delegate.iterator[method] === undefined)) { // A return or throw (when the delegate iterator has no throw // method) always terminates the yield* loop. context.delegate = null; // If the delegate iterator has a return method, give it a // chance to clean up. var returnMethod = delegate.iterator["return"]; if (returnMethod) { var record = tryCatch(returnMethod, delegate.iterator, arg); if (record.type === "throw") { // If the return method threw an exception, let that // exception prevail over the original return or throw. method = "throw"; arg = record.arg; continue; } } if (method === "return") { // Continue with the outer return, now that the delegate // iterator has been terminated. continue; } } var record = tryCatch( delegate.iterator[method], delegate.iterator, arg ); if (record.type === "throw") { context.delegate = null; // Like returning generator.throw(uncaught), but without the // overhead of an extra function call. method = "throw"; arg = record.arg; continue; } // Delegate generator ran and handled its own exceptions so // regardless of what the method was, we continue as if it is // "next" with an undefined arg. method = "next"; arg = undefined; var info = record.arg; if (info.done) { context[delegate.resultName] = info.value; context.next = delegate.nextLoc; } else { state = GenStateSuspendedYield; return info; } context.delegate = null; } if (method === "next") { if (state === GenStateSuspendedYield) { context.sent = arg; } else { context.sent = undefined; } } else if (method === "throw") { if (state === GenStateSuspendedStart) { state = GenStateCompleted; throw arg; } if (context.dispatchException(arg)) { // If the dispatched exception was caught by a catch block, // then let that catch block handle the exception normally. method = "next"; arg = undefined; } } else if (method === "return") { context.abrupt("return", arg); } state = GenStateExecuting; var record = tryCatch(innerFn, self, context); if (record.type === "normal") { // If an exception is thrown from innerFn, we leave state === // GenStateExecuting and loop back for another invocation. state = context.done ? GenStateCompleted : GenStateSuspendedYield; var info = { value: record.arg, done: context.done }; if (record.arg === ContinueSentinel) { if (context.delegate && method === "next") { // Deliberately forget the last sent value so that we don't // accidentally pass it on to the delegate. arg = undefined; } } else { return info; } } else if (record.type === "throw") { state = GenStateCompleted; // Dispatch the exception by looping back around to the // context.dispatchException(arg) call above. method = "throw"; arg = record.arg; } } }; } // Define Generator.prototype.{next,throw,return} in terms of the // unified ._invoke helper method. defineIteratorMethods(Gp); Gp[iteratorSymbol] = function() { return this; }; Gp.toString = function() { return "[object Generator]"; }; function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; if (1 in locs) { entry.catchLoc = locs[1]; } if (2 in locs) { entry.finallyLoc = locs[2]; entry.afterLoc = locs[3]; } this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal"; delete record.arg; entry.completion = record; } function Context(tryLocsList) { // The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries = [{ tryLoc: "root" }]; tryLocsList.forEach(pushTryEntry, this); this.reset(true); } runtime.keys = function(object) { var keys = []; for (var key in object) { keys.push(key); } keys.reverse(); // Rather than returning an object with a next method, we keep // things simple and return the next function itself. return function next() { while (keys.length) { var key = keys.pop(); if (key in object) { next.value = key; next.done = false; return next; } } // To avoid creating an additional object, we just hang the .value // and .done properties off the next function object itself. This // also ensures that the minifier will not anonymize the function. next.done = true; return next; }; }; function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) { return iteratorMethod.call(iterable); } if (typeof iterable.next === "function") { return iterable; } if (!isNaN(iterable.length)) { var i = -1, next = function next() { while (++i < iterable.length) { if (hasOwn.call(iterable, i)) { next.value = iterable[i]; next.done = false; return next; } } next.value = undefined; next.done = true; return next; }; return next.next = next; } } // Return an iterator with no values. return { next: doneResult }; } runtime.values = values; function doneResult() { return { value: undefined, done: true }; } Context.prototype = { constructor: Context, reset: function(skipTempReset) { this.prev = 0; this.next = 0; this.sent = undefined; this.done = false; this.delegate = null; this.tryEntries.forEach(resetTryEntry); if (!skipTempReset) { for (var name in this) { // Not sure about the optimal order of these conditions: if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { this[name] = undefined; } } } }, stop: function() { this.done = true; var rootEntry = this.tryEntries[0]; var rootRecord = rootEntry.completion; if (rootRecord.type === "throw") { throw rootRecord.arg; } return this.rval; }, dispatchException: function(exception) { if (this.done) { throw exception; } var context = this; function handle(loc, caught) { record.type = "throw"; record.arg = exception; context.next = loc; return !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; var record = entry.completion; if (entry.tryLoc === "root") { // Exception thrown outside of any try block that could handle // it, so set the completion value of the entire function to // throw the exception. return handle("end"); } if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"); var hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } else if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else if (hasCatch) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } } else if (hasFinally) { if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else { throw new Error("try statement without catch or finally"); } } } }, abrupt: function(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { // Ignore the finally entry if control is not jumping to a // location outside the try/catch block. finallyEntry = null; } var record = finallyEntry ? finallyEntry.completion : {}; record.type = type; record.arg = arg; if (finallyEntry) { this.next = finallyEntry.finallyLoc; } else { this.complete(record); } return ContinueSentinel; }, complete: function(record, afterLoc) { if (record.type === "throw") { throw record.arg; } if (record.type === "break" || record.type === "continue") { this.next = record.arg; } else if (record.type === "return") { this.rval = record.arg; this.next = "end"; } else if (record.type === "normal" && afterLoc) { this.next = afterLoc; } }, finish: function(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) { this.complete(entry.completion, entry.afterLoc); resetTryEntry(entry); return ContinueSentinel; } } }, "catch": function(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (record.type === "throw") { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } // The context.catch method must only be called with a location // argument that corresponds to a known catch block. throw new Error("illegal catch attempt"); }, delegateYield: function(iterable, resultName, nextLoc) { this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }; return ContinueSentinel; } }; })( // Among the various tricks for obtaining a reference to the global // object, this seems to be the most reliable technique that does not // use indirect eval (which violates Content Security Policy). typeof global === "object" ? global : typeof window === "object" ? window : typeof self === "object" ? self : this ); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":1}]},{},[2]);
components/form/RadioGroup.js
resource-watch/resource-watch
import React from 'react'; import PropTypes from 'prop-types'; // Components import FormElement from './FormElement'; class RadioGroup extends FormElement { state = { value: this.props.properties.default } /** * UI EVENTS * - onChange */ triggerChange(e) { // Set state this.setState({ value: e.currentTarget.value }, () => { // Trigger validation this.triggerValidate(); if (this.props.onChange) this.props.onChange(this.state.value); }); } render() { const { name, properties, options } = this.props; const { value } = this.state; return ( <div className={`c-radio-box ${this.props.className}`}> {options.map((item) => ( <div key={`${item.value}`} className="c-radio"> <input {...properties} type="radio" name={name} id={`radio-${name}-${item.value}`} value={item.value} checked={item.value === value} onChange={this.triggerChange} /> <label htmlFor={`radio-${name}-${item.value}`}> <span /> {item.label} </label> </div> ))} </div> ); } } RadioGroup.propTypes = { name: PropTypes.string.isRequired, options: PropTypes.array.isRequired, properties: PropTypes.object.isRequired, className: PropTypes.string, onChange: PropTypes.func, }; export default RadioGroup;
src/molecules/asides/ImageAside/index.js
policygenius/athenaeum
import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import Icon from 'atoms/Icon'; import Text from 'atoms/Text'; import styles from './image-aside.module.scss'; function ImageAside( props ) { const { className, header, image, subheader, basic, compact, centered, dataSrc, maxWidth, icon, simple, small, bold } = props; const classes = [ basic && styles['basic'], centered && styles['centered'], compact && styles['compact'], simple && styles['simple'], small && styles['small'], bold && styles['bold'], className, ]; const renderIconImage = () => { if (!icon && !dataSrc) return null; if (icon) return <Icon icon={icon} className={styles['icon']} />; return ( <div className={styles['image-wrapper']} style={{ maxWidth }}> <img className={styles['image']} src={image} data-src={dataSrc} alt='' /> </div> ); }; const renderSubHeader = () => { if (!subheader) return null; return ( <Text className={styles['subheader']}> { subheader } </Text> ); }; return ( <div className={classnames(...classes)}> { renderIconImage() } <aside className={styles['aside']}> <Text font='a' size={7} > { header } </Text> { renderSubHeader() } </aside> </div> ); } ImageAside.propTypes = { /** * basic variant */ basic: PropTypes.bool, /** * supply any additional class names */ className: PropTypes.string, /** * centered variant */ centered: PropTypes.bool, /** * compact variant */ compact: PropTypes.bool, /** * main header text for aside */ header: PropTypes.string.isRequired, /** * This is the icon name from the [Icon component](/#icon). */ icon: PropTypes.string, /** * simple variant */ simple: PropTypes.bool, /** * small variant */ small: PropTypes.bool, /** * bold variant */ bold: PropTypes.bool, /** * text displayed below the main header */ subheader: PropTypes.string, /** * image to be displayed via `src` tag */ image: PropTypes.string, /** * dataSrc that is passed to the `<img>` */ dataSrc: PropTypes.string, /** * use to set a max-width on the image. * Will be inlined via styles object */ maxWidth: PropTypes.string, }; ImageAside.defaultProps = { basic: true }; export default ImageAside;
packages/material-ui-icons/src/BrokenImageSharp.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M21 3v8.59l-3-3.01-4 4.01-4-4-4 4-3-3.01V3h18zm-3 8.42l3 3.01V21H3v-8.58l3 2.99 4-4 4 4 4-3.99z" /></g></React.Fragment> , 'BrokenImageSharp');
tgui/packages/tgui/interfaces/NtosRobotact.js
XDTM/tgstation
import { classes } from 'common/react'; import { resolveAsset } from '../assets'; import { useBackend, useSharedState } from '../backend'; import { AnimatedNumber, Box, Button, Flex, Fragment, Icon, NoticeBox, Section, Slider, ProgressBar, LabeledList, Table, Tabs } from '../components'; import { NtosWindow } from '../layouts'; export const NtosRobotact = (props, context) => { const { act, data } = useBackend(context); const { PC_device_theme } = data; return ( <NtosWindow width={800} height={600} theme={PC_device_theme}> <NtosWindow.Content> <NtosRobotactContent /> </NtosWindow.Content> </NtosWindow> ); }; export const NtosRobotactContent = (props, context) => { const { act, data } = useBackend(context); const [tab_main, setTab_main] = useSharedState(context, 'tab_main', 1); const [tab_sub, setTab_sub] = useSharedState(context, 'tab_sub', 1); const { charge, maxcharge, integrity, lampIntensity, cover, locomotion, wireModule, wireCamera, wireAI, wireLaw, sensors, printerPictures, printerToner, printerTonerMax, thrustersInstalled, thrustersStatus, } = data; const borgName = data.name || []; const borgType = data.designation || []; const masterAI = data.masterAI || []; const laws = data.Laws || []; const borgLog = data.borgLog || []; const borgUpgrades = data.borgUpgrades || []; return ( <Flex direction={"column"}> <Flex.Item position="relative" mb={1}> <Tabs> <Tabs.Tab icon="list" lineHeight="23px" selected={tab_main === 1} onClick={() => setTab_main(1)}> Status </Tabs.Tab> <Tabs.Tab icon="list" lineHeight="23px" selected={tab_main === 2} onClick={() => setTab_main(2)}> Logs </Tabs.Tab> </Tabs> </Flex.Item> {tab_main === 1 && ( <Fragment> <Flex direction={"row"}> <Flex.Item width="30%"> <Section title="Configuration" fill> <LabeledList> <LabeledList.Item label="Unit"> {borgName.slice(0, 17)} </LabeledList.Item> <LabeledList.Item label="Type"> {borgType} </LabeledList.Item> <LabeledList.Item label="AI"> {masterAI.slice(0, 17)} </LabeledList.Item> </LabeledList> </Section> </Flex.Item> <Flex.Item grow={1} ml={1}> <Section title="Status"> Charge: <Button content="Power Alert" disabled={charge} onClick={() => act('alertPower')} /> <ProgressBar value={charge / maxcharge} ranges={{ good: [0.5, Infinity], average: [0.1, 0.5], bad: [-Infinity, 0.1], }}> <AnimatedNumber value={charge} /> </ProgressBar> Chassis Integrity: <ProgressBar value={integrity} minValue={0} maxValue={100} ranges={{ bad: [-Infinity, 25], average: [25, 75], good: [75, Infinity], }} /> </Section> <Section title="Lamp Power"> <Slider value={lampIntensity} step={1} stepPixelSize={25} maxValue={5} minValue={1} onChange={(e, value) => act('lampIntensity', { ref: value, })} /> Lamp power usage: {lampIntensity/2} watts </Section> </Flex.Item> <Flex.Item width="50%" ml={1}> <Section fitted> <Tabs fluid={1} textAlign="center"> <Tabs.Tab icon="" lineHeight="23px" selected={tab_sub === 1} onClick={() => setTab_sub(1)}> Actions </Tabs.Tab> <Tabs.Tab icon="" lineHeight="23px" selected={tab_sub === 2} onClick={() => setTab_sub(2)}> Upgrades </Tabs.Tab> <Tabs.Tab icon="" lineHeight="23px" selected={tab_sub === 3} onClick={() => setTab_sub(3)}> Diagnostics </Tabs.Tab> </Tabs> </Section> {tab_sub === 1 && ( <Section> <LabeledList> <LabeledList.Item label="Maintenance Cover"> <Button.Confirm content="Unlock" disabled={cover==="UNLOCKED"} onClick={() => act('coverunlock')} /> </LabeledList.Item> <LabeledList.Item label="Sensor Overlay"> <Button content={sensors} onClick={() => act('toggleSensors')} /> </LabeledList.Item> <LabeledList.Item label={"Stored Photos (" + printerPictures + ")"}> <Button content="View" disabled={!printerPictures} onClick={() => act('viewImage')} /> <Button content="Print" disabled={!printerPictures} onClick={() => act('printImage')} /> </LabeledList.Item> <LabeledList.Item label="Printer Toner"> <ProgressBar value={printerToner / printerTonerMax} /> </LabeledList.Item> {!!thrustersInstalled && ( <LabeledList.Item label="Toggle Thrusters"> <Button content={thrustersStatus} onClick={() => act('toggleThrusters')} /> </LabeledList.Item> )} </LabeledList> </Section> )} {tab_sub === 2 && ( <Section> {borgUpgrades.map(upgrade => ( <Box mb={1} key={upgrade}> {upgrade} </Box> ))} </Section> )} {tab_sub === 3 && ( <Section> <LabeledList> <LabeledList.Item label="AI Connection" color={wireAI==="FAULT"?'red': wireAI==="READY"?'yellow': 'green'}> {wireAI} </LabeledList.Item> <LabeledList.Item label="LawSync" color={wireLaw==="FAULT"?"red":"green"}> {wireLaw} </LabeledList.Item> <LabeledList.Item label="Camera" color={wireCamera==="FAULT"?'red': wireCamera==="DISABLED"?'yellow': 'green'}> {wireCamera} </LabeledList.Item> <LabeledList.Item label="Module Controller" color={wireModule==="FAULT"?"red":"green"}> {wireModule} </LabeledList.Item> <LabeledList.Item label="Motor Controller" color={locomotion==="FAULT"?'red': locomotion==="DISABLED"?'yellow': 'green'}> {locomotion} </LabeledList.Item> <LabeledList.Item label="Maintenance Cover" color={cover==="UNLOCKED"?"red":"green"}> {cover} </LabeledList.Item> </LabeledList> </Section> )} </Flex.Item> </Flex> <Flex.Item height={21} mt={1}> <Section title="Laws" fill scrollable buttons={( <Fragment> <Button content="State Laws" onClick={() => act('lawstate')} /> <Button icon="volume-off" onClick={() => act('lawchannel')} /> </Fragment> )}> {laws.map(law => ( <Box mb={1} key={law}> {law} </Box> ))} </Section> </Flex.Item> </Fragment> )} {tab_main === 2 && ( <Flex.Item> <Section backgroundColor="black" height={40}> <NtosWindow.Content scrollable> {borgLog.map(log => ( <Box mb={1} key={log}> <font color="green">{log}</font> </Box> ))} </NtosWindow.Content> </Section> </Flex.Item> )} </Flex> ); };
wp-content/themes/Walleto_backk/js_ba/jquery-1.5.1.min.js
mssnaveensharma/fourchillies
/*! * jQuery JavaScript Library v1.5.1 * http://jquery.com/ * * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Wed Feb 23 13:55:29 2011 -0500 */ (function(a,b){function cg(a){return d.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cd(a){if(!bZ[a]){var b=d("<"+a+">").appendTo("body"),c=b.css("display");b.remove();if(c==="none"||c==="")c="block";bZ[a]=c}return bZ[a]}function cc(a,b){var c={};d.each(cb.concat.apply([],cb.slice(0,b)),function(){c[this]=a});return c}function bY(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function bX(){try{return new a.XMLHttpRequest}catch(b){}}function bW(){d(a).unload(function(){for(var a in bU)bU[a](0,1)})}function bQ(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var e=a.dataTypes,f={},g,h,i=e.length,j,k=e[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h==="string"&&(f[h.toLowerCase()]=a.converters[h]);l=k,k=e[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=f[m]||f["* "+k];if(!n){p=b;for(o in f){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=f[j[1]+" "+k];if(p){o=f[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&d.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function bP(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function bO(a,b,c,e){if(d.isArray(b)&&b.length)d.each(b,function(b,f){c||bq.test(a)?e(a,f):bO(a+"["+(typeof f==="object"||d.isArray(f)?b:"")+"]",f,c,e)});else if(c||b==null||typeof b!=="object")e(a,b);else if(d.isArray(b)||d.isEmptyObject(b))e(a,"");else for(var f in b)bO(a+"["+f+"]",b[f],c,e)}function bN(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bH,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l==="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=bN(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bN(a,c,d,e,"*",g));return l}function bM(a){return function(b,c){typeof b!=="string"&&(c=b,b="*");if(d.isFunction(c)){var e=b.toLowerCase().split(bB),f=0,g=e.length,h,i,j;for(;f<g;f++)h=e[f],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bo(a,b,c){var e=b==="width"?bi:bj,f=b==="width"?a.offsetWidth:a.offsetHeight;if(c==="border")return f;d.each(e,function(){c||(f-=parseFloat(d.css(a,"padding"+this))||0),c==="margin"?f+=parseFloat(d.css(a,"margin"+this))||0:f-=parseFloat(d.css(a,"border"+this+"Width"))||0});return f}function ba(a,b){b.src?d.ajax({url:b.src,async:!1,dataType:"script"}):d.globalEval(b.text||b.textContent||b.innerHTML||""),b.parentNode&&b.parentNode.removeChild(b)}function _(a){return"getElementsByTagName"in a?a.getElementsByTagName("*"):"querySelectorAll"in a?a.querySelectorAll("*"):[]}function $(a,b){if(b.nodeType===1){var c=b.nodeName.toLowerCase();b.clearAttributes(),b.mergeAttributes(a);if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(d.expando)}}function Z(a,b){if(b.nodeType===1&&d.hasData(a)){var c=d.expando,e=d.data(a),f=d.data(b,e);if(e=e[c]){var g=e.events;f=f[c]=d.extend({},e);if(g){delete f.handle,f.events={};for(var h in g)for(var i=0,j=g[h].length;i<j;i++)d.event.add(b,h+(g[h][i].namespace?".":"")+g[h][i].namespace,g[h][i],g[h][i].data)}}}}function Y(a,b){return d.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function O(a,b,c){if(d.isFunction(b))return d.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return d.grep(a,function(a,d){return a===b===c});if(typeof b==="string"){var e=d.grep(a,function(a){return a.nodeType===1});if(J.test(b))return d.filter(b,e,!c);b=d.filter(b,e)}return d.grep(a,function(a,e){return d.inArray(a,b)>=0===c})}function N(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function F(a,b){return(a&&a!=="*"?a+".":"")+b.replace(r,"`").replace(s,"&")}function E(a){var b,c,e,f,g,h,i,j,k,l,m,n,o,q=[],r=[],s=d._data(this,"events");if(a.liveFired!==this&&s&&s.live&&!a.target.disabled&&(!a.button||a.type!=="click")){a.namespace&&(n=new RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)")),a.liveFired=this;var t=s.live.slice(0);for(i=0;i<t.length;i++)g=t[i],g.origType.replace(p,"")===a.type?r.push(g.selector):t.splice(i--,1);f=d(a.target).closest(r,a.currentTarget);for(j=0,k=f.length;j<k;j++){m=f[j];for(i=0;i<t.length;i++){g=t[i];if(m.selector===g.selector&&(!n||n.test(g.namespace))&&!m.elem.disabled){h=m.elem,e=null;if(g.preType==="mouseenter"||g.preType==="mouseleave")a.type=g.preType,e=d(a.relatedTarget).closest(g.selector)[0];(!e||e!==h)&&q.push({elem:h,handleObj:g,level:m.level})}}}for(j=0,k=q.length;j<k;j++){f=q[j];if(c&&f.level>c)break;a.currentTarget=f.elem,a.data=f.handleObj.data,a.handleObj=f.handleObj,o=f.handleObj.origHandler.apply(f.elem,arguments);if(o===!1||a.isPropagationStopped()){c=f.level,o===!1&&(b=!1);if(a.isImmediatePropagationStopped())break}}return b}}function C(a,c,e){var f=d.extend({},e[0]);f.type=a,f.originalEvent={},f.liveFired=b,d.event.handle.call(c,f),f.isDefaultPrevented()&&e[0].preventDefault()}function w(){return!0}function v(){return!1}function g(a){for(var b in a)if(b!=="toJSON")return!1;return!0}function f(a,c,f){if(f===b&&a.nodeType===1){f=a.getAttribute("data-"+c);if(typeof f==="string"){try{f=f==="true"?!0:f==="false"?!1:f==="null"?null:d.isNaN(f)?e.test(f)?d.parseJSON(f):f:parseFloat(f)}catch(g){}d.data(a,c,f)}else f=b}return f}var c=a.document,d=function(){function I(){if(!d.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(I,1);return}d.ready()}}var d=function(a,b){return new d.fn.init(a,b,g)},e=a.jQuery,f=a.$,g,h=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,i=/\S/,j=/^\s+/,k=/\s+$/,l=/\d/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=navigator.userAgent,w,x=!1,y,z="then done fail isResolved isRejected promise".split(" "),A,B=Object.prototype.toString,C=Object.prototype.hasOwnProperty,D=Array.prototype.push,E=Array.prototype.slice,F=String.prototype.trim,G=Array.prototype.indexOf,H={};d.fn=d.prototype={constructor:d,init:function(a,e,f){var g,i,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!e&&c.body){this.context=c,this[0]=c.body,this.selector="body",this.length=1;return this}if(typeof a==="string"){g=h.exec(a);if(!g||!g[1]&&e)return!e||e.jquery?(e||f).find(a):this.constructor(e).find(a);if(g[1]){e=e instanceof d?e[0]:e,k=e?e.ownerDocument||e:c,j=m.exec(a),j?d.isPlainObject(e)?(a=[c.createElement(j[1])],d.fn.attr.call(a,e,!0)):a=[k.createElement(j[1])]:(j=d.buildFragment([g[1]],[k]),a=(j.cacheable?d.clone(j.fragment):j.fragment).childNodes);return d.merge(this,a)}i=c.getElementById(g[2]);if(i&&i.parentNode){if(i.id!==g[2])return f.find(a);this.length=1,this[0]=i}this.context=c,this.selector=a;return this}if(d.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return d.makeArray(a,this)},selector:"",jquery:"1.5.1",length:0,size:function(){return this.length},toArray:function(){return E.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var e=this.constructor();d.isArray(a)?D.apply(e,a):d.merge(e,a),e.prevObject=this,e.context=this.context,b==="find"?e.selector=this.selector+(this.selector?" ":"")+c:b&&(e.selector=this.selector+"."+b+"("+c+")");return e},each:function(a,b){return d.each(this,a,b)},ready:function(a){d.bindReady(),y.done(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(E.apply(this,arguments),"slice",E.call(arguments).join(","))},map:function(a){return this.pushStack(d.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:D,sort:[].sort,splice:[].splice},d.fn.init.prototype=d.fn,d.extend=d.fn.extend=function(){var a,c,e,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i==="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!=="object"&&!d.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){e=i[c],f=a[c];if(i===f)continue;l&&f&&(d.isPlainObject(f)||(g=d.isArray(f)))?(g?(g=!1,h=e&&d.isArray(e)?e:[]):h=e&&d.isPlainObject(e)?e:{},i[c]=d.extend(l,h,f)):f!==b&&(i[c]=f)}return i},d.extend({noConflict:function(b){a.$=f,b&&(a.jQuery=e);return d},isReady:!1,readyWait:1,ready:function(a){a===!0&&d.readyWait--;if(!d.readyWait||a!==!0&&!d.isReady){if(!c.body)return setTimeout(d.ready,1);d.isReady=!0;if(a!==!0&&--d.readyWait>0)return;y.resolveWith(c,[d]),d.fn.trigger&&d(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!x){x=!0;if(c.readyState==="complete")return setTimeout(d.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",A,!1),a.addEventListener("load",d.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",A),a.attachEvent("onload",d.ready);var b=!1;try{b=a.frameElement==null}catch(e){}c.documentElement.doScroll&&b&&I()}}},isFunction:function(a){return d.type(a)==="function"},isArray:Array.isArray||function(a){return d.type(a)==="array"},isWindow:function(a){return a&&typeof a==="object"&&"setInterval"in a},isNaN:function(a){return a==null||!l.test(a)||isNaN(a)},type:function(a){return a==null?String(a):H[B.call(a)]||"object"},isPlainObject:function(a){if(!a||d.type(a)!=="object"||a.nodeType||d.isWindow(a))return!1;if(a.constructor&&!C.call(a,"constructor")&&!C.call(a.constructor.prototype,"isPrototypeOf"))return!1;var c;for(c in a){}return c===b||C.call(a,c)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw a},parseJSON:function(b){if(typeof b!=="string"||!b)return null;b=d.trim(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return a.JSON&&a.JSON.parse?a.JSON.parse(b):(new Function("return "+b))();d.error("Invalid JSON: "+b)},parseXML:function(b,c,e){a.DOMParser?(e=new DOMParser,c=e.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b)),e=c.documentElement,(!e||!e.nodeName||e.nodeName==="parsererror")&&d.error("Invalid XML: "+b);return c},noop:function(){},globalEval:function(a){if(a&&i.test(a)){var b=c.head||c.getElementsByTagName("head")[0]||c.documentElement,e=c.createElement("script");d.support.scriptEval()?e.appendChild(c.createTextNode(a)):e.text=a,b.insertBefore(e,b.firstChild),b.removeChild(e)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,e){var f,g=0,h=a.length,i=h===b||d.isFunction(a);if(e){if(i){for(f in a)if(c.apply(a[f],e)===!1)break}else for(;g<h;)if(c.apply(a[g++],e)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(var j=a[0];g<h&&c.call(j,g,j)!==!1;j=a[++g]){}return a},trim:F?function(a){return a==null?"":F.call(a)}:function(a){return a==null?"":(a+"").replace(j,"").replace(k,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var e=d.type(a);a.length==null||e==="string"||e==="function"||e==="regexp"||d.isWindow(a)?D.call(c,a):d.merge(c,a)}return c},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var c=0,d=b.length;c<d;c++)if(b[c]===a)return c;return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length==="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,b,c){var d=[],e;for(var f=0,g=a.length;f<g;f++)e=b(a[f],f,c),e!=null&&(d[d.length]=e);return d.concat.apply([],d)},guid:1,proxy:function(a,c,e){arguments.length===2&&(typeof c==="string"?(e=a,a=e[c],c=b):c&&!d.isFunction(c)&&(e=c,c=b)),!c&&a&&(c=function(){return a.apply(e||this,arguments)}),a&&(c.guid=a.guid=a.guid||c.guid||d.guid++);return c},access:function(a,c,e,f,g,h){var i=a.length;if(typeof c==="object"){for(var j in c)d.access(a,j,c[j],f,g,e);return a}if(e!==b){f=!h&&f&&d.isFunction(e);for(var k=0;k<i;k++)g(a[k],c,f?e.call(a[k],k,g(a[k],c)):e,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getcurrent_time('timestamp',0)},_Deferred:function(){var a=[],b,c,e,f={done:function(){if(!e){var c=arguments,g,h,i,j,k;b&&(k=b,b=0);for(g=0,h=c.length;g<h;g++)i=c[g],j=d.type(i),j==="array"?f.done.apply(f,i):j==="function"&&a.push(i);k&&f.resolveWith(k[0],k[1])}return this},resolveWith:function(d,f){if(!e&&!b&&!c){c=1;try{while(a[0])a.shift().apply(d,f)}catch(g){throw g}finally{b=[d,f],c=0}}return this},resolve:function(){f.resolveWith(d.isFunction(this.promise)?this.promise():this,arguments);return this},isResolved:function(){return c||b},cancel:function(){e=1,a=[];return this}};return f},Deferred:function(a){var b=d._Deferred(),c=d._Deferred(),e;d.extend(b,{then:function(a,c){b.done(a).fail(c);return this},fail:c.done,rejectWith:c.resolveWith,reject:c.resolve,isRejected:c.isResolved,promise:function(a){if(a==null){if(e)return e;e=a={}}var c=z.length;while(c--)a[z[c]]=b[z[c]];return a}}),b.done(c.cancel).fail(b.cancel),delete b.cancel,a&&a.call(b,b);return b},when:function(a){var b=arguments.length,c=b<=1&&a&&d.isFunction(a.promise)?a:d.Deferred(),e=c.promise();if(b>1){var f=E.call(arguments,0),g=b,h=function(a){return function(b){f[a]=arguments.length>1?E.call(arguments,0):b,--g||c.resolveWith(e,f)}};while(b--)a=f[b],a&&d.isFunction(a.promise)?a.promise().then(h(b),c.reject):--g;g||c.resolveWith(e,f)}else c!==a&&c.resolve(a);return e},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}d.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.subclass=this.subclass,a.fn.init=function b(b,c){c&&c instanceof d&&!(c instanceof a)&&(c=a(c));return d.fn.init.call(this,b,c,e)},a.fn.init.prototype=a.fn;var e=a(c);return a},browser:{}}),y=d._Deferred(),d.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){H["[object "+b+"]"]=b.toLowerCase()}),w=d.uaMatch(v),w.browser&&(d.browser[w.browser]=!0,d.browser.version=w.version),d.browser.webkit&&(d.browser.safari=!0),G&&(d.inArray=function(a,b){return G.call(b,a)}),i.test(" ")&&(j=/^[\s\xA0]+/,k=/[\s\xA0]+$/),g=d(c),c.addEventListener?A=function(){c.removeEventListener("DOMContentLoaded",A,!1),d.ready()}:c.attachEvent&&(A=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",A),d.ready())});return d}();(function(){d.support={};var b=c.createElement("div");b.style.display="none",b.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var e=b.getElementsByTagName("*"),f=b.getElementsByTagName("a")[0],g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=b.getElementsByTagName("input")[0];if(e&&e.length&&f){d.support={leadingWhitespace:b.firstChild.nodeType===3,tbody:!b.getElementsByTagName("tbody").length,htmlSerialize:!!b.getElementsByTagName("link").length,style:/red/.test(f.getAttribute("style")),hrefNormalized:f.getAttribute("href")==="/a",opacity:/^0.55$/.test(f.style.opacity),cssFloat:!!f.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,deleteExpando:!0,optDisabled:!1,checkClone:!1,noCloneEvent:!0,noCloneChecked:!0,boxModel:null,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableHiddenOffsets:!0},i.checked=!0,d.support.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,d.support.optDisabled=!h.disabled;var j=null;d.support.scriptEval=function(){if(j===null){var b=c.documentElement,e=c.createElement("script"),f="script"+d.now();try{e.appendChild(c.createTextNode("window."+f+"=1;"))}catch(g){}b.insertBefore(e,b.firstChild),a[f]?(j=!0,delete a[f]):j=!1,b.removeChild(e),b=e=f=null}return j};try{delete b.test}catch(k){d.support.deleteExpando=!1}!b.addEventListener&&b.attachEvent&&b.fireEvent&&(b.attachEvent("onclick",function l(){d.support.noCloneEvent=!1,b.detachEvent("onclick",l)}),b.cloneNode(!0).fireEvent("onclick")),b=c.createElement("div"),b.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";var m=c.createDocumentFragment();m.appendChild(b.firstChild),d.support.checkClone=m.cloneNode(!0).cloneNode(!0).lastChild.checked,d(function(){var a=c.createElement("div"),b=c.getElementsByTagName("body")[0];if(b){a.style.width=a.style.paddingLeft="1px",b.appendChild(a),d.boxModel=d.support.boxModel=a.offsetWidth===2,"zoom"in a.style&&(a.style.display="inline",a.style.zoom=1,d.support.inlineBlockNeedsLayout=a.offsetWidth===2,a.style.display="",a.innerHTML="<div style='width:4px;'></div>",d.support.shrinkWrapBlocks=a.offsetWidth!==2),a.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";var e=a.getElementsByTagName("td");d.support.reliableHiddenOffsets=e[0].offsetHeight===0,e[0].style.display="",e[1].style.display="none",d.support.reliableHiddenOffsets=d.support.reliableHiddenOffsets&&e[0].offsetHeight===0,a.innerHTML="",b.removeChild(a).style.display="none",a=e=null}});var n=function(a){var b=c.createElement("div");a="on"+a;if(!b.attachEvent)return!0;var d=a in b;d||(b.setAttribute(a,"return;"),d=typeof b[a]==="function"),b=null;return d};d.support.submitBubbles=n("submit"),d.support.changeBubbles=n("change"),b=e=f=null}})();var e=/^(?:\{.*\}|\[.*\])$/;d.extend({cache:{},uuid:0,expando:"jQuery"+(d.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?d.cache[a[d.expando]]:a[d.expando];return!!a&&!g(a)},data:function(a,c,e,f){if(d.acceptData(a)){var g=d.expando,h=typeof c==="string",i,j=a.nodeType,k=j?d.cache:a,l=j?a[d.expando]:a[d.expando]&&d.expando;if((!l||f&&l&&!k[l][g])&&h&&e===b)return;l||(j?a[d.expando]=l=++d.uuid:l=d.expando),k[l]||(k[l]={},j||(k[l].toJSON=d.noop));if(typeof c==="object"||typeof c==="function")f?k[l][g]=d.extend(k[l][g],c):k[l]=d.extend(k[l],c);i=k[l],f&&(i[g]||(i[g]={}),i=i[g]),e!==b&&(i[c]=e);if(c==="events"&&!i[c])return i[g]&&i[g].events;return h?i[c]:i}},removeData:function(b,c,e){if(d.acceptData(b)){var f=d.expando,h=b.nodeType,i=h?d.cache:b,j=h?b[d.expando]:d.expando;if(!i[j])return;if(c){var k=e?i[j][f]:i[j];if(k){delete k[c];if(!g(k))return}}if(e){delete i[j][f];if(!g(i[j]))return}var l=i[j][f];d.support.deleteExpando||i!=a?delete i[j]:i[j]=null,l?(i[j]={},h||(i[j].toJSON=d.noop),i[j][f]=l):h&&(d.support.deleteExpando?delete b[d.expando]:b.removeAttribute?b.removeAttribute(d.expando):b[d.expando]=null)}},_data:function(a,b,c){return d.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=d.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),d.fn.extend({data:function(a,c){var e=null;if(typeof a==="undefined"){if(this.length){e=d.data(this[0]);if(this[0].nodeType===1){var g=this[0].attributes,h;for(var i=0,j=g.length;i<j;i++)h=g[i].name,h.indexOf("data-")===0&&(h=h.substr(5),f(this[0],h,e[h]))}}return e}if(typeof a==="object")return this.each(function(){d.data(this,a)});var k=a.split(".");k[1]=k[1]?"."+k[1]:"";if(c===b){e=this.triggerHandler("getData"+k[1]+"!",[k[0]]),e===b&&this.length&&(e=d.data(this[0],a),e=f(this[0],a,e));return e===b&&k[1]?this.data(k[0]):e}return this.each(function(){var b=d(this),e=[k[0],c];b.triggerHandler("setData"+k[1]+"!",e),d.data(this,a,c),b.triggerHandler("changeData"+k[1]+"!",e)})},removeData:function(a){return this.each(function(){d.removeData(this,a)})}}),d.extend({queue:function(a,b,c){if(a){b=(b||"fx")+"queue";var e=d._data(a,b);if(!c)return e||[];!e||d.isArray(c)?e=d._data(a,b,d.makeArray(c)):e.push(c);return e}},dequeue:function(a,b){b=b||"fx";var c=d.queue(a,b),e=c.shift();e==="inprogress"&&(e=c.shift()),e&&(b==="fx"&&c.unshift("inprogress"),e.call(a,function(){d.dequeue(a,b)})),c.length||d.removeData(a,b+"queue",!0)}}),d.fn.extend({queue:function(a,c){typeof a!=="string"&&(c=a,a="fx");if(c===b)return d.queue(this[0],a);return this.each(function(b){var e=d.queue(this,a,c);a==="fx"&&e[0]!=="inprogress"&&d.dequeue(this,a)})},dequeue:function(a){return this.each(function(){d.dequeue(this,a)})},delay:function(a,b){a=d.fx?d.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(){var c=this;setTimeout(function(){d.dequeue(c,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var h=/[\n\t\r]/g,i=/\s+/,j=/\r/g,k=/^(?:href|src|style)$/,l=/^(?:button|input)$/i,m=/^(?:button|input|object|select|textarea)$/i,n=/^a(?:rea)?$/i,o=/^(?:radio|checkbox)$/i;d.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"},d.fn.extend({attr:function(a,b){return d.access(this,a,b,!0,d.attr)},removeAttr:function(a,b){return this.each(function(){d.attr(this,a,""),this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.addClass(a.call(this,b,c.attr("class")))});if(a&&typeof a==="string"){var b=(a||"").split(i);for(var c=0,e=this.length;c<e;c++){var f=this[c];if(f.nodeType===1)if(f.className){var g=" "+f.className+" ",h=f.className;for(var j=0,k=b.length;j<k;j++)g.indexOf(" "+b[j]+" ")<0&&(h+=" "+b[j]);f.className=d.trim(h)}else f.className=a}}return this},removeClass:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.removeClass(a.call(this,b,c.attr("class")))});if(a&&typeof a==="string"||a===b){var c=(a||"").split(i);for(var e=0,f=this.length;e<f;e++){var g=this[e];if(g.nodeType===1&&g.className)if(a){var j=(" "+g.className+" ").replace(h," ");for(var k=0,l=c.length;k<l;k++)j=j.replace(" "+c[k]+" "," ");g.className=d.trim(j)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,e=typeof b==="boolean";if(d.isFunction(a))return this.each(function(c){var e=d(this);e.toggleClass(a.call(this,c,e.attr("class"),b),b)});return this.each(function(){if(c==="string"){var f,g=0,h=d(this),j=b,k=a.split(i);while(f=k[g++])j=e?j:!h.hasClass(f),h[j?"addClass":"removeClass"](f)}else if(c==="undefined"||c==="boolean")this.className&&d._data(this,"__className__",this.className),this.className=this.className||a===!1?"":d._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ";for(var c=0,d=this.length;c<d;c++)if((" "+this[c].className+" ").replace(h," ").indexOf(b)>-1)return!0;return!1},val:function(a){if(!arguments.length){var c=this[0];if(c){if(d.nodeName(c,"option")){var e=c.attributes.value;return!e||e.specified?c.value:c.text}if(d.nodeName(c,"select")){var f=c.selectedIndex,g=[],h=c.options,i=c.type==="select-one";if(f<0)return null;for(var k=i?f:0,l=i?f+1:h.length;k<l;k++){var m=h[k];if(m.selected&&(d.support.optDisabled?!m.disabled:m.getAttribute("disabled")===null)&&(!m.parentNode.disabled||!d.nodeName(m.parentNode,"optgroup"))){a=d(m).val();if(i)return a;g.push(a)}}if(i&&!g.length&&h.length)return d(h[f]).val();return g}if(o.test(c.type)&&!d.support.checkOn)return c.getAttribute("value")===null?"on":c.value;return(c.value||"").replace(j,"")}return b}var n=d.isFunction(a);return this.each(function(b){var c=d(this),e=a;if(this.nodeType===1){n&&(e=a.call(this,b,c.val())),e==null?e="":typeof e==="number"?e+="":d.isArray(e)&&(e=d.map(e,function(a){return a==null?"":a+""}));if(d.isArray(e)&&o.test(this.type))this.checked=d.inArray(c.val(),e)>=0;else if(d.nodeName(this,"select")){var f=d.makeArray(e);d("option",this).each(function(){this.selected=d.inArray(d(this).val(),f)>=0}),f.length||(this.selectedIndex=-1)}else this.value=e}})}}),d.extend({attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,e,f){if(!a||a.nodeType===3||a.nodeType===8||a.nodeType===2)return b;if(f&&c in d.attrFn)return d(a)[c](e);var g=a.nodeType!==1||!d.isXMLDoc(a),h=e!==b;c=g&&d.props[c]||c;if(a.nodeType===1){var i=k.test(c);if(c==="selected"&&!d.support.optSelected){var j=a.parentNode;j&&(j.selectedIndex,j.parentNode&&j.parentNode.selectedIndex)}if((c in a||a[c]!==b)&&g&&!i){h&&(c==="type"&&l.test(a.nodeName)&&a.parentNode&&d.error("type property can't be changed"),e===null?a.nodeType===1&&a.removeAttribute(c):a[c]=e);if(d.nodeName(a,"form")&&a.getAttributeNode(c))return a.getAttributeNode(c).nodeValue;if(c==="tabIndex"){var o=a.getAttributeNode("tabIndex");return o&&o.specified?o.value:m.test(a.nodeName)||n.test(a.nodeName)&&a.href?0:b}return a[c]}if(!d.support.style&&g&&c==="style"){h&&(a.style.cssText=""+e);return a.style.cssText}h&&a.setAttribute(c,""+e);if(!a.attributes[c]&&(a.hasAttribute&&!a.hasAttribute(c)))return b;var p=!d.support.hrefNormalized&&g&&i?a.getAttribute(c,2):a.getAttribute(c);return p===null?b:p}h&&(a[c]=e);return a[c]}});var p=/\.(.*)$/,q=/^(?:textarea|input|select)$/i,r=/\./g,s=/ /g,t=/[^\w\s.|`]/g,u=function(a){return a.replace(t,"\\$&")};d.event={add:function(c,e,f,g){if(c.nodeType!==3&&c.nodeType!==8){try{d.isWindow(c)&&(c!==a&&!c.frameElement)&&(c=a)}catch(h){}if(f===!1)f=v;else if(!f)return;var i,j;f.handler&&(i=f,f=i.handler),f.guid||(f.guid=d.guid++);var k=d._data(c);if(!k)return;var l=k.events,m=k.handle;l||(k.events=l={}),m||(k.handle=m=function(){return typeof d!=="undefined"&&!d.event.triggered?d.event.handle.apply(m.elem,arguments):b}),m.elem=c,e=e.split(" ");var n,o=0,p;while(n=e[o++]){j=i?d.extend({},i):{handler:f,data:g},n.indexOf(".")>-1?(p=n.split("."),n=p.shift(),j.namespace=p.slice(0).sort().join(".")):(p=[],j.namespace=""),j.type=n,j.guid||(j.guid=f.guid);var q=l[n],r=d.event.special[n]||{};if(!q){q=l[n]=[];if(!r.setup||r.setup.call(c,g,p,m)===!1)c.addEventListener?c.addEventListener(n,m,!1):c.attachEvent&&c.attachEvent("on"+n,m)}r.add&&(r.add.call(c,j),j.handler.guid||(j.handler.guid=f.guid)),q.push(j),d.event.global[n]=!0}c=null}},global:{},remove:function(a,c,e,f){if(a.nodeType!==3&&a.nodeType!==8){e===!1&&(e=v);var g,h,i,j,k=0,l,m,n,o,p,q,r,s=d.hasData(a)&&d._data(a),t=s&&s.events;if(!s||!t)return;c&&c.type&&(e=c.handler,c=c.type);if(!c||typeof c==="string"&&c.charAt(0)==="."){c=c||"";for(h in t)d.event.remove(a,h+c);return}c=c.split(" ");while(h=c[k++]){r=h,q=null,l=h.indexOf(".")<0,m=[],l||(m=h.split("."),h=m.shift(),n=new RegExp("(^|\\.)"+d.map(m.slice(0).sort(),u).join("\\.(?:.*\\.)?")+"(\\.|$)")),p=t[h];if(!p)continue;if(!e){for(j=0;j<p.length;j++){q=p[j];if(l||n.test(q.namespace))d.event.remove(a,r,q.handler,j),p.splice(j--,1)}continue}o=d.event.special[h]||{};for(j=f||0;j<p.length;j++){q=p[j];if(e.guid===q.guid){if(l||n.test(q.namespace))f==null&&p.splice(j--,1),o.remove&&o.remove.call(a,q);if(f!=null)break}}if(p.length===0||f!=null&&p.length===1)(!o.teardown||o.teardown.call(a,m)===!1)&&d.removeEvent(a,h,s.handle),g=null,delete t[h]}if(d.isEmptyObject(t)){var w=s.handle;w&&(w.elem=null),delete s.events,delete s.handle,d.isEmptyObject(s)&&d.removeData(a,b,!0)}}},trigger:function(a,c,e){var f=a.type||a,g=arguments[3];if(!g){a=typeof a==="object"?a[d.expando]?a:d.extend(d.Event(f),a):d.Event(f),f.indexOf("!")>=0&&(a.type=f=f.slice(0,-1),a.exclusive=!0),e||(a.stopPropagation(),d.event.global[f]&&d.each(d.cache,function(){var b=d.expando,e=this[b];e&&e.events&&e.events[f]&&d.event.trigger(a,c,e.handle.elem)}));if(!e||e.nodeType===3||e.nodeType===8)return b;a.result=b,a.target=e,c=d.makeArray(c),c.unshift(a)}a.currentTarget=e;var h=d._data(e,"handle");h&&h.apply(e,c);var i=e.parentNode||e.ownerDocument;try{e&&e.nodeName&&d.noData[e.nodeName.toLowerCase()]||e["on"+f]&&e["on"+f].apply(e,c)===!1&&(a.result=!1,a.preventDefault())}catch(j){}if(!a.isPropagationStopped()&&i)d.event.trigger(a,c,i,!0);else if(!a.isDefaultPrevented()){var k,l=a.target,m=f.replace(p,""),n=d.nodeName(l,"a")&&m==="click",o=d.event.special[m]||{};if((!o._default||o._default.call(e,a)===!1)&&!n&&!(l&&l.nodeName&&d.noData[l.nodeName.toLowerCase()])){try{l[m]&&(k=l["on"+m],k&&(l["on"+m]=null),d.event.triggered=!0,l[m]())}catch(q){}k&&(l["on"+m]=k),d.event.triggered=!1}}},handle:function(c){var e,f,g,h,i,j=[],k=d.makeArray(arguments);c=k[0]=d.event.fix(c||a.event),c.currentTarget=this,e=c.type.indexOf(".")<0&&!c.exclusive,e||(g=c.type.split("."),c.type=g.shift(),j=g.slice(0).sort(),h=new RegExp("(^|\\.)"+j.join("\\.(?:.*\\.)?")+"(\\.|$)")),c.namespace=c.namespace||j.join("."),i=d._data(this,"events"),f=(i||{})[c.type];if(i&&f){f=f.slice(0);for(var l=0,m=f.length;l<m;l++){var n=f[l];if(e||h.test(n.namespace)){c.handler=n.handler,c.data=n.data,c.handleObj=n;var o=n.handler.apply(this,k);o!==b&&(c.result=o,o===!1&&(c.preventDefault(),c.stopPropagation()));if(c.isImmediatePropagationStopped())break}}}return c.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(a){if(a[d.expando])return a;var e=a;a=d.Event(e);for(var f=this.props.length,g;f;)g=this.props[--f],a[g]=e[g];a.target||(a.target=a.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),!a.relatedTarget&&a.fromElement&&(a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement);if(a.pageX==null&&a.clientX!=null){var h=c.documentElement,i=c.body;a.pageX=a.clientX+(h&&h.scrollLeft||i&&i.scrollLeft||0)-(h&&h.clientLeft||i&&i.clientLeft||0),a.pageY=a.clientY+(h&&h.scrollTop||i&&i.scrollTop||0)-(h&&h.clientTop||i&&i.clientTop||0)}a.which==null&&(a.charCode!=null||a.keyCode!=null)&&(a.which=a.charCode!=null?a.charCode:a.keyCode),!a.metaKey&&a.ctrlKey&&(a.metaKey=a.ctrlKey),!a.which&&a.button!==b&&(a.which=a.button&1?1:a.button&2?3:a.button&4?2:0);return a},guid:1e8,proxy:d.proxy,special:{ready:{setup:d.bindReady,teardown:d.noop},live:{add:function(a){d.event.add(this,F(a.origType,a.selector),d.extend({},a,{handler:E,guid:a.handler.guid}))},remove:function(a){d.event.remove(this,F(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,c){d.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}}},d.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},d.Event=function(a){if(!this.preventDefault)return new d.Event(a);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?w:v):this.type=a,this.timeStamp=d.now(),this[d.expando]=!0},d.Event.prototype={preventDefault:function(){this.isDefaultPrevented=w;var a=this.originalEvent;a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=w;var a=this.originalEvent;a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=w,this.stopPropagation()},isDefaultPrevented:v,isPropagationStopped:v,isImmediatePropagationStopped:v};var x=function(a){var b=a.relatedTarget;try{if(b!==c&&!b.parentNode)return;while(b&&b!==this)b=b.parentNode;b!==this&&(a.type=a.data,d.event.handle.apply(this,arguments))}catch(e){}},y=function(a){a.type=a.data,d.event.handle.apply(this,arguments)};d.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){d.event.special[a]={setup:function(c){d.event.add(this,b,c&&c.selector?y:x,a)},teardown:function(a){d.event.remove(this,b,a&&a.selector?y:x)}}}),d.support.submitBubbles||(d.event.special.submit={setup:function(a,b){if(this.nodeName&&this.nodeName.toLowerCase()!=="form")d.event.add(this,"click.specialSubmit",function(a){var b=a.target,c=b.type;(c==="submit"||c==="image")&&d(b).closest("form").length&&C("submit",this,arguments)}),d.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,c=b.type;(c==="text"||c==="password")&&d(b).closest("form").length&&a.keyCode===13&&C("submit",this,arguments)});else return!1},teardown:function(a){d.event.remove(this,".specialSubmit")}});if(!d.support.changeBubbles){var z,A=function(a){var b=a.type,c=a.value;b==="radio"||b==="checkbox"?c=a.checked:b==="select-multiple"?c=a.selectedIndex>-1?d.map(a.options,function(a){return a.selected}).join("-"):"":a.nodeName.toLowerCase()==="select"&&(c=a.selectedIndex);return c},B=function B(a){var c=a.target,e,f;if(q.test(c.nodeName)&&!c.readOnly){e=d._data(c,"_change_data"),f=A(c),(a.type!=="focusout"||c.type!=="radio")&&d._data(c,"_change_data",f);if(e===b||f===e)return;if(e!=null||f)a.type="change",a.liveFired=b,d.event.trigger(a,arguments[1],c)}};d.event.special.change={filters:{focusout:B,beforedeactivate:B,click:function(a){var b=a.target,c=b.type;(c==="radio"||c==="checkbox"||b.nodeName.toLowerCase()==="select")&&B.call(this,a)},keydown:function(a){var b=a.target,c=b.type;(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(c==="checkbox"||c==="radio")||c==="select-multiple")&&B.call(this,a)},beforeactivate:function(a){var b=a.target;d._data(b,"_change_data",A(b))}},setup:function(a,b){if(this.type==="file")return!1;for(var c in z)d.event.add(this,c+".specialChange",z[c]);return q.test(this.nodeName)},teardown:function(a){d.event.remove(this,".specialChange");return q.test(this.nodeName)}},z=d.event.special.change.filters,z.focus=z.beforeactivate}c.addEventListener&&d.each({focus:"focusin",blur:"focusout"},function(a,b){function c(a){a=d.event.fix(a),a.type=b;return d.event.handle.call(this,a)}d.event.special[b]={setup:function(){this.addEventListener(a,c,!0)},teardown:function(){this.removeEventListener(a,c,!0)}}}),d.each(["bind","one"],function(a,c){d.fn[c]=function(a,e,f){if(typeof a==="object"){for(var g in a)this[c](g,e,a[g],f);return this}if(d.isFunction(e)||e===!1)f=e,e=b;var h=c==="one"?d.proxy(f,function(a){d(this).unbind(a,h);return f.apply(this,arguments)}):f;if(a==="unload"&&c!=="one")this.one(a,e,f);else for(var i=0,j=this.length;i<j;i++)d.event.add(this[i],a,h,e);return this}}),d.fn.extend({unbind:function(a,b){if(typeof a!=="object"||a.preventDefault)for(var e=0,f=this.length;e<f;e++)d.event.remove(this[e],a,b);else for(var c in a)this.unbind(c,a[c]);return this},delegate:function(a,b,c,d){return this.live(b,c,d,a)},undelegate:function(a,b,c){return arguments.length===0?this.unbind("live"):this.die(b,null,c,a)},trigger:function(a,b){return this.each(function(){d.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){var c=d.Event(a);c.preventDefault(),c.stopPropagation(),d.event.trigger(c,b,this[0]);return c.result}},toggle:function(a){var b=arguments,c=1;while(c<b.length)d.proxy(a,b[c++]);return this.click(d.proxy(a,function(e){var f=(d._data(this,"lastToggle"+a.guid)||0)%c;d._data(this,"lastToggle"+a.guid,f+1),e.preventDefault();return b[f].apply(this,arguments)||!1}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var D={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};d.each(["live","die"],function(a,c){d.fn[c]=function(a,e,f,g){var h,i=0,j,k,l,m=g||this.selector,n=g?this:d(this.context);if(typeof a==="object"&&!a.preventDefault){for(var o in a)n[c](o,e,a[o],m);return this}d.isFunction(e)&&(f=e,e=b),a=(a||"").split(" ");while((h=a[i++])!=null){j=p.exec(h),k="",j&&(k=j[0],h=h.replace(p,""));if(h==="hover"){a.push("mouseenter"+k,"mouseleave"+k);continue}l=h,h==="focus"||h==="blur"?(a.push(D[h]+k),h=h+k):h=(D[h]||h)+k;if(c==="live")for(var q=0,r=n.length;q<r;q++)d.event.add(n[q],"live."+F(h,m),{data:e,selector:m,handler:f,origType:h,origHandler:f,preType:l});else n.unbind("live."+F(h,m),f)}return this}}),d.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),function(a,b){d.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)},d.attrFn&&(d.attrFn[b]=!0)}),function(){function u(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}if(i.nodeType===1){f||(i.sizcache=c,i.sizset=g);if(typeof b!=="string"){if(i===b){j=!0;break}}else if(k.filter(b,[i]).length>0){j=i;break}}i=i[a]}d[g]=j}}}function t(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}i.nodeType===1&&!f&&(i.sizcache=c,i.sizset=g);if(i.nodeName.toLowerCase()===b){j=i;break}i=i[a]}d[g]=j}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,f=Object.prototype.toString,g=!1,h=!0,i=/\\/g,j=/\W/;[0,0].sort(function(){h=!1;return 0});var k=function(b,d,e,g){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!=="string")return e;var i,j,n,o,q,r,s,t,u=!0,w=k.isXML(d),x=[],y=b;do{a.exec(""),i=a.exec(y);if(i){y=i[3],x.push(i[1]);if(i[2]){o=i[3];break}}}while(i);if(x.length>1&&m.exec(b))if(x.length===2&&l.relative[x[0]])j=v(x[0]+x[1],d);else{j=l.relative[x[0]]?[d]:k(x.shift(),d);while(x.length)b=x.shift(),l.relative[b]&&(b+=x.shift()),j=v(b,j)}else{!g&&x.length>1&&d.nodeType===9&&!w&&l.match.ID.test(x[0])&&!l.match.ID.test(x[x.length-1])&&(q=k.find(x.shift(),d,w),d=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]);if(d){q=g?{expr:x.pop(),set:p(g)}:k.find(x.pop(),x.length===1&&(x[0]==="~"||x[0]==="+")&&d.parentNode?d.parentNode:d,w),j=q.expr?k.filter(q.expr,q.set):q.set,x.length>0?n=p(j):u=!1;while(x.length)r=x.pop(),s=r,l.relative[r]?s=x.pop():r="",s==null&&(s=d),l.relative[r](n,s,w)}else n=x=[]}n||(n=j),n||k.error(r||b);if(f.call(n)==="[object Array]")if(u)if(d&&d.nodeType===1)for(t=0;n[t]!=null;t++)n[t]&&(n[t]===!0||n[t].nodeType===1&&k.contains(d,n[t]))&&e.push(j[t]);else for(t=0;n[t]!=null;t++)n[t]&&n[t].nodeType===1&&e.push(j[t]);else e.push.apply(e,n);else p(n,e);o&&(k(o,h,e,g),k.uniqueSort(e));return e};k.uniqueSort=function(a){if(r){g=h,a.sort(r);if(g)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},k.matches=function(a,b){return k(a,null,null,b)},k.matchesSelector=function(a,b){return k(b,null,null,[a]).length>0},k.find=function(a,b,c){var d;if(!a)return[];for(var e=0,f=l.order.length;e<f;e++){var g,h=l.order[e];if(g=l.leftMatch[h].exec(a)){var j=g[1];g.splice(1,1);if(j.substr(j.length-1)!=="\\"){g[1]=(g[1]||"").replace(i,""),d=l.find[h](g,b,c);if(d!=null){a=a.replace(l.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!=="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},k.filter=function(a,c,d,e){var f,g,h=a,i=[],j=c,m=c&&c[0]&&k.isXML(c[0]);while(a&&c.length){for(var n in l.filter)if((f=l.leftMatch[n].exec(a))!=null&&f[2]){var o,p,q=l.filter[n],r=f[1];g=!1,f.splice(1,1);if(r.substr(r.length-1)==="\\")continue;j===i&&(i=[]);if(l.preFilter[n]){f=l.preFilter[n](f,j,d,i,e,m);if(f){if(f===!0)continue}else g=o=!0}if(f)for(var s=0;(p=j[s])!=null;s++)if(p){o=q(p,f,s,j);var t=e^!!o;d&&o!=null?t?g=!0:j[s]=!1:t&&(i.push(p),g=!0)}if(o!==b){d||(j=i),a=a.replace(l.match[n],"");if(!g)return[];break}}if(a===h)if(g==null)k.error(a);else break;h=a}return j},k.error=function(a){throw"Syntax error, unrecognized expression: "+a};var l=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b==="string",d=c&&!j.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1){}a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&k.filter(b,a,!0)},">":function(a,b){var c,d=typeof b==="string",e=0,f=a.length;if(d&&!j.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&k.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=u;typeof b==="string"&&!j.test(b)&&(b=b.toLowerCase(),d=b,g=t),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=u;typeof b==="string"&&!j.test(b)&&(b=b.toLowerCase(),d=b,g=t),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!=="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!=="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!=="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(i,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(i,"")},TAG:function(a,b){return a[1].replace(i,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||k.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&k.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(i,"");!f&&l.attrMap[g]&&(a[1]=l.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(i,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=k(b[3],null,null,c);else{var g=k.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(l.match.POS.test(b[0])||l.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!k(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){return"text"===a.getAttribute("type")},radio:function(a){return"radio"===a.type},checkbox:function(a){return"checkbox"===a.type},file:function(a){return"file"===a.type},password:function(a){return"password"===a.type},submit:function(a){return"submit"===a.type},image:function(a){return"image"===a.type},reset:function(a){return"reset"===a.type},button:function(a){return"button"===a.type||a.nodeName.toLowerCase()==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=l.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||k.getText([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}k.error(e)},CHILD:function(a,b){var c=b[1],d=a;switch(c){case"only":case"first":while(d=d.previousSibling)if(d.nodeType===1)return!1;if(c==="first")return!0;d=a;case"last":while(d=d.nextSibling)if(d.nodeType===1)return!1;return!0;case"nth":var e=b[2],f=b[3];if(e===1&&f===0)return!0;var g=b[0],h=a.parentNode;if(h&&(h.sizcache!==g||!a.nodeIndex)){var i=0;for(d=h.firstChild;d;d=d.nextSibling)d.nodeType===1&&(d.nodeIndex=++i);h.sizcache=g}var j=a.nodeIndex-f;return e===0?j===0:j%e===0&&j/e>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=l.attrHandle[c]?l.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=l.setFilters[e];if(f)return f(a,c,b,d)}}},m=l.match.POS,n=function(a,b){return"\\"+(b-0+1)};for(var o in l.match)l.match[o]=new RegExp(l.match[o].source+/(?![^\[]*\])(?![^\(]*\))/.source),l.leftMatch[o]=new RegExp(/(^(?:.|\r|\n)*?)/.source+l.match[o].source.replace(/\\(\d+)/g,n));var p=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(q){p=function(a,b){var c=0,d=b||[];if(f.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length==="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var r,s;c.documentElement.compareDocumentPosition?r=function(a,b){if(a===b){g=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(r=function(a,b){var c,d,e=[],f=[],h=a.parentNode,i=b.parentNode,j=h;if(a===b){g=!0;return 0}if(h===i)return s(a,b);if(!h)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return s(e[k],f[k]);return k===c?s(a,f[k],-1):s(e[k],b,1)},s=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),k.getText=function(a){var b="",c;for(var d=0;a[d];d++)c=a[d],c.nodeType===3||c.nodeType===4?b+=c.nodeValue:c.nodeType!==8&&(b+=k.getText(c.childNodes));return b},function(){var a=c.createElement("div"),d="script"+(new Date).getcurrent_time('timestamp',0),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(l.find.ID=function(a,c,d){if(typeof c.getElementById!=="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!=="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},l.filter.ID=function(a,b){var c=typeof a.getAttributeNode!=="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(l.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!=="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(l.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=k,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){k=function(b,e,f,g){e=e||c;if(!g&&!k.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return p(e.getElementsByTagName(b),f);if(h[2]&&l.find.CLASS&&e.getElementsByClassName)return p(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return p([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return p([],f);if(i.id===h[3])return p([i],f)}try{return p(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var m=e,n=e.getAttribute("id"),o=n||d,q=e.parentNode,r=/^\s*[+~]/.test(b);n?o=o.replace(/'/g,"\\$&"):e.setAttribute("id",o),r&&q&&(e=e.parentNode);try{if(!r||q)return p(e.querySelectorAll("[id='"+o+"'] "+b),f)}catch(s){}finally{n||m.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)k[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector,d=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(e){d=!0}b&&(k.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(a))try{if(d||!l.match.PSEUDO.test(c)&&!/!=/.test(c))return b.call(a,c)}catch(e){}return k(c,null,null,[a]).length>0})}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;l.order.splice(1,0,"CLASS"),l.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!=="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?k.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?k.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:k.contains=function(){return!1},k.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var v=function(a,b){var c,d=[],e="",f=b.nodeType?[b]:b;while(c=l.match.PSEUDO.exec(a))e+=c[0],a=a.replace(l.match.PSEUDO,"");a=l.relative[a]?a+"*":a;for(var g=0,h=f.length;g<h;g++)k(a,f[g],d);return k.filter(e,d)};d.find=k,d.expr=k.selectors,d.expr[":"]=d.expr.filters,d.unique=k.uniqueSort,d.text=k.getText,d.isXMLDoc=k.isXML,d.contains=k.contains}();var G=/Until$/,H=/^(?:parents|prevUntil|prevAll)/,I=/,/,J=/^.[^:#\[\.,]*$/,K=Array.prototype.slice,L=d.expr.match.POS,M={children:!0,contents:!0,next:!0,prev:!0};d.fn.extend({find:function(a){var b=this.pushStack("","find",a),c=0;for(var e=0,f=this.length;e<f;e++){c=b.length,d.find(a,this[e],b);if(e>0)for(var g=c;g<b.length;g++)for(var h=0;h<c;h++)if(b[h]===b[g]){b.splice(g--,1);break}}return b},has:function(a){var b=d(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(d.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(O(this,a,!1),"not",a)},filter:function(a){return this.pushStack(O(this,a,!0),"filter",a)},is:function(a){return!!a&&d.filter(a,this).length>0},closest:function(a,b){var c=[],e,f,g=this[0];if(d.isArray(a)){var h,i,j={},k=1;if(g&&a.length){for(e=0,f=a.length;e<f;e++)i=a[e],j[i]||(j[i]=d.expr.match.POS.test(i)?d(i,b||this.context):i);while(g&&g.ownerDocument&&g!==b){for(i in j)h=j[i],(h.jquery?h.index(g)>-1:d(g).is(h))&&c.push({selector:i,elem:g,level:k});g=g.parentNode,k++}}return c}var l=L.test(a)?d(a,b||this.context):null;for(e=0,f=this.length;e<f;e++){g=this[e];while(g){if(l?l.index(g)>-1:d.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b)break}}c=c.length>1?d.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a||typeof a==="string")return d.inArray(this[0],a?d(a):this.parent().children());return d.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a==="string"?d(a,b):d.makeArray(a),e=d.merge(this.get(),c);return this.pushStack(N(c[0])||N(e[0])?e:d.unique(e))},andSelf:function(){return this.add(this.prevObject)}}),d.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return d.dir(a,"parentNode")},parentsUntil:function(a,b,c){return d.dir(a,"parentNode",c)},next:function(a){return d.nth(a,2,"nextSibling")},prev:function(a){return d.nth(a,2,"previousSibling")},nextAll:function(a){return d.dir(a,"nextSibling")},prevAll:function(a){return d.dir(a,"previousSibling")},nextUntil:function(a,b,c){return d.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return d.dir(a,"previousSibling",c)},siblings:function(a){return d.sibling(a.parentNode.firstChild,a)},children:function(a){return d.sibling(a.firstChild)},contents:function(a){return d.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:d.makeArray(a.childNodes)}},function(a,b){d.fn[a]=function(c,e){var f=d.map(this,b,c),g=K.call(arguments);G.test(a)||(e=c),e&&typeof e==="string"&&(f=d.filter(e,f)),f=this.length>1&&!M[a]?d.unique(f):f,(this.length>1||I.test(e))&&H.test(a)&&(f=f.reverse());return this.pushStack(f,a,g.join(","))}}),d.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?d.find.matchesSelector(b[0],a)?[b[0]]:[]:d.find.matches(a,b)},dir:function(a,c,e){var f=[],g=a[c];while(g&&g.nodeType!==9&&(e===b||g.nodeType!==1||!d(g).is(e)))g.nodeType===1&&f.push(g),g=g[c];return f},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var P=/ jQuery\d+="(?:\d+|null)"/g,Q=/^\s+/,R=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,S=/<([\w:]+)/,T=/<tbody/i,U=/<|&#?\w+;/,V=/<(?:script|object|embed|option|style)/i,W=/checked\s*(?:[^=]|=\s*.checked.)/i,X={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};X.optgroup=X.option,X.tbody=X.tfoot=X.colgroup=X.caption=X.thead,X.th=X.td,d.support.htmlSerialize||(X._default=[1,"div<div>","</div>"]),d.fn.extend({text:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.text(a.call(this,b,c.text()))});if(typeof a!=="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return d.text(this)},wrapAll:function(a){if(d.isFunction(a))return this.each(function(b){d(this).wrapAll(a.call(this,b))});if(this[0]){var b=d(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(d.isFunction(a))return this.each(function(b){d(this).wrapInner(a.call(this,b))});return this.each(function(){var b=d(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){d(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){d.nodeName(this,"body")||d(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=d(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,d(arguments[0]).toArray());return a}},remove:function(a,b){for(var c=0,e;(e=this[c])!=null;c++)if(!a||d.filter(a,[e]).length)!b&&e.nodeType===1&&(d.cleanData(e.getElementsByTagName("*")),d.cleanData([e])),e.parentNode&&e.parentNode.removeChild(e);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&d.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return d.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(P,""):null;if(typeof a!=="string"||V.test(a)||!d.support.leadingWhitespace&&Q.test(a)||X[(S.exec(a)||["",""])[1].toLowerCase()])d.isFunction(a)?this.each(function(b){var c=d(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);else{a=a.replace(R,"<$1></$2>");try{for(var c=0,e=this.length;c<e;c++)this[c].nodeType===1&&(d.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(f){this.empty().append(a)}}return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(d.isFunction(a))return this.each(function(b){var c=d(this),e=c.html();c.replaceWith(a.call(this,b,e))});typeof a!=="string"&&(a=d(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;d(this).remove(),b?d(b).before(a):d(c).append(a)})}return this.pushStack(d(d.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,e){var f,g,h,i,j=a[0],k=[];if(!d.support.checkClone&&arguments.length===3&&typeof j==="string"&&W.test(j))return this.each(function(){d(this).domManip(a,c,e,!0)});if(d.isFunction(j))return this.each(function(f){var g=d(this);a[0]=j.call(this,f,c?g.html():b),g.domManip(a,c,e)});if(this[0]){i=j&&j.parentNode,d.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?f={fragment:i}:f=d.buildFragment(a,this,k),h=f.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&d.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)e.call(c?Y(this[l],g):this[l],f.cacheable||m>1&&l<n?d.clone(h,!0,!0):h)}k.length&&d.each(k,ba)}return this}}),d.buildFragment=function(a,b,e){var f,g,h,i=b&&b[0]?b[0].ownerDocument||b[0]:c;a.length===1&&typeof a[0]==="string"&&a[0].length<512&&i===c&&a[0].charAt(0)==="<"&&!V.test(a[0])&&(d.support.checkClone||!W.test(a[0]))&&(g=!0,h=d.fragments[a[0]],h&&(h!==1&&(f=h))),f||(f=i.createDocumentFragment(),d.clean(a,i,f,e)),g&&(d.fragments[a[0]]=h?f:1);return{fragment:f,cacheable:g}},d.fragments={},d.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){d.fn[a]=function(c){var e=[],f=d(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&f.length===1){f[b](this[0]);return this}for(var h=0,i=f.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();d(f[h])[b](j),e=e.concat(j)}return this.pushStack(e,a,f.selector)}}),d.extend({clone:function(a,b,c){var e=a.cloneNode(!0),f,g,h;if((!d.support.noCloneEvent||!d.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!d.isXMLDoc(a)){$(a,e),f=_(a),g=_(e);for(h=0;f[h];++h)$(f[h],g[h])}if(b){Z(a,e);if(c){f=_(a),g=_(e);for(h=0;f[h];++h)Z(f[h],g[h])}}return e},clean:function(a,b,e,f){b=b||c,typeof b.createElement==="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var g=[];for(var h=0,i;(i=a[h])!=null;h++){typeof i==="number"&&(i+="");if(!i)continue;if(typeof i!=="string"||U.test(i)){if(typeof i==="string"){i=i.replace(R,"<$1></$2>");var j=(S.exec(i)||["",""])[1].toLowerCase(),k=X[j]||X._default,l=k[0],m=b.createElement("div");m.innerHTML=k[1]+i+k[2];while(l--)m=m.lastChild;if(!d.support.tbody){var n=T.test(i),o=j==="table"&&!n?m.firstChild&&m.firstChild.childNodes:k[1]==="<table>"&&!n?m.childNodes:[];for(var p=o.length-1;p>=0;--p)d.nodeName(o[p],"tbody")&&!o[p].childNodes.length&&o[p].parentNode.removeChild(o[p])}!d.support.leadingWhitespace&&Q.test(i)&&m.insertBefore(b.createTextNode(Q.exec(i)[0]),m.firstChild),i=m.childNodes}}else i=b.createTextNode(i);i.nodeType?g.push(i):g=d.merge(g,i)}if(e)for(h=0;g[h];h++)!f||!d.nodeName(g[h],"script")||g[h].type&&g[h].type.toLowerCase()!=="text/javascript"?(g[h].nodeType===1&&g.splice.apply(g,[h+1,0].concat(d.makeArray(g[h].getElementsByTagName("script")))),e.appendChild(g[h])):f.push(g[h].parentNode?g[h].parentNode.removeChild(g[h]):g[h]);return g},cleanData:function(a){var b,c,e=d.cache,f=d.expando,g=d.event.special,h=d.support.deleteExpando;for(var i=0,j;(j=a[i])!=null;i++){if(j.nodeName&&d.noData[j.nodeName.toLowerCase()])continue;c=j[d.expando];if(c){b=e[c]&&e[c][f];if(b&&b.events){for(var k in b.events)g[k]?d.event.remove(j,k):d.removeEvent(j,k,b.handle);b.handle&&(b.handle.elem=null)}h?delete j[d.expando]:j.removeAttribute&&j.removeAttribute(d.expando),delete e[c]}}}});var bb=/alpha\([^)]*\)/i,bc=/opacity=([^)]*)/,bd=/-([a-z])/ig,be=/([A-Z])/g,bf=/^-?\d+(?:px)?$/i,bg=/^-?\d/,bh={position:"absolute",visibility:"hidden",display:"block"},bi=["Left","Right"],bj=["Top","Bottom"],bk,bl,bm,bn=function(a,b){return b.toUpperCase()};d.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return d.access(this,a,c,!0,function(a,c,e){return e!==b?d.style(a,c,e):d.css(a,c)})},d.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bk(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{zIndex:!0,fontWeight:!0,opacity:!0,zoom:!0,lineHeight:!0},cssProps:{"float":d.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,e,f){if(a&&a.nodeType!==3&&a.nodeType!==8&&a.style){var g,h=d.camelCase(c),i=a.style,j=d.cssHooks[h];c=d.cssProps[h]||h;if(e===b){if(j&&"get"in j&&(g=j.get(a,!1,f))!==b)return g;return i[c]}if(typeof e==="number"&&isNaN(e)||e==null)return;typeof e==="number"&&!d.cssNumber[h]&&(e+="px");if(!j||!("set"in j)||(e=j.set(a,e))!==b)try{i[c]=e}catch(k){}}},css:function(a,c,e){var f,g=d.camelCase(c),h=d.cssHooks[g];c=d.cssProps[g]||g;if(h&&"get"in h&&(f=h.get(a,!0,e))!==b)return f;if(bk)return bk(a,c,g)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]},camelCase:function(a){return a.replace(bd,bn)}}),d.curCSS=d.css,d.each(["height","width"],function(a,b){d.cssHooks[b]={get:function(a,c,e){var f;if(c){a.offsetWidth!==0?f=bo(a,b,e):d.swap(a,bh,function(){f=bo(a,b,e)});if(f<=0){f=bk(a,b,b),f==="0px"&&bm&&(f=bm(a,b,b));if(f!=null)return f===""||f==="auto"?"0px":f}if(f<0||f==null){f=a.style[b];return f===""||f==="auto"?"0px":f}return typeof f==="string"?f:f+"px"}},set:function(a,b){if(!bf.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),d.support.opacity||(d.cssHooks.opacity={get:function(a,b){return bc.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style;c.zoom=1;var e=d.isNaN(b)?"":"alpha(opacity="+b*100+")",f=c.filter||"";c.filter=bb.test(f)?f.replace(bb,e):c.filter+" "+e}}),c.defaultView&&c.defaultView.getComputedStyle&&(bl=function(a,c,e){var f,g,h;e=e.replace(be,"-$1").toLowerCase();if(!(g=a.ownerDocument.defaultView))return b;if(h=g.getComputedStyle(a,null))f=h.getPropertyValue(e),f===""&&!d.contains(a.ownerDocument.documentElement,a)&&(f=d.style(a,e));return f}),c.documentElement.currentStyle&&(bm=function(a,b){var c,d=a.currentStyle&&a.currentStyle[b],e=a.runtimeStyle&&a.runtimeStyle[b],f=a.style;!bf.test(d)&&bg.test(d)&&(c=f.left,e&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":d||0,d=f.pixelLeft+"px",f.left=c,e&&(a.runtimeStyle.left=e));return d===""?"auto":d}),bk=bl||bm,d.expr&&d.expr.filters&&(d.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!d.support.reliableHiddenOffsets&&(a.style.display||d.css(a,"display"))==="none"},d.expr.filters.visible=function(a){return!d.expr.filters.hidden(a)});var bp=/%20/g,bq=/\[\]$/,br=/\r?\n/g,bs=/#.*$/,bt=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bu=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bv=/(?:^file|^widget|\-extension):$/,bw=/^(?:GET|HEAD)$/,bx=/^\/\//,by=/\?/,bz=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bA=/^(?:select|textarea)/i,bB=/\s+/,bC=/([?&])_=[^&]*/,bD=/(^|\-)([a-z])/g,bE=function(a,b,c){return b+c.toUpperCase()},bF=/^([\w\+\.\-]+:)\/\/([^\/?#:]*)(?::(\d+))?/,bG=d.fn.load,bH={},bI={},bJ,bK;try{bJ=c.location.href}catch(bL){bJ=c.createElement("a"),bJ.href="",bJ=bJ.href}bK=bF.exec(bJ.toLowerCase()),d.fn.extend({load:function(a,c,e){if(typeof a!=="string"&&bG)return bG.apply(this,arguments);if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var g=a.slice(f,a.length);a=a.slice(0,f)}var h="GET";c&&(d.isFunction(c)?(e=c,c=b):typeof c==="object"&&(c=d.param(c,d.ajaxSettings.traditional),h="POST"));var i=this;d.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?d("<div>").append(c.replace(bz,"")).find(g):c)),e&&i.each(e,[c,b,a])}});return this},serialize:function(){return d.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?d.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bA.test(this.nodeName)||bu.test(this.type))}).map(function(a,b){var c=d(this).val();return c==null?null:d.isArray(c)?d.map(c,function(a,c){return{name:b.name,value:a.replace(br,"\r\n")}}):{name:b.name,value:c.replace(br,"\r\n")}}).get()}}),d.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){d.fn[b]=function(a){return this.bind(b,a)}}),d.each(["get","post"],function(a,c){d[c]=function(a,e,f,g){d.isFunction(e)&&(g=g||f,f=e,e=b);return d.ajax({type:c,url:a,data:e,success:f,dataType:g})}}),d.extend({getScript:function(a,c){return d.get(a,b,c,"script")},getJSON:function(a,b,c){return d.get(a,b,c,"json")},ajaxSetup:function(a,b){b?d.extend(!0,a,d.ajaxSettings,b):(b=a,a=d.extend(!0,d.ajaxSettings,b));for(var c in {context:1,url:1})c in b?a[c]=b[c]:c in d.ajaxSettings&&(a[c]=d.ajaxSettings[c]);return a},ajaxSettings:{url:bJ,isLocal:bv.test(bK[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":"*/*"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":d.parseJSON,"text xml":d.parseXML}},ajaxPrefilter:bM(bH),ajaxTransport:bM(bI),ajax:function(a,c){function v(a,c,l,n){if(r!==2){r=2,p&&clearTimeout(p),o=b,m=n||"",u.readyState=a?4:0;var q,t,v,w=l?bP(e,u,l):b,x,y;if(a>=200&&a<300||a===304){if(e.ifModified){if(x=u.getResponseHeader("Last-Modified"))d.lastModified[k]=x;if(y=u.getResponseHeader("Etag"))d.etag[k]=y}if(a===304)c="notmodified",q=!0;else try{t=bQ(e,w),c="success",q=!0}catch(z){c="parsererror",v=z}}else{v=c;if(!c||a)c="error",a<0&&(a=0)}u.status=a,u.statusText=c,q?h.resolveWith(f,[t,c,u]):h.rejectWith(f,[u,c,v]),u.statusCode(j),j=b,s&&g.trigger("ajax"+(q?"Success":"Error"),[u,e,q?t:v]),i.resolveWith(f,[u,c]),s&&(g.trigger("ajaxComplete",[u,e]),--d.active||d.event.trigger("ajaxStop"))}}typeof a==="object"&&(c=a,a=b),c=c||{};var e=d.ajaxSetup({},c),f=e.context||e,g=f!==e&&(f.nodeType||f instanceof d)?d(f):d.event,h=d.Deferred(),i=d._Deferred(),j=e.statusCode||{},k,l={},m,n,o,p,q,r=0,s,t,u={readyState:0,setRequestHeader:function(a,b){r||(l[a.toLowerCase().replace(bD,bE)]=b);return this},getAllResponseHeaders:function(){return r===2?m:null},getResponseHeader:function(a){var c;if(r===2){if(!n){n={};while(c=bt.exec(m))n[c[1].toLowerCase()]=c[2]}c=n[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){r||(e.mimeType=a);return this},abort:function(a){a=a||"abort",o&&o.abort(a),v(0,a);return this}};h.promise(u),u.success=u.done,u.error=u.fail,u.complete=i.done,u.statusCode=function(a){if(a){var b;if(r<2)for(b in a)j[b]=[j[b],a[b]];else b=a[u.status],u.then(b,b)}return this},e.url=((a||e.url)+"").replace(bs,"").replace(bx,bK[1]+"//"),e.dataTypes=d.trim(e.dataType||"*").toLowerCase().split(bB),e.crossDomain||(q=bF.exec(e.url.toLowerCase()),e.crossDomain=q&&(q[1]!=bK[1]||q[2]!=bK[2]||(q[3]||(q[1]==="http:"?80:443))!=(bK[3]||(bK[1]==="http:"?80:443)))),e.data&&e.processData&&typeof e.data!=="string"&&(e.data=d.param(e.data,e.traditional)),bN(bH,e,c,u);if(r===2)return!1;s=e.global,e.type=e.type.toUpperCase(),e.hasContent=!bw.test(e.type),s&&d.active++===0&&d.event.trigger("ajaxStart");if(!e.hasContent){e.data&&(e.url+=(by.test(e.url)?"&":"?")+e.data),k=e.url;if(e.cache===!1){var w=d.now(),x=e.url.replace(bC,"$1_="+w);e.url=x+(x===e.url?(by.test(e.url)?"&":"?")+"_="+w:"")}}if(e.data&&e.hasContent&&e.contentType!==!1||c.contentType)l["Content-Type"]=e.contentType;e.ifModified&&(k=k||e.url,d.lastModified[k]&&(l["If-Modified-Since"]=d.lastModified[k]),d.etag[k]&&(l["If-None-Match"]=d.etag[k])),l.Accept=e.dataTypes[0]&&e.accepts[e.dataTypes[0]]?e.accepts[e.dataTypes[0]]+(e.dataTypes[0]!=="*"?", */*; q=0.01":""):e.accepts["*"];for(t in e.headers)u.setRequestHeader(t,e.headers[t]);if(e.beforeSend&&(e.beforeSend.call(f,u,e)===!1||r===2)){u.abort();return!1}for(t in {success:1,error:1,complete:1})u[t](e[t]);o=bN(bI,e,c,u);if(o){u.readyState=1,s&&g.trigger("ajaxSend",[u,e]),e.async&&e.timeout>0&&(p=setTimeout(function(){u.abort("timeout")},e.timeout));try{r=1,o.send(l,v)}catch(y){status<2?v(-1,y):d.error(y)}}else v(-1,"No Transport");return u},param:function(a,c){var e=[],f=function(a,b){b=d.isFunction(b)?b():b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=d.ajaxSettings.traditional);if(d.isArray(a)||a.jquery&&!d.isPlainObject(a))d.each(a,function(){f(this.name,this.value)});else for(var g in a)bO(g,a[g],c,f);return e.join("&").replace(bp,"+")}}),d.extend({active:0,lastModified:{},etag:{}});var bR=d.now(),bS=/(\=)\?(&|$)|()\?\?()/i;d.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return d.expando+"_"+bR++}}),d.ajaxPrefilter("json jsonp",function(b,c,e){var f=typeof b.data==="string";if(b.dataTypes[0]==="jsonp"||c.jsonpCallback||c.jsonp!=null||b.jsonp!==!1&&(bS.test(b.url)||f&&bS.test(b.data))){var g,h=b.jsonpCallback=d.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2",m=function(){a[h]=i,g&&d.isFunction(i)&&a[h](g[0])};b.jsonp!==!1&&(j=j.replace(bS,l),b.url===j&&(f&&(k=k.replace(bS,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},e.then(m,m),b.converters["script json"]=function(){g||d.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),d.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){d.globalEval(a);return a}}}),d.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),d.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var bT=d.now(),bU,bV;d.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&bX()||bY()}:bX,bV=d.ajaxSettings.xhr(),d.support.ajax=!!bV,d.support.cors=bV&&"withCredentials"in bV,bV=b,d.support.ajax&&d.ajaxTransport(function(a){if(!a.crossDomain||d.support.cors){var c;return{send:function(e,f){var g=a.xhr(),h,i;a.username?g.open(a.type,a.url,a.async,a.username,a.password):g.open(a.type,a.url,a.async);if(a.xhrFields)for(i in a.xhrFields)g[i]=a.xhrFields[i];a.mimeType&&g.overrideMimeType&&g.overrideMimeType(a.mimeType),(!a.crossDomain||a.hasContent)&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(i in e)g.setRequestHeader(i,e[i])}catch(j){}g.send(a.hasContent&&a.data||null),c=function(e,i){var j,k,l,m,n;try{if(c&&(i||g.readyState===4)){c=b,h&&(g.onreadystatechange=d.noop,delete bU[h]);if(i)g.readyState!==4&&g.abort();else{j=g.status,l=g.getAllResponseHeaders(),m={},n=g.responseXML,n&&n.documentElement&&(m.xml=n),m.text=g.responseText;try{k=g.statusText}catch(o){k=""}j||!a.isLocal||a.crossDomain?j===1223&&(j=204):j=m.text?200:404}}}catch(p){i||f(-1,p)}m&&f(j,k,m,l)},a.async&&g.readyState!==4?(bU||(bU={},bW()),h=bT++,g.onreadystatechange=bU[h]=c):c()},abort:function(){c&&c(0,1)}}}});var bZ={},b$=/^(?:toggle|show|hide)$/,b_=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,ca,cb=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];d.fn.extend({show:function(a,b,c){var e,f;if(a||a===0)return this.animate(cc("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)e=this[g],f=e.style.display,!d._data(e,"olddisplay")&&f==="none"&&(f=e.style.display=""),f===""&&d.css(e,"display")==="none"&&d._data(e,"olddisplay",cd(e.nodeName));for(g=0;g<h;g++){e=this[g],f=e.style.display;if(f===""||f==="none")e.style.display=d._data(e,"olddisplay")||""}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cc("hide",3),a,b,c);for(var e=0,f=this.length;e<f;e++){var g=d.css(this[e],"display");g!=="none"&&!d._data(this[e],"olddisplay")&&d._data(this[e],"olddisplay",g)}for(e=0;e<f;e++)this[e].style.display="none";return this},_toggle:d.fn.toggle,toggle:function(a,b,c){var e=typeof a==="boolean";d.isFunction(a)&&d.isFunction(b)?this._toggle.apply(this,arguments):a==null||e?this.each(function(){var b=e?a:d(this).is(":hidden");d(this)[b?"show":"hide"]()}):this.animate(cc("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,e){var f=d.speed(b,c,e);if(d.isEmptyObject(a))return this.each(f.complete);return this[f.queue===!1?"each":"queue"](function(){var b=d.extend({},f),c,e=this.nodeType===1,g=e&&d(this).is(":hidden"),h=this;for(c in a){var i=d.camelCase(c);c!==i&&(a[i]=a[c],delete a[c],c=i);if(a[c]==="hide"&&g||a[c]==="show"&&!g)return b.complete.call(this);if(e&&(c==="height"||c==="width")){b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(d.css(this,"display")==="inline"&&d.css(this,"float")==="none")if(d.support.inlineBlockNeedsLayout){var j=cd(this.nodeName);j==="inline"?this.style.display="inline-block":(this.style.display="inline",this.style.zoom=1)}else this.style.display="inline-block"}d.isArray(a[c])&&((b.specialEasing=b.specialEasing||{})[c]=a[c][1],a[c]=a[c][0])}b.overflow!=null&&(this.style.overflow="hidden"),b.curAnim=d.extend({},a),d.each(a,function(c,e){var f=new d.fx(h,b,c);if(b$.test(e))f[e==="toggle"?g?"show":"hide":e](a);else{var i=b_.exec(e),j=f.cur();if(i){var k=parseFloat(i[2]),l=i[3]||(d.cssNumber[c]?"":"px");l!=="px"&&(d.style(h,c,(k||1)+l),j=(k||1)/f.cur()*j,d.style(h,c,j+l)),i[1]&&(k=(i[1]==="-="?-1:1)*k+j),f.custom(j,k,l)}else f.custom(j,e,"")}});return!0})},stop:function(a,b){var c=d.timers;a&&this.queue([]),this.each(function(){for(var a=c.length-1;a>=0;a--)c[a].elem===this&&(b&&c[a](!0),c.splice(a,1))}),b||this.dequeue();return this}}),d.each({slideDown:cc("show",1),slideUp:cc("hide",1),slideToggle:cc("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){d.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),d.extend({speed:function(a,b,c){var e=a&&typeof a==="object"?d.extend({},a):{complete:c||!c&&b||d.isFunction(a)&&a,duration:a,easing:c&&b||b&&!d.isFunction(b)&&b};e.duration=d.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in d.fx.speeds?d.fx.speeds[e.duration]:d.fx.speeds._default,e.old=e.complete,e.complete=function(){e.queue!==!1&&d(this).dequeue(),d.isFunction(e.old)&&e.old.call(this)};return e},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig||(b.orig={})}}),d.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(d.fx.step[this.prop]||d.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=d.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,b,c){function g(a){return e.step(a)}var e=this,f=d.fx;this.startTime=d.now(),this.start=a,this.end=b,this.unit=c||this.unit||(d.cssNumber[this.prop]?"":"px"),this.now=this.start,this.pos=this.state=0,g.elem=this.elem,g()&&d.timers.push(g)&&!ca&&(ca=setInterval(f.tick,f.interval))},show:function(){this.options.orig[this.prop]=d.style(this.elem,this.prop),this.options.show=!0,this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),d(this.elem).show()},hide:function(){this.options.orig[this.prop]=d.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b=d.now(),c=!0;if(a||b>=this.options.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),this.options.curAnim[this.prop]=!0;for(var e in this.options.curAnim)this.options.curAnim[e]!==!0&&(c=!1);if(c){if(this.options.overflow!=null&&!d.support.shrinkWrapBlocks){var f=this.elem,g=this.options;d.each(["","X","Y"],function(a,b){f.style["overflow"+b]=g.overflow[a]})}this.options.hide&&d(this.elem).hide();if(this.options.hide||this.options.show)for(var h in this.options.curAnim)d.style(this.elem,h,this.options.orig[h]);this.options.complete.call(this.elem)}return!1}var i=b-this.startTime;this.state=i/this.options.duration;var j=this.options.specialEasing&&this.options.specialEasing[this.prop],k=this.options.easing||(d.easing.swing?"swing":"linear");this.pos=d.easing[j||k](this.state,i,0,1,this.options.duration),this.now=this.start+(this.end-this.start)*this.pos,this.update();return!0}},d.extend(d.fx,{tick:function(){var a=d.timers;for(var b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||d.fx.stop()},interval:13,stop:function(){clearInterval(ca),ca=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){d.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit:a.elem[a.prop]=a.now}}}),d.expr&&d.expr.filters&&(d.expr.filters.animated=function(a){return d.grep(d.timers,function(b){return a===b.elem}).length});var ce=/^t(?:able|d|h)$/i,cf=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?d.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){d.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return d.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(e){}var f=b.ownerDocument,g=f.documentElement;if(!c||!d.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=f.body,i=cg(f),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||d.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||d.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:d.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){d.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return d.offset.bodyOffset(b);d.offset.initialize();var c,e=b.offsetParent,f=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(d.offset.supportsFixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===e&&(l+=b.offsetTop,m+=b.offsetLeft,d.offset.doesNotAddBorder&&(!d.offset.doesAddBorderForTableAndCells||!ce.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),f=e,e=b.offsetParent),d.offset.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;d.offset.supportsFixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},d.offset={initialize:function(){var a=c.body,b=c.createElement("div"),e,f,g,h,i=parseFloat(d.css(a,"marginTop"))||0,j="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";d.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"}),b.innerHTML=j,a.insertBefore(b,a.firstChild),e=b.firstChild,f=e.firstChild,h=e.nextSibling.firstChild.firstChild,this.doesNotAddBorder=f.offsetTop!==5,this.doesAddBorderForTableAndCells=h.offsetTop===5,f.style.position="fixed",f.style.top="20px",this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15,f.style.position=f.style.top="",e.style.overflow="hidden",e.style.position="relative",this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5,this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==i,a.removeChild(b),a=b=e=f=g=h=null,d.offset.initialize=d.noop},bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;d.offset.initialize(),d.offset.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(d.css(a,"marginTop"))||0,c+=parseFloat(d.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var e=d.css(a,"position");e==="static"&&(a.style.position="relative");var f=d(a),g=f.offset(),h=d.css(a,"top"),i=d.css(a,"left"),j=e==="absolute"&&d.inArray("auto",[h,i])>-1,k={},l={},m,n;j&&(l=f.position()),m=j?l.top:parseInt(h,10)||0,n=j?l.left:parseInt(i,10)||0,d.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):f.css(k)}},d.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),e=cf.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(d.css(a,"marginTop"))||0,c.left-=parseFloat(d.css(a,"marginLeft"))||0,e.top+=parseFloat(d.css(b[0],"borderTopWidth"))||0,e.left+=parseFloat(d.css(b[0],"borderLeftWidth"))||0;return{top:c.top-e.top,left:c.left-e.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&(!cf.test(a.nodeName)&&d.css(a,"position")==="static"))a=a.offsetParent;return a})}}),d.each(["Left","Top"],function(a,c){var e="scroll"+c;d.fn[e]=function(c){var f=this[0],g;if(!f)return null;if(c!==b)return this.each(function(){g=cg(this),g?g.scrollTo(a?d(g).scrollLeft():c,a?c:d(g).scrollTop()):this[e]=c});g=cg(f);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:d.support.boxModel&&g.document.documentElement[e]||g.document.body[e]:f[e]}}),d.each(["Height","Width"],function(a,c){var e=c.toLowerCase();d.fn["inner"+c]=function(){return this[0]?parseFloat(d.css(this[0],e,"padding")):null},d.fn["outer"+c]=function(a){return this[0]?parseFloat(d.css(this[0],e,a?"margin":"border")):null},d.fn[e]=function(a){var f=this[0];if(!f)return a==null?null:this;if(d.isFunction(a))return this.each(function(b){var c=d(this);c[e](a.call(this,b,c[e]()))});if(d.isWindow(f)){var g=f.document.documentElement["client"+c];return f.document.compatMode==="CSS1Compat"&&g||f.document.body["client"+c]||g}if(f.nodeType===9)return Math.max(f.documentElement["client"+c],f.body["scroll"+c],f.documentElement["scroll"+c],f.body["offset"+c],f.documentElement["offset"+c]);if(a===b){var h=d.css(f,e),i=parseFloat(h);return d.isNaN(i)?h:i}return this.css(e,typeof a==="string"?a:a+"px")}}),a.jQuery=a.$=d})(window);
src/docs/Example.js
eliaslopezgt/ps-react-eli
import React from 'react'; import PropTypes from 'prop-types'; import CodeExample from './CodeExample'; class Example extends React.Component { constructor(props) { super(props); this.state = { showCode: false }; } toggleCode = event => { event.preventDefault(); this.setState(prevState => { return {showCode: !prevState.showCode}; }); } render() { const {showCode} = this.state; const {code, description, name} = this.props.example; // Must use CommonJS require to dynamically require because ES Modules must be statically analyzable. const ExampleComponent = require(`./examples/${this.props.componentName}/${name}`).default; return ( <div className="example"> {description && <h4>{description}</h4> } <ExampleComponent /> <p> <a href="" onClick={this.toggleCode}> {showCode ? 'Hide' : 'Show'} Code </a> </p> {showCode && <CodeExample>{code}</CodeExample>} </div> ); } } Example.propTypes = { example: PropTypes.object.isRequired, componentName: PropTypes.string.isRequired }; export default Example;
app/components/SideBar.js
thenormalsquid/electronApp
// @flow import React from 'react'; import { compose, pure } from 'recompose'; import { Link } from 'react-router-dom'; import styles from './SideBar.css'; type WrappedProps = { }; type Props = { filters: Array; } & WrappedProps; // this component is used in routes.js export const SideBar = (props: Props) => <div className={styles.container}> <ul> {props.filters.map((route, i) => { return ( <li key={i}><Link to={`/filters/${i}`}>{route.name}</Link></li> ); })} </ul> </div>; const enhance = compose( pure ); export default enhance(SideBar);
app/javascript/mastodon/features/hashtag_timeline/index.js
abcang/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import StatusListContainer from '../ui/containers/status_list_container'; import Column from '../../components/column'; import ColumnHeader from '../../components/column_header'; import ColumnSettingsContainer from './containers/column_settings_container'; import { expandHashtagTimeline, clearTimeline } from '../../actions/timelines'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import { FormattedMessage } from 'react-intl'; import { connectHashtagStream } from '../../actions/streaming'; import { isEqual } from 'lodash'; const mapStateToProps = (state, props) => ({ hasUnread: state.getIn(['timelines', `hashtag:${props.params.id}${props.params.local ? ':local' : ''}`, 'unread']) > 0, }); export default @connect(mapStateToProps) class HashtagTimeline extends React.PureComponent { disconnects = []; static propTypes = { params: PropTypes.object.isRequired, columnId: PropTypes.string, dispatch: PropTypes.func.isRequired, hasUnread: PropTypes.bool, multiColumn: PropTypes.bool, }; handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('HASHTAG', { id: this.props.params.id })); } } title = () => { let title = [this.props.params.id]; if (this.additionalFor('any')) { title.push(' ', <FormattedMessage key='any' id='hashtag.column_header.tag_mode.any' values={{ additional: this.additionalFor('any') }} defaultMessage='or {additional}' />); } if (this.additionalFor('all')) { title.push(' ', <FormattedMessage key='all' id='hashtag.column_header.tag_mode.all' values={{ additional: this.additionalFor('all') }} defaultMessage='and {additional}' />); } if (this.additionalFor('none')) { title.push(' ', <FormattedMessage key='none' id='hashtag.column_header.tag_mode.none' values={{ additional: this.additionalFor('none') }} defaultMessage='without {additional}' />); } return title; } additionalFor = (mode) => { const { tags } = this.props.params; if (tags && (tags[mode] || []).length > 0) { return tags[mode].map(tag => tag.value).join('/'); } else { return ''; } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } _subscribe (dispatch, id, tags = {}, local) { let any = (tags.any || []).map(tag => tag.value); let all = (tags.all || []).map(tag => tag.value); let none = (tags.none || []).map(tag => tag.value); [id, ...any].map(tag => { this.disconnects.push(dispatch(connectHashtagStream(id, tag, local, status => { let tags = status.tags.map(tag => tag.name); return all.filter(tag => tags.includes(tag)).length === all.length && none.filter(tag => tags.includes(tag)).length === 0; }))); }); } _unsubscribe () { this.disconnects.map(disconnect => disconnect()); this.disconnects = []; } componentDidMount () { const { dispatch } = this.props; const { id, tags, local } = this.props.params; this._subscribe(dispatch, id, tags, local); dispatch(expandHashtagTimeline(id, { tags, local })); } componentWillReceiveProps (nextProps) { const { dispatch, params } = this.props; const { id, tags, local } = nextProps.params; if (id !== params.id || !isEqual(tags, params.tags) || !isEqual(local, params.local)) { this._unsubscribe(); this._subscribe(dispatch, id, tags, local); dispatch(clearTimeline(`hashtag:${id}${local ? ':local' : ''}`)); dispatch(expandHashtagTimeline(id, { tags, local })); } } componentWillUnmount () { this._unsubscribe(); } setRef = c => { this.column = c; } handleLoadMore = maxId => { const { id, tags, local } = this.props.params; this.props.dispatch(expandHashtagTimeline(id, { maxId, tags, local })); } render () { const { hasUnread, columnId, multiColumn } = this.props; const { id, local } = this.props.params; const pinned = !!columnId; return ( <Column bindToDocument={!multiColumn} ref={this.setRef} label={`#${id}`}> <ColumnHeader icon='hashtag' active={hasUnread} title={this.title()} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} showBackButton > {columnId && <ColumnSettingsContainer columnId={columnId} />} </ColumnHeader> <StatusListContainer trackScroll={!pinned} scrollKey={`hashtag_timeline-${columnId}`} timelineId={`hashtag:${id}${local ? ':local' : ''}`} onLoadMore={this.handleLoadMore} emptyMessage={<FormattedMessage id='empty_column.hashtag' defaultMessage='There is nothing in this hashtag yet.' />} bindToDocument={!multiColumn} /> </Column> ); } }
docs/app/Examples/elements/Loader/Variations/LoaderExampleInlineCentered.js
shengnian/shengnian-ui-react
import React from 'react' import { Loader } from 'shengnian-ui-react' const LoaderExampleInlineCentered = () => ( <Loader active inline='centered' /> ) export default LoaderExampleInlineCentered
src/DropdownMenu.js
wjb12/react-bootstrap
import React from 'react'; import keycode from 'keycode'; import classNames from 'classnames'; import RootCloseWrapper from 'react-overlays/lib/RootCloseWrapper'; import ValidComponentChildren from './utils/ValidComponentChildren'; import createChainedFunction from './utils/createChainedFunction'; class DropdownMenu extends React.Component { constructor(props) { super(props); this.focusNext = this.focusNext.bind(this); this.focusPrevious = this.focusPrevious.bind(this); this.getFocusableMenuItems = this.getFocusableMenuItems.bind(this); this.getItemsAndActiveIndex = this.getItemsAndActiveIndex.bind(this); this.handleKeyDown = this.handleKeyDown.bind(this); } handleKeyDown(event) { switch (event.keyCode) { case keycode.codes.down: this.focusNext(); event.preventDefault(); break; case keycode.codes.up: this.focusPrevious(); event.preventDefault(); break; case keycode.codes.esc: case keycode.codes.tab: this.props.onClose(event); break; default: } } focusNext() { let { items, activeItemIndex } = this.getItemsAndActiveIndex(); if (items.length === 0) { return; } if (activeItemIndex === items.length - 1) { items[0].focus(); return; } items[activeItemIndex + 1].focus(); } focusPrevious() { let { items, activeItemIndex } = this.getItemsAndActiveIndex(); if (activeItemIndex === 0) { items[items.length - 1].focus(); return; } items[activeItemIndex - 1].focus(); } getItemsAndActiveIndex() { let items = this.getFocusableMenuItems(); let activeElement = document.activeElement; let activeItemIndex = items.indexOf(activeElement); return {items, activeItemIndex}; } getFocusableMenuItems() { let menuNode = React.findDOMNode(this); if (menuNode === undefined) { return []; } return [].slice.call(menuNode.querySelectorAll('[tabIndex="-1"]'), 0); } render() { let {children, onSelect, pullRight, className, labelledBy, open, onClose, ...props} = this.props; const items = ValidComponentChildren.map(children, child => { let childProps = child.props || {}; return React.cloneElement(child, { onKeyDown: createChainedFunction(childProps.onKeyDown, this.handleKeyDown), onSelect: createChainedFunction(childProps.onSelect, onSelect) }, childProps.children); }); const classes = { 'dropdown-menu': true, 'dropdown-menu-right': pullRight }; let list = ( <ul className={classNames(className, classes)} role="menu" aria-labelledby={labelledBy} {...props} > {items} </ul> ); if (open) { list = ( <RootCloseWrapper noWrap onRootClose={onClose}> {list} </RootCloseWrapper> ); } return list; } } DropdownMenu.defaultProps = { bsRole: 'menu', pullRight: false }; DropdownMenu.propTypes = { open: React.PropTypes.bool, pullRight: React.PropTypes.bool, onClose: React.PropTypes.func, labelledBy: React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number ]), onSelect: React.PropTypes.func }; export default DropdownMenu;
packages/material-ui-icons/src/LoyaltyRounded.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M21.41 11.58l-9-9C12.05 2.22 11.55 2 11 2H4c-1.1 0-2 .9-2 2v7c0 .55.22 1.05.59 1.42l9 9c.36.36.86.58 1.41.58s1.05-.22 1.41-.59l7-7c.37-.36.59-.86.59-1.41s-.23-1.06-.59-1.42zM5.5 7C4.67 7 4 6.33 4 5.5S4.67 4 5.5 4 7 4.67 7 5.5 6.33 7 5.5 7zm11.77 8.27l-3.92 3.92c-.2.2-.51.2-.71 0l-3.92-3.92c-.57-.58-.87-1.43-.67-2.34.19-.88.89-1.61 1.76-1.84.94-.25 1.85.04 2.44.65l.75.72.73-.73c.45-.45 1.08-.73 1.77-.73 1.38 0 2.5 1.12 2.5 2.5 0 .69-.28 1.32-.73 1.77z" /> , 'LoyaltyRounded');
react/gameday2/components/embeds/EmbedTwitch.js
phil-lopreiato/the-blue-alliance
import React from 'react' import { webcastPropType } from '../../utils/webcastUtils' const EmbedTwitch = (props) => { const channel = props.webcast.channel const iframeSrc = `https://player.twitch.tv/?channel=${channel}` return ( <iframe src={iframeSrc} frameBorder="0" scrolling="no" height="100%" width="100%" allowFullScreen /> ) } EmbedTwitch.propTypes = { webcast: webcastPropType.isRequired, } export default EmbedTwitch
ajax/libs/yui/3.17.2/event-focus/event-focus-debug.js
chinakids/cdnjs
/* YUI 3.17.2 (build 9c3c78e) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('event-focus', function (Y, NAME) { /** * Adds bubbling and delegation support to DOM events focus and blur. * * @module event * @submodule event-focus */ var Event = Y.Event, YLang = Y.Lang, isString = YLang.isString, arrayIndex = Y.Array.indexOf, useActivate = (function() { // Changing the structure of this test, so that it doesn't use inline JS in HTML, // which throws an exception in Win8 packaged apps, due to additional security restrictions: // http://msdn.microsoft.com/en-us/library/windows/apps/hh465380.aspx#differences var supported = false, doc = Y.config.doc, p; if (doc) { p = doc.createElement("p"); p.setAttribute("onbeforeactivate", ";"); // onbeforeactivate is a function in IE8+. // onbeforeactivate is a string in IE6,7 (unfortunate, otherwise we could have just checked for function below). // onbeforeactivate is a function in IE10, in a Win8 App environment (no exception running the test). // onbeforeactivate is undefined in Webkit/Gecko. // onbeforeactivate is a function in Webkit/Gecko if it's a supported event (e.g. onclick). supported = (p.onbeforeactivate !== undefined); } return supported; }()); function define(type, proxy, directEvent) { var nodeDataKey = '_' + type + 'Notifiers'; Y.Event.define(type, { _useActivate : useActivate, _attach: function (el, notifier, delegate) { if (Y.DOM.isWindow(el)) { return Event._attach([type, function (e) { notifier.fire(e); }, el]); } else { return Event._attach( [proxy, this._proxy, el, this, notifier, delegate], { capture: true }); } }, _proxy: function (e, notifier, delegate) { var target = e.target, currentTarget = e.currentTarget, notifiers = target.getData(nodeDataKey), yuid = Y.stamp(currentTarget._node), defer = (useActivate || target !== currentTarget), directSub; notifier.currentTarget = (delegate) ? target : currentTarget; notifier.container = (delegate) ? currentTarget : null; // Maintain a list to handle subscriptions from nested // containers div#a>div#b>input #a.on(focus..) #b.on(focus..), // use one focus or blur subscription that fires notifiers from // #b then #a to emulate bubble sequence. if (!notifiers) { notifiers = {}; target.setData(nodeDataKey, notifiers); // only subscribe to the element's focus if the target is // not the current target ( if (defer) { directSub = Event._attach( [directEvent, this._notify, target._node]).sub; directSub.once = true; } } else { // In old IE, defer is always true. In capture-phase browsers, // The delegate subscriptions will be encountered first, which // will establish the notifiers data and direct subscription // on the node. If there is also a direct subscription to the // node's focus/blur, it should not call _notify because the // direct subscription from the delegate sub(s) exists, which // will call _notify. So this avoids _notify being called // twice, unnecessarily. defer = true; } if (!notifiers[yuid]) { notifiers[yuid] = []; } notifiers[yuid].push(notifier); if (!defer) { this._notify(e); } }, _notify: function (e, container) { var currentTarget = e.currentTarget, notifierData = currentTarget.getData(nodeDataKey), axisNodes = currentTarget.ancestors(), doc = currentTarget.get('ownerDocument'), delegates = [], // Used to escape loops when there are no more // notifiers to consider count = notifierData ? Y.Object.keys(notifierData).length : 0, target, notifiers, notifier, yuid, match, tmp, i, len, sub, ret; // clear the notifications list (mainly for delegation) currentTarget.clearData(nodeDataKey); // Order the delegate subs by their placement in the parent axis axisNodes.push(currentTarget); // document.get('ownerDocument') returns null // which we'll use to prevent having duplicate Nodes in the list if (doc) { axisNodes.unshift(doc); } // ancestors() returns the Nodes from top to bottom axisNodes._nodes.reverse(); if (count) { // Store the count for step 2 tmp = count; axisNodes.some(function (node) { var yuid = Y.stamp(node), notifiers = notifierData[yuid], i, len; if (notifiers) { count--; for (i = 0, len = notifiers.length; i < len; ++i) { if (notifiers[i].handle.sub.filter) { delegates.push(notifiers[i]); } } } return !count; }); count = tmp; } // Walk up the parent axis, notifying direct subscriptions and // testing delegate filters. while (count && (target = axisNodes.shift())) { yuid = Y.stamp(target); notifiers = notifierData[yuid]; if (notifiers) { for (i = 0, len = notifiers.length; i < len; ++i) { notifier = notifiers[i]; sub = notifier.handle.sub; match = true; e.currentTarget = target; if (sub.filter) { match = sub.filter.apply(target, [target, e].concat(sub.args || [])); // No longer necessary to test against this // delegate subscription for the nodes along // the parent axis. delegates.splice( arrayIndex(delegates, notifier), 1); } if (match) { // undefined for direct subs e.container = notifier.container; ret = notifier.fire(e); } if (ret === false || e.stopped === 2) { break; } } delete notifiers[yuid]; count--; } if (e.stopped !== 2) { // delegates come after subs targeting this specific node // because they would not normally report until they'd // bubbled to the container node. for (i = 0, len = delegates.length; i < len; ++i) { notifier = delegates[i]; sub = notifier.handle.sub; if (sub.filter.apply(target, [target, e].concat(sub.args || []))) { e.container = notifier.container; e.currentTarget = target; ret = notifier.fire(e); } if (ret === false || e.stopped === 2 || // If e.stopPropagation() is called, notify any // delegate subs from the same container, but break // once the container changes. This emulates // delegate() behavior for events like 'click' which // won't notify delegates higher up the parent axis. (e.stopped && delegates[i+1] && delegates[i+1].container !== notifier.container)) { break; } } } if (e.stopped) { break; } } }, on: function (node, sub, notifier) { sub.handle = this._attach(node._node, notifier); }, detach: function (node, sub) { sub.handle.detach(); }, delegate: function (node, sub, notifier, filter) { if (isString(filter)) { sub.filter = function (target) { return Y.Selector.test(target._node, filter, node === target ? null : node._node); }; } sub.handle = this._attach(node._node, notifier, true); }, detachDelegate: function (node, sub) { sub.handle.detach(); } }, true); } // For IE, we need to defer to focusin rather than focus because // `el.focus(); doSomething();` executes el.onbeforeactivate, el.onactivate, // el.onfocusin, doSomething, then el.onfocus. All others support capture // phase focus, which executes before doSomething. To guarantee consistent // behavior for this use case, IE's direct subscriptions are made against // focusin so subscribers will be notified before js following el.focus() is // executed. if (useActivate) { // name capture phase direct subscription define("focus", "beforeactivate", "focusin"); define("blur", "beforedeactivate", "focusout"); } else { define("focus", "focus", "focus"); define("blur", "blur", "blur"); } }, '3.17.2', {"requires": ["event-synthetic"]});
src/js/components/Menu.js
odedre/grommet-final
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { findDOMNode } from 'react-dom'; import classnames from 'classnames'; import KeyboardAccelerators from '../utils/KeyboardAccelerators'; import { filterByFocusable } from '../utils/DOM'; import Drop, { dropAlignPropType } from '../utils/Drop'; import Intl from '../utils/Intl'; import Props from '../utils/Props'; import Responsive from '../utils/Responsive'; import Box from './Box'; import Button from './Button'; import DropCaretIcon from './icons/base/Down'; import MoreIcon from './icons/base/More'; import CSSClassnames from '../utils/CSSClassnames'; const CLASS_ROOT = CSSClassnames.MENU; function isFunction (obj) { return obj && obj.constructor && obj.call && obj.apply; } // We have a separate module for the drop component // so we can transfer the router context. /** * @description Presents a list of choices responsively. A Menu can either present the list of choices inline or within a drop down behind a control that opens it. * * Properties for Box are also available. * * @example * import Menu from 'grommet/components/Menu'; * * <Menu responsive={true} * icon={<Actions />} * label='Label' * inline={true} * primary={true}> * <Anchor href='#' * className='active'> * First action * </Anchor> * <Anchor href='#'> * Second action * </Anchor> * <Anchor href='#'> * Third action * </Anchor> * </Menu> * * */ class MenuDrop extends Component { constructor(props, context) { super(props, context); this._onUpKeyPress = this._onUpKeyPress.bind(this); this._onDownKeyPress = this._onDownKeyPress.bind(this); this._processTab = this._processTab.bind(this); } getChildContext () { return { intl: this.props.intl, history: this.props.history, router: this.props.router, store: this.props.store }; } componentDidMount () { this._originalFocusedElement = document.activeElement; this._keyboardHandlers = { tab: this._processTab, up: this._onUpKeyPress, left: this._onUpKeyPress, down: this._onDownKeyPress, right: this._onDownKeyPress }; KeyboardAccelerators.startListeningToKeyboard(this, this._keyboardHandlers); } componentWillUnmount () { if (this._originalFocusedElement.focus) { this._originalFocusedElement.focus(); } else if (this._originalFocusedElement.parentNode && this._originalFocusedElement.parentNode.focus) { // required for IE11 and Edge this._originalFocusedElement.parentNode.focus(); } KeyboardAccelerators.stopListeningToKeyboard(this, this._keyboardHandlers); } _processTab (event) { let container = findDOMNode(this.menuDropRef); let items = container.getElementsByTagName('*'); items = filterByFocusable(items); if (!items || items.length === 0) { event.preventDefault(); } else { if (event.shiftKey) { if (event.target === items[0]) { items[items.length - 1].focus(); event.preventDefault(); } } else if (event.target === items[items.length - 1]) { items[0].focus(); event.preventDefault(); } } } _onUpKeyPress (event) { event.preventDefault(); const container = findDOMNode(this.navContainerRef); let menuItems = container.childNodes; if (!this.activeMenuItem) { let lastMenuItem = menuItems[menuItems.length - 1]; this.activeMenuItem = lastMenuItem; } else if (this.activeMenuItem.previousSibling) { this.activeMenuItem = this.activeMenuItem.previousSibling; } let classes = this.activeMenuItem.className.split(/\s+/); let tagName = this.activeMenuItem.tagName.toLowerCase(); // want to skip items of the menu that are not focusable. if (tagName !== 'button' && tagName !== 'a' && classes.indexOf('check-box') === -1) { if (this.activeMenuItem === menuItems[0]) { return true; } else { // If this item is not focusable, check the next item. return this._onUpKeyPress(event); } } this.activeMenuItem.focus(); // Stops KeyboardAccelerators from calling the other listeners. // Works limilar to event.stopPropagation(). return true; } _onDownKeyPress (event) { event.preventDefault(); const container = findDOMNode(this.navContainerRef); let menuItems = container.childNodes; if (!this.activeMenuItem) { this.activeMenuItem = menuItems[0]; } else if (this.activeMenuItem.nextSibling) { this.activeMenuItem = this.activeMenuItem.nextSibling; } let classes = this.activeMenuItem.className.split(/\s+/); let tagName = this.activeMenuItem.tagName.toLowerCase(); // want to skip items of the menu that are not focusable. if (tagName !== 'button' && tagName !== 'a' && classes.indexOf('check-box') === -1) { if (this.activeMenuItem === menuItems[menuItems.length - 1]) { return true; } else { // If this item is not focusable, check the next item. return this._onDownKeyPress(event); } } this.activeMenuItem.focus(); // Stops KeyboardAccelerators from calling the other listeners. // Works limilar to event.stopPropagation(). return true; } render () { const { dropAlign, size, children, control, colorIndex, onClick, ...props } = this.props; const restProps = Props.omit(props, [ ...Object.keys(MenuDrop.childContextTypes), ...Object.keys(MenuDrop.propTypes) ]); // Put nested Menus inline const menuDropChildren = React.Children.map(children, child => { let result = child; if (child && isFunction(child.type) && child.type.prototype._renderMenuDrop) { result = React.cloneElement(child, { inline: 'expanded', direction: 'column' }); } return result; }); let contents = [ React.cloneElement(control, {key: 'control', fill: true}), <Box {...restProps} key="nav" ref={ref => this.navContainerRef = ref} tag="nav" className={`${CLASS_ROOT}__contents`} primary={false}> {menuDropChildren} </Box> ]; if (dropAlign.bottom) { contents.reverse(); } let classes = classnames( `${CLASS_ROOT}__drop`, { [`${CLASS_ROOT}__drop--align-right`]: dropAlign.right, [`${CLASS_ROOT}__drop--${size}`]: size } ); return ( <Box ref={ref => this.menuDropRef = ref} className={classes} colorIndex={colorIndex} onClick={onClick} focusable={false}> {contents} </Box> ); } } MenuDrop.propTypes = { control: PropTypes.node, dropAlign: dropAlignPropType, dropColorIndex: PropTypes.string, onClick: PropTypes.func.isRequired, router: PropTypes.any, size: PropTypes.oneOf(['small', 'medium', 'large']), store: PropTypes.any, ...Box.propTypes }; MenuDrop.childContextTypes = { history: PropTypes.any, intl: PropTypes.any, router: PropTypes.any, store: PropTypes.any }; export default class Menu extends Component { constructor(props, context) { super(props, context); this._onOpen = this._onOpen.bind(this); this._onClose = this._onClose.bind(this); this._checkOnClose = this._checkOnClose.bind(this); this._onSink = this._onSink.bind(this); this._onResponsive = this._onResponsive.bind(this); this._onFocusControl = this._onFocusControl.bind(this); this._onBlurControl = this._onBlurControl.bind(this); let inline; if (props.hasOwnProperty('inline')) { inline = props.inline; } else { inline = (! props.label && ! props.icon); } let responsive; if (props.hasOwnProperty('responsive')) { responsive = props.responsive; } else { responsive = (inline && 'row' === props.direction); } this.state = { // state may be 'collapsed', 'focused' or 'expanded' (active). state: 'collapsed', initialInline: inline, inline: inline, responsive: responsive }; } componentDidMount () { if (this.state.responsive) { this._responsive = Responsive.start(this._onResponsive); } } componentWillReceiveProps (nextProps) { if (this.props.inline !== nextProps.inline || this.props.icon !== nextProps.icon) { this.setState({ inline: nextProps.hasOwnProperty('inline') ? nextProps.inline : (!nextProps.label && !nextProps.icon) }); } } componentDidUpdate (prevProps, prevState) { if (this.state.state !== prevState.state) { let activeKeyboardHandlers = { esc: this._onClose }; let focusedKeyboardHandlers = { space: this._onOpen, down: this._onOpen, enter: this._onOpen }; switch (this.state.state) { case 'collapsed': KeyboardAccelerators.stopListeningToKeyboard( this, focusedKeyboardHandlers ); KeyboardAccelerators.stopListeningToKeyboard( this, activeKeyboardHandlers ); document.removeEventListener('click', this._checkOnClose); document.removeEventListener('touchstart', this._checkOnClose); if (this._drop) { this._drop.remove(); this._drop = undefined; } break; case 'focused': KeyboardAccelerators.stopListeningToKeyboard( this, activeKeyboardHandlers ); KeyboardAccelerators.startListeningToKeyboard( this, focusedKeyboardHandlers ); break; case 'expanded': // only add the drop again if the instance is not defined // see https://github.com/grommet/grommet/issues/1431 if (!this._drop) { KeyboardAccelerators.stopListeningToKeyboard( this, focusedKeyboardHandlers ); KeyboardAccelerators.startListeningToKeyboard( this, activeKeyboardHandlers ); document.addEventListener('click', this._checkOnClose); document.addEventListener('touchstart', this._checkOnClose); this._drop = new Drop(findDOMNode(this._controlRef), this._renderMenuDrop(), { align: this.props.dropAlign, colorIndex: this.props.dropColorIndex, focusControl: true }); } break; } } else if (this.state.state === 'expanded') { this._drop.render(this._renderMenuDrop()); } } componentWillUnmount () { document.removeEventListener('click', this._checkOnClose); document.removeEventListener('touchstart', this._checkOnClose); KeyboardAccelerators.stopListeningToKeyboard(this); if (this._drop) { this._drop.remove(); } if (this._responsive) { this._responsive.stop(); } } _onOpen () { if(findDOMNode(this._controlRef).contains(document.activeElement)) { this.setState({state: 'expanded'}); } } _onClose () { this.setState({state: 'collapsed'}); } _checkOnClose (event) { const drop = findDOMNode(this._menuDrop); const control = findDOMNode(this._controlRef); if (drop && !drop.contains(event.target) && !control.contains(event.target)) { this._onClose(); } } _onSink (event) { event.stopPropagation(); // need to go native to prevent closing via document event.nativeEvent.stopImmediatePropagation(); } _onResponsive (small) { // deactivate if we change resolutions let newState = this.state.state; if (this.state.state === 'expanded') { newState = 'focused'; } if (small) { this.setState({inline: false, active: newState, controlCollapsed: true}); } else { this.setState({ inline: this.state.initialInline, active: newState, state: 'collapsed', controlCollapsed: false }); } } _onFocusControl () { if (this.state.state !== 'focused') { this.setState({state: 'focused'}); } } _onBlurControl () { if (this.state.state === 'focused') { this.setState({state: 'collapsed'}); } } _renderButtonProps () { const { icon, label } = this.props; // Use default icon if no label or icon is provided if (!label && !icon) { return { icon: <MoreIcon /> }; } // Return provided label(if any) and provided icon, or default // to DropCaretIcon return { label, icon: icon || <DropCaretIcon a11yTitle='menu-down' /> }; } _renderMenuDrop () { let closeLabel = Intl.getMessage(this.context.intl, 'Close'); let menuLabel = Intl.getMessage(this.context.intl, 'Menu'); let menuTitle = ( `${closeLabel} ${this.props.a11yTitle || this.props.label || ''} ` + `${menuLabel}` ); let control = ( <Button className={`${CLASS_ROOT}__control`} plain={true} a11yTitle={menuTitle} reverse={true} {...this._renderButtonProps()} onClick={this._onClose} /> ); let boxProps = Props.pick(this.props, Object.keys(Box.propTypes)); let onClick = this.props.closeOnClick ? this._onClose : this._onSink; return ( <MenuDrop {...boxProps} {...this.context} dropAlign={this.props.dropAlign} size={this.props.size} onClick={onClick} control={control} ref={(ref) => this._menuDrop = ref}> {this.props.children} </MenuDrop> ); } render () { const { a11yTitle, children, className, direction, fill, label, primary, size, pad, ...props } = this.props; delete props.closeOnClick; delete props.dropColorIndex; delete props.dropAlign; delete props.icon; delete props.inline; const { inline } = this.state; const classes = classnames( CLASS_ROOT, { [`${CLASS_ROOT}--${direction}`]: direction, [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--primary`]: primary, [`${CLASS_ROOT}--inline`]: inline, [`${CLASS_ROOT}--controlled`]: !inline, [`${CLASS_ROOT}__control`]: !inline, [`${CLASS_ROOT}--labelled`]: !inline && label, [`${CLASS_ROOT}--fill`]: fill }, className ); if (inline) { let menuLabel; if ('expanded' === inline) { menuLabel = ( <div className={`${CLASS_ROOT}__label`}> {label} </div> ); } return ( <Box {...props} pad={pad} direction={direction} tag="nav" className={classes} primary={false}> {menuLabel} {children} </Box> ); } else { const openLabel = Intl.getMessage(this.context.intl, 'Open'); const menuLabel = Intl.getMessage(this.context.intl, 'Menu'); const menuTitle = ( `${openLabel} ${a11yTitle || label || ''} ` + `${menuLabel}` ); return ( <Box ref={ref => this._controlRef = ref} {...props} className={classes}> <Button plain={true} reverse={true} a11yTitle={menuTitle} {...this._renderButtonProps()} onClick={() => this.setState({state: 'expanded'})} onFocus={this._onFocusControl} onBlur={this._onBlurControl} /> </Box> ); } } } Menu.propTypes = { /** * @property {PropTypes.bool} closeOnClick - Indicates whether the opened menu drop down should close when clicked. Defaults to true. */ closeOnClick: PropTypes.bool, /** * @property {PropTypes.custom} dropAlign - Where to place the drop down. The keys correspond to a side of the drop down. The values correspond to a side of the control. For instance, {left: 'left', top: 'bottom'} would align the left edges and the top of the drop down to the bottom of the control. At most one of left or right and one of top or bottom should be specified. */ dropAlign: dropAlignPropType, dropColorIndex: PropTypes.string, /** * @property {PropTypes.node} icon - Indicates that the menu should be collapsed and the icon shown as a control top open it. */ icon: PropTypes.node, id: PropTypes.string, /** * @property {[PropTypes.bool,expand]} inline - Indicates whether the menu should be shown inline or a control shown to open it in a drop down. If false, the specified label or icon will be shown, if neither are specified, a default icon will be shown. */ inline: PropTypes.oneOfType([PropTypes.bool, PropTypes.oneOf(['expand'])]), /** * @property {PropTypes.bool} fill - Indicates whether an inline menu should take up the available space of its parent container or not. Defaults to false. */ fill: PropTypes.bool, /** * @property {PropTypes.string} label - Indicates that the menu should be collapsed and the label shown as a control top open it. */ label: PropTypes.string, /** * @property {['small', 'medium', 'large']} size - The size of the Menu. Defaults to medium. */ size: PropTypes.oneOf(['small', 'medium', 'large']), ...Box.propTypes }; Menu.contextTypes = { history: PropTypes.any, intl: PropTypes.any, router: PropTypes.any, store: PropTypes.any }; Menu.defaultProps = { closeOnClick: true, direction: 'column', dropAlign: {top: 'top', left: 'left'}, pad: 'none' };
analysis/rogueoutlaw/src/modules/spells/RollTheBonesEfficiency.js
yajinni/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import { SpellLink } from 'interface'; import { formatPercentage } from 'common/format'; import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer'; import { t } from '@lingui/macro'; import Events from 'parser/core/Events'; import RollTheBonesCastTracker, { ROLL_THE_BONES_CATEGORIES } from '../features/RollTheBonesCastTracker'; const MID_TIER_REFRESH_TIME = 11000; const HIGH_TIER_REFRESH_TIME = 3000; /** * Roll the Bones is pretty complex with a number of rules around when to use it. I've done my best to break this down into four main suggestions * Ruthless Precision and Grand Melee are the two 'good' buffs. The other four are 'bad' buffs * * 1 - Uptime (handled in separate module, as close to 100% as possible) * 2 - Low value rolls (1 'bad' buff, reroll as soon as you can) * 3 - Mid value rolls (2 'bad' buffs, reroll at the pandemic window) * 4 - High value rolls (1 'good' buff, 2 buffs where at least one is a 'good' buff, or 5 buffs, keep as long as you can, rerolling under 3 seconds is considered fine) */ class RollTheBonesEfficiency extends Analyzer { get goodLowValueRolls() { const delayedRolls = this.rollTheBonesCastTracker.rolltheBonesCastValues[ROLL_THE_BONES_CATEGORIES.LOW_VALUE] .filter(cast => cast.RTBIsDelayed).length; const totalRolls = this.rollTheBonesCastTracker.rolltheBonesCastValues[ROLL_THE_BONES_CATEGORIES.LOW_VALUE].length; return totalRolls - delayedRolls; } get goodMidValueRolls() { // todo get the actual pandemic window. it's tricky because it's based on the next cast, and it's not really important that the player is exact anyway return this.rollTheBonesCastTracker.rolltheBonesCastValues[ROLL_THE_BONES_CATEGORIES.MID_VALUE] .filter(cast => this.rollTheBonesCastTracker.castRemainingDuration(cast) > HIGH_TIER_REFRESH_TIME && this.rollTheBonesCastTracker.castRemainingDuration(cast) < MID_TIER_REFRESH_TIME).length; } get goodHighValueRolls() { return this.rollTheBonesCastTracker.rolltheBonesCastValues[ROLL_THE_BONES_CATEGORIES.HIGH_VALUE] .filter(cast => this.rollTheBonesCastTracker.castRemainingDuration(cast) <= HIGH_TIER_REFRESH_TIME).length; } get rollSuggestions() { const rtbCastValues = this.rollTheBonesCastTracker.rolltheBonesCastValues; return [ // Percentage of low rolls that weren't rerolled right away, meaning a different finisher was cast first // Inverted to make all three suggestions consistent { label: 'low value', pass: this.goodLowValueRolls, total: rtbCastValues[ROLL_THE_BONES_CATEGORIES.LOW_VALUE].length, extraSuggestion: <>If you roll a single buff and it's not one of the two highest value, try to reroll it as soon as you can.</>, suggestionThresholds: this.rollSuggestionThreshold(this.goodLowValueRolls, rtbCastValues[ROLL_THE_BONES_CATEGORIES.LOW_VALUE].length), }, // Percentage of mid rolls that were rerolled at or below pandemic, but above 3 seconds { label: 'mid value', pass: this.goodMidValueRolls, total: rtbCastValues[ROLL_THE_BONES_CATEGORIES.MID_VALUE].length, extraSuggestion: <>If you roll two buffs and neither is one of the two highest value, try to reroll them once you reach the pandemic window, at about 9-10 seconds remaining.</>, suggestionThresholds: this.rollSuggestionThreshold(this.goodMidValueRolls, rtbCastValues[ROLL_THE_BONES_CATEGORIES.MID_VALUE].length), }, // Percentage of good rolls that were rerolled below 3 seconds { label: 'high value', pass: this.goodHighValueRolls, total: rtbCastValues[ROLL_THE_BONES_CATEGORIES.HIGH_VALUE].length, extraSuggestion: <>If you ever roll one of the two highest value buffs (especially with a 5 buff roll!), try to leave the buff active as long as possible, refreshing with less than 3 seconds remaining.</>, suggestionThresholds: this.rollSuggestionThreshold(this.goodHighValueRolls, rtbCastValues[ROLL_THE_BONES_CATEGORIES.HIGH_VALUE].length), }, ]; } static dependencies = { rollTheBonesCastTracker: RollTheBonesCastTracker, }; constructor(...args) { super(...args); this.active = !this.selectedCombatant.hasTalent(SPELLS.SLICE_AND_DICE.id); this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell([SPELLS.DISPATCH, SPELLS.BETWEEN_THE_EYES]), this.onCast); } onCast(event) { if (event.ability.guid !== SPELLS.DISPATCH.id && event.ability.guid !== SPELLS.BETWEEN_THE_EYES.id) { return; } const lastCast = this.rollTheBonesCastTracker.lastCast; if (lastCast && this.rollTheBonesCastTracker.categorizeCast(lastCast) === ROLL_THE_BONES_CATEGORIES.LOW_VALUE) { //FIX WHEN UPDATING ROGUE TO TS lastCast.RTBIsDelayed = true; } } rollSuggestionThreshold(pass, total) { return { actual: total === 0 ? 1 : pass / total, isLessThan: { minor: 1, average: 0.9, major: 0.8, }, style: 'percentage', }; } suggestions(when) { this.rollSuggestions.forEach(suggestion => { when(suggestion.suggestionThresholds).addSuggestion((suggest, actual, recommended) => suggest(<>Your efficiency with refreshing <SpellLink id={SPELLS.ROLL_THE_BONES.id} /> after a {suggestion.label} roll could be improved. <SpellLink id={SPELLS.RUTHLESS_PRECISION.id} /> and <SpellLink id={SPELLS.GRAND_MELEE.id} /> are your highest value buffs from <SpellLink id={SPELLS.ROLL_THE_BONES.id} />. {suggestion.extraSuggestion || ''}</>) .icon(SPELLS.ROLL_THE_BONES.icon) .actual(t({ id: "rogue.outlaw.suggestions.rollTheBones.efficiency", message: `${formatPercentage(actual)}% (${suggestion.pass} out of ${suggestion.total}) efficient rerolls` })) .recommended(`${formatPercentage(recommended)}% is recommended`)); }); } } export default RollTheBonesEfficiency;
src/js/components/Menu/stories/BottomControlButton.js
grommet/grommet
import React from 'react'; import { Box, Menu } from 'grommet'; const ControlBottomMenu = () => ( <Box height="medium" justify="center" align="center" pad="large"> <Menu dropProps={{ align: { bottom: 'bottom', left: 'left' } }} label="actions" items={[ { label: 'Profile', onClick: () => {} }, { label: 'Settings', onClick: () => {} }, { label: 'FAQ', onClick: () => {} }, ]} /> </Box> ); export const BottomControlButton = () => <ControlBottomMenu />; BottomControlButton.storyName = 'Bottom control button'; BottomControlButton.parameters = { chromatic: { disable: true }, }; export default { title: 'Controls/Menu/Bottom control button', };
third_party/prometheus_ui/base/web/ui/node_modules/reactstrap/src/FormText.js
GoogleCloudPlatform/prometheus-engine
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { mapToCssModules, tagPropType } from './utils'; const propTypes = { children: PropTypes.node, inline: PropTypes.bool, tag: tagPropType, color: PropTypes.string, className: PropTypes.string, cssModule: PropTypes.object, }; const defaultProps = { tag: 'small', color: 'muted', }; const FormText = (props) => { const { className, cssModule, inline, color, tag: Tag, ...attributes } = props; const classes = mapToCssModules(classNames( className, !inline ? 'form-text' : false, color ? `text-${color}` : false ), cssModule); return ( <Tag {...attributes} className={classes} /> ); }; FormText.propTypes = propTypes; FormText.defaultProps = defaultProps; export default FormText;
src/about/index.js
guokeke/image-editor
/** * React Static Boilerplate * https://github.com/kriasoft/react-static-boilerplate * * Copyright © 2015-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Layout from '../../components/Layout'; import s from './styles.css'; import { title, html } from './index.md'; class AboutPage extends React.Component { componentDidMount() { document.title = title; } render() { return ( <Layout className={s.content}> <h1>{title}</h1> <div // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: html }} /> </Layout> ); } } export default AboutPage;
src/svg-icons/image/movie-filter.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageMovieFilter = (props) => ( <SvgIcon {...props}> <path d="M18 4l2 3h-3l-2-3h-2l2 3h-3l-2-3H8l2 3H7L5 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4h-4zm-6.75 11.25L10 18l-1.25-2.75L6 14l2.75-1.25L10 10l1.25 2.75L14 14l-2.75 1.25zm5.69-3.31L16 14l-.94-2.06L13 11l2.06-.94L16 8l.94 2.06L19 11l-2.06.94z"/> </SvgIcon> ); ImageMovieFilter = pure(ImageMovieFilter); ImageMovieFilter.displayName = 'ImageMovieFilter'; ImageMovieFilter.muiName = 'SvgIcon'; export default ImageMovieFilter;
index.ios.js
Innogator/VaultMobile
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; class VaultMobile extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.ios.js </Text> <Text style={styles.instructions}> Press Cmd+R to reload,{'\n'} Cmd+D or shake for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('VaultMobile', () => VaultMobile);
actor-apps/app-web/src/app/components/SidebarSection.react.js
shenhzou654321/actor-platform
import React from 'react'; import { Styles, Tabs, Tab } from 'material-ui'; import ActorTheme from 'constants/ActorTheme'; import HeaderSection from 'components/sidebar/HeaderSection.react'; import RecentSection from 'components/sidebar/RecentSection.react'; import ContactsSection from 'components/sidebar/ContactsSection.react'; const ThemeManager = new Styles.ThemeManager(); class SidebarSection extends React.Component { static childContextTypes = { muiTheme: React.PropTypes.object }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } constructor(props) { super(props); ThemeManager.setTheme(ActorTheme); } render() { return ( <aside className="sidebar"> <HeaderSection/> <Tabs className="sidebar__tabs" contentContainerClassName="sidebar__tabs__tab-content" tabItemContainerClassName="sidebar__tabs__tab-items"> <Tab label="Recent"> <RecentSection/> </Tab> <Tab label="Contacts"> <ContactsSection/> </Tab> </Tabs> </aside> ); } } export default SidebarSection;
src/component/loggedOutState/LoginToView.js
BristolPound/cyclos-mobile-3-TownPound
import React from 'react' import { View, Image, Dimensions } from 'react-native' import Colors from '@Colors/colors' import DefaultText from '../DefaultText' import Images from '@Assets/images' const screenWidth = Dimensions.get('window').width, screenHeight = Dimensions.get('window').height const styles = { container: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: Colors.offWhite, width: screenWidth, height: screenHeight, position: 'absolute' }, text: { color: Colors.gray4, marginBottom: 8, fontSize: 20 }, image: { marginBottom: 20 } } export const emptyStateImage = { spending: 'spending', map: 'map', account: 'account' } const getImageSource = (image) => { switch(image) { case emptyStateImage.spending: return Images.spending case emptyStateImage.map: return Images.map case emptyStateImage.account: return Images.account } } const LoginToView = (props) => <View style={styles.container}> <Image style={styles.image} source={getImageSource(props.image)} /> <DefaultText style={styles.text}>{props.lineOne}</DefaultText> <DefaultText style={styles.text}>{props.lineTwo}</DefaultText> </View> export default LoginToView
packages/cf-component-button/src/ButtonGroup.js
koddsson/cf-ui
import React from 'react'; import PropTypes from 'prop-types'; import { createComponent } from 'cf-style-container'; const styles = props => { const theme = props.theme; return { display: theme.display, position: theme.position, verticalAlign: theme.verticalAlign, whiteSpace: theme.whiteSpace }; }; const getGroupByIndex = (index, length) => { if (index === length - 1) { return 'last'; } if (index === 0) { return 'first'; } return 'inbetween'; }; const addGroupProps = (children, spaced) => React.Children.map(children, (child, index) => { if (React.isValidElement(child)) { return React.cloneElement(child, { group: getGroupByIndex(index, React.Children.count(children)), spaced }); } return child; }); class ButtonGroup extends React.Component { render() { const { className, children, spaced } = this.props; return <div className={className}>{addGroupProps(children, spaced)}</div>; } } ButtonGroup.propTypes = { children: PropTypes.node, spaced: PropTypes.bool, className: PropTypes.string.isRequired }; export default createComponent(styles, ButtonGroup);
src/svg-icons/maps/directions-railway.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsDirectionsRailway = (props) => ( <SvgIcon {...props}> <path d="M4 15.5C4 17.43 5.57 19 7.5 19L6 20.5v.5h12v-.5L16.5 19c1.93 0 3.5-1.57 3.5-3.5V5c0-3.5-3.58-4-8-4s-8 .5-8 4v10.5zm8 1.5c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm6-7H6V5h12v5z"/> </SvgIcon> ); MapsDirectionsRailway = pure(MapsDirectionsRailway); MapsDirectionsRailway.displayName = 'MapsDirectionsRailway'; MapsDirectionsRailway.muiName = 'SvgIcon'; export default MapsDirectionsRailway;
src/interface/others/ChangelogTab.js
FaideWW/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import Changelog from 'interface/home/Changelog'; const ChangelogTab = (_, { config }) => <Changelog changelog={config.changelog} />; ChangelogTab.contextTypes = { config: PropTypes.object.isRequired, }; export default ChangelogTab;
src/components/Pagination.js
wrleskovec/thoughtcrime
import React from 'react'; export default function Pagination(props) { const { numOfPages, onPageClick, pageN } = props; const pages = []; // expert lvl algebra I const endPageDiff = numOfPages - (pageN + 5); const endPage = (endPageDiff > -1) ? pageN + 5 : numOfPages; const startPageDiff = (endPage - 6 > 0) ? endPage - 6 : pageN; const startPage = (endPage - startPageDiff > 5) ? startPageDiff : 0; for (let i = startPage; i < endPage; i++) { pages.push( <li key={i} className={(pageN === i) ? 'active' : ''}> <a key={`page${i}`} id={`page${i}`} href="#"> {i + 1} </a> </li>); } return ( <nav className="tablePagination" aria-label="..."> <ul className="pagination" onClick={onPageClick}> <li> <a id="prev" href="#" aria-label="Next"> {'<'} </a> </li> {pages} <li> <a id="next" href="#" aria-label="Next"> {'>'} </a> </li> </ul> </nav> ); }
src/components/layout/header-scrolling.js
KleeGroup/focus-components
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import applicationStore from 'focus-core/application/built-in-store'; import Scroll from '../../behaviours/scroll'; import connect from '../../behaviours/store/connect'; // Component default props. const defaultProps = { canDeploy: true, // Determines if the header can be deployed (revealing the cartridge component) or not. notifySizeChange: undefined, // A handler to notify other elements that the header has added/removed the cartridge. scrollTargetSelector: undefined // Selector for the domNode on which the scroll is attached. }; // Component props definition. const propTypes = { canDeploy: PropTypes.bool, notifySizeChange: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), scrollTargetSelector: PropTypes.string }; // getState function. function getState() { const processMode = applicationStore.getMode(); let mode = 'consult'; if (processMode && processMode.edit && processMode.edit > 0) { mode = 'edit'; } return { mode: mode, route: applicationStore.getRoute(), canDeploy: applicationStore.getCanDeploy() }; } /** * HeaderScrolling component. */ @connect([{ store: applicationStore, properties: ['mode', 'route', 'canDeploy'] }], getState) @Scroll class HeaderScrolling extends Component { constructor(props) { super(props); this.state = { ...getState(), isDeployed: true }; } /** @inheriteddoc */ componentWillMount() { this.handleScroll(); const { scrollTargetSelector } = this.props; this.scrollTargetNode = (scrollTargetSelector && scrollTargetSelector !== '') ? document.querySelector(scrollTargetSelector) : window; } /** @inheriteddoc */ componentDidMount() { this.scrollTargetNode.addEventListener('scroll', this.handleScroll); this.scrollTargetNode.addEventListener('resize', this.handleScroll); } /** @inheriteddoc */ componentWillReceiveProps({ canDeploy }) { this.setState({ isDeployed: true }, () => this.handleScroll(null, canDeploy)); } /** @inheriteddoc */ componentWillUnmount() { this.scrollTargetNode.removeEventListener('scroll', this.handleScroll); this.scrollTargetNode.removeEventListener('resize', this.handleScroll); } /** * Notify other elements that the header has added/removed the cartridge. */ _notifySizeChange = () => { const { notifySizeChange } = this.props; const { isDeployed } = this.state; if (notifySizeChange) { notifySizeChange(isDeployed); } }; /** * Handle the scroll event in order to show/hide the cartridge. * @param {object} event [description] */ handleScroll = (event, canDeploy) => { let { deployThreshold, placeholderHeight } = this.state; if (this.state.isDeployed) { const content = this.refs ? this.refs.header : undefined; deployThreshold = content ? content.clientHeight - 60 : 1000; // 1000 is arbitrary, but a value high enough is required by default. placeholderHeight = content ? content.clientHeight : 1000; this.setState({ deployThreshold, placeholderHeight }); } const { top } = this.scrollPosition(); const isDeployed = (canDeploy !== undefined ? canDeploy : this.props.canDeploy) ? top <= deployThreshold : false; if (isDeployed !== this.state.isDeployed) { this.setState({ isDeployed }, this._notifySizeChange); } }; /** @inheriteddoc */ render() { const { isDeployed, placeholderHeight } = this.state; const { children, canDeploy, mode, route } = this.props; return ( <header ref='header' data-focus='header-scrolling' data-mode={mode} data-route={route} data-deployed={isDeployed}> {children} {!isDeployed ? <div style={{ height: canDeploy ? placeholderHeight : 60, width: '100%' }} /> : ''} </header> ); } } // Static props. HeaderScrolling.displayName = 'HeaderScrolling'; HeaderScrolling.defaultProps = defaultProps; HeaderScrolling.propTypes = propTypes; export default HeaderScrolling;
source/client/components/MobilePayment.js
NAlexandrov/yaw
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import MobilePaymentContract from './MobilePaymentContract'; import MobilePaymentSuccess from './MobilePaymentSuccess'; /** * Класс компонента MobilePayment */ class MobilePayment extends Component { /** * Конструктор * @param {Object} props свойства компонента MobilePayment */ constructor(props) { super(props); this.state = { stage: 'contract' }; } /** * Обработка успешного платежа * @param {Object} transaction данные о транзакции */ onPaymentSuccess(transaction) { this.props.onTransaction(); this.setState({ stage: 'success', transaction, }); } /** * Повторить платеж */ repeatPayment() { this.setState({ stage: 'contract' }); } /** * Рендер компонента * * @override * @returns {JSX} */ render() { const { activeCard, user } = this.props; if (this.state.stage === 'success') { return ( <MobilePaymentSuccess user={user} activeCard={activeCard} transaction={this.state.transaction} repeatPayment={() => this.repeatPayment()} /> ); } return ( <MobilePaymentContract activeCard={activeCard} onPaymentSuccess={(transaction) => this.onPaymentSuccess(transaction)} /> ); } } MobilePayment.propTypes = { user: PropTypes.shape({ email: PropTypes.string.isRequired, }), activeCard: PropTypes.shape({ id: PropTypes.number, theme: PropTypes.object, }).isRequired, onTransaction: PropTypes.func.isRequired, }; export default MobilePayment;
docs/app/Examples/collections/Grid/Variations/GridExampleTextAlignmentMixed.js
vageeshb/Semantic-UI-React
import React from 'react' import { Grid, Menu } from 'semantic-ui-react' const GridExampleTextAlignmentJustified = () => ( <Grid> <Grid.Row columns={3}> <Grid.Column> <Menu fluid vertical> <Menu.Item className='header'>Cats</Menu.Item> </Menu> </Grid.Column> <Grid.Column textAlign='center'> <Menu fluid vertical> <Menu.Item className='header'>Dogs</Menu.Item> <Menu.Item>Poodle</Menu.Item> <Menu.Item>Cockerspaniel</Menu.Item> </Menu> </Grid.Column> <Grid.Column> <Menu fluid vertical> <Menu.Item className='header'>Monkeys</Menu.Item> </Menu> </Grid.Column> </Grid.Row> <Grid.Row textAlign='justified'> <Grid.Column> <p> Justified content fits exactly inside the grid column, taking up the entire width from one side to the other. Justified content fits exactly inside the grid column, taking up the entire width from one side to the other. Justified content fits exactly inside the grid column, taking up the entire width from one side to the other. Justified content fits exactly inside the grid column, taking up the entire width from one side to the other. Justified content fits exactly inside the grid column, taking up the entire width from one side to the other. </p> </Grid.Column> </Grid.Row> </Grid> ) export default GridExampleTextAlignmentJustified
ajax/libs/forerunnerdb/1.3.219/fdb-legacy.min.js
dannyxx001/cdnjs
!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("../lib/Core");a("../lib/CollectionGroup"),a("../lib/View"),a("../lib/Highchart"),a("../lib/Persist"),a("../lib/Document"),a("../lib/Overview"),a("../lib/OldView"),a("../lib/OldView.Bind"),a("../lib/Grid");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/CollectionGroup":5,"../lib/Core":6,"../lib/Document":9,"../lib/Grid":10,"../lib/Highchart":11,"../lib/OldView":26,"../lib/OldView.Bind":25,"../lib/Overview":29,"../lib/Persist":31,"../lib/View":34}],2:[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":33}],3:[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":33}],4:[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("dropped"===this._state)return a&&a(!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log("Dropping collection "+this._name),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.$super.apply(this,arguments)}),d.synthesize(n.prototype,"mongoEmulation"),n.prototype.setData=function(a,b,c){if("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": 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'ForerunnerDB.Collection "'+this.name()+'": Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: '+d[this._primaryKey]}else h.set(d[k],d);e=JSON.stringify(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("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": 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("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": 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("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": 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('Updating some collection data for collection "'+this.name()+'"');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'ForerunnerDB.Collection "'+this.name()+'": 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":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":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'ForerunnerDB.Collection "'+this.name()+'": 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'ForerunnerDB.Collection "'+this.name()+'": 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'ForerunnerDB.Collection "'+this.name()+'": 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'ForerunnerDB.Collection "'+this.name()+'": Cannot addToSet on a key that is not an array! ('+p+")";var s,t,u,v,w=a[p],x=w.length,y=!0,z=d&&d.$addToSet;for(b[p].$key?(u=!1,v=new h(b[p].$key),t=v.value(b[p])[0],delete b[p].$key):z&&z.key?(u=!1,v=new h(z.key),t=v.value(b[p])[0]):(t=JSON.stringify(b[p]),u=!0),s=0;x>s;s++)if(u){if(JSON.stringify(w[s])===t){y=!1;break}}else if(t===v.value(w[s])[0]){y=!1;break}y&&(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'ForerunnerDB.Collection "'+this.name()+'": Cannot splicePush with a key that is not an array! ('+p+")";if(l=b.$index,void 0===l)throw'ForerunnerDB.Collection "'+this.name()+'": 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'ForerunnerDB.Collection "'+this.name()+'": 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 A=b.$index;if(void 0===A)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot move without a $index integer value!';delete b.$index,this._updateSpliceMove(a[p],j,A),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'ForerunnerDB.Collection "'+this.name()+'": 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("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": 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.deferEmit=function(a,b){var c,d=this;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("ForerunnerDB.Collection: Emitting "+c[0]),d.emit.apply(d,c)},1))},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("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": 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=JSON.stringify(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=JSON.stringify(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("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": 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=JSON.stringify(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("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": 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)),b.$orderBy&&(H.time("sort"),e=this.sort(b.$orderBy,e),H.time("sort")),H.time("tableScan: "+d)),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'ForerunnerDB.Collection "'+this.name()+'": 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 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=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=a.shift(),g=[];if(a.length>0){b=this._sort(f,b),d=this.bucket(f.___fdbKey,b);for(e in d)d.hasOwnProperty(e)&&(c=[].concat(a),g=g.concat(this._bucketSort(c,d[e])));return g}return this._sort(f,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'ForerunnerDB.Collection "'+this.name()+'": $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={};for(c=0;c<b.length;c++)d[b[c][a]]=d[b[c][a]]||[],d[b[c][a]].push(b[c]);return d},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("dropped"===this._state)throw'ForerunnerDB.Collection "'+this.name()+'": 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'ForerunnerDB.Collection "'+this.name()+'": Collection 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({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'ForerunnerDB.Db "'+this.name()+'": Cannot get collection '+b+" because it does not exist and auto-create has been disabled!";this.debug()&&console.log("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'ForerunnerDB.Db "'+this.name()+'": 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":7,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":28,"./Path":30,"./ReactorIO":32,"./Shared":33}],5:[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"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw'ForerunnerDB.CollectionGroup "'+this.name()+'": All collections in a collection group must have the same primary key!'}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=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("dropped"!==this._state){var a,b,c;if(this._debug&&console.log("Dropping collection group "+this._name),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":4,"./Shared":33}],6:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;if(void 0!==a){for(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":8,"./Metrics.js":15,"./Overload":28,"./Shared":33}],7:[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}},{}],8:[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={}},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("dropped"!==this._state){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("dropped"!==this._state){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("dropped"!==this._state){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("dropped"!==this._state){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},b.exports=j},{"./Collection.js":4,"./Crc.js":7,"./Metrics.js":15,"./Overload":28,"./Shared":33}],9:[function(a,b,c){"use strict";var d,e,f;d=a("./Shared");var g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a){this._name=a,this._data={}},d.addModule("Document",g),d.mixin(g.prototype,"Mixin.Common"),d.mixin(g.prototype,"Mixin.Events"),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Constants"),d.mixin(g.prototype,"Mixin.Triggers"),d.mixin(g.prototype,"Mixin.Matching"),d.mixin(g.prototype,"Mixin.Updating"),e=a("./Collection"),f=d.modules.Db,d.synthesize(g.prototype,"state"),d.synthesize(g.prototype,"db"),d.synthesize(g.prototype,"name"),g.prototype.setData=function(a,b){var c,d;if(a)if(b=b||{$decouple:!0},b&&b.$decouple===!0&&(a=this.decouple(a)),this._linked){d={};for(c in this._data)"jQuery"!==c.substr(0,6)&&this._data.hasOwnProperty(c)&&void 0===a[c]&&(d[c]=1);a.$unset=d,this.updateObject(this._data,a,{})}else this._data=a;return this},g.prototype.find=function(a,b){var c;return c=b&&b.$decouple===!1?this._data:this.decouple(this._data)},g.prototype.update=function(a,b,c){this.updateObject(this._data,b,a,c)},g.prototype.updateObject=e.prototype.updateObject,g.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},g.prototype._updateProperty=function(a,b,c){this._linked?(window.jQuery.observable(a).setProperty(b,c),this.debug()&&console.log('ForerunnerDB.Document: Setting data-bound document property "'+b+'" for collection "'+this.name()+'"')):(a[b]=c,this.debug()&&console.log('ForerunnerDB.Document: Setting non-data-bound document property "'+b+'" for collection "'+this.name()+'"'))},g.prototype._updateIncrement=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]+c):a[b]+=c},g.prototype._updateSpliceMove=function(a,b,c){this._linked?(window.jQuery.observable(a).move(b,c),this.debug()&&console.log('ForerunnerDB.Document: Moving data-bound document array index from "'+b+'" to "'+c+'" for collection "'+this.name()+'"')):(a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log('ForerunnerDB.Document: Moving non-data-bound document array index from "'+b+'" to "'+c+'" for collection "'+this.name()+'"'))},g.prototype._updateSplicePush=function(a,b,c){a.length>b?this._linked?window.jQuery.observable(a).insert(b,c):a.splice(b,0,c):this._linked?window.jQuery.observable(a).insert(c):a.push(c)},g.prototype._updatePush=function(a,b){this._linked?window.jQuery.observable(a).insert(b):a.push(b)},g.prototype._updatePull=function(a,b){this._linked?window.jQuery.observable(a).remove(b):a.splice(b,1)},g.prototype._updateMultiply=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]*c):a[b]*=c},g.prototype._updateRename=function(a,b,c){var d=a[b];this._linked?(window.jQuery.observable(a).setProperty(c,d),window.jQuery.observable(a).removeProperty(b)):(a[c]=d,delete a[b])},g.prototype._updateUnset=function(a,b){this._linked?window.jQuery.observable(a).removeProperty(b):delete a[b]},g.prototype.drop=function(){return"dropped"===this._state?!0:this._db&&this._name&&this._db&&this._db._document&&this._db._document[this._name]?(this._state="dropped",delete this._db._document[this._name],delete this._data,this.emit("drop",this),!0):!1},f.prototype.document=function(a){if(a){if(a instanceof g){if("droppped"!==a.state())return a;a=a.name()}return this._document=this._document||{},this._document[a]=this._document[a]||new g(a).db(this),this._document[a]}return this._document},f.prototype.documents=function(){var a,b,c=[];for(b in this._document)this._document.hasOwnProperty(b)&&(a=this._document[b],c.push({name:b,linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Document"),b.exports=g},{"./Collection":4,"./Shared":33}],10:[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._selector=a,this._template=b,this._options=c||{},this._debug={},this._id=this.objectId(),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)}},d.addModule("Grid",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"),d.mixin(l.prototype,"Mixin.Events"),f=a("./Collection"),g=a("./CollectionGroup"),h=a("./View"),k=a("./ReactorIO"),i=f.prototype.init,e=d.modules.Db,j=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),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.from=function(a){return void 0!==a&&(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this)),"string"==typeof a&&(a=this._db.collection(a)),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this.refresh()),this},l.prototype.db=function(a){return void 0!==a?(this._db=a,this):this._db},l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.drop=function(){return"dropped"===this._state?!0:this._from?(this._from.unlink(this._selector,this.template()),this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this),(this.debug()||this._db&&this._db.debug())&&console.log("ForerunnerDB.Grid: Dropping grid "+this._selector),this._state="dropped",this._db&&this._selector&&delete this._db._grid[this._selector],this.emit("drop",this),delete this._selector,delete this._template,delete this._from,delete this._db,!0):!1},l.prototype.template=function(a){return void 0!==a?(this._template=a,this):this._template},l.prototype._sortGridClick=function(a){var b,c=window.jQuery(a.currentTarget),e=c.attr("data-grid-sort")||"",f=-1===parseInt(c.attr("data-grid-dir")||"-1",10)?1:-1,g=e.split(","),h={};for(window.jQuery(this._selector).find("[data-grid-dir]").removeAttr("data-grid-dir"),c.attr("data-grid-dir",f),b=0;b<g.length;b++)h[g]=f;d.mixin(h,this._options.$orderBy),this._from.orderBy(h),this.emit("sort",h)},l.prototype.refresh=function(){if(this._from){if(!this._from.link)throw"Grid requires the AutoBind module in order to operate!";var a=this,b=window.jQuery(this._selector),c=function(){a._sortGridClick.apply(a,arguments)};if(b.html(""),a._from.orderBy&&b.off("click","[data-grid-sort]",c),a._from.query&&b.off("click","[data-grid-filter]",c),a._options.$wrap=a._options.$wrap||"gridRow",a._from.link(a._selector,a.template(),a._options),a._from.orderBy&&b.on("click","[data-grid-sort]",c),a._from.query){var d={};b.find("[data-grid-filter]").each(function(c,e){e=window.jQuery(e);var f,g,h,i,j=e.attr("data-grid-filter"),k=e.attr("data-grid-vartype"),l={},m=e.html(),n=a._db.view("tmpGridFilter_"+a._id+"_"+j);l[j]=1,i={$distinct:l},n.query(i).orderBy(l).from(a._from._from),h=['<div class="dropdown" id="'+a._id+"_"+j+'">','<button class="btn btn-default dropdown-toggle" type="button" id="'+a._id+"_"+j+'_dropdownButton" data-toggle="dropdown" aria-expanded="true">',m+' <span class="caret"></span>',"</button>","</div>"],f=window.jQuery(h.join("")),g=window.jQuery('<ul class="dropdown-menu" role="menu" id="'+a._id+"_"+j+'_dropdownMenu"></ul>'),f.append(g),e.html(f),n.link(g,{template:['<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">','<input type="search" class="form-control gridFilterSearch" placeholder="Search...">','<span class="input-group-btn">','<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>',"</span>","</li>",'<li role="presentation" class="divider"></li>','<li role="presentation" data-val="$all">','<a role="menuitem" tabindex="-1">','<input type="checkbox" checked>&nbsp;All',"</a>","</li>",'<li role="presentation" class="divider"></li>',"{^{for options}}",'<li role="presentation" data-link="data-val{:'+j+'}">','<a role="menuitem" tabindex="-1">','<input type="checkbox">&nbsp;{^{:'+j+"}}","</a>","</li>","{{/for}}"].join("")},{$wrap:"options"}),b.on("keyup","#"+a._id+"_"+j+"_dropdownMenu .gridFilterSearch",function(a){var b=window.jQuery(this),c=n.query(),d=b.val();d?c[j]=new RegExp(d,"gi"):delete c[j],n.query(c)}),b.on("click","#"+a._id+"_"+j+"_dropdownMenu .gridFilterClearSearch",function(a){window.jQuery(this).parents("li").find(".gridFilterSearch").val("");var b=n.query();delete b[j],n.query(b)}),b.on("click","#"+a._id+"_"+j+"_dropdownMenu li",function(b){b.stopPropagation();var c,e,f,g,h,i=$(this),l=i.find('input[type="checkbox"]'),m=!0;if(window.jQuery(b.target).is("input")?(l.prop("checked",l.prop("checked")),e=l.is(":checked")):(l.prop("checked",!l.prop("checked")),e=l.is(":checked")),g=window.jQuery(this),c=g.attr("data-val"),"$all"===c)delete d[j],g.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop("checked",!1);else{switch(g.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop("checked",!1),k){case"integer":c=parseInt(c,10);break;case"float":c=parseFloat(c)}for(d[j]=d[j]||{$in:[]},f=d[j].$in,h=0;h<f.length;h++)if(f[h]===c){e===!1&&f.splice(h,1),m=!1;break}m&&e&&f.push(c),f.length||delete d[j]}a._from.queryData(d),a._from.pageFirst&&a._from.pageFirst()})})}a.emit("refresh")}return this},l.prototype.count=function(){return this._from.count()},f.prototype.grid=h.prototype.grid=function(a,b,c){if(this._db&&this._db._grid){if(void 0!==a){if(void 0!==b){if(this._db._grid[a])throw'ForerunnerDB.Collection/View "'+this.name()+'": Cannot create a grid using this collection/view because a grid with this name already exists: '+a;var d=new l(a,b,c).db(this._db).from(this);return this._grid=this._grid||[],this._grid.push(d),this._db._grid[a]=d,d}return this._db._grid[a]}return this._db._grid}},f.prototype.unGrid=h.prototype.unGrid=function(a,b,c){var d,e;if(this._db&&this._db._grid){if(a&&b){if(this._db._grid[a])return e=this._db._grid[a],delete this._db._grid[a],e.drop();throw'ForerunnerDB.Collection/View "'+this.name()+'": Cannot remove a grid using this collection/view because a grid with this name does not exist: '+name}for(d in this._db._grid)this._db._grid.hasOwnProperty(d)&&(e=this._db._grid[d],delete this._db._grid[d],e.drop(),this.debug()&&console.log('ForerunnerDB.Collection/View "'+this.name()+'": Removed grid binding "'+d+'"'));this._db._grid={}}},f.prototype._addGrid=g.prototype._addGrid=h.prototype._addGrid=function(a){return void 0!==a&&(this._grid=this._grid||[],this._grid.push(a)),this},f.prototype._removeGrid=g.prototype._removeGrid=h.prototype._removeGrid=function(a){if(void 0!==a&&this._grid){var b=this._grid.indexOf(a);b>-1&&this._grid.splice(b,1)}return this},e.prototype.init=function(){this._grid={},j.apply(this,arguments)},e.prototype.gridExists=function(a){return Boolean(this._grid[a])},e.prototype.grid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log("Db.Grid: Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.unGrid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log("Db.Grid: Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.grids=function(){var a,b,c=[];for(b in this._grid)this._grid.hasOwnProperty(b)&&(a=this._grid[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Grid"),b.exports=l},{"./Collection":4,"./CollectionGroup":5,"./ReactorIO":32,"./Shared":33,"./View":34}],11:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),g=a("./Overload");var h=function(a,b){this.init.apply(this,arguments)};h.prototype.init=function(a,b){if(this._options=b,this._selector=window.jQuery(this._options.selector),!this._selector[0])throw'ForerunnerDB.Highchart "'+a.name()+'": Chart target element does not exist via selector: '+this._options.selector;this._listeners={},this._collection=a,this._options.series=[],b.chartOptions=b.chartOptions||{},b.chartOptions.credits=!1;var c,d,e;switch(this._options.type){case"pie":this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts(),c=this._collection.find(),d={allowPointSelect:!0,cursor:"pointer",dataLabels:{enabled:!0,format:"<b>{point.name}</b>: {y} ({point.percentage:.0f}%)",style:{color:window.Highcharts.theme&&window.Highcharts.theme.contrastTextColor||"black"}}},e=this.pieDataFromCollectionData(c,this._options.keyField,this._options.valField),window.jQuery.extend(d,this._options.seriesOptions),window.jQuery.extend(d,{name:this._options.seriesName,data:e}),this._chart.addSeries(d,!0,!0);break;case"line":case"area":case"column":case"bar":e=this.seriesDataFromCollectionData(this._options.seriesField,this._options.keyField,this._options.valField,this._options.orderBy),this._options.chartOptions.xAxis=e.xAxis,this._options.chartOptions.series=e.series,this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts();break;default:throw'ForerunnerDB.Highchart "'+a.name()+'": Chart type specified is not currently supported by ForerunnerDB: '+this._options.type}this._hookEvents()},d.addModule("Highchart",h),e=d.modules.Collection,f=e.prototype.init,d.mixin(h.prototype,"Mixin.Events"),d.synthesize(h.prototype,"state"),h.prototype.pieDataFromCollectionData=function(a,b,c){var d,e=[];for(d=0;d<a.length;d++)e.push([a[d][b],a[d][c]]);return e},h.prototype.seriesDataFromCollectionData=function(a,b,c,d){var e,f,g,h,i,j,k=this._collection.distinct(a),l=[],m={categories:[]};for(i=0;i<k.length;i++){for(e=k[i],f={},f[a]=e,h=[],g=this._collection.find(f,{orderBy:d}),j=0;j<g.length;j++)m.categories.push(g[j][b]),h.push(g[j][c]);l.push({name:e,data:h})}return{xAxis:m,series:l}},h.prototype._hookEvents=function(){var a=this;a._collection.on("change",function(){a._changeListener.apply(a,arguments)}),a._collection.on("drop",function(){a.drop.apply(a,arguments)})},h.prototype._changeListener=function(){var a=this;if("undefined"!=typeof a._collection&&a._chart){var b,c=a._collection.find();switch(a._options.type){case"pie":a._chart.series[0].setData(a.pieDataFromCollectionData(c,a._options.keyField,a._options.valField),!0,!0);break;case"bar":case"line":case"area":case"column":var d=a.seriesDataFromCollectionData(a._options.seriesField,a._options.keyField,a._options.valField,a._options.orderBy);for(a._chart.xAxis[0].setCategories(d.xAxis.categories),b=0;b<d.series.length;b++)a._chart.series[b]?a._chart.series[b].setData(d.series[b].data,!0,!0):a._chart.addSeries(d.series[b],!0,!0)}}},h.prototype.drop=function(){return"dropped"!==this._state?(this._state="dropped",this._chart&&this._chart.destroy(),this._collection&&(this._collection.off("change",this._changeListener),this._collection.off("drop",this.drop),this._collection._highcharts&&delete this._collection._highcharts[this._options.selector]),delete this._chart,delete this._options,delete this._collection,this.emit("drop",this),!0):!0},e.prototype.init=function(){this._highcharts={},f.apply(this,arguments)},e.prototype.pieChart=new g({object:function(a){return a.type="pie",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="pie",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.selector=a,e.keyField=b,e.valField=c,e.seriesName=d,this.pieChart(e)}}),e.prototype.lineChart=new g({object:function(a){return a.type="line",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="line",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.lineChart(e)}}),e.prototype.areaChart=new g({object:function(a){return a.type="area",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{}, a.chartOptions.chart.type="area",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.areaChart(e)}}),e.prototype.columnChart=new g({object:function(a){return a.type="column",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="column",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.columnChart(e)}}),e.prototype.barChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.barChart(e)}}),e.prototype.stackedBarChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",a.plotOptions=a.plotOptions||{},a.plotOptions.series=a.plotOptions.series||{},a.plotOptions.series.stacking=a.plotOptions.series.stacking||"normal",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.stackedBarChart(e)}}),e.prototype.dropChart=function(a){this._highcharts&&this._highcharts[a]&&this._highcharts[a].drop()},d.finishModule("Highchart"),b.exports=h},{"./Overload":28,"./Shared":33}],12:[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":3,"./Path":30,"./Shared":33}],13:[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":30,"./Shared":33}],14:[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":33}],15:[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":27,"./Shared":33}],16:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],17:[function(a,b,c){"use strict";var d={chain:function(a){this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(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||"dropped"===d._state))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!";d.chainReceive(this,a,b,c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],18:[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=JSON.stringify(a),e=[];for(c=0;b>c;c++)e.push(JSON.parse(d));return e}return JSON.parse(JSON.stringify(a))}return void 0},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}]),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]}}},b.exports=d},{"./Overload":28}],19:[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},{}],20:[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;if(this._listeners[a]["*"]){var e=this._listeners[a]["*"];for(d=e.length,c=0;d>c;c++)e[c].apply(this,Array.prototype.slice.call(arguments,1))}if(b instanceof Array&&b[0]&&b[0][this._primaryKey]){var f,g,h=this._listeners[a];for(d=b.length,c=0;d>c;c++)if(h[b[c][this._primaryKey]])for(f=h[b[c][this._primaryKey]].length,g=0;f>g;g++)h[b[c][this._primaryKey]][g].apply(this,Array.prototype.slice.call(arguments,1))}}return this}};b.exports=e},{"./Overload":28}],21:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l,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(l in b)if(b.hasOwnProperty(l)){if(f=!1,k=l.substr(0,2),"//"===k)continue;if(0===k.indexOf("$")&&(j=this._matchOp(l,a,b[l],c,e),j>-1)){if(j){if("or"===d)return!0}else o=j;f=!0}if(!f&&b[l]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[l]&&b[l].test(a[l])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[l])if(void 0!==a[l])if(a[l]instanceof Array&&!(b[l]instanceof Array)){for(h=!1,i=0;i<a[l].length&&!(h=this._match(a[l][i],b[l],c,g,e));i++);if(h){if("or"===d)return!0}else o=!1}else if(!(a[l]instanceof Array)&&b[l]instanceof Array){for(h=!1,i=0;i<b[l].length&&!(h=this._match(a[l],b[l][i],c,g,e));i++);if(h){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(h=this._match(a[l],b[l],c,g,e)){if("or"===d)return!0}else o=!1;else if(h=this._match(void 0,b[l],c,g,e)){if("or"===d)return!0}else o=!1;else if(b[l]&&void 0!==b[l].$exists)if(h=this._match(void 0,b[l],c,g,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[l]===b[l]){if("or"===d)return!0}else if(a&&a[l]&&a[l]instanceof Array&&b[l]&&"object"!=typeof b[l]){for(h=!1,i=0;i<a[l].length&&!(h=this._match(a[l][i],b[l],c,g,e));i++);if(h){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'ForerunnerDB.Mixin.Matching "'+this.name()+'": 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'ForerunnerDB.Mixin.Matching "'+this.name()+'": 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)}return-1}};b.exports=d},{}],22:[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},{}],23:[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":28}],24:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log('ForerunnerDB.Mixin.Updating: Setting non-data-bound document property "'+b+'" for "'+this.name()+'"')},_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('ForerunnerDB.Mixin.Updating: Moving non-data-bound document array index from "'+b+'" to "'+c+'" for "'+this.name()+'"')},_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},{}],25:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),e=d.modules.Core,f=d.modules.OldView,g=f.prototype.init,f.prototype.init=function(){var a=this;this._binds=[],this._renderStart=0,this._renderEnd=0,this._deferQueue={insert:[],update:[],remove:[],upsert:[],_bindInsert:[],_bindUpdate:[],_bindRemove:[],_bindUpsert:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100,_bindInsert:100,_bindUpdate:100,_bindRemove:100,_bindUpsert:100},this._deferTime={insert:100,update:1,remove:1,upsert:1,_bindInsert:100,_bindUpdate:1,_bindRemove:1,_bindUpsert:1},g.apply(this,arguments),this.on("insert",function(b,c){a._bindEvent("insert",b,c)}),this.on("update",function(b,c){a._bindEvent("update",b,c)}),this.on("remove",function(b,c){a._bindEvent("remove",b,c)}),this.on("change",a._bindChange)},f.prototype.bind=function(a,b){if(!b||!b.template)throw'ForerunnerDB.OldView "'+this.name()+'": Cannot bind data to element, missing options information!';return this._binds[a]=b,this},f.prototype.unBind=function(a){return delete this._binds[a],this},f.prototype.isBound=function(a){return Boolean(this._binds[a])},f.prototype.bindSortDom=function(a,b){var c,d,e,f=window.jQuery(a);for(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sorting data in DOM...",b),c=0;c<b.length;c++)d=b[c],e=f.find("#"+d[this._primaryKey]),e.length?0===c?(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sort, moving to index 0...",e),f.prepend(e)):(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sort, moving to index "+c+"...",e),e.insertAfter(f.children(":eq("+(c-1)+")"))):this.debug()&&console.log("ForerunnerDB.OldView.Bind: Warning, element for array item not found!",d)},f.prototype.bindRefresh=function(a){var b,c,d=this._binds;a||(a={data:this.find()});for(b in d)d.hasOwnProperty(b)&&(c=d[b],this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sorting DOM..."),this.bindSortDom(b,a.data),c.afterOperation&&c.afterOperation(),c.refresh&&c.refresh())},f.prototype.bindRender=function(a,b){var c,d,e,f,g,h=this._binds[a],i=window.jQuery(a),j=window.jQuery("<ul></ul>");if(h){for(c=this._data.find(),f=function(a){j.append(a)},g=0;g<c.length;g++)d=c[g],e=h.template(d,f);b?b(a,j.html()):i.append(j.html())}},f.prototype.processQueue=function(a,b){var c=this._deferQueue[a],d=this._deferThreshold[a],e=this._deferTime[a];if(c.length){var f,g=this;c.length&&(f=c.length>d?c.splice(0,d):c.splice(0,c.length),this._bindEvent(a,f,[])),setTimeout(function(){g.processQueue(a,b)},e)}else b&&b(),this.emit("bindQueueComplete")},f.prototype._bindEvent=function(a,b,c){var d,e,f=this._binds,g=this.find({});for(e in f)if(f.hasOwnProperty(e))switch(d=f[e].reduce?this.find(f[e].reduce.query,f[e].reduce.options):g,a){case"insert":this._bindInsert(e,f[e],b,c,d);break;case"update":this._bindUpdate(e,f[e],b,c,d);break;case"remove":this._bindRemove(e,f[e],b,c,d)}},f.prototype._bindChange=function(a){this.debug()&&console.log("ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...",a),this.bindRefresh(a)},f.prototype._bindInsert=function(a,b,c,d,e){var f,g,h,i,j=window.jQuery(a);for(h=function(a,c,d,e){return function(a){b.insert?b.insert(a,c,d,e):b.prependInsert?j.prepend(a):j.append(a),b.afterInsert&&b.afterInsert(a,c,d,e)}},i=0;i<c.length;i++)f=j.find("#"+c[i][this._primaryKey]),f.length||(g=b.template(c[i],h(f,c[i],d,e)))},f.prototype._bindUpdate=function(a,b,c,d,e){var f,g,h,i=window.jQuery(a);for(g=function(a,c){return function(d){b.update?b.update(d,c,e,a.length?"update":"append"):a.length?a.replaceWith(d):b.prependUpdate?i.prepend(d):i.append(d),b.afterUpdate&&b.afterUpdate(d,c,e)}},h=0;h<c.length;h++)f=i.find("#"+c[h][this._primaryKey]),b.template(c[h],g(f,c[h]))},f.prototype._bindRemove=function(a,b,c,d,e){var f,g,h,i=window.jQuery(a);for(g=function(a,c,d){return function(){b.remove?b.remove(a,c,d):(a.remove(),b.afterRemove&&b.afterRemove(a,c,d))}},h=0;h<c.length;h++)f=i.find("#"+c[h][this._primaryKey]),f.length&&(b.beforeRemove?b.beforeRemove(f,c[h],e,g(f,c[h],e)):b.remove?b.remove(f,c[h],e):(f.remove(),b.afterRemove&&b.afterRemove(f,c[h],e)))}},{"./Shared":33}],26:[function(a,b,c){"use strict";var d,e,f,g,h,i,j;d=a("./Shared");var k=function(a){this.init.apply(this,arguments)};k.prototype.init=function(a){var b=this;this._name=a,this._listeners={},this._query={query:{},options:{}},this._onFromSetData=function(){b._onSetData.apply(b,arguments)},this._onFromInsert=function(){b._onInsert.apply(b,arguments)},this._onFromUpdate=function(){b._onUpdate.apply(b,arguments)},this._onFromRemove=function(){b._onRemove.apply(b,arguments)},this._onFromChange=function(){b.debug()&&console.log("ForerunnerDB.OldView: Received change"),b._onChange.apply(b,arguments)}},d.addModule("OldView",k),f=a("./CollectionGroup"),g=a("./Collection"),h=g.prototype.init,i=f.prototype.init,e=d.modules.Db,j=e.prototype.init,d.mixin(k.prototype,"Mixin.Events"),k.prototype.drop=function(){return(this._db||this._from)&&this._name?(this.debug()&&console.log("ForerunnerDB.OldView: Dropping view "+this._name),this._state="dropped",this.emit("drop",this),this._db&&this._db._oldViews&&delete this._db._oldViews[this._name],this._from&&this._from._oldViews&&delete this._from._oldViews[this._name],!0):!1},k.prototype.debug=function(){return!1},k.prototype.db=function(a){return void 0!==a?(this._db=a,this):this._db},k.prototype.from=function(a){if(void 0!==a){if("string"==typeof a){if(!this._db.collectionExists(a))throw'ForerunnerDB.OldView "'+this.name()+'": Invalid collection in view.from() call.';a=this._db.collection(a)}return this._from!==a&&(this._from&&this.removeFrom(),this.addFrom(a)),this}return this._from},k.prototype.addFrom=function(a){if(this._from=a,this._from)return this._from.on("setData",this._onFromSetData),this._from.on("change",this._onFromChange),this._from._addOldView(this),this._primaryKey=this._from._primaryKey,this.refresh(),this;throw'ForerunnerDB.OldView "'+this.name()+'": Cannot determine collection type in view.from()'},k.prototype.removeFrom=function(){this._from.off("setData",this._onFromSetData),this._from.off("change",this._onFromChange),this._from._removeOldView(this)},k.prototype.primaryKey=function(){return this._from?this._from.primaryKey():void 0},k.prototype.queryData=function(a,b,c){return void 0!==a&&(this._query.query=a),void 0!==b&&(this._query.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._query},k.prototype.queryAdd=function(a,b,c){var d,e=this._query.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b)&&(e[d]=a[d]);(void 0===c||c===!0)&&this.refresh()},k.prototype.queryRemove=function(a,b){var c,d=this._query.query;if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];(void 0===b||b===!0)&&this.refresh()},k.prototype.query=function(a,b){return void 0!==a?(this._query.query=a,(void 0===b||b===!0)&&this.refresh(),this):this._query.query},k.prototype.queryOptions=function(a,b){return void 0!==a?(this._query.options=a,(void 0===b||b===!0)&&this.refresh(),this):this._query.options},k.prototype.refresh=function(a){if(this._from){var b,c,d,e,f,g,h,i,j=this._data,k=[],l=[],m=[],n=!1;if(this.debug()&&(console.log("ForerunnerDB.OldView: Refreshing view "+this._name),console.log("ForerunnerDB.OldView: Existing data: "+("undefined"!=typeof this._data)),"undefined"!=typeof this._data&&console.log("ForerunnerDB.OldView: Current data rows: "+this._data.find().length)),this._query?(this.debug()&&console.log("ForerunnerDB.OldView: View has query and options, getting subset..."),this._data=this._from.subset(this._query.query,this._query.options)):this._query.options?(this.debug()&&console.log("ForerunnerDB.OldView: View has options, getting subset..."),this._data=this._from.subset({},this._query.options)):(this.debug()&&console.log("ForerunnerDB.OldView: View has no query or options, getting subset..."),this._data=this._from.subset({})),!a&&j)if(this.debug()&&console.log("ForerunnerDB.OldView: Refresh not forced, old data detected..."),d=this._data,j.subsetOf()===d.subsetOf()){for(this.debug()&&console.log("ForerunnerDB.OldView: Old and new data are from same collection..."),e=d.find(),b=j.find(),g=d._primaryKey,i=0;i<e.length;i++)h=e[i],f={},f[g]=h[g],c=j.find(f)[0],c?JSON.stringify(c)!==JSON.stringify(h)&&l.push(h):k.push(h);for(i=0;i<b.length;i++)h=b[i],f={},f[g]=h[g],d.find(f)[0]||m.push(h);this.debug()&&(console.log("ForerunnerDB.OldView: Removed "+m.length+" rows"),console.log("ForerunnerDB.OldView: Inserted "+k.length+" rows"),console.log("ForerunnerDB.OldView: Updated "+l.length+" rows")),k.length&&(this._onInsert(k,[]),n=!0),l.length&&(this._onUpdate(l,[]),n=!0),m.length&&(this._onRemove(m,[]),n=!0)}else this.debug()&&console.log("ForerunnerDB.OldView: Old and new data are from different collections..."),m=j.find(),m.length&&(this._onRemove(m),n=!0),k=d.find(),k.length&&(this._onInsert(k),n=!0);else this.debug()&&console.log("ForerunnerDB.OldView: Forcing data update",e),this._data=this._from.subset(this._query.query,this._query.options),e=this._data.find(),this.debug()&&console.log("ForerunnerDB.OldView: Emitting change event with data",e),this._onInsert(e,[]);this.debug()&&console.log("ForerunnerDB.OldView: Emitting change"),this.emit("change")}return this},k.prototype.count=function(){return this._data&&this._data._data?this._data._data.length:0},k.prototype.find=function(){return this._data?(this.debug()&&console.log("ForerunnerDB.OldView: Finding data in view collection...",this._data),this._data.find.apply(this._data,arguments)):[]},k.prototype.insert=function(){return this._from?this._from.insert.apply(this._from,arguments):[]},k.prototype.update=function(){return this._from?this._from.update.apply(this._from,arguments):[]},k.prototype.remove=function(){return this._from?this._from.remove.apply(this._from,arguments):[]},k.prototype._onSetData=function(a,b){this.emit("remove",b,[]),this.emit("insert",a,[])},k.prototype._onInsert=function(a,b){this.emit("insert",a,b); },k.prototype._onUpdate=function(a,b){this.emit("update",a,b)},k.prototype._onRemove=function(a,b){this.emit("remove",a,b)},k.prototype._onChange=function(){this.debug()&&console.log("ForerunnerDB.OldView: Refreshing data"),this.refresh()},g.prototype.init=function(){this._oldViews=[],h.apply(this,arguments)},g.prototype._addOldView=function(a){return void 0!==a&&(this._oldViews[a._name]=a),this},g.prototype._removeOldView=function(a){return void 0!==a&&delete this._oldViews[a._name],this},f.prototype.init=function(){this._oldViews=[],i.apply(this,arguments)},f.prototype._addOldView=function(a){return void 0!==a&&(this._oldViews[a._name]=a),this},f.prototype._removeOldView=function(a){return void 0!==a&&delete this._oldViews[a._name],this},e.prototype.init=function(){this._oldViews={},j.apply(this,arguments)},e.prototype.oldView=function(a){return this._oldViews[a]||this.debug()&&console.log("ForerunnerDB.OldView: Creating view "+a),this._oldViews[a]=this._oldViews[a]||new k(a).db(this),this._oldViews[a]},e.prototype.oldViewExists=function(a){return Boolean(this._oldViews[a])},e.prototype.oldViews=function(){var a,b=[];for(a in this._oldViews)this._oldViews.hasOwnProperty(a)&&b.push({name:a,count:this._oldViews[a].count()});return b},d.finishModule("OldView"),b.exports=k},{"./Collection":4,"./CollectionGroup":5,"./Shared":33}],27:[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":30,"./Shared":33}],28:[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: '+JSON.stringify(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},{}],29:[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;this._name=a,this._data=new g("__FDB__dc_data_"+this._name),this._collData=new f,this._collections=[],this._collectionDroppedWrap=function(){b._collectionDropped.apply(b,arguments)}},d.addModule("Overview",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"),d.mixin(h.prototype,"Mixin.Events"),f=a("./Collection"),g=a("./Document"),e=d.modules.Db,d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),d.synthesize(h.prototype,"query",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"queryOptions",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"reduce",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),h.prototype.from=function(a){return void 0!==a?("string"==typeof a&&(a=this._db.collection(a)),this._setFrom(a),this):this._collections},h.prototype.find=function(){return this._collData.find.apply(this._collData,arguments)},h.prototype.exec=function(){var a=this.reduce();return a?a.apply(this):void 0},h.prototype.count=function(){return this._collData.count.apply(this._collData,arguments)},h.prototype._setFrom=function(a){for(;this._collections.length;)this._removeCollection(this._collections[0]);return this._addCollection(a),this},h.prototype._addCollection=function(a){return-1===this._collections.indexOf(a)&&(this._collections.push(a),a.chain(this),a.on("drop",this._collectionDroppedWrap),this._refresh()),this},h.prototype._removeCollection=function(a){var b=this._collections.indexOf(a);return b>-1&&(this._collections.splice(a,1),a.unChain(this),a.off("drop",this._collectionDroppedWrap),this._refresh()),this},h.prototype._collectionDropped=function(a){a&&this._removeCollection(a)},h.prototype._refresh=function(){if("dropped"!==this._state){if(this._collections&&this._collections[0]){this._collData.primaryKey(this._collections[0].primaryKey());var a,b=[];for(a=0;a<this._collections.length;a++)b=b.concat(this._collections[a].find(this._query,this._queryOptions));this._collData.setData(b)}if(this._reduce){var c=this._reduce.apply(this);this._data.setData(c)}}},h.prototype._chainHandler=function(a){switch(a.type){case"setData":case"insert":case"update":case"remove":this._refresh()}},h.prototype.data=function(){return this._data},h.prototype.drop=function(){if("dropped"!==this._state){for(this._state="dropped",delete this._data,delete this._collData;this._collections.length;)this._removeCollection(this._collections[0]);delete this._collections,this._db&&this._name&&delete this._db._overview[this._name],delete this._name,this.emit("drop",this)}return!0},e.prototype.overview=function(a){return a?a instanceof h?a:(this._overview=this._overview||{},this._overview[a]=this._overview[a]||new h(a).db(this),this._overview[a]):this._overview||{}},e.prototype.overviews=function(){var a,b,c=[];for(b in this._overview)this._overview.hasOwnProperty(b)&&(a=this._overview[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Overview"),b.exports=h},{"./Collection":4,"./Document":9,"./Shared":33}],30:[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.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.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":33}],31:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m=a("./Shared"),n=a("localforage"),o=a("pako");k=function(){this.init.apply(this,arguments)},k.prototype.localforage=n,k.prototype.init=function(a){a.isClient()&&void 0!==window.Storage&&(this.mode("localforage"),n.config({driver:[n.INDEXEDDB,n.WEBSQL,n.LOCALSTORAGE],name:String(a.core().name()),storeName:"FDB"}))},m.addModule("Persist",k),m.mixin(k.prototype,"Mixin.ChainReactor"),d=m.modules.Db,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,j=d.prototype.drop,l=m.overload,k.prototype.mode=function(a){return void 0!==a?(this._mode=a,this):this._mode},k.prototype.driver=function(a){if(void 0!==a){switch(a.toUpperCase()){case"LOCALSTORAGE":n.setDriver(n.LOCALSTORAGE);break;case"WEBSQL":n.setDriver(n.WEBSQL);break;case"INDEXEDDB":n.setDriver(n.INDEXEDDB);break;default:throw"ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!"}return this}return n.driver()},k.prototype.decode=function(a,b){var c,d,e,f,g=!1;if(a){switch("c1::"===a.substr(0,4)?(a=a.substr(4),c=a.length,a=o.inflate(a,{to:"string"}),d=a.length,g=!0):c=d=a.length,e=a.split("::fdb::"),e[0]){case"json":f=JSON.parse(e[1]);break;case"raw":f=e[1]}b&&b(!1,f,{foundData:!0,rowCount:f.length,compression:{enabled:g,compressedBytes:c,uncompressedBytes:d,effect:Math.round(100/d*c)+"%"}})}else b&&b(!1,a,{foundData:!1,rowCount:0,compression:{compressedBytes:0,uncompressedBytes:0,effect:"0%"}})},k.prototype.encode=function(a,b){var c,d,e,f=a;a="object"==typeof a?"json::fdb::"+JSON.stringify(a):"raw::fdb::"+a,c=a.length,e="c1::"+o.deflate(a,{to:"string"}),d=e.length,c>d&&(a=e),b&&b(!1,a,{foundData:!0,rowCount:f.length,compression:{compressedBytes:d,uncompressedBytes:c,effect:Math.round(100/c*d)+"%"}})},k.prototype.save=function(a,b,c){switch(this.mode()){case"localforage":this.encode(b,function(b,d,e){n.setItem(a,d).then(function(a){c&&c(!1,a,e)},function(a){c&&c(a)})});break;default:c&&c("No data handler.")}},k.prototype.load=function(a,b){var c=this;switch(this.mode()){case"localforage":n.getItem(a).then(function(a){c.decode(a,b)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},k.prototype.drop=function(a,b){switch(this.mode()){case"localforage":n.removeItem(a).then(function(){b&&b(!1)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},e.prototype.drop=new l({"":function(){"dropped"!==this._state&&this.drop(!0)},"function":function(a){"dropped"!==this._state&&this.drop(!0,a)},"boolean":function(a){if("dropped"!==this._state){if(a){if(!this._name)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!";if(!this._db)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when the collection is not attached to a database!";this._db.persist.drop(this._db._name+"::"+this._name),this._db.persist.drop(this._db._name+"::"+this._name+"::metaData")}f.apply(this)}},"boolean, function":function(a,b){var c=this;"dropped"!==this._state&&(a&&(this._name?this._db?this._db.persist.drop(this._db._name+"::"+this._name,function(){c._db.persist.drop(c._db._name+"::"+c._name+"::metaData",b)}):b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!"):b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")),f.apply(this,b))}}),e.prototype.save=function(a){var b,c=this;c._name?c._db?(b=function(){c._db.persist.save(c._db._name+"::"+c._name,c._data,function(b,d,e){b?a&&a(b):c._db.persist.save(c._db._name+"::"+c._name+"::metaData",c.metaData(),function(b,c,d){a&&a(b,c,e,d)})})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.load=function(a){var b=this;b._name?b._db?b._db.persist.load(b._db._name+"::"+b._name,function(c,d,e){c?a&&a(c):(d&&b.setData(d),b._db.persist.load(b._db._name+"::"+b._name+"::metaData",function(c,d,f){c||d&&b.metaData(d),a&&a(c,e,f)}))}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")},d.prototype.init=function(){i.apply(this,arguments),this.persist=new k(this)},d.prototype.load=function(a){var b,c,d=this._collection,e=d.keys(),f=e.length;b=function(b){b?a&&a(b):(f--,0===f&&a&&a(!1))};for(c in d)d.hasOwnProperty(c)&&d[c].load(b)},d.prototype.save=function(a){var b,c,d=this._collection,e=d.keys(),f=e.length;b=function(b){b?a&&a(b):(f--,0===f&&a&&a(!1))};for(c in d)d.hasOwnProperty(c)&&d[c].save(b)},m.finishModule("Persist"),b.exports=k},{"./Collection":4,"./CollectionGroup":5,"./Shared":33,localforage:42,pako:44}],32:[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"dropped"!==this._state&&(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this)),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":33}],33:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.219",modules:{},_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.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":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Triggers":23,"./Mixin.Updating":24,"./Overload":28}],34:[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("__FDB__view_privateData_"+this._name)},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)),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._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(a.type){case"setData":this.debug()&&console.log('ForerunnerDB.View: Setting data on view "'+this.name()+'" 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('ForerunnerDB.View: Inserting some data on view "'+this.name()+'" in underlying (internal) view collection "'+this._privateData.name()+'"'),a.data=this.decouple(a.data),a.data instanceof Array||(a.data=[a.data]),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('ForerunnerDB.View: Updating some data on view "'+this.name()+'" 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('ForerunnerDB.View: Removing some data on view "'+this.name()+'" in underlying (internal) view collection "'+this._privateData.name()+'"'),this._transformRemove(a.data.query,a.options),this._privateData.remove(a.data.query,a.options)}},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"dropped"===this._state?!0:this._from?(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this),(this.debug()||this._db&&this._db.debug())&&console.log("ForerunnerDB.View: Dropping view "+this._name),this._state="dropped",this._io&&this._io.drop(),this._privateData&&this._privateData.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),delete this._chain,delete this._from,delete this._privateData,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0):!1},l.prototype.db=function(a){return void 0!==a?(this._db=a,this.privateData().db(a),this.publicData().db(a),this):this._db},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._privateData&&this._privateData._data?this._privateData._data.length: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'ForerunnerDB.Collection "'+this.name()+'": 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("Db.View: 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":2,"./Collection":4,"./CollectionGroup":5,"./ReactorIO":32,"./Shared":33}],35:[function(a,b,c){function d(){k=!1,h.length?j=h.concat(j):l=-1,j.length&&e()}function e(){if(!k){var a=setTimeout(d);k=!0;for(var b=j.length;b;){for(h=j,j=[];++l<b;)h[l].run();l=-1,b=j.length}h=null,k=!1,clearTimeout(a)}}function f(a,b){this.fun=a,this.array=b}function g(){}var h,i=b.exports={},j=[],k=!1,l=-1;i.nextTick=function(a){var b=new Array(arguments.length-1);if(arguments.length>1)for(var c=1;c<arguments.length;c++)b[c-1]=arguments[c];j.push(new f(a,b)),1!==j.length||k||setTimeout(e,0)},f.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=g,i.addListener=g,i.once=g,i.off=g,i.removeListener=g,i.removeAllListeners=g,i.emit=g,i.binding=function(a){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(a){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}],36:[function(a,b,c){"use strict";function d(a){function b(a){return null===j?void l.push(a):void g(function(){var b=j?a.onFulfilled:a.onRejected;if(null===b)return void(j?a.resolve:a.reject)(k);var c;try{c=b(k)}catch(d){return void a.reject(d)}a.resolve(c)})}function c(a){try{if(a===m)throw new TypeError("A promise cannot be resolved with itself.");if(a&&("object"==typeof a||"function"==typeof a)){var b=a.then;if("function"==typeof b)return void f(b.bind(a),c,h)}j=!0,k=a,i()}catch(d){h(d)}}function h(a){j=!1,k=a,i()}function i(){for(var a=0,c=l.length;c>a;a++)b(l[a]);l=null}if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof a)throw new TypeError("not a function");var j=null,k=null,l=[],m=this;this.then=function(a,c){return new d(function(d,f){b(new e(a,c,d,f))})},f(a,c,h)}function e(a,b,c,d){this.onFulfilled="function"==typeof a?a:null,this.onRejected="function"==typeof b?b:null,this.resolve=c,this.reject=d}function f(a,b,c){var d=!1;try{a(function(a){d||(d=!0,b(a)); },function(a){d||(d=!0,c(a))})}catch(e){if(d)return;d=!0,c(e)}}var g=a("asap");b.exports=d},{asap:38}],37:[function(a,b,c){"use strict";function d(a){this.then=function(b){return"function"!=typeof b?this:new e(function(c,d){f(function(){try{c(b(a))}catch(e){d(e)}})})}}var e=a("./core.js"),f=a("asap");b.exports=e,d.prototype=Object.create(e.prototype);var g=new d(!0),h=new d(!1),i=new d(null),j=new d(void 0),k=new d(0),l=new d("");e.resolve=function(a){if(a instanceof e)return a;if(null===a)return i;if(void 0===a)return j;if(a===!0)return g;if(a===!1)return h;if(0===a)return k;if(""===a)return l;if("object"==typeof a||"function"==typeof a)try{var b=a.then;if("function"==typeof b)return new e(b.bind(a))}catch(c){return new e(function(a,b){b(c)})}return new d(a)},e.from=e.cast=function(a){var b=new Error("Promise.from and Promise.cast are deprecated, use Promise.resolve instead");return b.name="Warning",console.warn(b.stack),e.resolve(a)},e.denodeify=function(a,b){return b=b||1/0,function(){var c=this,d=Array.prototype.slice.call(arguments);return new e(function(e,f){for(;d.length&&d.length>b;)d.pop();d.push(function(a,b){a?f(a):e(b)}),a.apply(c,d)})}},e.nodeify=function(a){return function(){var b=Array.prototype.slice.call(arguments),c="function"==typeof b[b.length-1]?b.pop():null;try{return a.apply(this,arguments).nodeify(c)}catch(d){if(null===c||"undefined"==typeof c)return new e(function(a,b){b(d)});f(function(){c(d)})}}},e.all=function(){var a=1===arguments.length&&Array.isArray(arguments[0]),b=Array.prototype.slice.call(a?arguments[0]:arguments);if(!a){var c=new Error("Promise.all should be called with a single array, calling it with multiple arguments is deprecated");c.name="Warning",console.warn(c.stack)}return new e(function(a,c){function d(f,g){try{if(g&&("object"==typeof g||"function"==typeof g)){var h=g.then;if("function"==typeof h)return void h.call(g,function(a){d(f,a)},c)}b[f]=g,0===--e&&a(b)}catch(i){c(i)}}if(0===b.length)return a([]);for(var e=b.length,f=0;f<b.length;f++)d(f,b[f])})},e.reject=function(a){return new e(function(b,c){c(a)})},e.race=function(a){return new e(function(b,c){a.forEach(function(a){e.resolve(a).then(b,c)})})},e.prototype.done=function(a,b){var c=arguments.length?this.then.apply(this,arguments):this;c.then(null,function(a){f(function(){throw a})})},e.prototype.nodeify=function(a){return"function"!=typeof a?this:void this.then(function(b){f(function(){a(null,b)})},function(b){f(function(){a(b)})})},e.prototype["catch"]=function(a){return this.then(null,a)}},{"./core.js":36,asap:38}],38:[function(a,b,c){(function(a){function c(){for(;e.next;){e=e.next;var a=e.task;e.task=void 0;var b=e.domain;b&&(e.domain=void 0,b.enter());try{a()}catch(d){if(i)throw b&&b.exit(),setTimeout(c,0),b&&b.enter(),d;setTimeout(function(){throw d},0)}b&&b.exit()}g=!1}function d(b){f=f.next={task:b,domain:i&&a.domain,next:null},g||(g=!0,h())}var e={task:void 0,next:null},f=e,g=!1,h=void 0,i=!1;if("undefined"!=typeof a&&a.nextTick)i=!0,h=function(){a.nextTick(c)};else if("function"==typeof setImmediate)h="undefined"!=typeof window?setImmediate.bind(window,c):function(){setImmediate(c)};else if("undefined"!=typeof MessageChannel){var j=new MessageChannel;j.port1.onmessage=c,h=function(){j.port2.postMessage(0)}}else h=function(){setTimeout(c,0)};b.exports=d}).call(this,a("_process"))},{_process:35}],39:[function(a,b,c){(function(){"use strict";function c(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=window.BlobBuilder||window.MSBlobBuilder||window.MozBlobBuilder||window.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function d(a){for(var b=a.length,c=new ArrayBuffer(b),d=new Uint8Array(c),e=0;b>e;e++)d[e]=a.charCodeAt(e);return c}function e(a){return new u(function(b,c){var d=new XMLHttpRequest;d.open("GET",a),d.withCredentials=!0,d.responseType="arraybuffer",d.onreadystatechange=function(){return 4===d.readyState?200===d.status?b({response:d.response,type:d.getResponseHeader("Content-Type")}):void c({status:d.status,response:d.response}):void 0},d.send()})}function f(a){return new u(function(b,d){var f=c([""],{type:"image/png"}),g=a.transaction([x],"readwrite");g.objectStore(x).put(f,"key"),g.oncomplete=function(){var c=a.transaction([x],"readwrite"),f=c.objectStore(x).get("key");f.onerror=d,f.onsuccess=function(a){var c=a.target.result,d=URL.createObjectURL(c);e(d).then(function(a){b(!(!a||"image/png"!==a.type))},function(){b(!1)}).then(function(){URL.revokeObjectURL(d)})}}})["catch"](function(){return!1})}function g(a){return"boolean"==typeof w?u.resolve(w):f(a).then(function(a){return w=a})}function h(a){return new u(function(b,c){var d=new FileReader;d.onerror=c,d.onloadend=function(c){var d=btoa(c.target.result||"");b({__local_forage_encoded_blob:!0,data:d,type:a.type})},d.readAsBinaryString(a)})}function i(a){var b=d(atob(a.data));return c([b],{type:a.type})}function j(a){return a&&a.__local_forage_encoded_blob}function k(a){var b=this,c={db:null};if(a)for(var d in a)c[d]=a[d];return new u(function(a,d){var e=v.open(c.name,c.version);e.onerror=function(){d(e.error)},e.onupgradeneeded=function(a){e.result.createObjectStore(c.storeName),a.oldVersion<=1&&e.result.createObjectStore(x)},e.onsuccess=function(){c.db=e.result,b._dbInfo=c,a()}})}function l(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new u(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),j(a)&&(a=i(a)),b(a)},g.onerror=function(){d(g.error)}})["catch"](d)});return t(d,b),d}function m(a,b){var c=this,d=new u(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),h=1;g.onsuccess=function(){var c=g.result;if(c){var d=c.value;j(d)&&(d=i(d));var e=a(d,c.key,h++);void 0!==e?b(e):c["continue"]()}else b()},g.onerror=function(){d(g.error)}})["catch"](d)});return t(d,b),d}function n(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new u(function(c,e){var f;d.ready().then(function(){return f=d._dbInfo,g(f.db)}).then(function(a){return!a&&b instanceof Blob?h(b):b}).then(function(b){var d=f.db.transaction(f.storeName,"readwrite"),g=d.objectStore(f.storeName);null===b&&(b=void 0);var h=g.put(b,a);d.oncomplete=function(){void 0===b&&(b=null),c(b)},d.onabort=d.onerror=function(){var a=h.error?h.error:h.transaction.error;e(a)}})["catch"](e)});return t(e,c),e}function o(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new u(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g["delete"](a);f.oncomplete=function(){b()},f.onerror=function(){d(h.error)},f.onabort=function(){var a=h.error?h.error:h.transaction.error;d(a)}})["catch"](d)});return t(d,b),d}function p(a){var b=this,c=new u(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;c(a)}})["catch"](c)});return t(c,a),c}function q(a){var b=this,c=new u(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}})["catch"](c)});return t(c,a),c}function r(a,b){var c=this,d=new u(function(b,d){return 0>a?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}})["catch"](d)});return t(d,b),d}function s(a){var b=this,c=new u(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b["continue"]()):void a(g)},f.onerror=function(){c(f.error)}})["catch"](c)});return t(c,a),c}function t(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var u="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,v=v||this.indexedDB||this.webkitIndexedDB||this.mozIndexedDB||this.OIndexedDB||this.msIndexedDB;if(v){var w,x="local-forage-detect-blob-support",y={_driver:"asyncStorage",_initStorage:k,iterate:m,getItem:l,setItem:n,removeItem:o,clear:p,length:q,key:r,keys:s};"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?b.exports=y:"function"==typeof define&&define.amd?define("asyncStorage",function(){return y}):this.asyncStorage=y}}).call(window)},{promise:37}],40:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={};if(b)for(var e in b)d[e]=b[e];d.keyPrefix=d.name+"/",c._dbInfo=d;var f=new m(function(b){s===r.DEFINE?a(["localforageSerializer"],b):b(s===r.EXPORT?a("./../utils/serializer"):n.localforageSerializer)});return f.then(function(a){return o=a,m.resolve()})}function d(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=p.length-1;c>=0;c--){var d=p.key(c);0===d.indexOf(a)&&p.removeItem(d)}});return l(c,a),c}function e(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=p.getItem(b.keyPrefix+a);return d&&(d=o.deserialize(d)),d});return l(d,b),d}function f(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo.keyPrefix,d=b.length,e=p.length,f=0;e>f;f++){var g=p.key(f),h=p.getItem(g);if(h&&(h=o.deserialize(h)),h=a(h,g.substring(d),f+1),void 0!==h)return h}});return l(d,b),d}function g(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=p.key(a)}catch(e){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return l(d,b),d}function h(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=p.length,d=[],e=0;c>e;e++)0===p.key(e).indexOf(a.keyPrefix)&&d.push(p.key(e).substring(a.keyPrefix.length));return d});return l(c,a),c}function i(a){var b=this,c=b.keys().then(function(a){return a.length});return l(c,a),c}function j(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo;p.removeItem(b.keyPrefix+a)});return l(d,b),d}function k(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=d.ready().then(function(){void 0===b&&(b=null);var c=b;return new m(function(e,f){o.serialize(b,function(b,g){if(g)f(g);else try{var h=d._dbInfo;p.setItem(h.keyPrefix+a,b),e(c)}catch(i){("QuotaExceededError"===i.name||"NS_ERROR_DOM_QUOTA_REACHED"===i.name)&&f(i),f(i)}})})});return l(e,c),e}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,n=this,o=null,p=null;try{if(!(this.localStorage&&"setItem"in this.localStorage))return;p=this.localStorage}catch(q){return}var r={DEFINE:1,EXPORT:2,WINDOW:3},s=r.WINDOW;"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?s=r.EXPORT:"function"==typeof define&&define.amd&&(s=r.DEFINE);var t={_driver:"localStorageWrapper",_initStorage:c,iterate:f,getItem:e,setItem:k,removeItem:j,clear:d,length:i,key:g,keys:h};s===r.EXPORT?b.exports=t:s===r.DEFINE?define("localStorageWrapper",function(){return t}):this.localStorageWrapper=t}).call(window)},{"./../utils/serializer":43,promise:37}],41:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={db:null};if(b)for(var e in b)d[e]="string"!=typeof b[e]?b[e].toString():b[e];var f=new m(function(b){r===q.DEFINE?a(["localforageSerializer"],b):b(r===q.EXPORT?a("./../utils/serializer"):n.localforageSerializer)}),g=new m(function(a,e){try{d.db=p(d.name,String(d.version),d.description,d.size)}catch(f){return c.setDriver(c.LOCALSTORAGE).then(function(){return c._initStorage(b)}).then(a)["catch"](e)}d.db.transaction(function(b){b.executeSql("CREATE TABLE IF NOT EXISTS "+d.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){c._dbInfo=d,a()},function(a,b){e(b)})})});return f.then(function(a){return o=a,g})}function d(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=o.deserialize(d)),b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function e(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var e=d.rows,f=e.length,g=0;f>g;g++){var h=e.item(g),i=h.value;if(i&&(i=o.deserialize(i)),i=a(i,h.key,g+1),void 0!==i)return void b(i)}b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new m(function(c,e){d.ready().then(function(){void 0===b&&(b=null);var f=b;o.serialize(b,function(b,g){if(g)e(g);else{var h=d._dbInfo;h.db.transaction(function(d){d.executeSql("INSERT OR REPLACE INTO "+h.storeName+" (key, value) VALUES (?, ?)",[a,b],function(){c(f)},function(a,b){e(b)})},function(a){a.code===a.QUOTA_ERR&&e(a)})}})})["catch"](e)});return l(e,c),e}function g(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[a],function(){b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function h(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function i(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,n=this,o=null,p=this.openDatabase;if(p){var q={DEFINE:1,EXPORT:2,WINDOW:3},r=q.WINDOW;"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?r=q.EXPORT:"function"==typeof define&&define.amd&&(r=q.DEFINE);var s={_driver:"webSQLStorage",_initStorage:c,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};r===q.DEFINE?define("webSQLStorage",function(){return s}):r===q.EXPORT?b.exports=s:this.webSQLStorage=s}}).call(window)},{"./../utils/serializer":43,promise:37}],42:[function(a,b,c){(function(){"use strict";function c(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function d(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(p(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function e(a){for(var b in i)if(i.hasOwnProperty(b)&&i[b]===a)return!0;return!1}function f(a){this._config=d({},m,a),this._driverSet=null,this._ready=!1,this._dbInfo=null;for(var b=0;b<k.length;b++)c(this,k[b]);this.setDriver(this._config.driver)}var g="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,h={},i={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},j=[i.INDEXEDDB,i.WEBSQL,i.LOCALSTORAGE],k=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],l={DEFINE:1,EXPORT:2,WINDOW:3},m={description:"",driver:j.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},n=l.WINDOW;"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?n=l.EXPORT:"function"==typeof define&&define.amd&&(n=l.DEFINE);var o=function(a){var b=b||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB,c={};return c[i.WEBSQL]=!!a.openDatabase,c[i.INDEXEDDB]=!!function(){if("undefined"!=typeof a.openDatabase&&a.navigator&&a.navigator.userAgent&&/Safari/.test(a.navigator.userAgent)&&!/Chrome/.test(a.navigator.userAgent))return!1;try{return b&&"function"==typeof b.open&&"undefined"!=typeof a.IDBKeyRange}catch(c){return!1}}(),c[i.LOCALSTORAGE]=!!function(){try{return a.localStorage&&"setItem"in a.localStorage&&a.localStorage.setItem}catch(b){return!1}}(),c}(this),p=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},q=this;f.prototype.INDEXEDDB=i.INDEXEDDB,f.prototype.LOCALSTORAGE=i.LOCALSTORAGE,f.prototype.WEBSQL=i.WEBSQL,f.prototype.config=function(a){if("object"==typeof a){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a)"storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),this._config[b]=a[b];return"driver"in a&&a.driver&&this.setDriver(this._config.driver),!0}return"string"==typeof a?this._config[a]:this._config},f.prototype.defineDriver=function(a,b,c){var d=new g(function(b,c){try{var d=a._driver,f=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),i=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(f);if(e(a._driver))return void c(i);for(var j=k.concat("_initStorage"),l=0;l<j.length;l++){var m=j[l];if(!m||!a[m]||"function"!=typeof a[m])return void c(f)}var n=g.resolve(!0);"_support"in a&&(n=a._support&&"function"==typeof a._support?a._support():g.resolve(!!a._support)),n.then(function(c){o[d]=c,h[d]=a,b()},c)}catch(p){c(p)}});return d.then(b,c),d},f.prototype.driver=function(){return this._driver||null},f.prototype.ready=function(a){var b=this,c=new g(function(a,c){b._driverSet.then(function(){null===b._ready&&(b._ready=b._initStorage(b._config)),b._ready.then(a,c)})["catch"](c)});return c.then(a,a),c},f.prototype.setDriver=function(b,c,d){function f(){i._config.driver=i.driver()}var i=this;return"string"==typeof b&&(b=[b]),this._driverSet=new g(function(c,d){var f=i._getFirstSupportedDriver(b),j=new Error("No available storage method found.");if(!f)return i._driverSet=g.reject(j),void d(j);if(i._dbInfo=null,i._ready=null,e(f)){var k=new g(function(b){if(n===l.DEFINE)a([f],b);else if(n===l.EXPORT)switch(f){case i.INDEXEDDB:b(a("./drivers/indexeddb"));break;case i.LOCALSTORAGE:b(a("./drivers/localstorage"));break;case i.WEBSQL:b(a("./drivers/websql"))}else b(q[f])});k.then(function(a){i._extend(a),c()})}else h[f]?(i._extend(h[f]),c()):(i._driverSet=g.reject(j),d(j))}),this._driverSet.then(f,f),this._driverSet.then(c,d),this._driverSet},f.prototype.supports=function(a){return!!o[a]},f.prototype._extend=function(a){d(this,a)},f.prototype._getFirstSupportedDriver=function(a){if(a&&p(a))for(var b=0;b<a.length;b++){var c=a[b];if(this.supports(c))return c}return null},f.prototype.createInstance=function(a){return new f(a)};var r=new f;n===l.DEFINE?define("localforage",function(){return r}):n===l.EXPORT?b.exports=r:this.localforage=r}).call(window)},{"./drivers/indexeddb":39,"./drivers/localstorage":40,"./drivers/websql":41,promise:37}],43:[function(a,b,c){(function(){"use strict";function c(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=y.BlobBuilder||y.MSBlobBuilder||y.MozBlobBuilder||y.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function d(a,b){var c="";if(a&&(c=a.toString()),a&&("[object ArrayBuffer]"===a.toString()||a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var d,e=k;a instanceof ArrayBuffer?(d=a,e+=m):(d=a.buffer,"[object Int8Array]"===c?e+=o:"[object Uint8Array]"===c?e+=p:"[object Uint8ClampedArray]"===c?e+=q:"[object Int16Array]"===c?e+=r:"[object Uint16Array]"===c?e+=t:"[object Int32Array]"===c?e+=s:"[object Uint32Array]"===c?e+=u:"[object Float32Array]"===c?e+=v:"[object Float64Array]"===c?e+=w:b(new Error("Failed to get type for BinaryArray"))),b(e+g(d))}else if("[object Blob]"===c){var f=new FileReader;f.onload=function(){var c=i+a.type+"~"+g(this.result);b(k+n+c)},f.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(h){console.error("Couldn't convert value into a JSON string: ",a),b(null,h)}}function e(a){if(a.substring(0,l)!==k)return JSON.parse(a);var b,d=a.substring(x),e=a.substring(l,x);if(e===n&&j.test(d)){var g=d.match(j);b=g[1],d=d.substring(g[0].length)}var h=f(d);switch(e){case m:return h;case n:return c([h],{type:b});case o:return new Int8Array(h);case p:return new Uint8Array(h);case q:return new Uint8ClampedArray(h);case r:return new Int16Array(h);case t:return new Uint16Array(h);case s:return new Int32Array(h);case u:return new Uint32Array(h);case v:return new Float32Array(h);case w:return new Float64Array(h);default:throw new Error("Unkown type: "+e)}}function f(a){var b,c,d,e,f,g=.75*a.length,i=a.length,j=0;"="===a[a.length-1]&&(g--,"="===a[a.length-2]&&g--);var k=new ArrayBuffer(g),l=new Uint8Array(k);for(b=0;i>b;b+=4)c=h.indexOf(a[b]),d=h.indexOf(a[b+1]),e=h.indexOf(a[b+2]),f=h.indexOf(a[b+3]),l[j++]=c<<2|d>>4,l[j++]=(15&d)<<4|e>>2,l[j++]=(3&e)<<6|63&f;return k}function g(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=h[c[b]>>2],d+=h[(3&c[b])<<4|c[b+1]>>4],d+=h[(15&c[b+1])<<2|c[b+2]>>6],d+=h[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}var h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i="~~local_forage_type~",j=/^~~local_forage_type~([^~]+)~/,k="__lfsc__:",l=k.length,m="arbf",n="blob",o="si08",p="ui08",q="uic8",r="si16",s="si32",t="ur16",u="ui32",v="fl32",w="fl64",x=l+m.length,y=this,z={serialize:d,deserialize:e,stringToBuffer:f,bufferToString:g};"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?b.exports=z:"function"==typeof define&&define.amd?define("localforageSerializer",function(){return z}):this.localforageSerializer=z}).call(window)},{}],44:[function(a,b,c){"use strict";var d=a("./lib/utils/common").assign,e=a("./lib/deflate"),f=a("./lib/inflate"),g=a("./lib/zlib/constants"),h={};d(h,e,f,g),b.exports=h},{"./lib/deflate":45,"./lib/inflate":46,"./lib/utils/common":47,"./lib/zlib/constants":50}],45:[function(a,b,c){"use strict";function d(a,b){var c=new u(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}function f(a,b){return b=b||{},b.gzip=!0,d(a,b)}var g=a("./zlib/deflate.js"),h=a("./utils/common"),i=a("./utils/strings"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=Object.prototype.toString,m=0,n=4,o=0,p=1,q=2,r=-1,s=0,t=8,u=function(a){this.options=h.assign({level:r,method:t,chunkSize:16384,windowBits:15,memLevel:8,strategy:s,to:""},a||{});var b=this.options;b.raw&&b.windowBits>0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=g.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==o)throw new Error(j[c]);b.header&&g.deflateSetHeader(this.strm,b.header)};u.prototype.push=function(a,b){var c,d,e=this.strm,f=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?n:m,"string"==typeof a?e.input=i.string2buf(a):"[object ArrayBuffer]"===l.call(a)?e.input=new Uint8Array(a):e.input=a,e.next_in=0,e.avail_in=e.input.length;do{if(0===e.avail_out&&(e.output=new h.Buf8(f),e.next_out=0,e.avail_out=f),c=g.deflate(e,d),c!==p&&c!==o)return this.onEnd(c),this.ended=!0,!1;(0===e.avail_out||0===e.avail_in&&(d===n||d===q))&&("string"===this.options.to?this.onData(i.buf2binstring(h.shrinkBuf(e.output,e.next_out))):this.onData(h.shrinkBuf(e.output,e.next_out)))}while((e.avail_in>0||0===e.avail_out)&&c!==p);return d===n?(c=g.deflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===o):d===q?(this.onEnd(o),e.avail_out=0,!0):!0},u.prototype.onData=function(a){this.chunks.push(a)},u.prototype.onEnd=function(a){a===o&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Deflate=u,c.deflate=d,c.deflateRaw=e,c.gzip=f},{"./utils/common":47,"./utils/strings":48,"./zlib/deflate.js":52,"./zlib/messages":57,"./zlib/zstream":59}],46:[function(a,b,c){"use strict";function d(a,b){var c=new n(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}var f=a("./zlib/inflate.js"),g=a("./utils/common"),h=a("./utils/strings"),i=a("./zlib/constants"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=a("./zlib/gzheader"),m=Object.prototype.toString,n=function(a){this.options=g.assign({chunkSize:16384,windowBits:0,to:""},a||{});var b=this.options;b.raw&&b.windowBits>=0&&b.windowBits<16&&(b.windowBits=-b.windowBits,0===b.windowBits&&(b.windowBits=-15)),!(b.windowBits>=0&&b.windowBits<16)||a&&a.windowBits||(b.windowBits+=32),b.windowBits>15&&b.windowBits<48&&0===(15&b.windowBits)&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=f.inflateInit2(this.strm,b.windowBits);if(c!==i.Z_OK)throw new Error(j[c]);this.header=new l,f.inflateGetHeader(this.strm,this.header)};n.prototype.push=function(a,b){var c,d,e,j,k,l=this.strm,n=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?i.Z_FINISH:i.Z_NO_FLUSH,"string"==typeof a?l.input=h.binstring2buf(a):"[object ArrayBuffer]"===m.call(a)?l.input=new Uint8Array(a):l.input=a,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new g.Buf8(n),l.next_out=0,l.avail_out=n),c=f.inflate(l,i.Z_NO_FLUSH),c!==i.Z_STREAM_END&&c!==i.Z_OK)return this.onEnd(c),this.ended=!0,!1;l.next_out&&(0===l.avail_out||c===i.Z_STREAM_END||0===l.avail_in&&(d===i.Z_FINISH||d===i.Z_SYNC_FLUSH))&&("string"===this.options.to?(e=h.utf8border(l.output,l.next_out),j=l.next_out-e,k=h.buf2string(l.output,e),l.next_out=j,l.avail_out=n-j,j&&g.arraySet(l.output,l.output,e,j,0),this.onData(k)):this.onData(g.shrinkBuf(l.output,l.next_out)))}while(l.avail_in>0&&c!==i.Z_STREAM_END);return c===i.Z_STREAM_END&&(d=i.Z_FINISH),d===i.Z_FINISH?(c=f.inflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===i.Z_OK):d===i.Z_SYNC_FLUSH?(this.onEnd(i.Z_OK),l.avail_out=0,!0):!0},n.prototype.onData=function(a){this.chunks.push(a)},n.prototype.onEnd=function(a){a===i.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=g.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=n,c.inflate=d,c.inflateRaw=e,c.ungzip=d},{"./utils/common":47,"./utils/strings":48,"./zlib/constants":50,"./zlib/gzheader":53,"./zlib/inflate.js":55,"./zlib/messages":57,"./zlib/zstream":59}],47:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;c.assign=function(a){for(var b=Array.prototype.slice.call(arguments,1);b.length;){var c=b.shift();if(c){if("object"!=typeof c)throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}}return a},c.shrinkBuf=function(a,b){return a.length===b?a:a.subarray?a.subarray(0,b):(a.length=b,a)};var e={arraySet:function(a,b,c,d,e){if(b.subarray&&a.subarray)return void a.set(b.subarray(c,c+d),e);for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){var b,c,d,e,f,g;for(d=0,b=0,c=a.length;c>b;b++)d+=a[b].length;for(g=new Uint8Array(d),e=0,b=0,c=a.length;c>b;b++)f=a[b],g.set(f,e),e+=f.length;return g}},f={arraySet:function(a,b,c,d,e){for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){return[].concat.apply([],a)}};c.setTyped=function(a){a?(c.Buf8=Uint8Array,c.Buf16=Uint16Array,c.Buf32=Int32Array,c.assign(c,e)):(c.Buf8=Array,c.Buf16=Array,c.Buf32=Array,c.assign(c,f))},c.setTyped(d)},{}],48:[function(a,b,c){"use strict";function d(a,b){if(65537>b&&(a.subarray&&g||!a.subarray&&f))return String.fromCharCode.apply(null,e.shrinkBuf(a,b));for(var c="",d=0;b>d;d++)c+=String.fromCharCode(a[d]);return c}var e=a("./common"),f=!0,g=!0;try{String.fromCharCode.apply(null,[0])}catch(h){f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(h){g=!1}for(var i=new e.Buf8(256),j=0;256>j;j++)i[j]=j>=252?6:j>=248?5:j>=240?4:j>=224?3:j>=192?2:1;i[254]=i[254]=1,c.string2buf=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=new e.Buf8(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},c.buf2binstring=function(a){return d(a,a.length)},c.binstring2buf=function(a){for(var b=new e.Buf8(a.length),c=0,d=b.length;d>c;c++)b[c]=a.charCodeAt(c);return b},c.buf2string=function(a,b){var c,e,f,g,h=b||a.length,j=new Array(2*h);for(e=0,c=0;h>c;)if(f=a[c++],128>f)j[e++]=f;else if(g=i[f],g>4)j[e++]=65533,c+=g-1;else{for(f&=2===g?31:3===g?15:7;g>1&&h>c;)f=f<<6|63&a[c++],g--;g>1?j[e++]=65533:65536>f?j[e++]=f:(f-=65536,j[e++]=55296|f>>10&1023,j[e++]=56320|1023&f)}return d(j,e)},c.utf8border=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+i[a[c]]>b?c:b}},{"./common":47}],49:[function(a,b,c){"use strict";function d(a,b,c,d){for(var e=65535&a|0,f=a>>>16&65535|0,g=0;0!==c;){g=c>2e3?2e3:c,c-=g;do e=e+b[d++]|0,f=f+e|0;while(--g);e%=65521,f%=65521}return e|f<<16|0}b.exports=d},{}],50:[function(a,b,c){b.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],51:[function(a,b,c){"use strict";function d(){for(var a,b=[],c=0;256>c;c++){a=c;for(var d=0;8>d;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function e(a,b,c,d){var e=f,g=d+c;a=-1^a;for(var h=d;g>h;h++)a=a>>>8^e[255&(a^b[h])];return-1^a}var f=d();b.exports=e},{}],52:[function(a,b,c){"use strict";function d(a,b){return a.msg=G[b],b}function e(a){return(a<<1)-(a>4?9:0)}function f(a){for(var b=a.length;--b>=0;)a[b]=0}function g(a){var b=a.state,c=b.pending;c>a.avail_out&&(c=a.avail_out),0!==c&&(C.arraySet(a.output,b.pending_buf,b.pending_out,c,a.next_out), a.next_out+=c,b.pending_out+=c,a.total_out+=c,a.avail_out-=c,b.pending-=c,0===b.pending&&(b.pending_out=0))}function h(a,b){D._tr_flush_block(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,b),a.block_start=a.strstart,g(a.strm)}function i(a,b){a.pending_buf[a.pending++]=b}function j(a,b){a.pending_buf[a.pending++]=b>>>8&255,a.pending_buf[a.pending++]=255&b}function k(a,b,c,d){var e=a.avail_in;return e>d&&(e=d),0===e?0:(a.avail_in-=e,C.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=E(a.adler,b,e,c):2===a.state.wrap&&(a.adler=F(a.adler,b,e,c)),a.next_in+=e,a.total_in+=e,e)}function l(a,b){var c,d,e=a.max_chain_length,f=a.strstart,g=a.prev_length,h=a.nice_match,i=a.strstart>a.w_size-ja?a.strstart-(a.w_size-ja):0,j=a.sWindow,k=a.w_mask,l=a.prev,m=a.strstart+ia,n=j[f+g-1],o=j[f+g];a.prev_length>=a.good_match&&(e>>=2),h>a.lookahead&&(h=a.lookahead);do if(c=b,j[c+g]===o&&j[c+g-1]===n&&j[c]===j[f]&&j[++c]===j[f+1]){f+=2,c++;do;while(j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&m>f);if(d=ia-(m-f),f=m-ia,d>g){if(a.match_start=b,g=d,d>=h)break;n=j[f+g-1],o=j[f+g]}}while((b=l[b&k])>i&&0!==--e);return g<=a.lookahead?g:a.lookahead}function m(a){var b,c,d,e,f,g=a.w_size;do{if(e=a.window_size-a.lookahead-a.strstart,a.strstart>=g+(g-ja)){C.arraySet(a.sWindow,a.sWindow,g,g,0),a.match_start-=g,a.strstart-=g,a.block_start-=g,c=a.hash_size,b=c;do d=a.head[--b],a.head[b]=d>=g?d-g:0;while(--c);c=g,b=c;do d=a.prev[--b],a.prev[b]=d>=g?d-g:0;while(--c);e+=g}if(0===a.strm.avail_in)break;if(c=k(a.strm,a.sWindow,a.strstart+a.lookahead,e),a.lookahead+=c,a.lookahead+a.insert>=ha)for(f=a.strstart-a.insert,a.ins_h=a.sWindow[f],a.ins_h=(a.ins_h<<a.hash_shift^a.sWindow[f+1])&a.hash_mask;a.insert&&(a.ins_h=(a.ins_h<<a.hash_shift^a.sWindow[f+ha-1])&a.hash_mask,a.prev[f&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=f,f++,a.insert--,!(a.lookahead+a.insert<ha)););}while(a.lookahead<ja&&0!==a.strm.avail_in)}function n(a,b){var c=65535;for(c>a.pending_buf_size-5&&(c=a.pending_buf_size-5);;){if(a.lookahead<=1){if(m(a),0===a.lookahead&&b===H)return sa;if(0===a.lookahead)break}a.strstart+=a.lookahead,a.lookahead=0;var d=a.block_start+c;if((0===a.strstart||a.strstart>=d)&&(a.lookahead=a.strstart-d,a.strstart=d,h(a,!1),0===a.strm.avail_out))return sa;if(a.strstart-a.block_start>=a.w_size-ja&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?sa:sa}function o(a,b){for(var c,d;;){if(a.lookahead<ja){if(m(a),a.lookahead<ja&&b===H)return sa;if(0===a.lookahead)break}if(c=0,a.lookahead>=ha&&(a.ins_h=(a.ins_h<<a.hash_shift^a.sWindow[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),0!==c&&a.strstart-c<=a.w_size-ja&&(a.match_length=l(a,c)),a.match_length>=ha)if(d=D._tr_tally(a,a.strstart-a.match_start,a.match_length-ha),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=ha){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<<a.hash_shift^a.sWindow[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart;while(0!==--a.match_length);a.strstart++}else a.strstart+=a.match_length,a.match_length=0,a.ins_h=a.sWindow[a.strstart],a.ins_h=(a.ins_h<<a.hash_shift^a.sWindow[a.strstart+1])&a.hash_mask;else d=D._tr_tally(a,0,a.sWindow[a.strstart]),a.lookahead--,a.strstart++;if(d&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=a.strstart<ha-1?a.strstart:ha-1,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function p(a,b){for(var c,d,e;;){if(a.lookahead<ja){if(m(a),a.lookahead<ja&&b===H)return sa;if(0===a.lookahead)break}if(c=0,a.lookahead>=ha&&(a.ins_h=(a.ins_h<<a.hash_shift^a.sWindow[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),a.prev_length=a.match_length,a.prev_match=a.match_start,a.match_length=ha-1,0!==c&&a.prev_length<a.max_lazy_match&&a.strstart-c<=a.w_size-ja&&(a.match_length=l(a,c),a.match_length<=5&&(a.strategy===S||a.match_length===ha&&a.strstart-a.match_start>4096)&&(a.match_length=ha-1)),a.prev_length>=ha&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-ha,d=D._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-ha),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=e&&(a.ins_h=(a.ins_h<<a.hash_shift^a.sWindow[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart);while(0!==--a.prev_length);if(a.match_available=0,a.match_length=ha-1,a.strstart++,d&&(h(a,!1),0===a.strm.avail_out))return sa}else if(a.match_available){if(d=D._tr_tally(a,0,a.sWindow[a.strstart-1]),d&&h(a,!1),a.strstart++,a.lookahead--,0===a.strm.avail_out)return sa}else a.match_available=1,a.strstart++,a.lookahead--}return a.match_available&&(d=D._tr_tally(a,0,a.sWindow[a.strstart-1]),a.match_available=0),a.insert=a.strstart<ha-1?a.strstart:ha-1,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function q(a,b){for(var c,d,e,f,g=a.sWindow;;){if(a.lookahead<=ia){if(m(a),a.lookahead<=ia&&b===H)return sa;if(0===a.lookahead)break}if(a.match_length=0,a.lookahead>=ha&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ia;do;while(d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&f>e);a.match_length=ia-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=ha?(c=D._tr_tally(a,1,a.match_length-ha),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=D._tr_tally(a,0,a.sWindow[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===H)return sa;break}if(a.match_length=0,c=D._tr_tally(a,0,a.sWindow[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function s(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=B[a.level].max_lazy,a.good_match=B[a.level].good_length,a.nice_match=B[a.level].nice_length,a.max_chain_length=B[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=ha-1,a.match_available=0,a.ins_h=0}function t(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Y,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.sWindow=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new C.Buf16(2*fa),this.dyn_dtree=new C.Buf16(2*(2*da+1)),this.bl_tree=new C.Buf16(2*(2*ea+1)),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new C.Buf16(ga+1),this.heap=new C.Buf16(2*ca+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new C.Buf16(2*ca+1),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function u(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=X,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?la:qa,a.adler=2===b.wrap?0:1,b.last_flush=H,D._tr_init(b),M):d(a,O)}function v(a){var b=u(a);return b===M&&s(a.state),b}function w(a,b){return a&&a.state?2!==a.state.wrap?O:(a.state.gzhead=b,M):O}function x(a,b,c,e,f,g){if(!a)return O;var h=1;if(b===R&&(b=6),0>e?(h=0,e=-e):e>15&&(h=2,e-=16),1>f||f>Z||c!==Y||8>e||e>15||0>b||b>9||0>g||g>V)return d(a,O);8===e&&(e=9);var i=new t;return a.state=i,i.strm=a,i.wrap=h,i.gzhead=null,i.w_bits=e,i.w_size=1<<i.w_bits,i.w_mask=i.w_size-1,i.hash_bits=f+7,i.hash_size=1<<i.hash_bits,i.hash_mask=i.hash_size-1,i.hash_shift=~~((i.hash_bits+ha-1)/ha),i.sWindow=new C.Buf8(2*i.w_size),i.head=new C.Buf16(i.hash_size),i.prev=new C.Buf16(i.w_size),i.lit_bufsize=1<<f+6,i.pending_buf_size=4*i.lit_bufsize,i.pending_buf=new C.Buf8(i.pending_buf_size),i.d_buf=i.lit_bufsize>>1,i.l_buf=3*i.lit_bufsize,i.level=b,i.strategy=g,i.method=c,v(a)}function y(a,b){return x(a,b,Y,$,_,W)}function z(a,b){var c,h,k,l;if(!a||!a.state||b>L||0>b)return a?d(a,O):O;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===ra&&b!==K)return d(a,0===a.avail_out?Q:O);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===la)if(2===h.wrap)a.adler=0,i(h,31),i(h,139),i(h,8),h.gzhead?(i(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),i(h,255&h.gzhead.time),i(h,h.gzhead.time>>8&255),i(h,h.gzhead.time>>16&255),i(h,h.gzhead.time>>24&255),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(i(h,255&h.gzhead.extra.length),i(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(a.adler=F(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=ma):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,wa),h.status=qa);else{var m=Y+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=T||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=ka),m+=31-m%31,h.status=qa,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===ma)if(h.gzhead.extra){for(k=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending!==h.pending_buf_size));)i(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=na)}else h.status=na;if(h.status===na)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.name.length?255&h.gzhead.name.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=oa)}else h.status=oa;if(h.status===oa)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.comment.length?255&h.gzhead.comment.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=pa)}else h.status=pa;if(h.status===pa&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&g(a),h.pending+2<=h.pending_buf_size&&(i(h,255&a.adler),i(h,a.adler>>8&255),a.adler=0,h.status=qa)):h.status=qa),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,M}else if(0===a.avail_in&&e(b)<=e(c)&&b!==K)return d(a,Q);if(h.status===ra&&0!==a.avail_in)return d(a,Q);if(0!==a.avail_in||0!==h.lookahead||b!==H&&h.status!==ra){var o=h.strategy===T?r(h,b):h.strategy===U?q(h,b):B[h.level].func(h,b);if((o===ua||o===va)&&(h.status=ra),o===sa||o===ua)return 0===a.avail_out&&(h.last_flush=-1),M;if(o===ta&&(b===I?D._tr_align(h):b!==L&&(D._tr_stored_block(h,0,0,!1),b===J&&(f(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),g(a),0===a.avail_out))return h.last_flush=-1,M}return b!==K?M:h.wrap<=0?N:(2===h.wrap?(i(h,255&a.adler),i(h,a.adler>>8&255),i(h,a.adler>>16&255),i(h,a.adler>>24&255),i(h,255&a.total_in),i(h,a.total_in>>8&255),i(h,a.total_in>>16&255),i(h,a.total_in>>24&255)):(j(h,a.adler>>>16),j(h,65535&a.adler)),g(a),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?M:N)}function A(a){var b;return a&&a.state?(b=a.state.status,b!==la&&b!==ma&&b!==na&&b!==oa&&b!==pa&&b!==qa&&b!==ra?d(a,O):(a.state=null,b===qa?d(a,P):M)):O}var B,C=a("../utils/common"),D=a("./trees"),E=a("./adler32"),F=a("./crc32"),G=a("./messages"),H=0,I=1,J=3,K=4,L=5,M=0,N=1,O=-2,P=-3,Q=-5,R=-1,S=1,T=2,U=3,V=4,W=0,X=2,Y=8,Z=9,$=15,_=8,aa=29,ba=256,ca=ba+1+aa,da=30,ea=19,fa=2*ca+1,ga=15,ha=3,ia=258,ja=ia+ha+1,ka=32,la=42,ma=69,na=73,oa=91,pa=103,qa=113,ra=666,sa=1,ta=2,ua=3,va=4,wa=3,xa=function(a,b,c,d,e){this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e};B=[new xa(0,0,0,0,n),new xa(4,4,8,4,o),new xa(4,5,16,8,o),new xa(4,6,32,32,o),new xa(4,4,16,16,p),new xa(8,16,32,32,p),new xa(8,16,128,128,p),new xa(8,32,128,256,p),new xa(32,128,258,1024,p),new xa(32,258,258,4096,p)],c.deflateInit=y,c.deflateInit2=x,c.deflateReset=v,c.deflateResetKeep=u,c.deflateSetHeader=w,c.deflate=z,c.deflateEnd=A,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":47,"./adler32":49,"./crc32":51,"./messages":57,"./trees":58}],53:[function(a,b,c){"use strict";function d(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}b.exports=d},{}],54:[function(a,b,c){"use strict";var d=30,e=12;b.exports=function(a,b){var c,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C;c=a.state,f=a.next_in,B=a.input,g=f+(a.avail_in-5),h=a.next_out,C=a.output,i=h-(b-a.avail_out),j=h+(a.avail_out-257),k=c.dmax,l=c.wsize,m=c.whave,n=c.wnext,o=c.sWindow,p=c.hold,q=c.bits,r=c.lencode,s=c.distcode,t=(1<<c.lenbits)-1,u=(1<<c.distbits)-1;a:do{15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=r[p&t];b:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,0===w)C[h++]=65535&v;else{if(!(16&w)){if(0===(64&w)){v=r[(65535&v)+(p&(1<<w)-1)];continue b}if(32&w){c.mode=e;break a}a.msg="invalid literal/length code",c.mode=d;break a}x=65535&v,w&=15,w&&(w>q&&(p+=B[f++]<<q,q+=8),x+=p&(1<<w)-1,p>>>=w,q-=w),15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=s[p&u];c:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,!(16&w)){if(0===(64&w)){v=s[(65535&v)+(p&(1<<w)-1)];continue c}a.msg="invalid distance code",c.mode=d;break a}if(y=65535&v,w&=15,w>q&&(p+=B[f++]<<q,q+=8,w>q&&(p+=B[f++]<<q,q+=8)),y+=p&(1<<w)-1,y>k){a.msg="invalid distance too far back",c.mode=d;break a}if(p>>>=w,q-=w,w=h-i,y>w){if(w=y-w,w>m&&c.sane){a.msg="invalid distance too far back",c.mode=d;break a}if(z=0,A=o,0===n){if(z+=l-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}else if(w>n){if(z+=l+n-w,w-=n,x>w){x-=w;do C[h++]=o[z++];while(--w);if(z=0,x>n){w=n,x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}}else if(z+=n-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}for(;x>2;)C[h++]=A[z++],C[h++]=A[z++],C[h++]=A[z++],x-=3;x&&(C[h++]=A[z++],x>1&&(C[h++]=A[z++]))}else{z=h-y;do C[h++]=C[z++],C[h++]=C[z++],C[h++]=C[z++],x-=3;while(x>2);x&&(C[h++]=C[z++],x>1&&(C[h++]=C[z++]))}break}}break}}while(g>f&&j>h);x=q>>3,f-=x,q-=x<<3,p&=(1<<q)-1,a.next_in=f,a.next_out=h,a.avail_in=g>f?5+(g-f):5-(f-g),a.avail_out=j>h?257+(j-h):257-(h-j),c.hold=p,c.bits=q}},{}],55:[function(a,b,c){"use strict";function d(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function e(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.sWindow=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(a){var b;return a&&a.state?(b=a.state,a.total_in=a.total_out=b.total=0,a.msg="",b.wrap&&(a.adler=1&b.wrap),b.mode=K,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new r.Buf32(oa),b.distcode=b.distdyn=new r.Buf32(pa),b.sane=1,b.back=-1,C):F}function g(a){var b;return a&&a.state?(b=a.state,b.wsize=0,b.whave=0,b.wnext=0,f(a)):F}function h(a,b){var c,d;return a&&a.state?(d=a.state,0>b?(c=0,b=-b):(c=(b>>4)+1,48>b&&(b&=15)),b&&(8>b||b>15)?F:(null!==d.sWindow&&d.wbits!==b&&(d.sWindow=null),d.wrap=c,d.wbits=b,g(a))):F}function i(a,b){var c,d;return a?(d=new e,a.state=d,d.sWindow=null,c=h(a,b),c!==C&&(a.state=null),c):F}function j(a){return i(a,ra)}function k(a){if(sa){var b;for(p=new r.Buf32(512),q=new r.Buf32(32),b=0;144>b;)a.lens[b++]=8;for(;256>b;)a.lens[b++]=9;for(;280>b;)a.lens[b++]=7;for(;288>b;)a.lens[b++]=8;for(v(x,a.lens,0,288,p,0,a.work,{bits:9}),b=0;32>b;)a.lens[b++]=5;v(y,a.lens,0,32,q,0,a.work,{bits:5}),sa=!1}a.lencode=p,a.lenbits=9,a.distcode=q,a.distbits=5}function l(a,b,c,d){var e,f=a.state;return null===f.sWindow&&(f.wsize=1<<f.wbits,f.wnext=0,f.whave=0,f.sWindow=new r.Buf8(f.wsize)),d>=f.wsize?(r.arraySet(f.sWindow,b,c-f.wsize,f.wsize,0),f.wnext=0,f.whave=f.wsize):(e=f.wsize-f.wnext,e>d&&(e=d),r.arraySet(f.sWindow,b,c-d,e,f.wnext),d-=e,d?(r.arraySet(f.sWindow,b,c-d,d,0),f.wnext=d,f.whave=f.wsize):(f.wnext+=e,f.wnext===f.wsize&&(f.wnext=0),f.whave<f.wsize&&(f.whave+=e))),0}function m(a,b){var c,e,f,g,h,i,j,m,n,o,p,q,oa,pa,qa,ra,sa,ta,ua,va,wa,xa,ya,za,Aa=0,Ba=new r.Buf8(4),Ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!a||!a.state||!a.output||!a.input&&0!==a.avail_in)return F;c=a.state,c.mode===V&&(c.mode=W),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,o=i,p=j,xa=C;a:for(;;)switch(c.mode){case K:if(0===c.wrap){c.mode=W;break}for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(2&c.wrap&&35615===m){c.check=0,Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0),m=0,n=0,c.mode=L;break}if(c.flags=0,c.head&&(c.head.done=!1),!(1&c.wrap)||(((255&m)<<8)+(m>>8))%31){a.msg="incorrect header check",c.mode=la;break}if((15&m)!==J){a.msg="unknown compression method",c.mode=la;break}if(m>>>=4,n-=4,wa=(15&m)+8,0===c.wbits)c.wbits=wa;else if(wa>c.wbits){a.msg="invalid sWindow size",c.mode=la;break}c.dmax=1<<wa,a.adler=c.check=1,c.mode=512&m?T:V,m=0,n=0;break;case L:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.flags=m,(255&c.flags)!==J){a.msg="unknown compression method",c.mode=la;break}if(57344&c.flags){a.msg="unknown header flags set",c.mode=la;break}c.head&&(c.head.text=m>>8&1),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=M;case M:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.time=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,Ba[2]=m>>>16&255,Ba[3]=m>>>24&255,c.check=t(c.check,Ba,4,0)),m=0,n=0,c.mode=N;case N:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.xflags=255&m,c.head.os=m>>8),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=O;case O:if(1024&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length=m,c.head&&(c.head.extra_len=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0}else c.head&&(c.head.extra=null);c.mode=P;case P:if(1024&c.flags&&(q=c.length,q>i&&(q=i),q&&(c.head&&(wa=c.head.extra_len-c.length,c.head.extra||(c.head.extra=new Array(c.head.extra_len)),r.arraySet(c.head.extra,e,g,q,wa)),512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,c.length-=q),c.length))break a;c.length=0,c.mode=Q;case Q:if(2048&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.name+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.name=null);c.length=0,c.mode=R;case R:if(4096&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.comment+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.comment=null);c.mode=S;case S:if(512&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(65535&c.check)){a.msg="header crc mismatch",c.mode=la;break}m=0,n=0}c.head&&(c.head.hcrc=c.flags>>9&1,c.head.done=!0),a.adler=c.check=0,c.mode=V;break;case T:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}a.adler=c.check=d(m),m=0,n=0,c.mode=U;case U:if(0===c.havedict)return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,E;a.adler=c.check=1,c.mode=V;case V:if(b===A||b===B)break a;case W:if(c.last){m>>>=7&n,n-=7&n,c.mode=ia;break}for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}switch(c.last=1&m,m>>>=1,n-=1,3&m){case 0:c.mode=X;break;case 1:if(k(c),c.mode=ba,b===B){m>>>=2,n-=2;break a}break;case 2:c.mode=$;break;case 3:a.msg="invalid block type",c.mode=la}m>>>=2,n-=2;break;case X:for(m>>>=7&n,n-=7&n;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if((65535&m)!==(m>>>16^65535)){a.msg="invalid stored block lengths",c.mode=la;break}if(c.length=65535&m,m=0,n=0,c.mode=Y,b===B)break a;case Y:c.mode=Z;case Z:if(q=c.length){if(q>i&&(q=i),q>j&&(q=j),0===q)break a;r.arraySet(f,e,g,q,h),i-=q,g+=q,j-=q,h+=q,c.length-=q;break}c.mode=V;break;case $:for(;14>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.nlen=(31&m)+257,m>>>=5,n-=5,c.ndist=(31&m)+1,m>>>=5,n-=5,c.ncode=(15&m)+4,m>>>=4,n-=4,c.nlen>286||c.ndist>30){a.msg="too many length or distance symbols",c.mode=la;break}c.have=0,c.mode=_;case _:for(;c.have<c.ncode;){for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.lens[Ca[c.have++]]=7&m,m>>>=3,n-=3}for(;c.have<19;)c.lens[Ca[c.have++]]=0;if(c.lencode=c.lendyn,c.lenbits=7,ya={bits:c.lenbits},xa=v(w,c.lens,0,19,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid code lengths set",c.mode=la;break}c.have=0,c.mode=aa;case aa:for(;c.have<c.nlen+c.ndist;){for(;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(16>sa)m>>>=qa,n-=qa,c.lens[c.have++]=sa;else{if(16===sa){for(za=qa+2;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m>>>=qa,n-=qa,0===c.have){a.msg="invalid bit length repeat",c.mode=la;break}wa=c.lens[c.have-1],q=3+(3&m),m>>>=2,n-=2}else if(17===sa){for(za=qa+3;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=3+(7&m),m>>>=3,n-=3}else{for(za=qa+7;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=11+(127&m),m>>>=7,n-=7}if(c.have+q>c.nlen+c.ndist){a.msg="invalid bit length repeat",c.mode=la;break}for(;q--;)c.lens[c.have++]=wa}}if(c.mode===la)break;if(0===c.lens[256]){a.msg="invalid code -- missing end-of-block",c.mode=la;break}if(c.lenbits=9,ya={bits:c.lenbits},xa=v(x,c.lens,0,c.nlen,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid literal/lengths set",c.mode=la;break}if(c.distbits=6,c.distcode=c.distdyn,ya={bits:c.distbits},xa=v(y,c.lens,c.nlen,c.ndist,c.distcode,0,c.work,ya),c.distbits=ya.bits,xa){a.msg="invalid distances set",c.mode=la;break}if(c.mode=ba,b===B)break a;case ba:c.mode=ca;case ca:if(i>=6&&j>=258){a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,u(a,p),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,c.mode===V&&(c.back=-1);break}for(c.back=0;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(ra&&0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.lencode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,c.length=sa,0===ra){c.mode=ha;break}if(32&ra){c.back=-1,c.mode=V;break}if(64&ra){a.msg="invalid literal/length code",c.mode=la;break}c.extra=15&ra,c.mode=da;case da:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}c.was=c.length,c.mode=ea;case ea:for(;Aa=c.distcode[m&(1<<c.distbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.distcode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,64&ra){a.msg="invalid distance code",c.mode=la;break}c.offset=sa,c.extra=15&ra,c.mode=fa;case fa:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.offset+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}if(c.offset>c.dmax){a.msg="invalid distance too far back",c.mode=la;break}c.mode=ga;case ga:if(0===j)break a;if(q=p-j,c.offset>q){if(q=c.offset-q,q>c.whave&&c.sane){a.msg="invalid distance too far back",c.mode=la;break}q>c.wnext?(q-=c.wnext,oa=c.wsize-q):oa=c.wnext-q,q>c.length&&(q=c.length),pa=c.sWindow}else pa=f,oa=h-c.offset,q=c.length;q>j&&(q=j),j-=q,c.length-=q;do f[h++]=pa[oa++];while(--q);0===c.length&&(c.mode=ca);break;case ha:if(0===j)break a;f[h++]=c.length,j--,c.mode=ca;break;case ia:if(c.wrap){for(;32>n;){if(0===i)break a;i--,m|=e[g++]<<n,n+=8}if(p-=j,a.total_out+=p,c.total+=p,p&&(a.adler=c.check=c.flags?t(c.check,f,p,h-p):s(c.check,f,p,h-p)),p=j,(c.flags?m:d(m))!==c.check){a.msg="incorrect data check",c.mode=la;break}m=0,n=0}c.mode=ja;case ja:if(c.wrap&&c.flags){for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(4294967295&c.total)){a.msg="incorrect length check",c.mode=la;break}m=0,n=0}c.mode=ka;case ka:xa=D;break a;case la:xa=G;break a;case ma:return H;case na:default:return F}return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,(c.wsize||p!==a.avail_out&&c.mode<la&&(c.mode<ia||b!==z))&&l(a,a.output,a.next_out,p-a.avail_out)?(c.mode=ma,H):(o-=a.avail_in,p-=a.avail_out,a.total_in+=o,a.total_out+=p,c.total+=p,c.wrap&&p&&(a.adler=c.check=c.flags?t(c.check,f,p,a.next_out-p):s(c.check,f,p,a.next_out-p)),a.data_type=c.bits+(c.last?64:0)+(c.mode===V?128:0)+(c.mode===ba||c.mode===Y?256:0),(0===o&&0===p||b===z)&&xa===C&&(xa=I),xa)}function n(a){if(!a||!a.state)return F;var b=a.state;return b.sWindow&&(b.sWindow=null),a.state=null,C}function o(a,b){var c;return a&&a.state?(c=a.state,0===(2&c.wrap)?F:(c.head=b,b.done=!1,C)):F}var p,q,r=a("../utils/common"),s=a("./adler32"),t=a("./crc32"),u=a("./inffast"),v=a("./inftrees"),w=0,x=1,y=2,z=4,A=5,B=6,C=0,D=1,E=2,F=-2,G=-3,H=-4,I=-5,J=8,K=1,L=2,M=3,N=4,O=5,P=6,Q=7,R=8,S=9,T=10,U=11,V=12,W=13,X=14,Y=15,Z=16,$=17,_=18,aa=19,ba=20,ca=21,da=22,ea=23,fa=24,ga=25,ha=26,ia=27,ja=28,ka=29,la=30,ma=31,na=32,oa=852,pa=592,qa=15,ra=qa,sa=!0;c.inflateReset=g,c.inflateReset2=h,c.inflateResetKeep=f,c.inflateInit=j,c.inflateInit2=i,c.inflate=m,c.inflateEnd=n,c.inflateGetHeader=o,c.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":47,"./adler32":49,"./crc32":51,"./inffast":54,"./inftrees":56}],56:[function(a,b,c){"use strict";var d=a("../utils/common"),e=15,f=852,g=592,h=0,i=1,j=2,k=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],l=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],m=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],n=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];b.exports=function(a,b,c,o,p,q,r,s){var t,u,v,w,x,y,z,A,B,C=s.bits,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=null,O=0,P=new d.Buf16(e+1),Q=new d.Buf16(e+1),R=null,S=0;for(D=0;e>=D;D++)P[D]=0;for(E=0;o>E;E++)P[b[c+E]]++;for(H=C,G=e;G>=1&&0===P[G];G--);if(H>G&&(H=G),0===G)return p[q++]=20971520,p[q++]=20971520,s.bits=1,0;for(F=1;G>F&&0===P[F];F++);for(F>H&&(H=F),K=1,D=1;e>=D;D++)if(K<<=1,K-=P[D],0>K)return-1;if(K>0&&(a===h||1!==G))return-1;for(Q[1]=0,D=1;e>D;D++)Q[D+1]=Q[D]+P[D];for(E=0;o>E;E++)0!==b[c+E]&&(r[Q[b[c+E]]++]=E);if(a===h?(N=R=r,y=19):a===i?(N=k,O-=257,R=l,S-=257,y=256):(N=m,R=n,y=-1),M=0,E=0,D=F,x=q,I=H,J=0,v=-1,L=1<<H,w=L-1,a===i&&L>f||a===j&&L>g)return 1;for(var T=0;;){T++,z=D-J,r[E]<y?(A=0,B=r[E]):r[E]>y?(A=R[S+r[E]],B=N[O+r[E]]):(A=96,B=0),t=1<<D-J,u=1<<I,F=u;do u-=t,p[x+(M>>J)+u]=z<<24|A<<16|B|0;while(0!==u);for(t=1<<D-1;M&t;)t>>=1;if(0!==t?(M&=t-1,M+=t):M=0,E++,0===--P[D]){if(D===G)break;D=b[c+r[E]]}if(D>H&&(M&w)!==v){for(0===J&&(J=H),x+=F,I=D-J,K=1<<I;G>I+J&&(K-=P[I+J],!(0>=K));)I++,K<<=1;if(L+=1<<I,a===i&&L>f||a===j&&L>g)return 1;v=M&w,p[v]=H<<24|I<<16|x-q|0}}return 0!==M&&(p[x+M]=D-J<<24|64<<16|0),s.bits=H,0}},{"../utils/common":47}],57:[function(a,b,c){"use strict";b.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],58:[function(a,b,c){"use strict";function d(a){for(var b=a.length;--b>=0;)a[b]=0}function e(a){return 256>a?ga[a]:ga[256+(a>>>7)]}function f(a,b){a.pending_buf[a.pending++]=255&b,a.pending_buf[a.pending++]=b>>>8&255}function g(a,b,c){a.bi_valid>V-c?(a.bi_buf|=b<<a.bi_valid&65535,f(a,a.bi_buf),a.bi_buf=b>>V-a.bi_valid,a.bi_valid+=c-V):(a.bi_buf|=b<<a.bi_valid&65535,a.bi_valid+=c)}function h(a,b,c){g(a,c[2*b],c[2*b+1])}function i(a,b){var c=0;do c|=1&a,a>>>=1,c<<=1;while(--b>0);return c>>>1}function j(a){16===a.bi_valid?(f(a,a.bi_buf),a.bi_buf=0,a.bi_valid=0):a.bi_valid>=8&&(a.pending_buf[a.pending++]=255&a.bi_buf,a.bi_buf>>=8,a.bi_valid-=8)}function k(a,b){var c,d,e,f,g,h,i=b.dyn_tree,j=b.max_code,k=b.stat_desc.static_tree,l=b.stat_desc.has_stree,m=b.stat_desc.extra_bits,n=b.stat_desc.extra_base,o=b.stat_desc.max_length,p=0;for(f=0;U>=f;f++)a.bl_count[f]=0;for(i[2*a.heap[a.heap_max]+1]=0,c=a.heap_max+1;T>c;c++)d=a.heap[c],f=i[2*i[2*d+1]+1]+1,f>o&&(f=o,p++),i[2*d+1]=f,d>j||(a.bl_count[f]++,g=0,d>=n&&(g=m[d-n]),h=i[2*d],a.opt_len+=h*(f+g),l&&(a.static_len+=h*(k[2*d+1]+g)));if(0!==p){do{for(f=o-1;0===a.bl_count[f];)f--;a.bl_count[f]--,a.bl_count[f+1]+=2,a.bl_count[o]--,p-=2}while(p>0);for(f=o;0!==f;f--)for(d=a.bl_count[f];0!==d;)e=a.heap[--c],e>j||(i[2*e+1]!==f&&(a.opt_len+=(f-i[2*e+1])*i[2*e],i[2*e+1]=f),d--)}}function l(a,b,c){var d,e,f=new Array(U+1),g=0;for(d=1;U>=d;d++)f[d]=g=g+c[d-1]<<1;for(e=0;b>=e;e++){var h=a[2*e+1];0!==h&&(a[2*e]=i(f[h]++,h))}}function m(){var a,b,c,d,e,f=new Array(U+1);for(c=0,d=0;O-1>d;d++)for(ia[d]=c,a=0;a<1<<_[d];a++)ha[c++]=d;for(ha[c-1]=d,e=0,d=0;16>d;d++)for(ja[d]=e,a=0;a<1<<aa[d];a++)ga[e++]=d;for(e>>=7;R>d;d++)for(ja[d]=e<<7,a=0;a<1<<aa[d]-7;a++)ga[256+e++]=d;for(b=0;U>=b;b++)f[b]=0;for(a=0;143>=a;)ea[2*a+1]=8,a++,f[8]++;for(;255>=a;)ea[2*a+1]=9,a++,f[9]++;for(;279>=a;)ea[2*a+1]=7,a++,f[7]++;for(;287>=a;)ea[2*a+1]=8,a++,f[8]++;for(l(ea,Q+1,f),a=0;R>a;a++)fa[2*a+1]=5,fa[2*a]=i(a,5);ka=new na(ea,_,P+1,Q,U),la=new na(fa,aa,0,R,U),ma=new na(new Array(0),ba,0,S,W)}function n(a){var b;for(b=0;Q>b;b++)a.dyn_ltree[2*b]=0;for(b=0;R>b;b++)a.dyn_dtree[2*b]=0;for(b=0;S>b;b++)a.bl_tree[2*b]=0;a.dyn_ltree[2*X]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function o(a){a.bi_valid>8?f(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function p(a,b,c,d){o(a),d&&(f(a,c),f(a,~c)),E.arraySet(a.pending_buf,a.sWindow,b,c,a.pending),a.pending+=c}function q(a,b,c,d){var e=2*b,f=2*c;return a[e]<a[f]||a[e]===a[f]&&d[b]<=d[c]}function r(a,b,c){for(var d=a.heap[c],e=c<<1;e<=a.heap_len&&(e<a.heap_len&&q(b,a.heap[e+1],a.heap[e],a.depth)&&e++,!q(b,d,a.heap[e],a.depth));)a.heap[c]=a.heap[e],c=e,e<<=1;a.heap[c]=d}function s(a,b,c){var d,f,i,j,k=0;if(0!==a.last_lit)do d=a.pending_buf[a.d_buf+2*k]<<8|a.pending_buf[a.d_buf+2*k+1],f=a.pending_buf[a.l_buf+k],k++,0===d?h(a,f,b):(i=ha[f],h(a,i+P+1,b),j=_[i],0!==j&&(f-=ia[i],g(a,f,j)),d--,i=e(d),h(a,i,c),j=aa[i],0!==j&&(d-=ja[i],g(a,d,j)));while(k<a.last_lit);h(a,X,b)}function t(a,b){var c,d,e,f=b.dyn_tree,g=b.stat_desc.static_tree,h=b.stat_desc.has_stree,i=b.stat_desc.elems,j=-1; for(a.heap_len=0,a.heap_max=T,c=0;i>c;c++)0!==f[2*c]?(a.heap[++a.heap_len]=j=c,a.depth[c]=0):f[2*c+1]=0;for(;a.heap_len<2;)e=a.heap[++a.heap_len]=2>j?++j:0,f[2*e]=1,a.depth[e]=0,a.opt_len--,h&&(a.static_len-=g[2*e+1]);for(b.max_code=j,c=a.heap_len>>1;c>=1;c--)r(a,f,c);e=i;do c=a.heap[1],a.heap[1]=a.heap[a.heap_len--],r(a,f,1),d=a.heap[1],a.heap[--a.heap_max]=c,a.heap[--a.heap_max]=d,f[2*e]=f[2*c]+f[2*d],a.depth[e]=(a.depth[c]>=a.depth[d]?a.depth[c]:a.depth[d])+1,f[2*c+1]=f[2*d+1]=e,a.heap[1]=e++,r(a,f,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],k(a,b),l(f,j,a.bl_count)}function u(a,b,c){var d,e,f=-1,g=b[1],h=0,i=7,j=4;for(0===g&&(i=138,j=3),b[2*(c+1)+1]=65535,d=0;c>=d;d++)e=g,g=b[2*(d+1)+1],++h<i&&e===g||(j>h?a.bl_tree[2*e]+=h:0!==e?(e!==f&&a.bl_tree[2*e]++,a.bl_tree[2*Y]++):10>=h?a.bl_tree[2*Z]++:a.bl_tree[2*$]++,h=0,f=e,0===g?(i=138,j=3):e===g?(i=6,j=3):(i=7,j=4))}function v(a,b,c){var d,e,f=-1,i=b[1],j=0,k=7,l=4;for(0===i&&(k=138,l=3),d=0;c>=d;d++)if(e=i,i=b[2*(d+1)+1],!(++j<k&&e===i)){if(l>j){do h(a,e,a.bl_tree);while(0!==--j)}else 0!==e?(e!==f&&(h(a,e,a.bl_tree),j--),h(a,Y,a.bl_tree),g(a,j-3,2)):10>=j?(h(a,Z,a.bl_tree),g(a,j-3,3)):(h(a,$,a.bl_tree),g(a,j-11,7));j=0,f=e,0===i?(k=138,l=3):e===i?(k=6,l=3):(k=7,l=4)}}function w(a){var b;for(u(a,a.dyn_ltree,a.l_desc.max_code),u(a,a.dyn_dtree,a.d_desc.max_code),t(a,a.bl_desc),b=S-1;b>=3&&0===a.bl_tree[2*ca[b]+1];b--);return a.opt_len+=3*(b+1)+5+5+4,b}function x(a,b,c,d){var e;for(g(a,b-257,5),g(a,c-1,5),g(a,d-4,4),e=0;d>e;e++)g(a,a.bl_tree[2*ca[e]+1],3);v(a,a.dyn_ltree,b-1),v(a,a.dyn_dtree,c-1)}function y(a){var b,c=4093624447;for(b=0;31>=b;b++,c>>>=1)if(1&c&&0!==a.dyn_ltree[2*b])return G;if(0!==a.dyn_ltree[18]||0!==a.dyn_ltree[20]||0!==a.dyn_ltree[26])return H;for(b=32;P>b;b++)if(0!==a.dyn_ltree[2*b])return H;return G}function z(a){pa||(m(),pa=!0),a.l_desc=new oa(a.dyn_ltree,ka),a.d_desc=new oa(a.dyn_dtree,la),a.bl_desc=new oa(a.bl_tree,ma),a.bi_buf=0,a.bi_valid=0,n(a)}function A(a,b,c,d){g(a,(J<<1)+(d?1:0),3),p(a,b,c,!0)}function B(a){g(a,K<<1,3),h(a,X,ea),j(a)}function C(a,b,c,d){var e,f,h=0;a.level>0?(a.strm.data_type===I&&(a.strm.data_type=y(a)),t(a,a.l_desc),t(a,a.d_desc),h=w(a),e=a.opt_len+3+7>>>3,f=a.static_len+3+7>>>3,e>=f&&(e=f)):e=f=c+5,e>=c+4&&-1!==b?A(a,b,c,d):a.strategy===F||f===e?(g(a,(K<<1)+(d?1:0),3),s(a,ea,fa)):(g(a,(L<<1)+(d?1:0),3),x(a,a.l_desc.max_code+1,a.d_desc.max_code+1,h+1),s(a,a.dyn_ltree,a.dyn_dtree)),n(a),d&&o(a)}function D(a,b,c){return a.pending_buf[a.d_buf+2*a.last_lit]=b>>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&b,a.pending_buf[a.l_buf+a.last_lit]=255&c,a.last_lit++,0===b?a.dyn_ltree[2*c]++:(a.matches++,b--,a.dyn_ltree[2*(ha[c]+P+1)]++,a.dyn_dtree[2*e(b)]++),a.last_lit===a.lit_bufsize-1}var E=a("../utils/common"),F=4,G=0,H=1,I=2,J=0,K=1,L=2,M=3,N=258,O=29,P=256,Q=P+1+O,R=30,S=19,T=2*Q+1,U=15,V=16,W=7,X=256,Y=16,Z=17,$=18,_=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],aa=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],ba=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],da=512,ea=new Array(2*(Q+2));d(ea);var fa=new Array(2*R);d(fa);var ga=new Array(da);d(ga);var ha=new Array(N-M+1);d(ha);var ia=new Array(O);d(ia);var ja=new Array(R);d(ja);var ka,la,ma,na=function(a,b,c,d,e){this.static_tree=a,this.extra_bits=b,this.extra_base=c,this.elems=d,this.max_length=e,this.has_stree=a&&a.length},oa=function(a,b){this.dyn_tree=a,this.max_code=0,this.stat_desc=b},pa=!1;c._tr_init=z,c._tr_stored_block=A,c._tr_flush_block=C,c._tr_tally=D,c._tr_align=B},{"../utils/common":47}],59:[function(a,b,c){"use strict";function d(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}b.exports=d},{}]},{},[1]);
client/apps/plugin-status/log.js
Automattic/woocommerce-connect-client
/** * External dependencies */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { localize } from 'i18n-calypso'; /** * Internal dependencies */ import ClipboardButton from 'components/forms/clipboard-button'; import FormFieldset from 'components/forms/form-fieldset'; import FormLabel from 'components/forms/form-label'; import FormTextarea from 'components/forms/form-textarea'; import FormSettingExplanation from 'components/forms/form-setting-explanation'; import notices from 'notices'; class LogView extends Component { onCopy = () => { const { translate } = this.props; notices.success( translate( 'Log tail copied to clipboard' ), { duration: 2000 } ); } render() { const { key, title, tail, url, count, translate } = this.props; const id = `wcs-log-${ key }`; return ( <FormFieldset> <FormLabel htmlFor={ id }>{ title }</FormLabel> <FormTextarea id={ id } name={ id } readOnly value={ tail } /> <FormSettingExplanation className="plugin-status__log-explanation"> <span className="plugin-status__log-explanation-span"> { translate( 'Last %s entry. {{a}}Show full log{{/a}}', 'Last %s entries. {{a}}Show full log{{/a}}', { args: [ count ], count: count, components: { a: <a href={ url } /> }, } ) } </span> <ClipboardButton text={ tail } onCopy={ this.onCopy } compact> { translate( 'Copy for support' ) } </ClipboardButton> </FormSettingExplanation> </FormFieldset> ); } } LogView.propTypes = { title: PropTypes.string, logKey: PropTypes.string, }; export default connect( ( state, { logKey } ) => state.status.logs[ logKey ] )( localize( LogView ) );
ajax/libs/ember-data.js/2.11.0/ember-data.prod.js
jonobr1/cdnjs
(function(){ "use strict"; /*! * @overview Ember Data * @copyright Copyright 2011-2016 Tilde Inc. and contributors. * Portions Copyright 2011 LivingSocial Inc. * @license Licensed under MIT license (see license.js) * @version 2.11.0 */ var loader, define, requireModule, require, requirejs; (function(global) { 'use strict'; var stats; // Save off the original values of these globals, so we can restore them if someone asks us to var oldGlobals = { loader: loader, define: define, requireModule: requireModule, require: require, requirejs: requirejs }; requirejs = require = requireModule = function(name) { stats.require++; var pending = []; var mod = findModule(name, '(require)', pending); for (var i = pending.length - 1; i >= 0; i--) { pending[i].exports(); } return mod.module.exports; }; function resetStats() { stats = { define: 0, require: 0, reify: 0, findDeps: 0, modules: 0, exports: 0, resolve: 0, resolveRelative: 0, findModule: 0, pendingQueueLength: 0 }; requirejs._stats = stats; } resetStats(); loader = { noConflict: function(aliases) { var oldName, newName; for (oldName in aliases) { if (aliases.hasOwnProperty(oldName)) { if (oldGlobals.hasOwnProperty(oldName)) { newName = aliases[oldName]; global[newName] = global[oldName]; global[oldName] = oldGlobals[oldName]; } } } } }; var _isArray; if (!Array.isArray) { _isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } else { _isArray = Array.isArray; } var registry = {}; var seen = {}; var uuid = 0; function unsupportedModule(length) { throw new Error('an unsupported module was defined, expected `define(name, deps, module)` instead got: `' + length + '` arguments to define`'); } var defaultDeps = ['require', 'exports', 'module']; function Module(name, deps, callback, alias) { stats.modules++; this.id = uuid++; this.name = name; this.deps = !deps.length && callback.length ? defaultDeps : deps; this.module = { exports: {} }; this.callback = callback; this.hasExportsAsDep = false; this.isAlias = alias; this.reified = new Array(deps.length); /* Each module normally passes through these states, in order: new : initial state pending : this module is scheduled to be executed reifying : this module's dependencies are being executed reified : this module's dependencies finished executing successfully errored : this module's dependencies failed to execute finalized : this module executed successfully */ this.state = 'new'; } Module.prototype.makeDefaultExport = function() { var exports = this.module.exports; if (exports !== null && (typeof exports === 'object' || typeof exports === 'function') && exports['default'] === undefined && !Object.isFrozen(exports)) { exports['default'] = exports; } }; Module.prototype.exports = function() { // if finalized, there is no work to do. If reifying, there is a // circular dependency so we must return our (partial) exports. if (this.state === 'finalized' || this.state === 'reifying') { return this.module.exports; } stats.exports++; if (loader.wrapModules) { this.callback = loader.wrapModules(this.name, this.callback); } this.reify(); var result = this.callback.apply(this, this.reified); this.state = 'finalized'; if (!(this.hasExportsAsDep && result === undefined)) { this.module.exports = result; } this.makeDefaultExport(); return this.module.exports; }; Module.prototype.unsee = function() { this.state = 'new'; this.module = { exports: {} }; }; Module.prototype.reify = function() { if (this.state === 'reified') { return; } this.state = 'reifying'; try { this.reified = this._reify(); this.state = 'reified'; } finally { if (this.state === 'reifying') { this.state = 'errored'; } } }; Module.prototype._reify = function() { stats.reify++; var reified = this.reified.slice(); for (var i = 0; i < reified.length; i++) { var mod = reified[i]; reified[i] = mod.exports ? mod.exports : mod.module.exports(); } return reified; }; Module.prototype.findDeps = function(pending) { if (this.state !== 'new') { return; } stats.findDeps++; this.state = 'pending'; var deps = this.deps; for (var i = 0; i < deps.length; i++) { var dep = deps[i]; var entry = this.reified[i] = { exports: undefined, module: undefined }; if (dep === 'exports') { this.hasExportsAsDep = true; entry.exports = this.module.exports; } else if (dep === 'require') { entry.exports = this.makeRequire(); } else if (dep === 'module') { entry.exports = this.module; } else { entry.module = findModule(resolve(dep, this.name), this.name, pending); } } }; Module.prototype.makeRequire = function() { var name = this.name; var r = function(dep) { return require(resolve(dep, name)); }; r['default'] = r; r.has = function(dep) { return has(resolve(dep, name)); }; return r; }; define = function(name, deps, callback) { stats.define++; if (arguments.length < 2) { unsupportedModule(arguments.length); } if (!_isArray(deps)) { callback = deps; deps = []; } if (callback instanceof Alias) { registry[name] = new Module(callback.name, deps, callback, true); } else { registry[name] = new Module(name, deps, callback, false); } }; // we don't support all of AMD // define.amd = {}; // we will support petals... define.petal = { }; function Alias(path) { this.name = path; } define.alias = function(path) { return new Alias(path); }; function missingModule(name, referrer) { throw new Error('Could not find module `' + name + '` imported from `' + referrer + '`'); } function findModule(name, referrer, pending) { stats.findModule++; var mod = registry[name] || registry[name + '/index']; while (mod && mod.isAlias) { mod = registry[mod.name]; } if (!mod) { missingModule(name, referrer); } if (pending && mod.state !== 'pending' && mod.state !== 'finalized') { mod.findDeps(pending); pending.push(mod); stats.pendingQueueLength++; } return mod; } function resolve(child, name) { stats.resolve++; if (child.charAt(0) !== '.') { return child; } stats.resolveRelative++; var parts = child.split('/'); var nameParts = name.split('/'); var parentBase = nameParts.slice(0, -1); for (var i = 0, l = parts.length; i < l; i++) { var part = parts[i]; if (part === '..') { if (parentBase.length === 0) { throw new Error('Cannot access parent module of root'); } parentBase.pop(); } else if (part === '.') { continue; } else { parentBase.push(part); } } return parentBase.join('/'); } function has(name) { return !!(registry[name] || registry[name + '/index']); } requirejs.entries = requirejs._eak_seen = registry; requirejs.has = has; requirejs.unsee = function(moduleName) { findModule(moduleName, '(unsee)', false).unsee(); }; requirejs.clear = function() { resetStats(); requirejs.entries = requirejs._eak_seen = registry = {}; seen = {}; }; // prime define('foo', function() {}); define('foo/bar', [], function() {}); define('foo/asdf', ['module', 'exports', 'require'], function(module, exports, require) { if (require.has('foo/bar')) { require('foo/bar'); } }); define('foo/baz', [], define.alias('foo')); define('foo/quz', define.alias('foo')); define('foo/bar', ['foo', './quz', './baz', './asdf', './bar', '../foo'], function() {}); define('foo/main', ['foo/bar'], function() {}); require('foo/main'); require.unsee('foo/bar'); requirejs.clear(); if (typeof exports === 'object' && typeof module === 'object' && module.exports) { module.exports = { require: require, define: define }; } })(this); define("ember-data/-private/adapters", ["exports", "ember-data/adapters/json-api", "ember-data/adapters/rest"], function (exports, _emberDataAdaptersJsonApi, _emberDataAdaptersRest) { exports.JSONAPIAdapter = _emberDataAdaptersJsonApi.default; exports.RESTAdapter = _emberDataAdaptersRest.default; }); /** @module ember-data */ define('ember-data/-private/adapters/build-url-mixin', ['exports', 'ember'], function (exports, _ember) { var get = _ember.default.get; /** WARNING: This interface is likely to change in order to accomodate https://github.com/emberjs/rfcs/pull/4 ## Using BuildURLMixin To use url building, include the mixin when extending an adapter, and call `buildURL` where needed. The default behaviour is designed for RESTAdapter. ### Example ```javascript export default DS.Adapter.extend(BuildURLMixin, { findRecord: function(store, type, id, snapshot) { var url = this.buildURL(type.modelName, id, snapshot, 'findRecord'); return this.ajax(url, 'GET'); } }); ``` ### Attributes The `host` and `namespace` attributes will be used if defined, and are optional. @class BuildURLMixin @namespace DS */ exports.default = _ember.default.Mixin.create({ /** Builds a URL for a given type and optional ID. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). To override the pluralization see [pathForType](#method_pathForType). If an ID is specified, it adds the ID to the path generated for the type, separated by a `/`. When called by RESTAdapter.findMany() the `id` and `snapshot` parameters will be arrays of ids and snapshots. @method buildURL @param {String} modelName @param {(String|Array|Object)} id single id or array of ids or query @param {(DS.Snapshot|Array)} snapshot single snapshot or array of snapshots @param {String} requestType @param {Object} query object of query parameters to send for query requests. @return {String} url */ buildURL: function (modelName, id, snapshot, requestType, query) { switch (requestType) { case 'findRecord': return this.urlForFindRecord(id, modelName, snapshot); case 'findAll': return this.urlForFindAll(modelName, snapshot); case 'query': return this.urlForQuery(query, modelName); case 'queryRecord': return this.urlForQueryRecord(query, modelName); case 'findMany': return this.urlForFindMany(id, modelName, snapshot); case 'findHasMany': return this.urlForFindHasMany(id, modelName, snapshot); case 'findBelongsTo': return this.urlForFindBelongsTo(id, modelName, snapshot); case 'createRecord': return this.urlForCreateRecord(modelName, snapshot); case 'updateRecord': return this.urlForUpdateRecord(id, modelName, snapshot); case 'deleteRecord': return this.urlForDeleteRecord(id, modelName, snapshot); default: return this._buildURL(modelName, id); } }, /** @method _buildURL @private @param {String} modelName @param {String} id @return {String} url */ _buildURL: function (modelName, id) { var url = []; var host = get(this, 'host'); var prefix = this.urlPrefix(); var path; if (modelName) { path = this.pathForType(modelName); if (path) { url.push(path); } } if (id) { url.push(encodeURIComponent(id)); } if (prefix) { url.unshift(prefix); } url = url.join('/'); if (!host && url && url.charAt(0) !== '/') { url = '/' + url; } return url; }, /** Builds a URL for a `store.findRecord(type, id)` call. Example: ```app/adapters/user.js import DS from 'ember-data'; export default DS.JSONAPIAdapter.extend({ urlForFindRecord(id, modelName, snapshot) { let baseUrl = this.buildURL(); return `${baseUrl}/users/${snapshot.adapterOptions.user_id}/playlists/${id}`; } }); ``` @method urlForFindRecord @param {String} id @param {String} modelName @param {DS.Snapshot} snapshot @return {String} url */ urlForFindRecord: function (id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** Builds a URL for a `store.findAll(type)` call. Example: ```app/adapters/comment.js import DS from 'ember-data'; export default DS.JSONAPIAdapter.extend({ urlForFindAll(id, modelName, snapshot) { return 'data/comments.json'; } }); ``` @method urlForFindAll @param {String} modelName @param {DS.SnapshotRecordArray} snapshot @return {String} url */ urlForFindAll: function (modelName, snapshot) { return this._buildURL(modelName); }, /** Builds a URL for a `store.query(type, query)` call. Example: ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ host: 'https://api.github.com', urlForQuery (query, modelName) { switch(modelName) { case 'repo': return `https://api.github.com/orgs/${query.orgId}/repos`; default: return this._super(...arguments); } } }); ``` @method urlForQuery @param {Object} query @param {String} modelName @return {String} url */ urlForQuery: function (query, modelName) { return this._buildURL(modelName); }, /** Builds a URL for a `store.queryRecord(type, query)` call. Example: ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ urlForQueryRecord({ slug }, modelName) { let baseUrl = this.buildURL(); return `${baseUrl}/${encodeURIComponent(slug)}`; } }); ``` @method urlForQueryRecord @param {Object} query @param {String} modelName @return {String} url */ urlForQueryRecord: function (query, modelName) { return this._buildURL(modelName); }, /** Builds a URL for coalesceing multiple `store.findRecord(type, id) records into 1 request when the adapter's `coalesceFindRequests` property is true. Example: ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ urlForFindMany(ids, modelName) { let baseUrl = this.buildURL(); return `${baseUrl}/coalesce`; } }); ``` @method urlForFindMany @param {Array} ids @param {String} modelName @param {Array} snapshots @return {String} url */ urlForFindMany: function (ids, modelName, snapshots) { return this._buildURL(modelName); }, /** Builds a URL for fetching a async hasMany relationship when a url is not provided by the server. Example: ```app/adapters/application.js import DS from 'ember-data'; export default DS.JSONAPIAdapter.extend({ urlForFindHasMany(id, modelName, snapshot) { let baseUrl = this.buildURL(id, modelName); return `${baseUrl}/relationships`; } }); ``` @method urlForFindHasMany @param {String} id @param {String} modelName @param {DS.Snapshot} snapshot @return {String} url */ urlForFindHasMany: function (id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** Builds a URL for fetching a async belongsTo relationship when a url is not provided by the server. Example: ```app/adapters/application.js import DS from 'ember-data'; export default DS.JSONAPIAdapter.extend({ urlForFindBelongsTo(id, modelName, snapshot) { let baseUrl = this.buildURL(id, modelName); return `${baseUrl}/relationships`; } }); ``` @method urlForFindBelongsTo @param {String} id @param {String} modelName @param {DS.Snapshot} snapshot @return {String} url */ urlForFindBelongsTo: function (id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** Builds a URL for a `record.save()` call when the record was created locally using `store.createRecord()`. Example: ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ urlForCreateRecord(modelName, snapshot) { return this._super(...arguments) + '/new'; } }); ``` @method urlForCreateRecord @param {String} modelName @param {DS.Snapshot} snapshot @return {String} url */ urlForCreateRecord: function (modelName, snapshot) { return this._buildURL(modelName); }, /** Builds a URL for a `record.save()` call when the record has been update locally. Example: ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ urlForUpdateRecord(id, modelName, snapshot) { return `/${id}/feed?access_token=${snapshot.adapterOptions.token}`; } }); ``` @method urlForUpdateRecord @param {String} id @param {String} modelName @param {DS.Snapshot} snapshot @return {String} url */ urlForUpdateRecord: function (id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** Builds a URL for a `record.save()` call when the record has been deleted locally. Example: ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ urlForDeleteRecord(id, modelName, snapshot) { return this._super(...arguments) + '/destroy'; } }); ``` @method urlForDeleteRecord @param {String} id @param {String} modelName @param {DS.Snapshot} snapshot @return {String} url */ urlForDeleteRecord: function (id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** @method urlPrefix @private @param {String} path @param {String} parentURL @return {String} urlPrefix */ urlPrefix: function (path, parentURL) { var host = get(this, 'host'); var namespace = get(this, 'namespace'); if (!host || host === '/') { host = ''; } if (path) { // Protocol relative url if (/^\/\//.test(path) || /http(s)?:\/\//.test(path)) { // Do nothing, the full host is already included. return path; // Absolute path } else if (path.charAt(0) === '/') { return '' + host + path; // Relative path } else { return parentURL + '/' + path; } } // No path provided var url = []; if (host) { url.push(host); } if (namespace) { url.push(namespace); } return url.join('/'); }, /** Determines the pathname for a given type. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). ### Pathname customization For example if you have an object LineItem with an endpoint of "/line_items/". ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ pathForType: function(modelName) { var decamelized = Ember.String.decamelize(modelName); return Ember.String.pluralize(decamelized); } }); ``` @method pathForType @param {String} modelName @return {String} path **/ pathForType: function (modelName) { var camelized = _ember.default.String.camelize(modelName); return _ember.default.String.pluralize(camelized); } }); }); define('ember-data/-private/core', ['exports', 'ember', 'ember-data/version'], function (exports, _ember, _emberDataVersion) { /** @module ember-data */ /** All Ember Data classes, methods and functions are defined inside of this namespace. @class DS @static */ /** @property VERSION @type String @static */ var DS = _ember.default.Namespace.create({ VERSION: _emberDataVersion.default, name: "DS" }); if (_ember.default.libraries) { _ember.default.libraries.registerCoreLibrary('Ember Data', DS.VERSION); } exports.default = DS; }); define('ember-data/-private/debug', ['exports', 'ember'], function (exports, _ember) { exports.assert = assert; exports.debug = debug; exports.deprecate = deprecate; exports.info = info; exports.runInDebug = runInDebug; exports.instrument = instrument; exports.warn = warn; exports.debugSeal = debugSeal; exports.assertPolymorphicType = assertPolymorphicType; function assert() { return _ember.default.assert.apply(_ember.default, arguments); } function debug() { return _ember.default.debug.apply(_ember.default, arguments); } function deprecate() { return _ember.default.deprecate.apply(_ember.default, arguments); } function info() { return _ember.default.info.apply(_ember.default, arguments); } function runInDebug() { return _ember.default.runInDebug.apply(_ember.default, arguments); } function instrument(method) { return method(); } function warn() { return _ember.default.warn.apply(_ember.default, arguments); } function debugSeal() { return _ember.default.debugSeal.apply(_ember.default, arguments); } function checkPolymorphic(modelClass, addedModelClass) { if (modelClass.__isMixin) { //TODO Need to do this in order to support mixins, should convert to public api //once it exists in Ember return modelClass.__mixin.detect(addedModelClass.PrototypeMixin); } if (_ember.default.MODEL_FACTORY_INJECTIONS) { modelClass = modelClass.superclass; } return modelClass.detect(addedModelClass); } /* Assert that `addedRecord` has a valid type so it can be added to the relationship of the `record`. The assert basically checks if the `addedRecord` can be added to the relationship (specified via `relationshipMeta`) of the `record`. This utility should only be used internally, as both record parameters must be an InternalModel and the `relationshipMeta` needs to be the meta information about the relationship, retrieved via `record.relationshipFor(key)`. @method assertPolymorphicType @param {InternalModel} internalModel @param {RelationshipMeta} relationshipMeta retrieved via `record.relationshipFor(key)` @param {InternalModel} addedRecord record which should be added/set for the relationship */ function assertPolymorphicType(parentInternalModel, relationshipMeta, addedInternalModel) { var addedModelName = addedInternalModel.modelName; var parentModelName = parentInternalModel.modelName; var key = relationshipMeta.key; var relationshipClass = parentInternalModel.store.modelFor(relationshipMeta.type); var assertionMessage = 'You cannot add a record of modelClass \'' + addedModelName + '\' to the \'' + parentModelName + '.' + key + '\' relationship (only \'' + relationshipClass.modelName + '\' allowed)'; assert(assertionMessage, checkPolymorphic(relationshipClass, addedInternalModel.modelClass)); } }); define('ember-data/-private/ext/date', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { /** Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601> © 2011 Colin Snover <http://zetafleet.com> Released under MIT license. @class Date @namespace Ember @static @deprecated */ _ember.default.Date = _ember.default.Date || {}; var origParse = Date.parse; var numericKeys = [1, 4, 5, 6, 7, 10, 11]; var parseDate = function (date) { var timestamp, struct; var minutesOffset = 0; // ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string // before falling back to any implementation-specific date parsing, so that’s what we do, even if native // implementations could be faster // 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm if (struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?:(\d{2}))?)?)?$/.exec(date)) { // avoid NaN timestamps caused by “undefined” values being passed to Date.UTC for (var i = 0, k; k = numericKeys[i]; ++i) { struct[k] = +struct[k] || 0; } // allow undefined days and months struct[2] = (+struct[2] || 1) - 1; struct[3] = +struct[3] || 1; if (struct[8] !== 'Z' && struct[9] !== undefined) { minutesOffset = struct[10] * 60 + struct[11]; if (struct[9] === '+') { minutesOffset = 0 - minutesOffset; } } timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]); } else { timestamp = origParse ? origParse(date) : NaN; } return timestamp; }; exports.parseDate = parseDate; _ember.default.Date.parse = function (date) { return parseDate(date); // throw deprecation }; if (_ember.default.EXTEND_PROTOTYPES === true || _ember.default.EXTEND_PROTOTYPES.Date) { Date.parse = parseDate; } }); /** @module ember-data */ define('ember-data/-private/features', ['exports', 'ember'], function (exports, _ember) { exports.default = isEnabled; function isEnabled() { var _Ember$FEATURES; return (_Ember$FEATURES = _ember.default.FEATURES).isEnabled.apply(_Ember$FEATURES, arguments); } }); define('ember-data/-private/global', ['exports'], function (exports) { /* globals global, window, self */ // originally from https://github.com/emberjs/ember.js/blob/c0bd26639f50efd6a03ee5b87035fd200e313b8e/packages/ember-environment/lib/global.js // from lodash to catch fake globals function checkGlobal(value) { return value && value.Object === Object ? value : undefined; } // element ids can ruin global miss checks function checkElementIdShadowing(value) { return value && value.nodeType === undefined ? value : undefined; } // export real global exports.default = checkGlobal(checkElementIdShadowing(typeof global === 'object' && global)) || checkGlobal(typeof self === 'object' && self) || checkGlobal(typeof window === 'object' && window) || new Function('return this')(); // eval outside of strict mode }); define("ember-data/-private/initializers/data-adapter", ["exports", "ember-data/-private/system/debug/debug-adapter"], function (exports, _emberDataPrivateSystemDebugDebugAdapter) { exports.default = initializeDebugAdapter; /* Configures a registry with injections on Ember applications for the Ember-Data store. Accepts an optional namespace argument. @method initializeDebugAdapter @param {Ember.Registry} registry */ function initializeDebugAdapter(registry) { registry.register('data-adapter:main', _emberDataPrivateSystemDebugDebugAdapter.default); } }); define('ember-data/-private/initializers/store-injections', ['exports'], function (exports) { exports.default = initializeStoreInjections; /* Configures a registry with injections on Ember applications for the Ember-Data store. Accepts an optional namespace argument. @method initializeStoreInjections @param {Ember.Registry} registry */ function initializeStoreInjections(registry) { // registry.injection for Ember < 2.1.0 // application.inject for Ember 2.1.0+ var inject = registry.inject || registry.injection; inject.call(registry, 'controller', 'store', 'service:store'); inject.call(registry, 'route', 'store', 'service:store'); inject.call(registry, 'data-adapter', 'store', 'service:store'); } }); define("ember-data/-private/initializers/store", ["exports", "ember-data/-private/system/store", "ember-data/-private/serializers", "ember-data/-private/adapters"], function (exports, _emberDataPrivateSystemStore, _emberDataPrivateSerializers, _emberDataPrivateAdapters) { exports.default = initializeStore; function has(applicationOrRegistry, fullName) { if (applicationOrRegistry.has) { // < 2.1.0 return applicationOrRegistry.has(fullName); } else { // 2.1.0+ return applicationOrRegistry.hasRegistration(fullName); } } /* Configures a registry for use with an Ember-Data store. Accepts an optional namespace argument. @method initializeStore @param {Ember.Registry} registry */ function initializeStore(registry) { // registry.optionsForType for Ember < 2.1.0 // application.registerOptionsForType for Ember 2.1.0+ var registerOptionsForType = registry.registerOptionsForType || registry.optionsForType; registerOptionsForType.call(registry, 'serializer', { singleton: false }); registerOptionsForType.call(registry, 'adapter', { singleton: false }); registry.register('serializer:-default', _emberDataPrivateSerializers.JSONSerializer); registry.register('serializer:-rest', _emberDataPrivateSerializers.RESTSerializer); registry.register('adapter:-rest', _emberDataPrivateAdapters.RESTAdapter); registry.register('adapter:-json-api', _emberDataPrivateAdapters.JSONAPIAdapter); registry.register('serializer:-json-api', _emberDataPrivateSerializers.JSONAPISerializer); if (!has(registry, 'service:store')) { registry.register('service:store', _emberDataPrivateSystemStore.default); } } }); define('ember-data/-private/initializers/transforms', ['exports', 'ember-data/-private/transforms'], function (exports, _emberDataPrivateTransforms) { exports.default = initializeTransforms; /* Configures a registry for use with Ember-Data transforms. @method initializeTransforms @param {Ember.Registry} registry */ function initializeTransforms(registry) { registry.register('transform:boolean', _emberDataPrivateTransforms.BooleanTransform); registry.register('transform:date', _emberDataPrivateTransforms.DateTransform); registry.register('transform:number', _emberDataPrivateTransforms.NumberTransform); registry.register('transform:string', _emberDataPrivateTransforms.StringTransform); } }); define('ember-data/-private/instance-initializers/initialize-store-service', ['exports'], function (exports) { exports.default = initializeStoreService; /* Configures a registry for use with an Ember-Data store. @method initializeStoreService @param {Ember.ApplicationInstance} applicationOrRegistry */ function initializeStoreService(application) { var container = application.lookup ? application : application.container; // Eagerly generate the store so defaultStore is populated. container.lookup('service:store'); } }); define("ember-data/-private/serializers", ["exports", "ember-data/serializers/json-api", "ember-data/serializers/json", "ember-data/serializers/rest"], function (exports, _emberDataSerializersJsonApi, _emberDataSerializersJson, _emberDataSerializersRest) { exports.JSONAPISerializer = _emberDataSerializersJsonApi.default; exports.JSONSerializer = _emberDataSerializersJson.default; exports.RESTSerializer = _emberDataSerializersRest.default; }); /** @module ember-data */ define("ember-data/-private/system/clone-null", ["exports", "ember-data/-private/system/empty-object"], function (exports, _emberDataPrivateSystemEmptyObject) { exports.default = cloneNull; function cloneNull(source) { var clone = new _emberDataPrivateSystemEmptyObject.default(); for (var key in source) { clone[key] = source[key]; } return clone; } }); define('ember-data/-private/system/coerce-id', ['exports'], function (exports) { exports.default = coerceId; // Used by the store to normalize IDs entering the store. Despite the fact // that developers may provide IDs as numbers (e.g., `store.findRecord('person', 1)`), // it is important that internally we use strings, since IDs may be serialized // and lose type information. For example, Ember's router may put a record's // ID into the URL, and if we later try to deserialize that URL and find the // corresponding record, we will not know if it is a string or a number. function coerceId(id) { return id === null || id === undefined || id === '' ? null : id + ''; } }); define("ember-data/-private/system/debug", ["exports", "ember-data/-private/system/debug/debug-adapter"], function (exports, _emberDataPrivateSystemDebugDebugAdapter) { exports.default = _emberDataPrivateSystemDebugDebugAdapter.default; }); /** @module ember-data */ define('ember-data/-private/system/debug/debug-adapter', ['exports', 'ember', 'ember-data/model'], function (exports, _ember, _emberDataModel) { var get = _ember.default.get; var capitalize = _ember.default.String.capitalize; var underscore = _ember.default.String.underscore; var assert = _ember.default.assert; /* Extend `Ember.DataAdapter` with ED specific code. @class DebugAdapter @namespace DS @extends Ember.DataAdapter @private */ exports.default = _ember.default.DataAdapter.extend({ getFilters: function () { return [{ name: 'isNew', desc: 'New' }, { name: 'isModified', desc: 'Modified' }, { name: 'isClean', desc: 'Clean' }]; }, detect: function (typeClass) { return typeClass !== _emberDataModel.default && _emberDataModel.default.detect(typeClass); }, columnsForType: function (typeClass) { var columns = [{ name: 'id', desc: 'Id' }]; var count = 0; var self = this; get(typeClass, 'attributes').forEach(function (meta, name) { if (count++ > self.attributeLimit) { return false; } var desc = capitalize(underscore(name).replace('_', ' ')); columns.push({ name: name, desc: desc }); }); return columns; }, getRecords: function (modelClass, modelName) { if (arguments.length < 2) { // Legacy Ember.js < 1.13 support var containerKey = modelClass._debugContainerKey; if (containerKey) { var match = containerKey.match(/model:(.*)/); if (match) { modelName = match[1]; } } } assert("Cannot find model name. Please upgrade to Ember.js >= 1.13 for Ember Inspector support", !!modelName); return this.get('store').peekAll(modelName); }, getRecordColumnValues: function (record) { var _this = this; var count = 0; var columnValues = { id: get(record, 'id') }; record.eachAttribute(function (key) { if (count++ > _this.attributeLimit) { return false; } var value = get(record, key); columnValues[key] = value; }); return columnValues; }, getRecordKeywords: function (record) { var keywords = []; var keys = _ember.default.A(['id']); record.eachAttribute(function (key) { return keys.push(key); }); keys.forEach(function (key) { return keywords.push(get(record, key)); }); return keywords; }, getRecordFilterValues: function (record) { return { isNew: record.get('isNew'), isModified: record.get('hasDirtyAttributes') && !record.get('isNew'), isClean: !record.get('hasDirtyAttributes') }; }, getRecordColor: function (record) { var color = 'black'; if (record.get('isNew')) { color = 'green'; } else if (record.get('hasDirtyAttributes')) { color = 'blue'; } return color; }, observeRecord: function (record, recordUpdated) { var releaseMethods = _ember.default.A(); var keysToObserve = _ember.default.A(['id', 'isNew', 'hasDirtyAttributes']); record.eachAttribute(function (key) { return keysToObserve.push(key); }); var adapter = this; keysToObserve.forEach(function (key) { var handler = function () { recordUpdated(adapter.wrapRecord(record)); }; _ember.default.addObserver(record, key, handler); releaseMethods.push(function () { _ember.default.removeObserver(record, key, handler); }); }); var release = function () { releaseMethods.forEach(function (fn) { return fn(); }); }; return release; } }); }); /** @module ember-data */ define('ember-data/-private/system/debug/debug-info', ['exports', 'ember'], function (exports, _ember) { exports.default = _ember.default.Mixin.create({ /** Provides info about the model for debugging purposes by grouping the properties into more semantic groups. Meant to be used by debugging tools such as the Chrome Ember Extension. - Groups all attributes in "Attributes" group. - Groups all belongsTo relationships in "Belongs To" group. - Groups all hasMany relationships in "Has Many" group. - Groups all flags in "Flags" group. - Flags relationship CPs as expensive properties. @method _debugInfo @for DS.Model @private */ _debugInfo: function () { var attributes = ['id']; var relationships = {}; var expensiveProperties = []; this.eachAttribute(function (name, meta) { return attributes.push(name); }); var groups = [{ name: 'Attributes', properties: attributes, expand: true }]; this.eachRelationship(function (name, relationship) { var properties = relationships[relationship.kind]; if (properties === undefined) { properties = relationships[relationship.kind] = []; groups.push({ name: relationship.name, properties: properties, expand: true }); } properties.push(name); expensiveProperties.push(name); }); groups.push({ name: 'Flags', properties: ['isLoaded', 'hasDirtyAttributes', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid'] }); return { propertyInfo: { // include all other mixins / properties (not just the grouped ones) includeOtherProperties: true, groups: groups, // don't pre-calculate unless cached expensiveProperties: expensiveProperties } }; } }); }); define("ember-data/-private/system/empty-object", ["exports"], function (exports) { exports.default = EmptyObject; // This exists because `Object.create(null)` is absurdly slow compared // to `new EmptyObject()`. In either case, you want a null prototype // when you're treating the object instances as arbitrary dictionaries // and don't want your keys colliding with build-in methods on the // default object prototype. var proto = Object.create(null, { // without this, we will always still end up with (new // EmptyObject()).constructor === Object constructor: { value: undefined, enumerable: false, writable: true } }); function EmptyObject() {} EmptyObject.prototype = proto; }); define('ember-data/-private/system/is-array-like', ['exports', 'ember'], function (exports, _ember) { exports.default = isArrayLike; /* We're using this to detect arrays and "array-like" objects. This is a copy of the `isArray` method found in `ember-runtime/utils` as we're currently unable to import non-exposed modules. This method was previously exposed as `Ember.isArray` but since https://github.com/emberjs/ember.js/pull/11463 `Ember.isArray` is an alias of `Array.isArray` hence removing the "array-like" part. */ function isArrayLike(obj) { if (!obj || obj.setInterval) { return false; } if (Array.isArray(obj)) { return true; } if (_ember.default.Array.detect(obj)) { return true; } var type = _ember.default.typeOf(obj); if ('array' === type) { return true; } if (obj.length !== undefined && 'object' === type) { return true; } return false; } }); define("ember-data/-private/system/many-array", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/store/common"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemStoreCommon) { var get = _ember.default.get; var set = _ember.default.set; /** A `ManyArray` is a `MutableArray` that represents the contents of a has-many relationship. The `ManyArray` is instantiated lazily the first time the relationship is requested. ### Inverses Often, the relationships in Ember Data applications will have an inverse. For example, imagine the following models are defined: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ comments: DS.hasMany('comment') }); ``` ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ post: DS.belongsTo('post') }); ``` If you created a new instance of `App.Post` and added a `App.Comment` record to its `comments` has-many relationship, you would expect the comment's `post` property to be set to the post that contained the has-many. We call the record to which a relationship belongs the relationship's _owner_. @class ManyArray @namespace DS @extends Ember.Object @uses Ember.MutableArray, Ember.Evented */ exports.default = _ember.default.Object.extend(_ember.default.MutableArray, _ember.default.Evented, { init: function () { this._super.apply(this, arguments); /** The loading state of this array @property {Boolean} isLoaded */ this.isLoaded = false; this.length = 0; /** Used for async `hasMany` arrays to keep track of when they will resolve. @property {Ember.RSVP.Promise} promise @private */ this.promise = null; /** Metadata associated with the request for async hasMany relationships. Example Given that the server returns the following JSON payload when fetching a hasMany relationship: ```js { "comments": [{ "id": 1, "comment": "This is the first comment", }, { // ... }], "meta": { "page": 1, "total": 5 } } ``` You can then access the metadata via the `meta` property: ```js post.get('comments').then(function(comments) { var meta = comments.get('meta'); // meta.page => 1 // meta.total => 5 }); ``` @property {Object} meta @public */ this.meta = this.meta || null; /** `true` if the relationship is polymorphic, `false` otherwise. @property {Boolean} isPolymorphic @private */ this.isPolymorphic = this.isPolymorphic || false; /** The relationship which manages this array. @property {ManyRelationship} relationship @private */ this.relationship = this.relationship || null; this.currentState = _ember.default.A([]); this.flushCanonical(false); }, objectAt: function (index) { //Ember observers such as 'firstObject', 'lastObject' might do out of bounds accesses if (!this.currentState[index]) { return undefined; } return this.currentState[index].getRecord(); }, flushCanonical: function () { var isInitialized = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; var toSet = this.canonicalState; //a hack for not removing new records //TODO remove once we have proper diffing var newRecords = this.currentState.filter( // only add new records which are not yet in the canonical state of this // relationship (a new record can be in the canonical state if it has // been 'acknowleged' to be in the relationship via a store.push) function (internalModel) { return internalModel.isNew() && toSet.indexOf(internalModel) === -1; }); toSet = toSet.concat(newRecords); var oldLength = this.length; this.arrayContentWillChange(0, this.length, toSet.length); // It’s possible the parent side of the relationship may have been unloaded by this point if ((0, _emberDataPrivateSystemStoreCommon._objectIsAlive)(this)) { this.set('length', toSet.length); } this.currentState = toSet; this.arrayContentDidChange(0, oldLength, this.length); if (isInitialized) { //TODO Figure out to notify only on additions and maybe only if unloaded this.relationship.notifyHasManyChanged(); } }, internalReplace: function (idx, amt, objects) { if (!objects) { objects = []; } this.arrayContentWillChange(idx, amt, objects.length); this.currentState.splice.apply(this.currentState, [idx, amt].concat(objects)); this.set('length', this.currentState.length); this.arrayContentDidChange(idx, amt, objects.length); }, //TODO(Igor) optimize internalRemoveRecords: function (records) { for (var i = 0; i < records.length; i++) { var index = this.currentState.indexOf(records[i]); this.internalReplace(index, 1); } }, //TODO(Igor) optimize internalAddRecords: function (records, idx) { if (idx === undefined) { idx = this.currentState.length; } this.internalReplace(idx, 0, records); }, replace: function (idx, amt, objects) { var records = undefined; if (amt > 0) { records = this.currentState.slice(idx, idx + amt); this.get('relationship').removeRecords(records); } if (objects) { this.get('relationship').addRecords(objects.map(function (obj) { return obj._internalModel; }), idx); } }, /** @method loadingRecordsCount @param {Number} count @private */ loadingRecordsCount: function (count) { this.loadingRecordsCount = count; }, /** @method loadedRecord @private */ loadedRecord: function () { this.loadingRecordsCount--; if (this.loadingRecordsCount === 0) { set(this, 'isLoaded', true); this.trigger('didLoad'); } }, /** Reloads all of the records in the manyArray. If the manyArray holds a relationship that was originally fetched using a links url Ember Data will revisit the original links url to repopulate the relationship. If the manyArray holds the result of a `store.query()` reload will re-run the original query. Example ```javascript var user = store.peekRecord('user', 1) user.login().then(function() { user.get('permissions').then(function(permissions) { return permissions.reload(); }); }); ``` @method reload @public */ reload: function () { return this.relationship.reload(); }, /** Saves all of the records in the `ManyArray`. Example ```javascript store.findRecord('inbox', 1).then(function(inbox) { inbox.get('messages').then(function(messages) { messages.forEach(function(message) { message.set('isRead', true); }); messages.save() }); }); ``` @method save @return {DS.PromiseArray} promise */ save: function () { var manyArray = this; var promiseLabel = 'DS: ManyArray#save ' + get(this, 'type'); var promise = _ember.default.RSVP.all(this.invoke("save"), promiseLabel).then(function () { return manyArray; }, null, 'DS: ManyArray#save return ManyArray'); return _emberDataPrivateSystemPromiseProxies.PromiseArray.create({ promise: promise }); }, /** Create a child record within the owner @method createRecord @private @param {Object} hash @return {DS.Model} record */ createRecord: function (hash) { var store = get(this, 'store'); var type = get(this, 'type'); var record; record = store.createRecord(type.modelName, hash); this.pushObject(record); return record; } }); }); /** @module ember-data */ define("ember-data/-private/system/model", ["exports", "ember-data/-private/system/model/model", "ember-data/attr", "ember-data/-private/system/model/states", "ember-data/-private/system/model/errors"], function (exports, _emberDataPrivateSystemModelModel, _emberDataAttr, _emberDataPrivateSystemModelStates, _emberDataPrivateSystemModelErrors) { exports.RootState = _emberDataPrivateSystemModelStates.default; exports.attr = _emberDataAttr.default; exports.Errors = _emberDataPrivateSystemModelErrors.default; exports.default = _emberDataPrivateSystemModelModel.default; }); /** @module ember-data */ define("ember-data/-private/system/model/attr", ["exports", "ember", "ember-data/-private/debug"], function (exports, _ember, _emberDataPrivateDebug) { var get = _ember.default.get; var Map = _ember.default.Map; /** @module ember-data */ /** @class Model @namespace DS */ var AttrClassMethodsMixin = _ember.default.Mixin.create({ /** A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are the meta object for the property. Example ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: attr('string'), lastName: attr('string'), birthday: attr('date') }); ``` ```javascript import Ember from 'ember'; import Person from 'app/models/person'; var attributes = Ember.get(Person, 'attributes') attributes.forEach(function(meta, name) { console.log(name, meta); }); // prints: // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} ``` @property attributes @static @type {Ember.Map} @readOnly */ attributes: _ember.default.computed(function () { var map = Map.create(); this.eachComputedProperty(function (name, meta) { if (meta.isAttribute) { meta.name = name; map.set(name, meta); } }); return map; }).readOnly(), /** A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are type of transformation applied to each attribute. This map does not include any attributes that do not have an transformation type. Example ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: attr(), lastName: attr('string'), birthday: attr('date') }); ``` ```javascript import Ember from 'ember'; import Person from 'app/models/person'; var transformedAttributes = Ember.get(Person, 'transformedAttributes') transformedAttributes.forEach(function(field, type) { console.log(field, type); }); // prints: // lastName string // birthday date ``` @property transformedAttributes @static @type {Ember.Map} @readOnly */ transformedAttributes: _ember.default.computed(function () { var map = Map.create(); this.eachAttribute(function (key, meta) { if (meta.type) { map.set(key, meta.type); } }); return map; }).readOnly(), /** Iterates through the attributes of the model, calling the passed function on each attribute. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, meta); ``` - `name` the name of the current property in the iteration - `meta` the meta object for the attribute property in the iteration Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```javascript import DS from 'ember-data'; var Person = DS.Model.extend({ firstName: attr('string'), lastName: attr('string'), birthday: attr('date') }); Person.eachAttribute(function(name, meta) { console.log(name, meta); }); // prints: // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} ``` @method eachAttribute @param {Function} callback The callback to execute @param {Object} [binding] the value to which the callback's `this` should be bound @static */ eachAttribute: function (callback, binding) { get(this, 'attributes').forEach(function (meta, name) { callback.call(binding, name, meta); }); }, /** Iterates through the transformedAttributes of the model, calling the passed function on each attribute. Note the callback will not be called for any attributes that do not have an transformation type. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, type); ``` - `name` the name of the current property in the iteration - `type` a string containing the name of the type of transformed applied to the attribute Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```javascript import DS from 'ember-data'; var Person = DS.Model.extend({ firstName: attr(), lastName: attr('string'), birthday: attr('date') }); Person.eachTransformedAttribute(function(name, type) { console.log(name, type); }); // prints: // lastName string // birthday date ``` @method eachTransformedAttribute @param {Function} callback The callback to execute @param {Object} [binding] the value to which the callback's `this` should be bound @static */ eachTransformedAttribute: function (callback, binding) { get(this, 'transformedAttributes').forEach(function (type, name) { callback.call(binding, name, type); }); } }); exports.AttrClassMethodsMixin = AttrClassMethodsMixin; var AttrInstanceMethodsMixin = _ember.default.Mixin.create({ eachAttribute: function (callback, binding) { this.constructor.eachAttribute(callback, binding); } }); exports.AttrInstanceMethodsMixin = AttrInstanceMethodsMixin; }); define('ember-data/-private/system/model/errors', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { var get = _ember.default.get; var set = _ember.default.set; var isEmpty = _ember.default.isEmpty; var makeArray = _ember.default.makeArray; var MapWithDefault = _ember.default.MapWithDefault; /** @module ember-data */ /** Holds validation errors for a given record, organized by attribute names. Every `DS.Model` has an `errors` property that is an instance of `DS.Errors`. This can be used to display validation error messages returned from the server when a `record.save()` rejects. For Example, if you had a `User` model that looked like this: ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ username: attr('string'), email: attr('string') }); ``` And you attempted to save a record that did not validate on the backend: ```javascript var user = store.createRecord('user', { username: 'tomster', email: 'invalidEmail' }); user.save(); ``` Your backend would be expected to return an error response that described the problem, so that error messages can be generated on the app. API responses will be translated into instances of `DS.Errors` differently, depending on the specific combination of adapter and serializer used. You may want to check the documentation or the source code of the libraries that you are using, to know how they expect errors to be communicated. Errors can be displayed to the user by accessing their property name to get an array of all the error objects for that property. Each error object is a JavaScript object with two keys: - `message` A string containing the error message from the backend - `attribute` The name of the property associated with this error message ```handlebars <label>Username: {{input value=username}} </label> {{#each model.errors.username as |error|}} <div class="error"> {{error.message}} </div> {{/each}} <label>Email: {{input value=email}} </label> {{#each model.errors.email as |error|}} <div class="error"> {{error.message}} </div> {{/each}} ``` You can also access the special `messages` property on the error object to get an array of all the error strings. ```handlebars {{#each model.errors.messages as |message|}} <div class="error"> {{message}} </div> {{/each}} ``` @class Errors @namespace DS @extends Ember.Object @uses Ember.Enumerable @uses Ember.Evented */ exports.default = _ember.default.ArrayProxy.extend(_ember.default.Evented, { /** Register with target handler @method registerHandlers @param {Object} target @param {Function} becameInvalid @param {Function} becameValid @deprecated */ registerHandlers: function (target, becameInvalid, becameValid) { this._registerHandlers(target, becameInvalid, becameValid); }, /** Register with target handler @method _registerHandlers @private */ _registerHandlers: function (target, becameInvalid, becameValid) { this.on('becameInvalid', target, becameInvalid); this.on('becameValid', target, becameValid); }, /** @property errorsByAttributeName @type {Ember.MapWithDefault} @private */ errorsByAttributeName: _ember.default.computed(function () { return MapWithDefault.create({ defaultValue: function () { return _ember.default.A(); } }); }), /** Returns errors for a given attribute ```javascript var user = store.createRecord('user', { username: 'tomster', email: 'invalidEmail' }); user.save().catch(function(){ user.get('errors').errorsFor('email'); // returns: // [{attribute: "email", message: "Doesn't look like a valid email."}] }); ``` @method errorsFor @param {String} attribute @return {Array} */ errorsFor: function (attribute) { return get(this, 'errorsByAttributeName').get(attribute); }, /** An array containing all of the error messages for this record. This is useful for displaying all errors to the user. ```handlebars {{#each model.errors.messages as |message|}} <div class="error"> {{message}} </div> {{/each}} ``` @property messages @type {Array} */ messages: _ember.default.computed.mapBy('content', 'message'), /** @property content @type {Array} @private */ content: _ember.default.computed(function () { return _ember.default.A(); }), /** @method unknownProperty @private */ unknownProperty: function (attribute) { var errors = this.errorsFor(attribute); if (isEmpty(errors)) { return null; } return errors; }, /** Total number of errors. @property length @type {Number} @readOnly */ /** @property isEmpty @type {Boolean} @readOnly */ isEmpty: _ember.default.computed.not('length').readOnly(), /** Adds error messages to a given attribute and sends `becameInvalid` event to the record. Example: ```javascript if (!user.get('username') { user.get('errors').add('username', 'This field is required'); } ``` @method add @param {String} attribute @param {(Array|String)} messages @deprecated */ add: function (attribute, messages) { var wasEmpty = get(this, 'isEmpty'); this._add(attribute, messages); if (wasEmpty && !get(this, 'isEmpty')) { this.trigger('becameInvalid'); } }, /** Adds error messages to a given attribute without sending event. @method _add @private */ _add: function (attribute, messages) { messages = this._findOrCreateMessages(attribute, messages); this.addObjects(messages); get(this, 'errorsByAttributeName').get(attribute).addObjects(messages); this.notifyPropertyChange(attribute); }, /** @method _findOrCreateMessages @private */ _findOrCreateMessages: function (attribute, messages) { var errors = this.errorsFor(attribute); var messagesArray = makeArray(messages); var _messages = new Array(messagesArray.length); for (var i = 0; i < messagesArray.length; i++) { var message = messagesArray[i]; var err = errors.findBy('message', message); if (err) { _messages[i] = err; } else { _messages[i] = { attribute: attribute, message: message }; } } return _messages; }, /** Removes all error messages from the given attribute and sends `becameValid` event to the record if there no more errors left. Example: ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ email: DS.attr('string'), twoFactorAuth: DS.attr('boolean'), phone: DS.attr('string') }); ``` ```app/routes/user/edit.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { save: function(user) { if (!user.get('twoFactorAuth')) { user.get('errors').remove('phone'); } user.save(); } } }); ``` @method remove @param {String} attribute @deprecated */ remove: function (attribute) { if (get(this, 'isEmpty')) { return; } this._remove(attribute); if (get(this, 'isEmpty')) { this.trigger('becameValid'); } }, /** Removes all error messages from the given attribute without sending event. @method _remove @private */ _remove: function (attribute) { if (get(this, 'isEmpty')) { return; } var content = this.rejectBy('attribute', attribute); set(this, 'content', content); get(this, 'errorsByAttributeName').delete(attribute); this.notifyPropertyChange(attribute); }, /** Removes all error messages and sends `becameValid` event to the record. Example: ```app/routes/user/edit.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { retrySave: function(user) { user.get('errors').clear(); user.save(); } } }); ``` @method clear @deprecated */ clear: function () { if (get(this, 'isEmpty')) { return; } this._clear(); this.trigger('becameValid'); }, /** Removes all error messages. to the record. @method _clear @private */ _clear: function () { if (get(this, 'isEmpty')) { return; } var errorsByAttributeName = get(this, 'errorsByAttributeName'); var attributes = _ember.default.A(); errorsByAttributeName.forEach(function (_, attribute) { attributes.push(attribute); }); errorsByAttributeName.clear(); attributes.forEach(function (attribute) { this.notifyPropertyChange(attribute); }, this); _ember.default.ArrayProxy.prototype.clear.call(this); }, /** Checks if there is error messages for the given attribute. ```app/routes/user/edit.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { save: function(user) { if (user.get('errors').has('email')) { return alert('Please update your email before attempting to save.'); } user.save(); } } }); ``` @method has @param {String} attribute @return {Boolean} true if there some errors on given attribute */ has: function (attribute) { return !isEmpty(this.errorsFor(attribute)); } }); }); define("ember-data/-private/system/model/internal-model", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/model/states", "ember-data/-private/system/relationships/state/create", "ember-data/-private/system/snapshot", "ember-data/-private/system/empty-object", "ember-data/-private/features", "ember-data/-private/utils", "ember-data/-private/system/references"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemModelStates, _emberDataPrivateSystemRelationshipsStateCreate, _emberDataPrivateSystemSnapshot, _emberDataPrivateSystemEmptyObject, _emberDataPrivateFeatures, _emberDataPrivateUtils, _emberDataPrivateSystemReferences) { var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var get = _ember.default.get; var set = _ember.default.set; var copy = _ember.default.copy; var EmberError = _ember.default.Error; var inspect = _ember.default.inspect; var isEmpty = _ember.default.isEmpty; var isEqual = _ember.default.isEqual; var emberRun = _ember.default.run; var setOwner = _ember.default.setOwner; var RSVP = _ember.default.RSVP; var Promise = _ember.default.RSVP.Promise; var assign = _ember.default.assign || _ember.default.merge; /* The TransitionChainMap caches the `state.enters`, `state.setups`, and final state reached when transitioning from one state to another, so that future transitions can replay the transition without needing to walk the state tree, collect these hook calls and determine the state to transition into. A future optimization would be to build a single chained method out of the collected enters and setups. It may also be faster to do a two level cache (from: { to }) instead of caching based on a key that adds the two together. */ var TransitionChainMap = new _emberDataPrivateSystemEmptyObject.default(); var _extractPivotNameCache = new _emberDataPrivateSystemEmptyObject.default(); var _splitOnDotCache = new _emberDataPrivateSystemEmptyObject.default(); function splitOnDot(name) { return _splitOnDotCache[name] || (_splitOnDotCache[name] = name.split('.')); } function extractPivotName(name) { return _extractPivotNameCache[name] || (_extractPivotNameCache[name] = splitOnDot(name)[0]); } // this (and all heimdall instrumentation) will be stripped by a babel transform // https://github.com/heimdalljs/babel5-plugin-strip-heimdall /* `InternalModel` is the Model class that we use internally inside Ember Data to represent models. Internal ED methods should only deal with `InternalModel` objects. It is a fast, plain Javascript class. We expose `DS.Model` to application code, by materializing a `DS.Model` from `InternalModel` lazily, as a performance optimization. `InternalModel` should never be exposed to application code. At the boundaries of the system, in places like `find`, `push`, etc. we convert between Models and InternalModels. We need to make sure that the properties from `InternalModel` are correctly exposed/proxied on `Model` if they are needed. @private @class InternalModel */ var InternalModel = (function () { function InternalModel(modelClass, id, store, data) { this.modelClass = modelClass; this.id = id; this.store = store; this._data = data || new _emberDataPrivateSystemEmptyObject.default(); this.modelName = modelClass.modelName; this.dataHasInitialized = false; this._loadingPromise = null; this._recordArrays = undefined; this._record = null; this.currentState = _emberDataPrivateSystemModelStates.default.empty; this.isReloading = false; this._isDestroyed = false; this.isError = false; this.error = null; // caches for lazy getters this.__deferredTriggers = null; this._references = null; this._recordReference = null; this.__inFlightAttributes = null; this.__relationships = null; this.__attributes = null; this.__implicitRelationships = null; } _createClass(InternalModel, [{ key: "isEmpty", value: function isEmpty() { return this.currentState.isEmpty; } }, { key: "isLoading", value: function isLoading() { return this.currentState.isLoading; } }, { key: "isLoaded", value: function isLoaded() { return this.currentState.isLoaded; } }, { key: "hasDirtyAttributes", value: function hasDirtyAttributes() { return this.currentState.hasDirtyAttributes; } }, { key: "isSaving", value: function isSaving() { return this.currentState.isSaving; } }, { key: "isDeleted", value: function isDeleted() { return this.currentState.isDeleted; } }, { key: "isNew", value: function isNew() { return this.currentState.isNew; } }, { key: "isValid", value: function isValid() { return this.currentState.isValid; } }, { key: "dirtyType", value: function dirtyType() { return this.currentState.dirtyType; } }, { key: "getRecord", value: function getRecord() { if (!this._record) { // lookupFactory should really return an object that creates // instances with the injections applied var createOptions = { store: this.store, _internalModel: this, id: this.id, currentState: this.currentState, isError: this.isError, adapterError: this.error }; if (setOwner) { // ensure that `getOwner(this)` works inside a model instance setOwner(createOptions, (0, _emberDataPrivateUtils.getOwner)(this.store)); } else { createOptions.container = this.store.container; } this._record = this.modelClass._create(createOptions); this._triggerDeferredTriggers(); } return this._record; } }, { key: "recordObjectWillDestroy", value: function recordObjectWillDestroy() { this._record = null; } }, { key: "deleteRecord", value: function deleteRecord() { this.send('deleteRecord'); } }, { key: "save", value: function save(options) { var promiseLabel = "DS: Model#save " + this; var resolver = RSVP.defer(promiseLabel); this.store.scheduleSave(this, resolver, options); return resolver.promise; } }, { key: "startedReloading", value: function startedReloading() { this.isReloading = true; if (this.hasRecord) { set(this.record, 'isReloading', true); } } }, { key: "finishedReloading", value: function finishedReloading() { this.isReloading = false; if (this.hasRecord) { set(this.record, 'isReloading', false); } } }, { key: "reload", value: function reload() { this.startedReloading(); var internalModel = this; var promiseLabel = "DS: Model#reload of " + this; return new Promise(function (resolve) { internalModel.send('reloadRecord', resolve); }, promiseLabel).then(function () { internalModel.didCleanError(); return internalModel; }, function (error) { internalModel.didError(error); throw error; }, "DS: Model#reload complete, update flags").finally(function () { internalModel.finishedReloading(); internalModel.updateRecordArrays(); }); } }, { key: "unloadRecord", value: function unloadRecord() { this.send('unloadRecord'); } }, { key: "eachRelationship", value: function eachRelationship(callback, binding) { return this.modelClass.eachRelationship(callback, binding); } }, { key: "eachAttribute", value: function eachAttribute(callback, binding) { return this.modelClass.eachAttribute(callback, binding); } }, { key: "inverseFor", value: function inverseFor(key) { return this.modelClass.inverseFor(key); } }, { key: "setupData", value: function setupData(data) { var changedKeys = this._changedKeys(data.attributes); assign(this._data, data.attributes); this.pushedData(); if (this.hasRecord) { this.record._notifyProperties(changedKeys); } this.didInitializeData(); } }, { key: "becameReady", value: function becameReady() { emberRun.schedule('actions', this.store.recordArrayManager, this.store.recordArrayManager.recordWasLoaded, this); } }, { key: "didInitializeData", value: function didInitializeData() { if (!this.dataHasInitialized) { this.becameReady(); this.dataHasInitialized = true; } } }, { key: "destroy", value: function destroy() { this._isDestroyed = true; if (this.hasRecord) { return this.record.destroy(); } } /* @method createSnapshot @private */ }, { key: "createSnapshot", value: function createSnapshot(options) { return new _emberDataPrivateSystemSnapshot.default(this, options); } /* @method loadingData @private @param {Promise} promise */ }, { key: "loadingData", value: function loadingData(promise) { this.send('loadingData', promise); } /* @method loadedData @private */ }, { key: "loadedData", value: function loadedData() { this.send('loadedData'); this.didInitializeData(); } /* @method notFound @private */ }, { key: "notFound", value: function notFound() { this.send('notFound'); } /* @method pushedData @private */ }, { key: "pushedData", value: function pushedData() { this.send('pushedData'); } }, { key: "flushChangedAttributes", value: function flushChangedAttributes() { this._inFlightAttributes = this._attributes; this._attributes = new _emberDataPrivateSystemEmptyObject.default(); } }, { key: "hasChangedAttributes", value: function hasChangedAttributes() { return Object.keys(this._attributes).length > 0; } /* Checks if the attributes which are considered as changed are still different to the state which is acknowledged by the server. This method is needed when data for the internal model is pushed and the pushed data might acknowledge dirty attributes as confirmed. @method updateChangedAttributes @private */ }, { key: "updateChangedAttributes", value: function updateChangedAttributes() { var changedAttributes = this.changedAttributes(); var changedAttributeNames = Object.keys(changedAttributes); var attrs = this._attributes; for (var i = 0, _length = changedAttributeNames.length; i < _length; i++) { var attribute = changedAttributeNames[i]; var data = changedAttributes[attribute]; var oldData = data[0]; var newData = data[1]; if (oldData === newData) { delete attrs[attribute]; } } } /* Returns an object, whose keys are changed properties, and value is an [oldProp, newProp] array. @method changedAttributes @private */ }, { key: "changedAttributes", value: function changedAttributes() { var oldData = this._data; var currentData = this._attributes; var inFlightData = this._inFlightAttributes; var newData = assign(copy(inFlightData), currentData); var diffData = new _emberDataPrivateSystemEmptyObject.default(); var newDataKeys = Object.keys(newData); for (var i = 0, _length2 = newDataKeys.length; i < _length2; i++) { var key = newDataKeys[i]; diffData[key] = [oldData[key], newData[key]]; } return diffData; } /* @method adapterWillCommit @private */ }, { key: "adapterWillCommit", value: function adapterWillCommit() { this.send('willCommit'); } /* @method adapterDidDirty @private */ }, { key: "adapterDidDirty", value: function adapterDidDirty() { this.send('becomeDirty'); this.updateRecordArraysLater(); } /* @method send @private @param {String} name @param {Object} context */ }, { key: "send", value: function send(name, context) { var currentState = this.currentState; if (!currentState[name]) { this._unhandledEvent(currentState, name, context); } return currentState[name](this, context); } }, { key: "notifyHasManyAdded", value: function notifyHasManyAdded(key, record, idx) { if (this.hasRecord) { this.record.notifyHasManyAdded(key, record, idx); } } }, { key: "notifyHasManyRemoved", value: function notifyHasManyRemoved(key, record, idx) { if (this.hasRecord) { this.record.notifyHasManyRemoved(key, record, idx); } } }, { key: "notifyBelongsToChanged", value: function notifyBelongsToChanged(key, record) { if (this.hasRecord) { this.record.notifyBelongsToChanged(key, record); } } }, { key: "notifyPropertyChange", value: function notifyPropertyChange(key) { if (this.hasRecord) { this.record.notifyPropertyChange(key); } } }, { key: "rollbackAttributes", value: function rollbackAttributes() { var dirtyKeys = Object.keys(this._attributes); this._attributes = new _emberDataPrivateSystemEmptyObject.default(); if (get(this, 'isError')) { this._inFlightAttributes = new _emberDataPrivateSystemEmptyObject.default(); this.didCleanError(); } //Eventually rollback will always work for relationships //For now we support it only out of deleted state, because we //have an explicit way of knowing when the server acked the relationship change if (this.isDeleted()) { //TODO: Should probably move this to the state machine somehow this.becameReady(); } if (this.isNew()) { this.clearRelationships(); } if (this.isValid()) { this._inFlightAttributes = new _emberDataPrivateSystemEmptyObject.default(); } this.send('rolledBack'); this.record._notifyProperties(dirtyKeys); } /* @method transitionTo @private @param {String} name */ }, { key: "transitionTo", value: function transitionTo(name) { // POSSIBLE TODO: Remove this code and replace with // always having direct reference to state objects var pivotName = extractPivotName(name); var state = this.currentState; var transitionMapId = state.stateName + "->" + name; do { if (state.exit) { state.exit(this); } state = state.parentState; } while (!state[pivotName]); var setups = undefined; var enters = undefined; var i = undefined; var l = undefined; var map = TransitionChainMap[transitionMapId]; if (map) { setups = map.setups; enters = map.enters; state = map.state; } else { setups = []; enters = []; var path = splitOnDot(name); for (i = 0, l = path.length; i < l; i++) { state = state[path[i]]; if (state.enter) { enters.push(state); } if (state.setup) { setups.push(state); } } TransitionChainMap[transitionMapId] = { setups: setups, enters: enters, state: state }; } for (i = 0, l = enters.length; i < l; i++) { enters[i].enter(this); } this.currentState = state; if (this.hasRecord) { set(this.record, 'currentState', state); } for (i = 0, l = setups.length; i < l; i++) { setups[i].setup(this); } this.updateRecordArraysLater(); } }, { key: "_unhandledEvent", value: function _unhandledEvent(state, name, context) { var errorMessage = "Attempted to handle event `" + name + "` "; errorMessage += "on " + String(this) + " while in state "; errorMessage += state.stateName + ". "; if (context !== undefined) { errorMessage += "Called with " + inspect(context) + "."; } throw new EmberError(errorMessage); } }, { key: "triggerLater", value: function triggerLater() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (this._deferredTriggers.push(args) !== 1) { return; } emberRun.schedule('actions', this, this._triggerDeferredTriggers); } }, { key: "_triggerDeferredTriggers", value: function _triggerDeferredTriggers() { //TODO: Before 1.0 we want to remove all the events that happen on the pre materialized record, //but for now, we queue up all the events triggered before the record was materialized, and flush //them once we have the record if (!this.hasRecord) { return; } for (var i = 0, l = this._deferredTriggers.length; i < l; i++) { this.record.trigger.apply(this.record, this._deferredTriggers[i]); } this._deferredTriggers.length = 0; } /* @method clearRelationships @private */ }, { key: "clearRelationships", value: function clearRelationships() { var _this = this; this.eachRelationship(function (name, relationship) { if (_this._relationships.has(name)) { var rel = _this._relationships.get(name); rel.clear(); rel.destroy(); } }); Object.keys(this._implicitRelationships).forEach(function (key) { _this._implicitRelationships[key].clear(); _this._implicitRelationships[key].destroy(); }); } /* When a find request is triggered on the store, the user can optionally pass in attributes and relationships to be preloaded. These are meant to behave as if they came back from the server, except the user obtained them out of band and is informing the store of their existence. The most common use case is for supporting client side nested URLs, such as `/posts/1/comments/2` so the user can do `store.findRecord('comment', 2, { preload: { post: 1 } })` without having to fetch the post. Preloaded data can be attributes and relationships passed in either as IDs or as actual models. @method preloadData @private @param {Object} preload */ }, { key: "preloadData", value: function preloadData(preload) { var _this2 = this; //TODO(Igor) consider the polymorphic case Object.keys(preload).forEach(function (key) { var preloadValue = get(preload, key); var relationshipMeta = _this2.modelClass.metaForProperty(key); if (relationshipMeta.isRelationship) { _this2._preloadRelationship(key, preloadValue); } else { _this2._data[key] = preloadValue; } }); } }, { key: "_preloadRelationship", value: function _preloadRelationship(key, preloadValue) { var relationshipMeta = this.modelClass.metaForProperty(key); var modelClass = relationshipMeta.type; if (relationshipMeta.kind === 'hasMany') { this._preloadHasMany(key, preloadValue, modelClass); } else { this._preloadBelongsTo(key, preloadValue, modelClass); } } }, { key: "_preloadHasMany", value: function _preloadHasMany(key, preloadValue, modelClass) { var recordsToSet = new Array(preloadValue.length); for (var i = 0; i < preloadValue.length; i++) { var recordToPush = preloadValue[i]; recordsToSet[i] = this._convertStringOrNumberIntoInternalModel(recordToPush, modelClass); } //We use the pathway of setting the hasMany as if it came from the adapter //because the user told us that they know this relationships exists already this._relationships.get(key).updateRecordsFromAdapter(recordsToSet); } }, { key: "_preloadBelongsTo", value: function _preloadBelongsTo(key, preloadValue, modelClass) { var recordToSet = this._convertStringOrNumberIntoInternalModel(preloadValue, modelClass); //We use the pathway of setting the hasMany as if it came from the adapter //because the user told us that they know this relationships exists already this._relationships.get(key).setRecord(recordToSet); } }, { key: "_convertStringOrNumberIntoInternalModel", value: function _convertStringOrNumberIntoInternalModel(value, modelClass) { if (typeof value === 'string' || typeof value === 'number') { return this.store._internalModelForId(modelClass, value); } if (value._internalModel) { return value._internalModel; } return value; } /* @method updateRecordArrays @private */ }, { key: "updateRecordArrays", value: function updateRecordArrays() { this._updatingRecordArraysLater = false; this.store.dataWasUpdated(this.modelClass, this); } }, { key: "setId", value: function setId(id) { this.id = id; if (this.record.get('id') !== id) { this.record.set('id', id); } } }, { key: "didError", value: function didError(error) { this.error = error; this.isError = true; if (this.hasRecord) { this.record.setProperties({ isError: true, adapterError: error }); } } }, { key: "didCleanError", value: function didCleanError() { this.error = null; this.isError = false; if (this.hasRecord) { this.record.setProperties({ isError: false, adapterError: null }); } } /* If the adapter did not return a hash in response to a commit, merge the changed attributes and relationships into the existing saved data. @method adapterDidCommit */ }, { key: "adapterDidCommit", value: function adapterDidCommit(data) { if (data) { data = data.attributes; } this.didCleanError(); var changedKeys = this._changedKeys(data); assign(this._data, this._inFlightAttributes); if (data) { assign(this._data, data); } this._inFlightAttributes = new _emberDataPrivateSystemEmptyObject.default(); this.send('didCommit'); this.updateRecordArraysLater(); if (!data) { return; } this.record._notifyProperties(changedKeys); } /* @method updateRecordArraysLater @private */ }, { key: "updateRecordArraysLater", value: function updateRecordArraysLater() { // quick hack (something like this could be pushed into run.once if (this._updatingRecordArraysLater) { return; } this._updatingRecordArraysLater = true; emberRun.schedule('actions', this, this.updateRecordArrays); } }, { key: "addErrorMessageToAttribute", value: function addErrorMessageToAttribute(attribute, message) { get(this.getRecord(), 'errors')._add(attribute, message); } }, { key: "removeErrorMessageFromAttribute", value: function removeErrorMessageFromAttribute(attribute) { get(this.getRecord(), 'errors')._remove(attribute); } }, { key: "clearErrorMessages", value: function clearErrorMessages() { get(this.getRecord(), 'errors')._clear(); } }, { key: "hasErrors", value: function hasErrors() { var errors = get(this.getRecord(), 'errors'); return !isEmpty(errors); } // FOR USE DURING COMMIT PROCESS /* @method adapterDidInvalidate @private */ }, { key: "adapterDidInvalidate", value: function adapterDidInvalidate(errors) { var attribute = undefined; for (attribute in errors) { if (errors.hasOwnProperty(attribute)) { this.addErrorMessageToAttribute(attribute, errors[attribute]); } } this.send('becameInvalid'); this._saveWasRejected(); } /* @method adapterDidError @private */ }, { key: "adapterDidError", value: function adapterDidError(error) { this.send('becameError'); this.didError(error); this._saveWasRejected(); } }, { key: "_saveWasRejected", value: function _saveWasRejected() { var keys = Object.keys(this._inFlightAttributes); var attrs = this._attributes; for (var i = 0; i < keys.length; i++) { if (attrs[keys[i]] === undefined) { attrs[keys[i]] = this._inFlightAttributes[keys[i]]; } } this._inFlightAttributes = new _emberDataPrivateSystemEmptyObject.default(); } /* Ember Data has 3 buckets for storing the value of an attribute on an internalModel. `_data` holds all of the attributes that have been acknowledged by a backend via the adapter. When rollbackAttributes is called on a model all attributes will revert to the record's state in `_data`. `_attributes` holds any change the user has made to an attribute that has not been acknowledged by the adapter. Any values in `_attributes` are have priority over values in `_data`. `_inFlightAttributes`. When a record is being synced with the backend the values in `_attributes` are copied to `_inFlightAttributes`. This way if the backend acknowledges the save but does not return the new state Ember Data can copy the values from `_inFlightAttributes` to `_data`. Without having to worry about changes made to `_attributes` while the save was happenign. Changed keys builds a list of all of the values that may have been changed by the backend after a successful save. It does this by iterating over each key, value pair in the payload returned from the server after a save. If the `key` is found in `_attributes` then the user has a local changed to the attribute that has not been synced with the server and the key is not included in the list of changed keys. If the value, for a key differs from the value in what Ember Data believes to be the truth about the backend state (A merger of the `_data` and `_inFlightAttributes` objects where `_inFlightAttributes` has priority) then that means the backend has updated the value and the key is added to the list of changed keys. @method _changedKeys @private */ }, { key: "_changedKeys", value: function _changedKeys(updates) { var changedKeys = []; if (updates) { var original = undefined, i = undefined, value = undefined, key = undefined; var keys = Object.keys(updates); var _length3 = keys.length; var attrs = this._attributes; original = assign(new _emberDataPrivateSystemEmptyObject.default(), this._data); original = assign(original, this._inFlightAttributes); for (i = 0; i < _length3; i++) { key = keys[i]; value = updates[key]; // A value in _attributes means the user has a local change to // this attributes. We never override this value when merging // updates from the backend so we should not sent a change // notification if the server value differs from the original. if (attrs[key] !== undefined) { continue; } if (!isEqual(original[key], value)) { changedKeys.push(key); } } } return changedKeys; } }, { key: "toString", value: function toString() { return "<" + this.modelName + ":" + this.id + ">"; } }, { key: "referenceFor", value: function referenceFor(kind, name) { var reference = this.references[name]; if (!reference) { var relationship = this._relationships.get(name); if (kind === "belongsTo") { reference = new _emberDataPrivateSystemReferences.BelongsToReference(this.store, this, relationship); } else if (kind === "hasMany") { reference = new _emberDataPrivateSystemReferences.HasManyReference(this.store, this, relationship); } this.references[name] = reference; } return reference; } }, { key: "type", get: function () { return this.modelClass; } }, { key: "recordReference", get: function () { if (this._recordReference === null) { this._recordReference = new _emberDataPrivateSystemReferences.RecordReference(this.store, this); } return this._recordReference; } }, { key: "references", get: function () { if (this._references === null) { this._references = new _emberDataPrivateSystemEmptyObject.default(); } return this._references; } }, { key: "_deferredTriggers", get: function () { if (this.__deferredTriggers === null) { this.__deferredTriggers = []; } return this.__deferredTriggers; } }, { key: "_attributes", get: function () { if (this.__attributes === null) { this.__attributes = new _emberDataPrivateSystemEmptyObject.default(); } return this.__attributes; }, set: function (v) { this.__attributes = v; } }, { key: "_relationships", get: function () { if (this.__relationships === null) { this.__relationships = new _emberDataPrivateSystemRelationshipsStateCreate.default(this); } return this.__relationships; } }, { key: "_inFlightAttributes", get: function () { if (this.__inFlightAttributes === null) { this.__inFlightAttributes = new _emberDataPrivateSystemEmptyObject.default(); } return this.__inFlightAttributes; }, set: function (v) { this.__inFlightAttributes = v; } /* implicit relationships are relationship which have not been declared but the inverse side exists on another record somewhere For example if there was ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ name: DS.attr() }) ``` but there is also ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ name: DS.attr(), comments: DS.hasMany('comment') }) ``` would have a implicit post relationship in order to be do things like remove ourselves from the post when we are deleted */ }, { key: "_implicitRelationships", get: function () { if (this.__implicitRelationships === null) { this.__implicitRelationships = new _emberDataPrivateSystemEmptyObject.default(); } return this.__implicitRelationships; } }, { key: "record", get: function () { return this._record; } }, { key: "isDestroyed", get: function () { return this._isDestroyed; } }, { key: "hasRecord", get: function () { return !!this._record; } }]); return InternalModel; })(); exports.default = InternalModel; if (false) { /* Returns the latest truth for an attribute - the canonical value, or the in-flight value. @method lastAcknowledgedValue @private */ InternalModel.prototype.lastAcknowledgedValue = function lastAcknowledgedValue(key) { if (key in this._inFlightAttributes) { return this._inFlightAttributes[key]; } else { return this._data[key]; } }; } }); define("ember-data/-private/system/model/model", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/model/errors", "ember-data/-private/system/debug/debug-info", "ember-data/-private/system/relationships/belongs-to", "ember-data/-private/system/relationships/has-many", "ember-data/-private/system/relationships/ext", "ember-data/-private/system/model/attr", "ember-data/-private/features", "ember-data/-private/system/model/states"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemModelErrors, _emberDataPrivateSystemDebugDebugInfo, _emberDataPrivateSystemRelationshipsBelongsTo, _emberDataPrivateSystemRelationshipsHasMany, _emberDataPrivateSystemRelationshipsExt, _emberDataPrivateSystemModelAttr, _emberDataPrivateFeatures, _emberDataPrivateSystemModelStates) { var get = _ember.default.get; var computed = _ember.default.computed; /** @module ember-data */ function intersection(array1, array2) { var result = []; array1.forEach(function (element) { if (array2.indexOf(element) >= 0) { result.push(element); } }); return result; } var RESERVED_MODEL_PROPS = ['currentState', 'data', 'store']; var retrieveFromCurrentState = computed('currentState', function (key) { return get(this._internalModel.currentState, key); }).readOnly(); /** The model class that all Ember Data records descend from. This is the public API of Ember Data models. If you are using Ember Data in your application, this is the class you should use. If you are working on Ember Data internals, you most likely want to be dealing with `InternalModel` @class Model @namespace DS @extends Ember.Object @uses Ember.Evented */ var Model = _ember.default.Object.extend(_ember.default.Evented, { _internalModel: null, store: null, /** If this property is `true` the record is in the `empty` state. Empty is the first state all records enter after they have been created. Most records created by the store will quickly transition to the `loading` state if data needs to be fetched from the server or the `created` state if the record is created on the client. A record can also enter the empty state if the adapter is unable to locate the record. @property isEmpty @type {Boolean} @readOnly */ isEmpty: retrieveFromCurrentState, /** If this property is `true` the record is in the `loading` state. A record enters this state when the store asks the adapter for its data. It remains in this state until the adapter provides the requested data. @property isLoading @type {Boolean} @readOnly */ isLoading: retrieveFromCurrentState, /** If this property is `true` the record is in the `loaded` state. A record enters this state when its data is populated. Most of a record's lifecycle is spent inside substates of the `loaded` state. Example ```javascript var record = store.createRecord('model'); record.get('isLoaded'); // true store.findRecord('model', 1).then(function(model) { model.get('isLoaded'); // true }); ``` @property isLoaded @type {Boolean} @readOnly */ isLoaded: retrieveFromCurrentState, /** If this property is `true` the record is in the `dirty` state. The record has local changes that have not yet been saved by the adapter. This includes records that have been created (but not yet saved) or deleted. Example ```javascript var record = store.createRecord('model'); record.get('hasDirtyAttributes'); // true store.findRecord('model', 1).then(function(model) { model.get('hasDirtyAttributes'); // false model.set('foo', 'some value'); model.get('hasDirtyAttributes'); // true }); ``` @since 1.13.0 @property hasDirtyAttributes @type {Boolean} @readOnly */ hasDirtyAttributes: computed('currentState.isDirty', function () { return this.get('currentState.isDirty'); }), /** If this property is `true` the record is in the `saving` state. A record enters the saving state when `save` is called, but the adapter has not yet acknowledged that the changes have been persisted to the backend. Example ```javascript var record = store.createRecord('model'); record.get('isSaving'); // false var promise = record.save(); record.get('isSaving'); // true promise.then(function() { record.get('isSaving'); // false }); ``` @property isSaving @type {Boolean} @readOnly */ isSaving: retrieveFromCurrentState, /** If this property is `true` the record is in the `deleted` state and has been marked for deletion. When `isDeleted` is true and `hasDirtyAttributes` is true, the record is deleted locally but the deletion was not yet persisted. When `isSaving` is true, the change is in-flight. When both `hasDirtyAttributes` and `isSaving` are false, the change has persisted. Example ```javascript var record = store.createRecord('model'); record.get('isDeleted'); // false record.deleteRecord(); // Locally deleted record.get('isDeleted'); // true record.get('hasDirtyAttributes'); // true record.get('isSaving'); // false // Persisting the deletion var promise = record.save(); record.get('isDeleted'); // true record.get('isSaving'); // true // Deletion Persisted promise.then(function() { record.get('isDeleted'); // true record.get('isSaving'); // false record.get('hasDirtyAttributes'); // false }); ``` @property isDeleted @type {Boolean} @readOnly */ isDeleted: retrieveFromCurrentState, /** If this property is `true` the record is in the `new` state. A record will be in the `new` state when it has been created on the client and the adapter has not yet report that it was successfully saved. Example ```javascript var record = store.createRecord('model'); record.get('isNew'); // true record.save().then(function(model) { model.get('isNew'); // false }); ``` @property isNew @type {Boolean} @readOnly */ isNew: retrieveFromCurrentState, /** If this property is `true` the record is in the `valid` state. A record will be in the `valid` state when the adapter did not report any server-side validation failures. @property isValid @type {Boolean} @readOnly */ isValid: retrieveFromCurrentState, /** If the record is in the dirty state this property will report what kind of change has caused it to move into the dirty state. Possible values are: - `created` The record has been created by the client and not yet saved to the adapter. - `updated` The record has been updated by the client and not yet saved to the adapter. - `deleted` The record has been deleted by the client and not yet saved to the adapter. Example ```javascript var record = store.createRecord('model'); record.get('dirtyType'); // 'created' ``` @property dirtyType @type {String} @readOnly */ dirtyType: retrieveFromCurrentState, /** If `true` the adapter reported that it was unable to save local changes to the backend for any reason other than a server-side validation error. Example ```javascript record.get('isError'); // false record.set('foo', 'valid value'); record.save().then(null, function() { record.get('isError'); // true }); ``` @property isError @type {Boolean} @readOnly */ isError: false, /** If `true` the store is attempting to reload the record form the adapter. Example ```javascript record.get('isReloading'); // false record.reload(); record.get('isReloading'); // true ``` @property isReloading @type {Boolean} @readOnly */ isReloading: false, /** All ember models have an id property. This is an identifier managed by an external source. These are always coerced to be strings before being used internally. Note when declaring the attributes for a model it is an error to declare an id attribute. ```javascript var record = store.createRecord('model'); record.get('id'); // null store.findRecord('model', 1).then(function(model) { model.get('id'); // '1' }); ``` @property id @type {String} */ id: null, /** @property currentState @private @type {Object} */ currentState: _emberDataPrivateSystemModelStates.default.empty, /** When the record is in the `invalid` state this object will contain any errors returned by the adapter. When present the errors hash contains keys corresponding to the invalid property names and values which are arrays of Javascript objects with two keys: - `message` A string containing the error message from the backend - `attribute` The name of the property associated with this error message ```javascript record.get('errors.length'); // 0 record.set('foo', 'invalid value'); record.save().catch(function() { record.get('errors').get('foo'); // [{message: 'foo should be a number.', attribute: 'foo'}] }); ``` The `errors` property us useful for displaying error messages to the user. ```handlebars <label>Username: {{input value=username}} </label> {{#each model.errors.username as |error|}} <div class="error"> {{error.message}} </div> {{/each}} <label>Email: {{input value=email}} </label> {{#each model.errors.email as |error|}} <div class="error"> {{error.message}} </div> {{/each}} ``` You can also access the special `messages` property on the error object to get an array of all the error strings. ```handlebars {{#each model.errors.messages as |message|}} <div class="error"> {{message}} </div> {{/each}} ``` @property errors @type {DS.Errors} */ errors: computed(function () { var errors = _emberDataPrivateSystemModelErrors.default.create(); errors._registerHandlers(this._internalModel, function () { this.send('becameInvalid'); }, function () { this.send('becameValid'); }); return errors; }).readOnly(), /** This property holds the `DS.AdapterError` object with which last adapter operation was rejected. @property adapterError @type {DS.AdapterError} */ adapterError: null, /** Create a JSON representation of the record, using the serialization strategy of the store's adapter. `serialize` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method serialize @param {Object} options @return {Object} an object whose values are primitive JSON values only */ serialize: function (options) { return this._internalModel.createSnapshot().serialize(options); }, /** Use [DS.JSONSerializer](DS.JSONSerializer.html) to get the JSON representation of a record. `toJSON` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method toJSON @param {Object} options @return {Object} A JSON representation of the object. */ toJSON: function (options) { // container is for lazy transform lookups var serializer = this.store.serializerFor('-default'); var snapshot = this._internalModel.createSnapshot(); return serializer.serialize(snapshot, options); }, /** Fired when the record is ready to be interacted with, that is either loaded from the server or created locally. @event ready */ ready: function () {}, /** Fired when the record is loaded from the server. @event didLoad */ didLoad: function () {}, /** Fired when the record is updated. @event didUpdate */ didUpdate: function () {}, /** Fired when a new record is commited to the server. @event didCreate */ didCreate: function () {}, /** Fired when the record is deleted. @event didDelete */ didDelete: function () {}, /** Fired when the record becomes invalid. @event becameInvalid */ becameInvalid: function () {}, /** Fired when the record enters the error state. @event becameError */ becameError: function () {}, /** Fired when the record is rolled back. @event rolledBack */ rolledBack: function () {}, //TODO Do we want to deprecate these? /** @method send @private @param {String} name @param {Object} context */ send: function (name, context) { return this._internalModel.send(name, context); }, /** @method transitionTo @private @param {String} name */ transitionTo: function (name) { return this._internalModel.transitionTo(name); }, /** Marks the record as deleted but does not save it. You must call `save` afterwards if you want to persist it. You might use this method if you want to allow the user to still `rollbackAttributes()` after a delete it was made. Example ```app/routes/model/delete.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { softDelete: function() { this.controller.get('model').deleteRecord(); }, confirm: function() { this.controller.get('model').save(); }, undo: function() { this.controller.get('model').rollbackAttributes(); } } }); ``` @method deleteRecord */ deleteRecord: function () { this._internalModel.deleteRecord(); }, /** Same as `deleteRecord`, but saves the record immediately. Example ```app/routes/model/delete.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { delete: function() { var controller = this.controller; controller.get('model').destroyRecord().then(function() { controller.transitionToRoute('model.index'); }); } } }); ``` If you pass an object on the `adapterOptions` property of the options argument it will be passed to you adapter via the snapshot ```js record.destroyRecord({ adapterOptions: { subscribe: false } }); ``` ```app/adapters/post.js import MyCustomAdapter from './custom-adapter'; export default MyCustomAdapter.extend({ deleteRecord: function(store, type, snapshot) { if (snapshot.adapterOptions.subscribe) { // ... } // ... } }); ``` @method destroyRecord @param {Object} options @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ destroyRecord: function (options) { this.deleteRecord(); return this.save(options); }, /** @method unloadRecord @private */ unloadRecord: function () { if (this.isDestroyed) { return; } this._internalModel.unloadRecord(); }, /** @method _notifyProperties @private */ _notifyProperties: function (keys) { _ember.default.beginPropertyChanges(); var key; for (var i = 0, length = keys.length; i < length; i++) { key = keys[i]; this.notifyPropertyChange(key); } _ember.default.endPropertyChanges(); }, /** Returns an object, whose keys are changed properties, and value is an [oldProp, newProp] array. The array represents the diff of the canonical state with the local state of the model. Note: if the model is created locally, the canonical state is empty since the adapter hasn't acknowledged the attributes yet: Example ```app/models/mascot.js import DS from 'ember-data'; export default DS.Model.extend({ name: attr('string'), isAdmin: attr('boolean', { defaultValue: false }) }); ``` ```javascript var mascot = store.createRecord('mascot'); mascot.changedAttributes(); // {} mascot.set('name', 'Tomster'); mascot.changedAttributes(); // { name: [undefined, 'Tomster'] } mascot.set('isAdmin', true); mascot.changedAttributes(); // { isAdmin: [undefined, true], name: [undefined, 'Tomster'] } mascot.save().then(function() { mascot.changedAttributes(); // {} mascot.set('isAdmin', false); mascot.changedAttributes(); // { isAdmin: [true, false] } }); ``` @method changedAttributes @return {Object} an object, whose keys are changed properties, and value is an [oldProp, newProp] array. */ changedAttributes: function () { return this._internalModel.changedAttributes(); }, //TODO discuss with tomhuda about events/hooks //Bring back as hooks? /** @method adapterWillCommit @private adapterWillCommit: function() { this.send('willCommit'); }, /** @method adapterDidDirty @private adapterDidDirty: function() { this.send('becomeDirty'); this.updateRecordArraysLater(); }, */ /** If the model `hasDirtyAttributes` this function will discard any unsaved changes. If the model `isNew` it will be removed from the store. Example ```javascript record.get('name'); // 'Untitled Document' record.set('name', 'Doc 1'); record.get('name'); // 'Doc 1' record.rollbackAttributes(); record.get('name'); // 'Untitled Document' ``` @since 1.13.0 @method rollbackAttributes */ rollbackAttributes: function () { this._internalModel.rollbackAttributes(); }, /* @method _createSnapshot @private */ _createSnapshot: function () { return this._internalModel.createSnapshot(); }, toStringExtension: function () { return get(this, 'id'); }, /** Save the record and persist any changes to the record to an external source via the adapter. Example ```javascript record.set('name', 'Tomster'); record.save().then(function() { // Success callback }, function() { // Error callback }); ``` If you pass an object on the `adapterOptions` property of the options argument it will be passed to you adapter via the snapshot ```js record.save({ adapterOptions: { subscribe: false } }); ``` ```app/adapters/post.js import MyCustomAdapter from './custom-adapter'; export default MyCustomAdapter.extend({ updateRecord: function(store, type, snapshot) { if (snapshot.adapterOptions.subscribe) { // ... } // ... } }); ``` @method save @param {Object} options @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ save: function (options) { var _this = this; return _emberDataPrivateSystemPromiseProxies.PromiseObject.create({ promise: this._internalModel.save(options).then(function () { return _this; }) }); }, /** Reload the record from the adapter. This will only work if the record has already finished loading. Example ```app/routes/model/view.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { reload: function() { this.controller.get('model').reload().then(function(model) { // do something with the reloaded model }); } } }); ``` @method reload @return {Promise} a promise that will be resolved with the record when the adapter returns successfully or rejected if the adapter returns with an error. */ reload: function () { var _this2 = this; return _emberDataPrivateSystemPromiseProxies.PromiseObject.create({ promise: this._internalModel.reload().then(function () { return _this2; }) }); }, /** Override the default event firing from Ember.Evented to also call methods with the given name. @method trigger @private @param {String} name */ trigger: function (name) { var length = arguments.length; var args = new Array(length - 1); for (var i = 1; i < length; i++) { args[i - 1] = arguments[i]; } _ember.default.tryInvoke(this, name, args); this._super.apply(this, arguments); }, willDestroy: function () { //TODO Move! this._super.apply(this, arguments); this._internalModel.clearRelationships(); this._internalModel.recordObjectWillDestroy(); //TODO should we set internalModel to null here? }, // This is a temporary solution until we refactor DS.Model to not // rely on the data property. willMergeMixin: function (props) { var constructor = this.constructor; }, attr: function () {}, /** Get the reference for the specified belongsTo relationship. Example ```javascript // models/blog.js export default DS.Model.extend({ user: DS.belongsTo({ async: true }) }); var blog = store.push({ type: 'blog', id: 1, relationships: { user: { data: { type: 'user', id: 1 } } } }); var userRef = blog.belongsTo('user'); // check if the user relationship is loaded var isLoaded = userRef.value() !== null; // get the record of the reference (null if not yet available) var user = userRef.value(); // get the identifier of the reference if (userRef.remoteType() === "id") { var id = userRef.id(); } else if (userRef.remoteType() === "link") { var link = userRef.link(); } // load user (via store.findRecord or store.findBelongsTo) userRef.load().then(...) // or trigger a reload userRef.reload().then(...) // provide data for reference userRef.push({ type: 'user', id: 1, attributes: { username: "@user" } }).then(function(user) { userRef.value() === user; }); ``` @method belongsTo @param {String} name of the relationship @since 2.5.0 @return {BelongsToReference} reference for this relationship */ belongsTo: function (name) { return this._internalModel.referenceFor('belongsTo', name); }, /** Get the reference for the specified hasMany relationship. Example ```javascript // models/blog.js export default DS.Model.extend({ comments: DS.hasMany({ async: true }) }); var blog = store.push({ type: 'blog', id: 1, relationships: { comments: { data: [ { type: 'comment', id: 1 }, { type: 'comment', id: 2 } ] } } }); var commentsRef = blog.hasMany('comments'); // check if the comments are loaded already var isLoaded = commentsRef.value() !== null; // get the records of the reference (null if not yet available) var comments = commentsRef.value(); // get the identifier of the reference if (commentsRef.remoteType() === "ids") { var ids = commentsRef.ids(); } else if (commentsRef.remoteType() === "link") { var link = commentsRef.link(); } // load comments (via store.findMany or store.findHasMany) commentsRef.load().then(...) // or trigger a reload commentsRef.reload().then(...) // provide data for reference commentsRef.push([{ type: 'comment', id: 1 }, { type: 'comment', id: 2 }]).then(function(comments) { commentsRef.value() === comments; }); ``` @method hasMany @param {String} name of the relationship @since 2.5.0 @return {HasManyReference} reference for this relationship */ hasMany: function (name) { return this._internalModel.referenceFor('hasMany', name); }, setId: _ember.default.observer('id', function () { this._internalModel.setId(this.get('id')); }) }); /** @property data @private @type {Object} */ Object.defineProperty(Model.prototype, 'data', { get: function () { return this._internalModel._data; } }); Model.reopenClass({ /** Alias DS.Model's `create` method to `_create`. This allows us to create DS.Model instances from within the store, but if end users accidentally call `create()` (instead of `createRecord()`), we can raise an error. @method _create @private @static */ _create: Model.create, /** Override the class' `create()` method to raise an error. This prevents end users from inadvertently calling `create()` instead of `createRecord()`. The store is still able to create instances by calling the `_create()` method. To create an instance of a `DS.Model` use [store.createRecord](DS.Store.html#method_createRecord). @method create @private @static */ create: function () { throw new _ember.default.Error("You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set."); }, /** Represents the model's class name as a string. This can be used to look up the model through DS.Store's modelFor method. `modelName` is generated for you by Ember Data. It will be a lowercased, dasherized string. For example: ```javascript store.modelFor('post').modelName; // 'post' store.modelFor('blog-post').modelName; // 'blog-post' ``` The most common place you'll want to access `modelName` is in your serializer's `payloadKeyFromModelName` method. For example, to change payload keys to underscore (instead of dasherized), you might use the following code: ```javascript export default var PostSerializer = DS.RESTSerializer.extend({ payloadKeyFromModelName: function(modelName) { return Ember.String.underscore(modelName); } }); ``` @property modelName @type String @readonly @static */ modelName: null }); // if `Ember.setOwner` is defined, accessing `this.container` is // deprecated (but functional). In "standard" Ember usage, this // deprecation is actually created via an `.extend` of the factory // inside the container itself, but that only happens on models // with MODEL_FACTORY_INJECTIONS enabled :( if (_ember.default.setOwner) { Object.defineProperty(Model.prototype, 'container', { configurable: true, enumerable: false, get: function () { return this.store.container; } }); } if (false) { Model.reopen({ /** Discards any unsaved changes to the given attribute. Example ```javascript record.get('name'); // 'Untitled Document' record.set('name', 'Doc 1'); record.get('name'); // 'Doc 1' record.resetAttribute('name'); record.get('name'); // 'Untitled Document' ``` @method resetAttribute */ resetAttribute: function (attributeName) { if (attributeName in this._internalModel._attributes) { this.set(attributeName, this._internalModel.lastAcknowledgedValue(attributeName)); } } }); } Model.reopenClass(_emberDataPrivateSystemRelationshipsExt.RelationshipsClassMethodsMixin); Model.reopenClass(_emberDataPrivateSystemModelAttr.AttrClassMethodsMixin); exports.default = Model.extend(_emberDataPrivateSystemDebugDebugInfo.default, _emberDataPrivateSystemRelationshipsBelongsTo.BelongsToMixin, _emberDataPrivateSystemRelationshipsExt.DidDefinePropertyMixin, _emberDataPrivateSystemRelationshipsExt.RelationshipsInstanceMethodsMixin, _emberDataPrivateSystemRelationshipsHasMany.HasManyMixin, _emberDataPrivateSystemModelAttr.AttrInstanceMethodsMixin); }); define('ember-data/-private/system/model/states', ['exports', 'ember-data/-private/debug'], function (exports, _emberDataPrivateDebug) { /* This file encapsulates the various states that a record can transition through during its lifecycle. */ /** ### State Each record has a `currentState` property that explicitly tracks what state a record is in at any given time. For instance, if a record is newly created and has not yet been sent to the adapter to be saved, it would be in the `root.loaded.created.uncommitted` state. If a record has had local modifications made to it that are in the process of being saved, the record would be in the `root.loaded.updated.inFlight` state. (This state paths will be explained in more detail below.) Events are sent by the record or its store to the record's `currentState` property. How the state reacts to these events is dependent on which state it is in. In some states, certain events will be invalid and will cause an exception to be raised. States are hierarchical and every state is a substate of the `RootState`. For example, a record can be in the `root.deleted.uncommitted` state, then transition into the `root.deleted.inFlight` state. If a child state does not implement an event handler, the state manager will attempt to invoke the event on all parent states until the root state is reached. The state hierarchy of a record is described in terms of a path string. You can determine a record's current state by getting the state's `stateName` property: ```javascript record.get('currentState.stateName'); //=> "root.created.uncommitted" ``` The hierarchy of valid states that ship with ember data looks like this: ```text * root * deleted * saved * uncommitted * inFlight * empty * loaded * created * uncommitted * inFlight * saved * updated * uncommitted * inFlight * loading ``` The `DS.Model` states are themselves stateless. What that means is that, the hierarchical states that each of *those* points to is a shared data structure. For performance reasons, instead of each record getting its own copy of the hierarchy of states, each record points to this global, immutable shared instance. How does a state know which record it should be acting on? We pass the record instance into the state's event handlers as the first argument. The record passed as the first parameter is where you should stash state about the record if needed; you should never store data on the state object itself. ### Events and Flags A state may implement zero or more events and flags. #### Events Events are named functions that are invoked when sent to a record. The record will first look for a method with the given name on the current state. If no method is found, it will search the current state's parent, and then its grandparent, and so on until reaching the top of the hierarchy. If the root is reached without an event handler being found, an exception will be raised. This can be very helpful when debugging new features. Here's an example implementation of a state with a `myEvent` event handler: ```javascript aState: DS.State.create({ myEvent: function(manager, param) { console.log("Received myEvent with", param); } }) ``` To trigger this event: ```javascript record.send('myEvent', 'foo'); //=> "Received myEvent with foo" ``` Note that an optional parameter can be sent to a record's `send()` method, which will be passed as the second parameter to the event handler. Events should transition to a different state if appropriate. This can be done by calling the record's `transitionTo()` method with a path to the desired state. The state manager will attempt to resolve the state path relative to the current state. If no state is found at that path, it will attempt to resolve it relative to the current state's parent, and then its parent, and so on until the root is reached. For example, imagine a hierarchy like this: * created * uncommitted <-- currentState * inFlight * updated * inFlight If we are currently in the `uncommitted` state, calling `transitionTo('inFlight')` would transition to the `created.inFlight` state, while calling `transitionTo('updated.inFlight')` would transition to the `updated.inFlight` state. Remember that *only events* should ever cause a state transition. You should never call `transitionTo()` from outside a state's event handler. If you are tempted to do so, create a new event and send that to the state manager. #### Flags Flags are Boolean values that can be used to introspect a record's current state in a more user-friendly way than examining its state path. For example, instead of doing this: ```javascript var statePath = record.get('stateManager.currentPath'); if (statePath === 'created.inFlight') { doSomething(); } ``` You can say: ```javascript if (record.get('isNew') && record.get('isSaving')) { doSomething(); } ``` If your state does not set a value for a given flag, the value will be inherited from its parent (or the first place in the state hierarchy where it is defined). The current set of flags are defined below. If you want to add a new flag, in addition to the area below, you will also need to declare it in the `DS.Model` class. * [isEmpty](DS.Model.html#property_isEmpty) * [isLoading](DS.Model.html#property_isLoading) * [isLoaded](DS.Model.html#property_isLoaded) * [hasDirtyAttributes](DS.Model.html#property_hasDirtyAttributes) * [isSaving](DS.Model.html#property_isSaving) * [isDeleted](DS.Model.html#property_isDeleted) * [isNew](DS.Model.html#property_isNew) * [isValid](DS.Model.html#property_isValid) @namespace DS @class RootState */ function didSetProperty(internalModel, context) { if (context.value === context.originalValue) { delete internalModel._attributes[context.name]; internalModel.send('propertyWasReset', context.name); } else if (context.value !== context.oldValue) { internalModel.send('becomeDirty'); } internalModel.updateRecordArraysLater(); } // Implementation notes: // // Each state has a boolean value for all of the following flags: // // * isLoaded: The record has a populated `data` property. When a // record is loaded via `store.find`, `isLoaded` is false // until the adapter sets it. When a record is created locally, // its `isLoaded` property is always true. // * isDirty: The record has local changes that have not yet been // saved by the adapter. This includes records that have been // created (but not yet saved) or deleted. // * isSaving: The record has been committed, but // the adapter has not yet acknowledged that the changes have // been persisted to the backend. // * isDeleted: The record was marked for deletion. When `isDeleted` // is true and `isDirty` is true, the record is deleted locally // but the deletion was not yet persisted. When `isSaving` is // true, the change is in-flight. When both `isDirty` and // `isSaving` are false, the change has persisted. // * isNew: The record was created on the client and the adapter // did not yet report that it was successfully saved. // * isValid: The adapter did not report any server-side validation // failures. // The dirty state is a abstract state whose functionality is // shared between the `created` and `updated` states. // // The deleted state shares the `isDirty` flag with the // subclasses of `DirtyState`, but with a very different // implementation. // // Dirty states have three child states: // // `uncommitted`: the store has not yet handed off the record // to be saved. // `inFlight`: the store has handed off the record to be saved, // but the adapter has not yet acknowledged success. // `invalid`: the record has invalid information and cannot be // sent to the adapter yet. var DirtyState = { initialState: 'uncommitted', // FLAGS isDirty: true, // SUBSTATES // When a record first becomes dirty, it is `uncommitted`. // This means that there are local pending changes, but they // have not yet begun to be saved, and are not invalid. uncommitted: { // EVENTS didSetProperty: didSetProperty, //TODO(Igor) reloading now triggers a //loadingData event, though it seems fine? loadingData: function () {}, propertyWasReset: function (internalModel, name) { if (!internalModel.hasChangedAttributes()) { internalModel.send('rolledBack'); } }, pushedData: function (internalModel) { internalModel.updateChangedAttributes(); if (!internalModel.hasChangedAttributes()) { internalModel.transitionTo('loaded.saved'); } }, becomeDirty: function () {}, willCommit: function (internalModel) { internalModel.transitionTo('inFlight'); }, reloadRecord: function (internalModel, resolve) { resolve(internalModel.store.reloadRecord(internalModel)); }, rolledBack: function (internalModel) { internalModel.transitionTo('loaded.saved'); }, becameInvalid: function (internalModel) { internalModel.transitionTo('invalid'); }, rollback: function (internalModel) { internalModel.rollbackAttributes(); internalModel.triggerLater('ready'); } }, // Once a record has been handed off to the adapter to be // saved, it is in the 'in flight' state. Changes to the // record cannot be made during this window. inFlight: { // FLAGS isSaving: true, // EVENTS didSetProperty: didSetProperty, becomeDirty: function () {}, pushedData: function () {}, unloadRecord: assertAgainstUnloadRecord, // TODO: More robust semantics around save-while-in-flight willCommit: function () {}, didCommit: function (internalModel) { internalModel.transitionTo('saved'); internalModel.send('invokeLifecycleCallbacks', this.dirtyType); }, becameInvalid: function (internalModel) { internalModel.transitionTo('invalid'); internalModel.send('invokeLifecycleCallbacks'); }, becameError: function (internalModel) { internalModel.transitionTo('uncommitted'); internalModel.triggerLater('becameError', internalModel); } }, // A record is in the `invalid` if the adapter has indicated // the the record failed server-side invalidations. invalid: { // FLAGS isValid: false, // EVENTS deleteRecord: function (internalModel) { internalModel.transitionTo('deleted.uncommitted'); }, didSetProperty: function (internalModel, context) { internalModel.removeErrorMessageFromAttribute(context.name); didSetProperty(internalModel, context); if (!internalModel.hasErrors()) { this.becameValid(internalModel); } }, becameInvalid: function () {}, becomeDirty: function () {}, pushedData: function () {}, willCommit: function (internalModel) { internalModel.clearErrorMessages(); internalModel.transitionTo('inFlight'); }, rolledBack: function (internalModel) { internalModel.clearErrorMessages(); internalModel.transitionTo('loaded.saved'); internalModel.triggerLater('ready'); }, becameValid: function (internalModel) { internalModel.transitionTo('uncommitted'); }, invokeLifecycleCallbacks: function (internalModel) { internalModel.triggerLater('becameInvalid', internalModel); } } }; // The created and updated states are created outside the state // chart so we can reopen their substates and add mixins as // necessary. function deepClone(object) { var clone = {}; var value = undefined; for (var prop in object) { value = object[prop]; if (value && typeof value === 'object') { clone[prop] = deepClone(value); } else { clone[prop] = value; } } return clone; } function mixin(original, hash) { for (var prop in hash) { original[prop] = hash[prop]; } return original; } function dirtyState(options) { var newState = deepClone(DirtyState); return mixin(newState, options); } var createdState = dirtyState({ dirtyType: 'created', // FLAGS isNew: true }); createdState.invalid.rolledBack = function (internalModel) { internalModel.transitionTo('deleted.saved'); }; createdState.uncommitted.rolledBack = function (internalModel) { internalModel.transitionTo('deleted.saved'); }; var updatedState = dirtyState({ dirtyType: 'updated' }); function createdStateDeleteRecord(internalModel) { internalModel.transitionTo('deleted.saved'); internalModel.send('invokeLifecycleCallbacks'); } createdState.uncommitted.deleteRecord = createdStateDeleteRecord; createdState.invalid.deleteRecord = createdStateDeleteRecord; createdState.uncommitted.rollback = function (internalModel) { DirtyState.uncommitted.rollback.apply(this, arguments); internalModel.transitionTo('deleted.saved'); }; createdState.uncommitted.pushedData = function (internalModel) { internalModel.transitionTo('loaded.updated.uncommitted'); internalModel.triggerLater('didLoad'); }; createdState.uncommitted.propertyWasReset = function () {}; function assertAgainstUnloadRecord(internalModel) {} updatedState.inFlight.unloadRecord = assertAgainstUnloadRecord; updatedState.uncommitted.deleteRecord = function (internalModel) { internalModel.transitionTo('deleted.uncommitted'); }; var RootState = { // FLAGS isEmpty: false, isLoading: false, isLoaded: false, isDirty: false, isSaving: false, isDeleted: false, isNew: false, isValid: true, // DEFAULT EVENTS // Trying to roll back if you're not in the dirty state // doesn't change your state. For example, if you're in the // in-flight state, rolling back the record doesn't move // you out of the in-flight state. rolledBack: function () {}, unloadRecord: function (internalModel) { // clear relationships before moving to deleted state // otherwise it fails internalModel.clearRelationships(); internalModel.transitionTo('deleted.saved'); }, propertyWasReset: function () {}, // SUBSTATES // A record begins its lifecycle in the `empty` state. // If its data will come from the adapter, it will // transition into the `loading` state. Otherwise, if // the record is being created on the client, it will // transition into the `created` state. empty: { isEmpty: true, // EVENTS loadingData: function (internalModel, promise) { internalModel._loadingPromise = promise; internalModel.transitionTo('loading'); }, loadedData: function (internalModel) { internalModel.transitionTo('loaded.created.uncommitted'); internalModel.triggerLater('ready'); }, pushedData: function (internalModel) { internalModel.transitionTo('loaded.saved'); internalModel.triggerLater('didLoad'); internalModel.triggerLater('ready'); } }, // A record enters this state when the store asks // the adapter for its data. It remains in this state // until the adapter provides the requested data. // // Usually, this process is asynchronous, using an // XHR to retrieve the data. loading: { // FLAGS isLoading: true, exit: function (internalModel) { internalModel._loadingPromise = null; }, // EVENTS pushedData: function (internalModel) { internalModel.transitionTo('loaded.saved'); internalModel.triggerLater('didLoad'); internalModel.triggerLater('ready'); //TODO this seems out of place here internalModel.didCleanError(); }, becameError: function (internalModel) { internalModel.triggerLater('becameError', internalModel); }, notFound: function (internalModel) { internalModel.transitionTo('empty'); } }, // A record enters this state when its data is populated. // Most of a record's lifecycle is spent inside substates // of the `loaded` state. loaded: { initialState: 'saved', // FLAGS isLoaded: true, //TODO(Igor) Reloading now triggers a loadingData event, //but it should be ok? loadingData: function () {}, // SUBSTATES // If there are no local changes to a record, it remains // in the `saved` state. saved: { setup: function (internalModel) { if (internalModel.hasChangedAttributes()) { internalModel.adapterDidDirty(); } }, // EVENTS didSetProperty: didSetProperty, pushedData: function () {}, becomeDirty: function (internalModel) { internalModel.transitionTo('updated.uncommitted'); }, willCommit: function (internalModel) { internalModel.transitionTo('updated.inFlight'); }, reloadRecord: function (internalModel, resolve) { resolve(internalModel.store.reloadRecord(internalModel)); }, deleteRecord: function (internalModel) { internalModel.transitionTo('deleted.uncommitted'); }, unloadRecord: function (internalModel) { // clear relationships before moving to deleted state // otherwise it fails internalModel.clearRelationships(); internalModel.transitionTo('deleted.saved'); }, didCommit: function () {}, // loaded.saved.notFound would be triggered by a failed // `reload()` on an unchanged record notFound: function () {} }, // A record is in this state after it has been locally // created but before the adapter has indicated that // it has been saved. created: createdState, // A record is in this state if it has already been // saved to the server, but there are new local changes // that have not yet been saved. updated: updatedState }, // A record is in this state if it was deleted from the store. deleted: { initialState: 'uncommitted', dirtyType: 'deleted', // FLAGS isDeleted: true, isLoaded: true, isDirty: true, // TRANSITIONS setup: function (internalModel) { internalModel.updateRecordArrays(); }, // SUBSTATES // When a record is deleted, it enters the `start` // state. It will exit this state when the record // starts to commit. uncommitted: { // EVENTS willCommit: function (internalModel) { internalModel.transitionTo('inFlight'); }, rollback: function (internalModel) { internalModel.rollbackAttributes(); internalModel.triggerLater('ready'); }, pushedData: function () {}, becomeDirty: function () {}, deleteRecord: function () {}, rolledBack: function (internalModel) { internalModel.transitionTo('loaded.saved'); internalModel.triggerLater('ready'); } }, // After a record starts committing, but // before the adapter indicates that the deletion // has saved to the server, a record is in the // `inFlight` substate of `deleted`. inFlight: { // FLAGS isSaving: true, // EVENTS unloadRecord: assertAgainstUnloadRecord, // TODO: More robust semantics around save-while-in-flight willCommit: function () {}, didCommit: function (internalModel) { internalModel.transitionTo('saved'); internalModel.send('invokeLifecycleCallbacks'); }, becameError: function (internalModel) { internalModel.transitionTo('uncommitted'); internalModel.triggerLater('becameError', internalModel); }, becameInvalid: function (internalModel) { internalModel.transitionTo('invalid'); internalModel.triggerLater('becameInvalid', internalModel); } }, // Once the adapter indicates that the deletion has // been saved, the record enters the `saved` substate // of `deleted`. saved: { // FLAGS isDirty: false, setup: function (internalModel) { internalModel.clearRelationships(); var store = internalModel.store; store._dematerializeRecord(internalModel); }, invokeLifecycleCallbacks: function (internalModel) { internalModel.triggerLater('didDelete', internalModel); internalModel.triggerLater('didCommit', internalModel); }, willCommit: function () {}, didCommit: function () {} }, invalid: { isValid: false, didSetProperty: function (internalModel, context) { internalModel.removeErrorMessageFromAttribute(context.name); didSetProperty(internalModel, context); if (!internalModel.hasErrors()) { this.becameValid(internalModel); } }, becameInvalid: function () {}, becomeDirty: function () {}, deleteRecord: function () {}, willCommit: function () {}, rolledBack: function (internalModel) { internalModel.clearErrorMessages(); internalModel.transitionTo('loaded.saved'); internalModel.triggerLater('ready'); }, becameValid: function (internalModel) { internalModel.transitionTo('uncommitted'); } } }, invokeLifecycleCallbacks: function (internalModel, dirtyType) { if (dirtyType === 'created') { internalModel.triggerLater('didCreate', internalModel); } else { internalModel.triggerLater('didUpdate', internalModel); } internalModel.triggerLater('didCommit', internalModel); } }; function wireState(object, parent, name) { // TODO: Use Object.create and copy instead object = mixin(parent ? Object.create(parent) : {}, object); object.parentState = parent; object.stateName = name; for (var prop in object) { if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') { continue; } if (typeof object[prop] === 'object') { object[prop] = wireState(object[prop], object, name + '.' + prop); } } return object; } exports.default = wireState(RootState, null, 'root'); }); /** @module ember-data */ define('ember-data/-private/system/normalize-link', ['exports'], function (exports) { exports.default = _normalizeLink; /* This method normalizes a link to an "links object". If the passed link is already an object it's returned without any modifications. See http://jsonapi.org/format/#document-links for more information. @method _normalizeLink @private @param {String} link @return {Object|null} @for DS */ function _normalizeLink(link) { switch (typeof link) { case 'object': return link; case 'string': return { href: link }; } return null; } }); define('ember-data/-private/system/normalize-model-name', ['exports', 'ember'], function (exports, _ember) { exports.default = normalizeModelName; // All modelNames are dasherized internally. Changing this function may // require changes to other normalization hooks (such as typeForRoot). /** This method normalizes a modelName into the format Ember Data uses internally. @method normalizeModelName @public @param {String} modelName @return {String} normalizedModelName @for DS */ function normalizeModelName(modelName) { return _ember.default.String.dasherize(modelName); } }); define('ember-data/-private/system/ordered-set', ['exports', 'ember'], function (exports, _ember) { exports.default = OrderedSet; var EmberOrderedSet = _ember.default.OrderedSet; var guidFor = _ember.default.guidFor; function OrderedSet() { this._super$constructor(); } OrderedSet.create = function () { var Constructor = this; return new Constructor(); }; OrderedSet.prototype = Object.create(EmberOrderedSet.prototype); OrderedSet.prototype.constructor = OrderedSet; OrderedSet.prototype._super$constructor = EmberOrderedSet; OrderedSet.prototype.addWithIndex = function (obj, idx) { var guid = guidFor(obj); var presenceSet = this.presenceSet; var list = this.list; if (presenceSet[guid] === true) { return; } presenceSet[guid] = true; if (idx === undefined || idx === null) { list.push(obj); } else { list.splice(idx, 0, obj); } this.size += 1; return this; }; }); define('ember-data/-private/system/promise-proxies', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { exports.promiseObject = promiseObject; exports.promiseArray = promiseArray; exports.proxyToContent = proxyToContent; exports.promiseManyArray = promiseManyArray; var get = _ember.default.get; var Promise = _ember.default.RSVP.Promise; /** A `PromiseArray` is an object that acts like both an `Ember.Array` and a promise. When the promise is resolved the resulting value will be set to the `PromiseArray`'s `content` property. This makes it easy to create data bindings with the `PromiseArray` that will be updated when the promise resolves. For more information see the [Ember.PromiseProxyMixin documentation](/api/classes/Ember.PromiseProxyMixin.html). Example ```javascript var promiseArray = DS.PromiseArray.create({ promise: $.getJSON('/some/remote/data.json') }); promiseArray.get('length'); // 0 promiseArray.then(function() { promiseArray.get('length'); // 100 }); ``` @class PromiseArray @namespace DS @extends Ember.ArrayProxy @uses Ember.PromiseProxyMixin */ var PromiseArray = _ember.default.ArrayProxy.extend(_ember.default.PromiseProxyMixin); exports.PromiseArray = PromiseArray; /** A `PromiseObject` is an object that acts like both an `Ember.Object` and a promise. When the promise is resolved, then the resulting value will be set to the `PromiseObject`'s `content` property. This makes it easy to create data bindings with the `PromiseObject` that will be updated when the promise resolves. For more information see the [Ember.PromiseProxyMixin documentation](/api/classes/Ember.PromiseProxyMixin.html). Example ```javascript var promiseObject = DS.PromiseObject.create({ promise: $.getJSON('/some/remote/data.json') }); promiseObject.get('name'); // null promiseObject.then(function() { promiseObject.get('name'); // 'Tomster' }); ``` @class PromiseObject @namespace DS @extends Ember.ObjectProxy @uses Ember.PromiseProxyMixin */ var PromiseObject = _ember.default.ObjectProxy.extend(_ember.default.PromiseProxyMixin); exports.PromiseObject = PromiseObject; function promiseObject(promise, label) { return PromiseObject.create({ promise: Promise.resolve(promise, label) }); } function promiseArray(promise, label) { return PromiseArray.create({ promise: Promise.resolve(promise, label) }); } /** A PromiseManyArray is a PromiseArray that also proxies certain method calls to the underlying manyArray. Right now we proxy: * `reload()` * `createRecord()` * `on()` * `one()` * `trigger()` * `off()` * `has()` @class PromiseManyArray @namespace DS @extends Ember.ArrayProxy */ function proxyToContent(method) { return function () { var _get; return (_get = get(this, 'content'))[method].apply(_get, arguments); }; } var PromiseManyArray = PromiseArray.extend({ reload: function () { return PromiseManyArray.create({ promise: get(this, 'content').reload() }); //I don't think this should ever happen right now, but worth guarding if we refactor the async relationships }, createRecord: proxyToContent('createRecord'), on: proxyToContent('on'), one: proxyToContent('one'), trigger: proxyToContent('trigger'), off: proxyToContent('off'), has: proxyToContent('has') }); exports.PromiseManyArray = PromiseManyArray; function promiseManyArray(promise, label) { return PromiseManyArray.create({ promise: Promise.resolve(promise, label) }); } }); define("ember-data/-private/system/record-array-manager", ["exports", "ember", "ember-data/-private/system/record-arrays", "ember-data/-private/system/ordered-set"], function (exports, _ember, _emberDataPrivateSystemRecordArrays, _emberDataPrivateSystemOrderedSet) { var get = _ember.default.get; var MapWithDefault = _ember.default.MapWithDefault; var emberRun = _ember.default.run; /** @class RecordArrayManager @namespace DS @private @extends Ember.Object */ exports.default = _ember.default.Object.extend({ init: function () { var _this = this; this.filteredRecordArrays = MapWithDefault.create({ defaultValue: function () { return []; } }); this.liveRecordArrays = MapWithDefault.create({ defaultValue: function (modelClass) { return _this.createRecordArray(modelClass); } }); this.changedRecords = []; this._adapterPopulatedRecordArrays = []; }, recordDidChange: function (record) { if (this.changedRecords.push(record) !== 1) { return; } emberRun.schedule('actions', this, this.updateRecordArrays); }, recordArraysForRecord: function (record) { record._recordArrays = record._recordArrays || _emberDataPrivateSystemOrderedSet.default.create(); return record._recordArrays; }, /** This method is invoked whenever data is loaded into the store by the adapter or updated by the adapter, or when a record has changed. It updates all record arrays that a record belongs to. To avoid thrashing, it only runs at most once per run loop. @method updateRecordArrays */ updateRecordArrays: function () { var _this2 = this; this.changedRecords.forEach(function (internalModel) { if (internalModel.isDestroyed || internalModel.currentState.stateName === 'root.deleted.saved') { _this2._recordWasDeleted(internalModel); } else { _this2._recordWasChanged(internalModel); } }); this.changedRecords.length = 0; }, _recordWasDeleted: function (record) { var recordArrays = record._recordArrays; if (!recordArrays) { return; } recordArrays.forEach(function (array) { return array._removeInternalModels([record]); }); record._recordArrays = null; }, _recordWasChanged: function (record) { var _this3 = this; var typeClass = record.type; var recordArrays = this.filteredRecordArrays.get(typeClass); var filter = undefined; recordArrays.forEach(function (array) { filter = get(array, 'filterFunction'); _this3.updateFilterRecordArray(array, filter, typeClass, record); }); }, //Need to update live arrays on loading recordWasLoaded: function (record) { var _this4 = this; var typeClass = record.type; var recordArrays = this.filteredRecordArrays.get(typeClass); var filter = undefined; recordArrays.forEach(function (array) { filter = get(array, 'filterFunction'); _this4.updateFilterRecordArray(array, filter, typeClass, record); }); if (this.liveRecordArrays.has(typeClass)) { var liveRecordArray = this.liveRecordArrays.get(typeClass); this._addInternalModelToRecordArray(liveRecordArray, record); } }, /** Update an individual filter. @method updateFilterRecordArray @param {DS.FilteredRecordArray} array @param {Function} filter @param {DS.Model} modelClass @param {InternalModel} internalModel */ updateFilterRecordArray: function (array, filter, modelClass, internalModel) { var shouldBeInArray = filter(internalModel.getRecord()); var recordArrays = this.recordArraysForRecord(internalModel); if (shouldBeInArray) { this._addInternalModelToRecordArray(array, internalModel); } else { recordArrays.delete(array); array._removeInternalModels([internalModel]); } }, _addInternalModelToRecordArray: function (array, internalModel) { var recordArrays = this.recordArraysForRecord(internalModel); if (!recordArrays.has(array)) { array._pushInternalModels([internalModel]); recordArrays.add(array); } }, syncLiveRecordArray: function (array, modelClass) { var hasNoPotentialDeletions = this.changedRecords.length === 0; var typeMap = this.store.typeMapFor(modelClass); var hasNoInsertionsOrRemovals = typeMap.records.length === array.length; /* Ideally the recordArrayManager has knowledge of the changes to be applied to liveRecordArrays, and is capable of strategically flushing those changes and applying small diffs if desired. However, until we've refactored recordArrayManager, this dirty check prevents us from unnecessarily wiping out live record arrays returned by peekAll. */ if (hasNoPotentialDeletions && hasNoInsertionsOrRemovals) { return; } this.populateLiveRecordArray(array, modelClass); }, populateLiveRecordArray: function (array, modelClass) { var typeMap = this.store.typeMapFor(modelClass); var records = typeMap.records; var record = undefined; for (var i = 0; i < records.length; i++) { record = records[i]; if (!record.isDeleted() && !record.isEmpty()) { this._addInternalModelToRecordArray(array, record); } } }, /** This method is invoked if the `filterFunction` property is changed on a `DS.FilteredRecordArray`. It essentially re-runs the filter from scratch. This same method is invoked when the filter is created in th first place. @method updateFilter @param {Array} array @param {Class} modelClass @param {Function} filter */ updateFilter: function (array, modelClass, filter) { var typeMap = this.store.typeMapFor(modelClass); var records = typeMap.records; var record = undefined; for (var i = 0; i < records.length; i++) { record = records[i]; if (!record.isDeleted() && !record.isEmpty()) { this.updateFilterRecordArray(array, filter, modelClass, record); } } }, /** Get the `DS.RecordArray` for a type, which contains all loaded records of given type. @method liveRecordArrayFor @param {Class} typeClass @return {DS.RecordArray} */ liveRecordArrayFor: function (typeClass) { return this.liveRecordArrays.get(typeClass); }, /** Create a `DS.RecordArray` for a type. @method createRecordArray @param {Class} modelClass @return {DS.RecordArray} */ createRecordArray: function (modelClass) { return _emberDataPrivateSystemRecordArrays.RecordArray.create({ type: modelClass, content: _ember.default.A(), store: this.store, isLoaded: true, manager: this }); }, /** Create a `DS.FilteredRecordArray` for a type and register it for updates. @method createFilteredRecordArray @param {DS.Model} typeClass @param {Function} filter @param {Object} query (optional @return {DS.FilteredRecordArray} */ createFilteredRecordArray: function (typeClass, filter, query) { var array = _emberDataPrivateSystemRecordArrays.FilteredRecordArray.create({ query: query, type: typeClass, content: _ember.default.A(), store: this.store, manager: this, filterFunction: filter }); this.registerFilteredRecordArray(array, typeClass, filter); return array; }, /** Create a `DS.AdapterPopulatedRecordArray` for a type with given query. @method createAdapterPopulatedRecordArray @param {DS.Model} typeClass @param {Object} query @return {DS.AdapterPopulatedRecordArray} */ createAdapterPopulatedRecordArray: function (typeClass, query) { var array = _emberDataPrivateSystemRecordArrays.AdapterPopulatedRecordArray.create({ type: typeClass, query: query, content: _ember.default.A(), store: this.store, manager: this }); this._adapterPopulatedRecordArrays.push(array); return array; }, /** Register a RecordArray for a given type to be backed by a filter function. This will cause the array to update automatically when records of that type change attribute values or states. @method registerFilteredRecordArray @param {DS.RecordArray} array @param {DS.Model} typeClass @param {Function} filter */ registerFilteredRecordArray: function (array, typeClass, filter) { var recordArrays = this.filteredRecordArrays.get(typeClass); recordArrays.push(array); this.updateFilter(array, typeClass, filter); }, /** Unregister a RecordArray. So manager will not update this array. @method unregisterRecordArray @param {DS.RecordArray} array */ unregisterRecordArray: function (array) { var typeClass = array.type; // unregister filtered record array var recordArrays = this.filteredRecordArrays.get(typeClass); var removedFromFiltered = remove(recordArrays, array); // remove from adapter populated record array var removedFromAdapterPopulated = remove(this._adapterPopulatedRecordArrays, array); if (!removedFromFiltered && !removedFromAdapterPopulated) { // unregister live record array if (this.liveRecordArrays.has(typeClass)) { var liveRecordArrayForType = this.liveRecordArrayFor(typeClass); if (array === liveRecordArrayForType) { this.liveRecordArrays.delete(typeClass); } } } }, willDestroy: function () { this._super.apply(this, arguments); this.filteredRecordArrays.forEach(function (value) { return flatten(value).forEach(destroy); }); this.liveRecordArrays.forEach(destroy); this._adapterPopulatedRecordArrays.forEach(destroy); } }); function destroy(entry) { entry.destroy(); } function flatten(list) { var length = list.length; var result = []; for (var i = 0; i < length; i++) { result = result.concat(list[i]); } return result; } function remove(array, item) { var index = array.indexOf(item); if (index !== -1) { array.splice(index, 1); return true; } return false; } }); /** @module ember-data */ define("ember-data/-private/system/record-arrays", ["exports", "ember-data/-private/system/record-arrays/record-array", "ember-data/-private/system/record-arrays/filtered-record-array", "ember-data/-private/system/record-arrays/adapter-populated-record-array"], function (exports, _emberDataPrivateSystemRecordArraysRecordArray, _emberDataPrivateSystemRecordArraysFilteredRecordArray, _emberDataPrivateSystemRecordArraysAdapterPopulatedRecordArray) { exports.RecordArray = _emberDataPrivateSystemRecordArraysRecordArray.default; exports.FilteredRecordArray = _emberDataPrivateSystemRecordArraysFilteredRecordArray.default; exports.AdapterPopulatedRecordArray = _emberDataPrivateSystemRecordArraysAdapterPopulatedRecordArray.default; }); /** @module ember-data */ define("ember-data/-private/system/record-arrays/adapter-populated-record-array", ["exports", "ember", "ember-data/-private/system/record-arrays/record-array", "ember-data/-private/system/clone-null"], function (exports, _ember, _emberDataPrivateSystemRecordArraysRecordArray, _emberDataPrivateSystemCloneNull) { /** @module ember-data */ var get = _ember.default.get; /** Represents an ordered list of records whose order and membership is determined by the adapter. For example, a query sent to the adapter may trigger a search on the server, whose results would be loaded into an instance of the `AdapterPopulatedRecordArray`. --- If you want to update the array and get the latest records from the adapter, you can invoke [`update()`](#method_update): Example ```javascript // GET /users?isAdmin=true var admins = store.query('user', { isAdmin: true }); admins.then(function() { console.log(admins.get("length")); // 42 }); // somewhere later in the app code, when new admins have been created // in the meantime // // GET /users?isAdmin=true admins.update().then(function() { admins.get('isUpdating'); // false console.log(admins.get("length")); // 123 }); admins.get('isUpdating'); // true ``` @class AdapterPopulatedRecordArray @namespace DS @extends DS.RecordArray */ exports.default = _emberDataPrivateSystemRecordArraysRecordArray.default.extend({ init: function () { // yes we are touching `this` before super, but ArrayProxy has a bug that requires this. this.set('content', this.get('content') || _ember.default.A()); this._super.apply(this, arguments); this.query = this.query || null; this.links = null; }, replace: function () { var type = get(this, 'type').toString(); throw new Error("The result of a server query (on " + type + ") is immutable."); }, _update: function () { var store = get(this, 'store'); var modelName = get(this, 'type.modelName'); var query = get(this, 'query'); return store._query(modelName, query, this); }, /** @method _setInternalModels @param {Array} internalModels @param {Object} payload normalized payload @private */ _setInternalModels: function (internalModels, payload) { var _this = this; // TODO: initial load should not cause change events at all, only // subsequent. This requires changing the public api of adapter.query, but // hopefully we can do that soon. this.get('content').setObjects(internalModels); this.setProperties({ isLoaded: true, isUpdating: false, meta: (0, _emberDataPrivateSystemCloneNull.default)(payload.meta), links: (0, _emberDataPrivateSystemCloneNull.default)(payload.links) }); internalModels.forEach(function (record) { return _this.manager.recordArraysForRecord(record).add(_this); }); // TODO: should triggering didLoad event be the last action of the runLoop? _ember.default.run.once(this, 'trigger', 'didLoad'); } }); }); define('ember-data/-private/system/record-arrays/filtered-record-array', ['exports', 'ember', 'ember-data/-private/system/record-arrays/record-array'], function (exports, _ember, _emberDataPrivateSystemRecordArraysRecordArray) { /** @module ember-data */ var get = _ember.default.get; /** Represents a list of records whose membership is determined by the store. As records are created, loaded, or modified, the store evaluates them to determine if they should be part of the record array. @class FilteredRecordArray @namespace DS @extends DS.RecordArray */ exports.default = _emberDataPrivateSystemRecordArraysRecordArray.default.extend({ init: function () { this._super.apply(this, arguments); this.set('filterFunction', this.get('filterFunction') || null); this.isLoaded = true; }, /** The filterFunction is a function used to test records from the store to determine if they should be part of the record array. Example ```javascript var allPeople = store.peekAll('person'); allPeople.mapBy('name'); // ["Tom Dale", "Yehuda Katz", "Trek Glowacki"] var people = store.filter('person', function(person) { if (person.get('name').match(/Katz$/)) { return true; } }); people.mapBy('name'); // ["Yehuda Katz"] var notKatzFilter = function(person) { return !person.get('name').match(/Katz$/); }; people.set('filterFunction', notKatzFilter); people.mapBy('name'); // ["Tom Dale", "Trek Glowacki"] ``` @method filterFunction @param {DS.Model} record @return {Boolean} `true` if the record should be in the array */ replace: function () { var type = get(this, 'type').toString(); throw new Error('The result of a client-side filter (on ' + type + ') is immutable.'); }, /** @method updateFilter @private */ _updateFilter: function () { if (get(this, 'isDestroying') || get(this, 'isDestroyed')) { return; } get(this, 'manager').updateFilter(this, get(this, 'type'), get(this, 'filterFunction')); }, updateFilter: _ember.default.observer('filterFunction', function () { _ember.default.run.once(this, this._updateFilter); }) }); }); define("ember-data/-private/system/record-arrays/record-array", ["exports", "ember", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/snapshot-record-array"], function (exports, _ember, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemSnapshotRecordArray) { var get = _ember.default.get; var set = _ember.default.set; var Promise = _ember.default.RSVP.Promise; /** A record array is an array that contains records of a certain type. The record array materializes records as needed when they are retrieved for the first time. You should not create record arrays yourself. Instead, an instance of `DS.RecordArray` or its subclasses will be returned by your application's store in response to queries. @class RecordArray @namespace DS @extends Ember.ArrayProxy @uses Ember.Evented */ exports.default = _ember.default.ArrayProxy.extend(_ember.default.Evented, { init: function () { this._super.apply(this, arguments); /** The model type contained by this record array. @property type @type DS.Model */ this.type = this.type || null; /** The array of client ids backing the record array. When a record is requested from the record array, the record for the client id at the same index is materialized, if necessary, by the store. @property content @private @type Ember.Array */ this.set('content', this.content || null); /** The flag to signal a `RecordArray` is finished loading data. Example ```javascript var people = store.peekAll('person'); people.get('isLoaded'); // true ``` @property isLoaded @type Boolean */ this.isLoaded = this.isLoaded || false; /** The flag to signal a `RecordArray` is currently loading data. Example ```javascript var people = store.peekAll('person'); people.get('isUpdating'); // false people.update(); people.get('isUpdating'); // true ``` @property isUpdating @type Boolean */ this.isUpdating = false; /** The store that created this record array. @property store @private @type DS.Store */ this.store = this.store || null; this._updatingPromise = null; }, replace: function () { var type = get(this, 'type').toString(); throw new Error("The result of a server query (for all " + type + " types) is immutable. To modify contents, use toArray()"); }, /** Retrieves an object from the content by index. @method objectAtContent @private @param {Number} index @return {DS.Model} record */ objectAtContent: function (index) { var internalModel = get(this, 'content').objectAt(index); return internalModel && internalModel.getRecord(); }, /** Used to get the latest version of all of the records in this array from the adapter. Example ```javascript var people = store.peekAll('person'); people.get('isUpdating'); // false people.update().then(function() { people.get('isUpdating'); // false }); people.get('isUpdating'); // true ``` @method update */ update: function () { var _this = this; if (get(this, 'isUpdating')) { return this._updatingPromise; } this.set('isUpdating', true); var updatingPromise = this._update().finally(function () { _this._updatingPromise = null; if (_this.get('isDestroying') || _this.get('isDestroyed')) { return; } _this.set('isUpdating', false); }); this._updatingPromise = updatingPromise; return updatingPromise; }, /* Update this RecordArray and return a promise which resolves once the update is finished. */ _update: function () { var store = get(this, 'store'); var modelName = get(this, 'type.modelName'); return store.findAll(modelName, { reload: true }); }, /** Adds an internal model to the `RecordArray` without duplicates @method addInternalModel @private @param {InternalModel} internalModel */ _pushInternalModels: function (internalModels) { // pushObjects because the internalModels._recordArrays set was already // consulted for inclusion, so addObject and its on .contains call is not // required. get(this, 'content').pushObjects(internalModels); }, /** Removes an internalModel to the `RecordArray`. @method removeInternalModel @private @param {InternalModel} internalModel */ _removeInternalModels: function (internalModels) { get(this, 'content').removeObjects(internalModels); }, /** Saves all of the records in the `RecordArray`. Example ```javascript var messages = store.peekAll('message'); messages.forEach(function(message) { message.set('hasBeenSeen', true); }); messages.save(); ``` @method save @return {DS.PromiseArray} promise */ save: function () { var _this2 = this; var promiseLabel = 'DS: RecordArray#save ' + get(this, 'type'); var promise = Promise.all(this.invoke('save'), promiseLabel).then(function () { return _this2; }, null, 'DS: RecordArray#save return RecordArray'); return _emberDataPrivateSystemPromiseProxies.PromiseArray.create({ promise: promise }); }, _dissociateFromOwnRecords: function () { var _this3 = this; this.get('content').forEach(function (internalModel) { var recordArrays = internalModel._recordArrays; if (recordArrays) { recordArrays.delete(_this3); } }); }, /** @method _unregisterFromManager @private */ _unregisterFromManager: function () { get(this, 'manager').unregisterRecordArray(this); }, willDestroy: function () { this._unregisterFromManager(); this._dissociateFromOwnRecords(); // TODO: we should not do work during destroy: // * when objects are destroyed, they should simply be left to do // * if logic errors do to this, that logic needs to be more careful during // teardown (ember provides isDestroying/isDestroyed) for this reason // * the exception being: if an dominator has a reference to this object, // and must be informed to release e.g. e.g. removing itself from th // recordArrayMananger set(this, 'content', null); set(this, 'length', 0); this._super.apply(this, arguments); }, /** r @method _createSnapshot @private */ _createSnapshot: function (options) { // this is private for users, but public for ember-data internals return new _emberDataPrivateSystemSnapshotRecordArray.default(this, this.get('meta'), options); }, /** r @method _takeSnapshot @private */ _takeSnapshot: function () { return get(this, 'content').map(function (internalModel) { return internalModel.createSnapshot(); }); } }); }); /** @module ember-data */ define('ember-data/-private/system/references', ['exports', 'ember-data/-private/system/references/record', 'ember-data/-private/system/references/belongs-to', 'ember-data/-private/system/references/has-many'], function (exports, _emberDataPrivateSystemReferencesRecord, _emberDataPrivateSystemReferencesBelongsTo, _emberDataPrivateSystemReferencesHasMany) { exports.RecordReference = _emberDataPrivateSystemReferencesRecord.default; exports.BelongsToReference = _emberDataPrivateSystemReferencesBelongsTo.default; exports.HasManyReference = _emberDataPrivateSystemReferencesHasMany.default; }); define('ember-data/-private/system/references/belongs-to', ['exports', 'ember-data/model', 'ember', 'ember-data/-private/system/references/reference', 'ember-data/-private/features', 'ember-data/-private/debug'], function (exports, _emberDataModel, _ember, _emberDataPrivateSystemReferencesReference, _emberDataPrivateFeatures, _emberDataPrivateDebug) { /** A BelongsToReference is a low level API that allows users and addon author to perform meta-operations on a belongs-to relationship. @class BelongsToReference @namespace DS @extends DS.Reference */ var BelongsToReference = function (store, parentInternalModel, belongsToRelationship) { this._super$constructor(store, parentInternalModel); this.belongsToRelationship = belongsToRelationship; this.type = belongsToRelationship.relationshipMeta.type; this.parent = parentInternalModel.recordReference; // TODO inverse }; BelongsToReference.prototype = Object.create(_emberDataPrivateSystemReferencesReference.default.prototype); BelongsToReference.prototype.constructor = BelongsToReference; BelongsToReference.prototype._super$constructor = _emberDataPrivateSystemReferencesReference.default; /** This returns a string that represents how the reference will be looked up when it is loaded. If the relationship has a link it will use the "link" otherwise it defaults to "id". Example ```javascript // models/blog.js export default DS.Model.extend({ user: DS.belongsTo({ async: true }) }); var blog = store.push({ type: 'blog', id: 1, relationships: { user: { data: { type: 'user', id: 1 } } } }); var userRef = blog.belongsTo('user'); // get the identifier of the reference if (userRef.remoteType() === "id") { var id = userRef.id(); } else if (userRef.remoteType() === "link") { var link = userRef.link(); } ``` @method remoteType @return {String} The name of the remote type. This should either be "link" or "id" */ BelongsToReference.prototype.remoteType = function () { if (this.belongsToRelationship.link) { return "link"; } return "id"; }; /** The `id` of the record that this reference refers to. Together, the `type()` and `id()` methods form a composite key for the identity map. This can be used to access the id of an async relationship without triggering a fetch that would normally happen if you attempted to use `record.get('relationship.id')`. Example ```javascript // models/blog.js export default DS.Model.extend({ user: DS.belongsTo({ async: true }) }); var blog = store.push({ data: { type: 'blog', id: 1, relationships: { user: { data: { type: 'user', id: 1 } } } } }); var userRef = blog.belongsTo('user'); // get the identifier of the reference if (userRef.remoteType() === "id") { var id = userRef.id(); } ``` @method id @return {String} The id of the record in this belongsTo relationship. */ BelongsToReference.prototype.id = function () { var inverseRecord = this.belongsToRelationship.inverseRecord; return inverseRecord && inverseRecord.id; }; /** The link Ember Data will use to fetch or reload this belongs-to relationship. Example ```javascript // models/blog.js export default DS.Model.extend({ user: DS.belongsTo({ async: true }) }); var blog = store.push({ data: { type: 'blog', id: 1, relationships: { user: { links: { related: '/articles/1/author' } } } } }); var userRef = blog.belongsTo('user'); // get the identifier of the reference if (userRef.remoteType() === "link") { var link = userRef.link(); } ``` @method link @return {String} The link Ember Data will use to fetch or reload this belongs-to relationship. */ BelongsToReference.prototype.link = function () { return this.belongsToRelationship.link; }; /** The meta data for the belongs-to relationship. Example ```javascript // models/blog.js export default DS.Model.extend({ user: DS.belongsTo({ async: true }) }); var blog = store.push({ data: { type: 'blog', id: 1, relationships: { user: { links: { related: { href: '/articles/1/author', meta: { lastUpdated: 1458014400000 } } } } } } }); var userRef = blog.belongsTo('user'); userRef.meta() // { lastUpdated: 1458014400000 } ``` @method meta @return {Object} The meta information for the belongs-oo relationship. */ BelongsToReference.prototype.meta = function () { return this.belongsToRelationship.meta; }; /** `push` can be used to update the data in the relationship and Ember Data will treat the new data as the conanical value of this relationship on the backend. Example ```javascript // models/blog.js export default DS.Model.extend({ user: DS.belongsTo({ async: true }) }); var blog = store.push({ data: { type: 'blog', id: 1, relationships: { user: { data: { type: 'user', id: 1 } } } } }); var userRef = blog.belongsTo('user'); // provide data for reference userRef.push({ data: { type: 'user', id: 1, attributes: { username: "@user" } } }).then(function(user) { userRef.value() === user; }); ``` @method push @param {Object|Promise} objectOrPromise a promise that resolves to a JSONAPI document object describing the new value of this relationship. @return {Promise<record>} A promise that resolves with the new value in this belongs-to relationship. */ BelongsToReference.prototype.push = function (objectOrPromise) { var _this = this; return _ember.default.RSVP.resolve(objectOrPromise).then(function (data) { var record; if (data instanceof _emberDataModel.default) { if (false) {} record = data; } else { record = _this.store.push(data); } _this.belongsToRelationship.setCanonicalRecord(record._internalModel); return record; }); }; /** `value()` synchronously returns the current value of the belongs-to relationship. Unlike `record.get('relationshipName')`, calling `value()` on a reference does not trigger a fetch if the async relationship is not yet loaded. If the relationship is not loaded it will always return `null`. Example ```javascript // models/blog.js export default DS.Model.extend({ user: DS.belongsTo({ async: true }) }); var blog = store.push({ data: { type: 'blog', id: 1, relationships: { user: { data: { type: 'user', id: 1 } } } } }); var userRef = blog.belongsTo('user'); userRef.value(); // null // provide data for reference userRef.push({ data: { type: 'user', id: 1, attributes: { username: "@user" } } }).then(function(user) { userRef.value(); // user }); ``` @method value @param {Object|Promise} objectOrPromise a promise that resolves to a JSONAPI document object describing the new value of this relationship. @return {DS.Model} the record in this relationship */ BelongsToReference.prototype.value = function () { var inverseRecord = this.belongsToRelationship.inverseRecord; if (inverseRecord && inverseRecord.isLoaded()) { return inverseRecord.getRecord(); } return null; }; /** Loads a record in a belongs to relationship if it is not already loaded. If the relationship is already loaded this method does not trigger a new load. Example ```javascript // models/blog.js export default DS.Model.extend({ user: DS.belongsTo({ async: true }) }); var blog = store.push({ data: { type: 'blog', id: 1, relationships: { user: { data: { type: 'user', id: 1 } } } } }); var userRef = blog.belongsTo('user'); userRef.value(); // null userRef.load().then(function(user) { userRef.value() === user }); @method load @return {Promise} a promise that resolves with the record in this belongs-to relationship. */ BelongsToReference.prototype.load = function () { var _this2 = this; if (this.remoteType() === "id") { return this.belongsToRelationship.getRecord(); } if (this.remoteType() === "link") { return this.belongsToRelationship.findLink().then(function (internalModel) { return _this2.value(); }); } }; /** Triggers a reload of the value in this relationship. If the remoteType is `"link"` Ember Data will use the relationship link to reload the relationship. Otherwise it will reload the record by its id. Example ```javascript // models/blog.js export default DS.Model.extend({ user: DS.belongsTo({ async: true }) }); var blog = store.push({ data: { type: 'blog', id: 1, relationships: { user: { data: { type: 'user', id: 1 } } } } }); var userRef = blog.belongsTo('user'); userRef.reload().then(function(user) { userRef.value() === user }); @method reload @return {Promise} a promise that resolves with the record in this belongs-to relationship after the reload has completed. */ BelongsToReference.prototype.reload = function () { var _this3 = this; return this.belongsToRelationship.reload().then(function (internalModel) { return _this3.value(); }); }; exports.default = BelongsToReference; }); define('ember-data/-private/system/references/has-many', ['exports', 'ember', 'ember-data/-private/system/references/reference', 'ember-data/-private/debug', 'ember-data/-private/features'], function (exports, _ember, _emberDataPrivateSystemReferencesReference, _emberDataPrivateDebug, _emberDataPrivateFeatures) { var resolve = _ember.default.RSVP.resolve; var get = _ember.default.get; var HasManyReference = function (store, parentInternalModel, hasManyRelationship) { this._super$constructor(store, parentInternalModel); this.hasManyRelationship = hasManyRelationship; this.type = hasManyRelationship.relationshipMeta.type; this.parent = parentInternalModel.recordReference; // TODO inverse }; HasManyReference.prototype = Object.create(_emberDataPrivateSystemReferencesReference.default.prototype); HasManyReference.prototype.constructor = HasManyReference; HasManyReference.prototype._super$constructor = _emberDataPrivateSystemReferencesReference.default; HasManyReference.prototype.remoteType = function () { if (this.hasManyRelationship.link) { return "link"; } return "ids"; }; HasManyReference.prototype.link = function () { return this.hasManyRelationship.link; }; HasManyReference.prototype.ids = function () { var members = this.hasManyRelationship.members.toArray(); return members.map(function (internalModel) { return internalModel.id; }); }; HasManyReference.prototype.meta = function () { return this.hasManyRelationship.meta; }; HasManyReference.prototype.push = function (objectOrPromise) { var _this = this; return resolve(objectOrPromise).then(function (payload) { var array = payload; if (false) {} var useLegacyArrayPush = true; if (typeof payload === "object" && payload.data) { array = payload.data; useLegacyArrayPush = array.length && array[0].data; if (false) {} } if (!false) { useLegacyArrayPush = true; } var internalModels = undefined; if (useLegacyArrayPush) { internalModels = array.map(function (obj) { var record = _this.store.push(obj); return record._internalModel; }); } else { var records = _this.store.push(payload); internalModels = _ember.default.A(records).mapBy('_internalModel'); } _this.hasManyRelationship.computeChanges(internalModels); return _this.hasManyRelationship.getManyArray(); }); }; HasManyReference.prototype._isLoaded = function () { var hasData = get(this.hasManyRelationship, 'hasData'); if (!hasData) { return false; } var members = this.hasManyRelationship.members.toArray(); return members.every(function (internalModel) { return internalModel.isLoaded() === true; }); }; HasManyReference.prototype.value = function () { if (this._isLoaded()) { return this.hasManyRelationship.getManyArray(); } return null; }; HasManyReference.prototype.load = function () { if (!this._isLoaded()) { return this.hasManyRelationship.getRecords(); } return resolve(this.hasManyRelationship.getManyArray()); }; HasManyReference.prototype.reload = function () { return this.hasManyRelationship.reload(); }; exports.default = HasManyReference; }); define('ember-data/-private/system/references/record', ['exports', 'ember', 'ember-data/-private/system/references/reference'], function (exports, _ember, _emberDataPrivateSystemReferencesReference) { /** An RecordReference is a low level API that allows users and addon author to perform meta-operations on a record. @class RecordReference @namespace DS */ var RecordReference = function (store, internalModel) { this._super$constructor(store, internalModel); this.type = internalModel.modelName; this._id = internalModel.id; }; RecordReference.prototype = Object.create(_emberDataPrivateSystemReferencesReference.default.prototype); RecordReference.prototype.constructor = RecordReference; RecordReference.prototype._super$constructor = _emberDataPrivateSystemReferencesReference.default; /** The `id` of the record that this reference refers to. Together, the `type` and `id` properties form a composite key for the identity map. Example ```javascript var userRef = store.getReference('user', 1); userRef.id(); // '1' ``` @method id @return {String} The id of the record. */ RecordReference.prototype.id = function () { return this._id; }; /** How the reference will be looked up when it is loaded: Currently this always return `identity` to signifying that a record will be loaded by the `type` and `id`. Example ```javascript var userRef = store.getReference('user', 1); userRef.remoteType(); // 'identity' ``` @method remoteType @return {String} 'identity' */ RecordReference.prototype.remoteType = function () { return 'identity'; }; /** This API allows you to provide a reference with new data. The simplest usage of this API is similar to `store.push`: you provide a normalized hash of data and the object represented by the reference will update. If you pass a promise to `push`, Ember Data will not ask the adapter for the data if another attempt to fetch it is made in the interim. When the promise resolves, the underlying object is updated with the new data, and the promise returned by *this function* is resolved with that object. For example, `recordReference.push(promise)` will be resolved with a record. Example ```javascript var userRef = store.getReference('user', 1); // provide data for reference userRef.push({ data: { id: 1, username: "@user" }}).then(function(user) { userRef.value() === user; }); ``` @method @param {Promise|Object} @returns Promise<record> a promise for the value (record or relationship) */ RecordReference.prototype.push = function (objectOrPromise) { var _this = this; return _ember.default.RSVP.resolve(objectOrPromise).then(function (data) { return _this.store.push(data); }); }; /** If the entity referred to by the reference is already loaded, it is present as `reference.value`. Otherwise the value returned by this function is `null`. Example ```javascript var userRef = store.getReference('user', 1); userRef.value(); // user ``` @method value @return {DS.Model} the record for this RecordReference */ RecordReference.prototype.value = function () { return this.internalModel.record; }; /** Triggers a fetch for the backing entity based on its `remoteType` (see `remoteType` definitions per reference type). Example ```javascript var userRef = store.getReference('user', 1); // load user (via store.find) userRef.load().then(...) ``` @method load @return {Promise<record>} the record for this RecordReference */ RecordReference.prototype.load = function () { return this.store.findRecord(this.type, this._id); }; /** Reloads the record if it is already loaded. If the record is not loaded it will load the record via `store.findRecord` Example ```javascript var userRef = store.getReference('user', 1); // or trigger a reload userRef.reload().then(...) ``` @method reload @return {Promise<record>} the record for this RecordReference */ RecordReference.prototype.reload = function () { var record = this.value(); if (record) { return record.reload(); } return this.load(); }; exports.default = RecordReference; }); define("ember-data/-private/system/references/reference", ["exports"], function (exports) { var Reference = function (store, internalModel) { this.store = store; this.internalModel = internalModel; }; Reference.prototype = { constructor: Reference }; exports.default = Reference; }); define('ember-data/-private/system/relationship-meta', ['exports', 'ember-inflector', 'ember-data/-private/system/normalize-model-name'], function (exports, _emberInflector, _emberDataPrivateSystemNormalizeModelName) { exports.typeForRelationshipMeta = typeForRelationshipMeta; exports.relationshipFromMeta = relationshipFromMeta; function typeForRelationshipMeta(meta) { var modelName; modelName = meta.type || meta.key; if (meta.kind === 'hasMany') { modelName = (0, _emberInflector.singularize)((0, _emberDataPrivateSystemNormalizeModelName.default)(modelName)); } return modelName; } function relationshipFromMeta(meta) { return { key: meta.key, kind: meta.kind, type: typeForRelationshipMeta(meta), options: meta.options, name: meta.name, parentType: meta.parentType, isRelationship: true }; } }); define("ember-data/-private/system/relationships/belongs-to", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/normalize-model-name"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemNormalizeModelName) { exports.default = belongsTo; /** `DS.belongsTo` is used to define One-To-One and One-To-Many relationships on a [DS.Model](/api/data/classes/DS.Model.html). `DS.belongsTo` takes an optional hash as a second parameter, currently supported options are: - `async`: A boolean value used to explicitly declare this to be an async relationship. - `inverse`: A string used to identify the inverse property on a related model in a One-To-Many relationship. See [Explicit Inverses](#toc_explicit-inverses) #### One-To-One To declare a one-to-one relationship between two models, use `DS.belongsTo`: ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ profile: DS.belongsTo('profile') }); ``` ```app/models/profile.js import DS from 'ember-data'; export default DS.Model.extend({ user: DS.belongsTo('user') }); ``` #### One-To-Many To declare a one-to-many relationship between two models, use `DS.belongsTo` in combination with `DS.hasMany`, like this: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ comments: DS.hasMany('comment') }); ``` ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ post: DS.belongsTo('post') }); ``` You can avoid passing a string as the first parameter. In that case Ember Data will infer the type from the key name. ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ post: DS.belongsTo() }); ``` will lookup for a Post type. @namespace @method belongsTo @for DS @param {String} modelName (optional) type of the relationship @param {Object} options (optional) a hash of options @return {Ember.computed} relationship */ function belongsTo(modelName, options) { var opts, userEnteredModelName; if (typeof modelName === 'object') { opts = modelName; userEnteredModelName = undefined; } else { opts = options; userEnteredModelName = modelName; } if (typeof userEnteredModelName === 'string') { userEnteredModelName = (0, _emberDataPrivateSystemNormalizeModelName.default)(userEnteredModelName); } opts = opts || {}; var meta = { type: userEnteredModelName, isRelationship: true, options: opts, kind: 'belongsTo', name: 'Belongs To', key: null }; return _ember.default.computed({ get: function (key) { if (opts.hasOwnProperty('serialize')) {} if (opts.hasOwnProperty('embedded')) {} return this._internalModel._relationships.get(key).getRecord(); }, set: function (key, value) { if (value === undefined) { value = null; } if (value && value.then) { this._internalModel._relationships.get(key).setRecordPromise(value); } else if (value) { this._internalModel._relationships.get(key).setRecord(value._internalModel); } else { this._internalModel._relationships.get(key).setRecord(value); } return this._internalModel._relationships.get(key).getRecord(); } }).meta(meta); } /* These observers observe all `belongsTo` relationships on the record. See `relationships/ext` to see how these observers get their dependencies. */ var BelongsToMixin = _ember.default.Mixin.create({ notifyBelongsToChanged: function (key) { this.notifyPropertyChange(key); } }); exports.BelongsToMixin = BelongsToMixin; }); define("ember-data/-private/system/relationships/ext", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/relationship-meta", "ember-data/-private/system/empty-object"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemRelationshipMeta, _emberDataPrivateSystemEmptyObject) { var get = _ember.default.get; var Map = _ember.default.Map; var MapWithDefault = _ember.default.MapWithDefault; var relationshipsDescriptor = _ember.default.computed(function () { if (_ember.default.testing === true && relationshipsDescriptor._cacheable === true) { relationshipsDescriptor._cacheable = false; } var map = new MapWithDefault({ defaultValue: function () { return []; } }); // Loop through each computed property on the class this.eachComputedProperty(function (name, meta) { // If the computed property is a relationship, add // it to the map. if (meta.isRelationship) { meta.key = name; var relationshipsForType = map.get((0, _emberDataPrivateSystemRelationshipMeta.typeForRelationshipMeta)(meta)); relationshipsForType.push({ name: name, kind: meta.kind }); } }); return map; }).readOnly(); var relatedTypesDescriptor = _ember.default.computed(function () { if (_ember.default.testing === true && relatedTypesDescriptor._cacheable === true) { relatedTypesDescriptor._cacheable = false; } var modelName; var types = _ember.default.A(); // Loop through each computed property on the class, // and create an array of the unique types involved // in relationships this.eachComputedProperty(function (name, meta) { if (meta.isRelationship) { meta.key = name; modelName = (0, _emberDataPrivateSystemRelationshipMeta.typeForRelationshipMeta)(meta); if (!types.includes(modelName)) { types.push(modelName); } } }); return types; }).readOnly(); var relationshipsByNameDescriptor = _ember.default.computed(function () { if (_ember.default.testing === true && relationshipsByNameDescriptor._cacheable === true) { relationshipsByNameDescriptor._cacheable = false; } var map = Map.create(); this.eachComputedProperty(function (name, meta) { if (meta.isRelationship) { meta.key = name; var relationship = (0, _emberDataPrivateSystemRelationshipMeta.relationshipFromMeta)(meta); relationship.type = (0, _emberDataPrivateSystemRelationshipMeta.typeForRelationshipMeta)(meta); map.set(name, relationship); } }); return map; }).readOnly(); /** @module ember-data */ /* This file defines several extensions to the base `DS.Model` class that add support for one-to-many relationships. */ /** @class Model @namespace DS */ var DidDefinePropertyMixin = _ember.default.Mixin.create({ /** This Ember.js hook allows an object to be notified when a property is defined. In this case, we use it to be notified when an Ember Data user defines a belongs-to relationship. In that case, we need to set up observers for each one, allowing us to track relationship changes and automatically reflect changes in the inverse has-many array. This hook passes the class being set up, as well as the key and value being defined. So, for example, when the user does this: ```javascript DS.Model.extend({ parent: DS.belongsTo('user') }); ``` This hook would be called with "parent" as the key and the computed property returned by `DS.belongsTo` as the value. @method didDefineProperty @param {Object} proto @param {String} key @param {Ember.ComputedProperty} value */ didDefineProperty: function (proto, key, value) { // Check if the value being set is a computed property. if (value instanceof _ember.default.ComputedProperty) { // If it is, get the metadata for the relationship. This is // populated by the `DS.belongsTo` helper when it is creating // the computed property. var meta = value.meta(); meta.parentType = proto.constructor; } } }); exports.DidDefinePropertyMixin = DidDefinePropertyMixin; /* These DS.Model extensions add class methods that provide relationship introspection abilities about relationships. A note about the computed properties contained here: **These properties are effectively sealed once called for the first time.** To avoid repeatedly doing expensive iteration over a model's fields, these values are computed once and then cached for the remainder of the runtime of your application. If your application needs to modify a class after its initial definition (for example, using `reopen()` to add additional attributes), make sure you do it before using your model with the store, which uses these properties extensively. */ var RelationshipsClassMethodsMixin = _ember.default.Mixin.create({ /** For a given relationship name, returns the model type of the relationship. For example, if you define a model like this: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ comments: DS.hasMany('comment') }); ``` Calling `store.modelFor('post').typeForRelationship('comments', store)` will return `Comment`. @method typeForRelationship @static @param {String} name the name of the relationship @param {store} store an instance of DS.Store @return {DS.Model} the type of the relationship, or undefined */ typeForRelationship: function (name, store) { var relationship = get(this, 'relationshipsByName').get(name); return relationship && store.modelFor(relationship.type); }, inverseMap: _ember.default.computed(function () { return new _emberDataPrivateSystemEmptyObject.default(); }), /** Find the relationship which is the inverse of the one asked for. For example, if you define models like this: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ comments: DS.hasMany('message') }); ``` ```app/models/message.js import DS from 'ember-data'; export default DS.Model.extend({ owner: DS.belongsTo('post') }); ``` store.modelFor('post').inverseFor('comments', store) -> { type: App.Message, name: 'owner', kind: 'belongsTo' } store.modelFor('message').inverseFor('owner', store) -> { type: App.Post, name: 'comments', kind: 'hasMany' } @method inverseFor @static @param {String} name the name of the relationship @param {DS.Store} store @return {Object} the inverse relationship, or null */ inverseFor: function (name, store) { var inverseMap = get(this, 'inverseMap'); if (inverseMap[name]) { return inverseMap[name]; } else { var inverse = this._findInverseFor(name, store); inverseMap[name] = inverse; return inverse; } }, //Calculate the inverse, ignoring the cache _findInverseFor: function (name, store) { var inverseType = this.typeForRelationship(name, store); if (!inverseType) { return null; } var propertyMeta = this.metaForProperty(name); //If inverse is manually specified to be null, like `comments: DS.hasMany('message', { inverse: null })` var options = propertyMeta.options; if (options.inverse === null) { return null; } var inverseName, inverseKind, inverse; //If inverse is specified manually, return the inverse if (options.inverse) { inverseName = options.inverse; inverse = _ember.default.get(inverseType, 'relationshipsByName').get(inverseName); inverseKind = inverse.kind; } else { //No inverse was specified manually, we need to use a heuristic to guess one if (propertyMeta.type === propertyMeta.parentType.modelName) {} var possibleRelationships = findPossibleInverses(this, inverseType); if (possibleRelationships.length === 0) { return null; } var filteredRelationships = possibleRelationships.filter(function (possibleRelationship) { var optionsForRelationship = inverseType.metaForProperty(possibleRelationship.name).options; return name === optionsForRelationship.inverse; }); if (filteredRelationships.length === 1) { possibleRelationships = filteredRelationships; } inverseName = possibleRelationships[0].name; inverseKind = possibleRelationships[0].kind; } function findPossibleInverses(type, inverseType, relationshipsSoFar) { var possibleRelationships = relationshipsSoFar || []; var relationshipMap = get(inverseType, 'relationships'); if (!relationshipMap) { return possibleRelationships; } var relationships = relationshipMap.get(type.modelName); relationships = relationships.filter(function (relationship) { var optionsForRelationship = inverseType.metaForProperty(relationship.name).options; if (!optionsForRelationship.inverse) { return true; } return name === optionsForRelationship.inverse; }); if (relationships) { possibleRelationships.push.apply(possibleRelationships, relationships); } //Recurse to support polymorphism if (type.superclass) { findPossibleInverses(type.superclass, inverseType, possibleRelationships); } return possibleRelationships; } return { type: inverseType, name: inverseName, kind: inverseKind }; }, /** The model's relationships as a map, keyed on the type of the relationship. The value of each entry is an array containing a descriptor for each relationship with that type, describing the name of the relationship as well as the type. For example, given the following model definition: ```app/models/blog.js import DS from 'ember-data'; export default DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This computed property would return a map describing these relationships, like this: ```javascript import Ember from 'ember'; import Blog from 'app/models/blog'; import User from 'app/models/user'; import Post from 'app/models/post'; var relationships = Ember.get(Blog, 'relationships'); relationships.get(User); //=> [ { name: 'users', kind: 'hasMany' }, // { name: 'owner', kind: 'belongsTo' } ] relationships.get(Post); //=> [ { name: 'posts', kind: 'hasMany' } ] ``` @property relationships @static @type Ember.Map @readOnly */ relationships: relationshipsDescriptor, /** A hash containing lists of the model's relationships, grouped by the relationship kind. For example, given a model with this definition: ```app/models/blog.js import DS from 'ember-data'; export default DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript import Ember from 'ember'; import Blog from 'app/models/blog'; var relationshipNames = Ember.get(Blog, 'relationshipNames'); relationshipNames.hasMany; //=> ['users', 'posts'] relationshipNames.belongsTo; //=> ['owner'] ``` @property relationshipNames @static @type Object @readOnly */ relationshipNames: _ember.default.computed(function () { var names = { hasMany: [], belongsTo: [] }; this.eachComputedProperty(function (name, meta) { if (meta.isRelationship) { names[meta.kind].push(name); } }); return names; }), /** An array of types directly related to a model. Each type will be included once, regardless of the number of relationships it has with the model. For example, given a model with this definition: ```app/models/blog.js import DS from 'ember-data'; export default DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript import Ember from 'ember'; import Blog from 'app/models/blog'; var relatedTypes = Ember.get(Blog, 'relatedTypes'); //=> [ User, Post ] ``` @property relatedTypes @static @type Ember.Array @readOnly */ relatedTypes: relatedTypesDescriptor, /** A map whose keys are the relationships of a model and whose values are relationship descriptors. For example, given a model with this definition: ```app/models/blog.js import DS from 'ember-data'; export default DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript import Ember from 'ember'; import Blog from 'app/models/blog'; var relationshipsByName = Ember.get(Blog, 'relationshipsByName'); relationshipsByName.get('users'); //=> { key: 'users', kind: 'hasMany', type: 'user', options: Object, isRelationship: true } relationshipsByName.get('owner'); //=> { key: 'owner', kind: 'belongsTo', type: 'user', options: Object, isRelationship: true } ``` @property relationshipsByName @static @type Ember.Map @readOnly */ relationshipsByName: relationshipsByNameDescriptor, /** A map whose keys are the fields of the model and whose values are strings describing the kind of the field. A model's fields are the union of all of its attributes and relationships. For example: ```app/models/blog.js import DS from 'ember-data'; export default DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post'), title: DS.attr('string') }); ``` ```js import Ember from 'ember'; import Blog from 'app/models/blog'; var fields = Ember.get(Blog, 'fields'); fields.forEach(function(kind, field) { console.log(field, kind); }); // prints: // users, hasMany // owner, belongsTo // posts, hasMany // title, attribute ``` @property fields @static @type Ember.Map @readOnly */ fields: _ember.default.computed(function () { var map = Map.create(); this.eachComputedProperty(function (name, meta) { if (meta.isRelationship) { map.set(name, meta.kind); } else if (meta.isAttribute) { map.set(name, 'attribute'); } }); return map; }).readOnly(), /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. @method eachRelationship @static @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function (callback, binding) { get(this, 'relationshipsByName').forEach(function (relationship, name) { callback.call(binding, name, relationship); }); }, /** Given a callback, iterates over each of the types related to a model, invoking the callback with the related type's class. Each type will be returned just once, regardless of how many different relationships it has with a model. @method eachRelatedType @static @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelatedType: function (callback, binding) { var relationshipTypes = get(this, 'relatedTypes'); for (var i = 0; i < relationshipTypes.length; i++) { var type = relationshipTypes[i]; callback.call(binding, type); } }, determineRelationshipType: function (knownSide, store) { var knownKey = knownSide.key; var knownKind = knownSide.kind; var inverse = this.inverseFor(knownKey, store); // let key; var otherKind = undefined; if (!inverse) { return knownKind === 'belongsTo' ? 'oneToNone' : 'manyToNone'; } // key = inverse.name; otherKind = inverse.kind; if (otherKind === 'belongsTo') { return knownKind === 'belongsTo' ? 'oneToOne' : 'manyToOne'; } else { return knownKind === 'belongsTo' ? 'oneToMany' : 'manyToMany'; } } }); exports.RelationshipsClassMethodsMixin = RelationshipsClassMethodsMixin; var RelationshipsInstanceMethodsMixin = _ember.default.Mixin.create({ /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, descriptor); ``` - `name` the name of the current property in the iteration - `descriptor` the meta object that describes this relationship The relationship descriptor argument is an object with the following properties. - **key** <span class="type">String</span> the name of this relationship on the Model - **kind** <span class="type">String</span> "hasMany" or "belongsTo" - **options** <span class="type">Object</span> the original options hash passed when the relationship was declared - **parentType** <span class="type">DS.Model</span> the type of the Model that owns this relationship - **type** <span class="type">String</span> the type name of the related Model Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serialize: function(record, options) { var json = {}; record.eachRelationship(function(name, descriptor) { if (descriptor.kind === 'hasMany') { var serializedHasManyName = name.toUpperCase() + '_IDS'; json[serializedHasManyName] = record.get(name).mapBy('id'); } }); return json; } }); ``` @method eachRelationship @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function (callback, binding) { this.constructor.eachRelationship(callback, binding); }, relationshipFor: function (name) { return get(this.constructor, 'relationshipsByName').get(name); }, inverseFor: function (key) { return this.constructor.inverseFor(key, this.store); } }); exports.RelationshipsInstanceMethodsMixin = RelationshipsInstanceMethodsMixin; }); define("ember-data/-private/system/relationships/has-many", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/normalize-model-name", "ember-data/-private/system/is-array-like"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemNormalizeModelName, _emberDataPrivateSystemIsArrayLike) { exports.default = hasMany; /** `DS.hasMany` is used to define One-To-Many and Many-To-Many relationships on a [DS.Model](/api/data/classes/DS.Model.html). `DS.hasMany` takes an optional hash as a second parameter, currently supported options are: - `async`: A boolean value used to explicitly declare this to be an async relationship. - `inverse`: A string used to identify the inverse property on a related model. #### One-To-Many To declare a one-to-many relationship between two models, use `DS.belongsTo` in combination with `DS.hasMany`, like this: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ comments: DS.hasMany('comment') }); ``` ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ post: DS.belongsTo('post') }); ``` #### Many-To-Many To declare a many-to-many relationship between two models, use `DS.hasMany`: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ tags: DS.hasMany('tag') }); ``` ```app/models/tag.js import DS from 'ember-data'; export default DS.Model.extend({ posts: DS.hasMany('post') }); ``` You can avoid passing a string as the first parameter. In that case Ember Data will infer the type from the singularized key name. ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ tags: DS.hasMany() }); ``` will lookup for a Tag type. #### Explicit Inverses Ember Data will do its best to discover which relationships map to one another. In the one-to-many code above, for example, Ember Data can figure out that changing the `comments` relationship should update the `post` relationship on the inverse because post is the only relationship to that model. However, sometimes you may have multiple `belongsTo`/`hasManys` for the same type. You can specify which property on the related model is the inverse using `DS.hasMany`'s `inverse` option: ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ onePost: DS.belongsTo('post'), twoPost: DS.belongsTo('post'), redPost: DS.belongsTo('post'), bluePost: DS.belongsTo('post') }); ``` ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ comments: DS.hasMany('comment', { inverse: 'redPost' }) }); ``` You can also specify an inverse on a `belongsTo`, which works how you'd expect. @namespace @method hasMany @for DS @param {String} type (optional) type of the relationship @param {Object} options (optional) a hash of options @return {Ember.computed} relationship */ function hasMany(type, options) { if (typeof type === 'object') { options = type; type = undefined; } options = options || {}; if (typeof type === 'string') { type = (0, _emberDataPrivateSystemNormalizeModelName.default)(type); } // Metadata about relationships is stored on the meta of // the relationship. This is used for introspection and // serialization. Note that `key` is populated lazily // the first time the CP is called. var meta = { type: type, isRelationship: true, options: options, kind: 'hasMany', name: 'Has Many', key: null }; return _ember.default.computed({ get: function (key) { var relationship = this._internalModel._relationships.get(key); return relationship.getRecords(); }, set: function (key, records) { var relationship = this._internalModel._relationships.get(key); relationship.clear(); relationship.addRecords(_ember.default.A(records).mapBy('_internalModel')); return relationship.getRecords(); } }).meta(meta); } var HasManyMixin = _ember.default.Mixin.create({ notifyHasManyAdded: function (key) { //We need to notifyPropertyChange in the adding case because we need to make sure //we fetch the newly added record in case it is unloaded //TODO(Igor): Consider whether we could do this only if the record state is unloaded //Goes away once hasMany is double promisified this.notifyPropertyChange(key); } }); exports.HasManyMixin = HasManyMixin; }); /** @module ember-data */ define("ember-data/-private/system/relationships/state/belongs-to", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/relationships/state/relationship"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemRelationshipsStateRelationship) { exports.default = BelongsToRelationship; function BelongsToRelationship(store, record, inverseKey, relationshipMeta) { this._super$constructor(store, record, inverseKey, relationshipMeta); this.record = record; this.key = relationshipMeta.key; this.inverseRecord = null; this.canonicalState = null; } BelongsToRelationship.prototype = Object.create(_emberDataPrivateSystemRelationshipsStateRelationship.default.prototype); BelongsToRelationship.prototype.constructor = BelongsToRelationship; BelongsToRelationship.prototype._super$constructor = _emberDataPrivateSystemRelationshipsStateRelationship.default; BelongsToRelationship.prototype.setRecord = function (newRecord) { if (newRecord) { this.addRecord(newRecord); } else if (this.inverseRecord) { this.removeRecord(this.inverseRecord); } this.setHasData(true); this.setHasLoaded(true); }; BelongsToRelationship.prototype.setCanonicalRecord = function (newRecord) { if (newRecord) { this.addCanonicalRecord(newRecord); } else if (this.canonicalState) { this.removeCanonicalRecord(this.canonicalState); } this.flushCanonicalLater(); }; BelongsToRelationship.prototype._super$addCanonicalRecord = _emberDataPrivateSystemRelationshipsStateRelationship.default.prototype.addCanonicalRecord; BelongsToRelationship.prototype.addCanonicalRecord = function (newRecord) { if (this.canonicalMembers.has(newRecord)) { return; } if (this.canonicalState) { this.removeCanonicalRecord(this.canonicalState); } this.canonicalState = newRecord; this._super$addCanonicalRecord(newRecord); }; BelongsToRelationship.prototype._super$flushCanonical = _emberDataPrivateSystemRelationshipsStateRelationship.default.prototype.flushCanonical; BelongsToRelationship.prototype.flushCanonical = function () { //temporary fix to not remove newly created records if server returned null. //TODO remove once we have proper diffing if (this.inverseRecord && this.inverseRecord.isNew() && !this.canonicalState) { return; } if (this.inverseRecord !== this.canonicalState) { this.inverseRecord = this.canonicalState; this.record.notifyBelongsToChanged(this.key); } this._super$flushCanonical(); }; BelongsToRelationship.prototype._super$addRecord = _emberDataPrivateSystemRelationshipsStateRelationship.default.prototype.addRecord; BelongsToRelationship.prototype.addRecord = function (newRecord) { if (this.members.has(newRecord)) { return; } if (this.inverseRecord) { this.removeRecord(this.inverseRecord); } this.inverseRecord = newRecord; this._super$addRecord(newRecord); this.record.notifyBelongsToChanged(this.key); }; BelongsToRelationship.prototype.setRecordPromise = function (newPromise) { var content = newPromise.get && newPromise.get('content'); this.setRecord(content ? content._internalModel : content); }; BelongsToRelationship.prototype._super$removeRecordFromOwn = _emberDataPrivateSystemRelationshipsStateRelationship.default.prototype.removeRecordFromOwn; BelongsToRelationship.prototype.removeRecordFromOwn = function (record) { if (!this.members.has(record)) { return; } this.inverseRecord = null; this._super$removeRecordFromOwn(record); this.record.notifyBelongsToChanged(this.key); }; BelongsToRelationship.prototype._super$removeCanonicalRecordFromOwn = _emberDataPrivateSystemRelationshipsStateRelationship.default.prototype.removeCanonicalRecordFromOwn; BelongsToRelationship.prototype.removeCanonicalRecordFromOwn = function (record) { if (!this.canonicalMembers.has(record)) { return; } this.canonicalState = null; this._super$removeCanonicalRecordFromOwn(record); }; BelongsToRelationship.prototype.findRecord = function () { if (this.inverseRecord) { return this.store._findByInternalModel(this.inverseRecord); } else { return _ember.default.RSVP.Promise.resolve(null); } }; BelongsToRelationship.prototype.fetchLink = function () { var _this = this; return this.store.findBelongsTo(this.record, this.link, this.relationshipMeta).then(function (record) { if (record) { _this.addRecord(record); } return record; }); }; BelongsToRelationship.prototype.getRecord = function () { var _this2 = this; //TODO(Igor) flushCanonical here once our syncing is not stupid if (this.isAsync) { var promise; if (this.link) { if (this.hasLoaded) { promise = this.findRecord(); } else { promise = this.findLink().then(function () { return _this2.findRecord(); }); } } else { promise = this.findRecord(); } return _emberDataPrivateSystemPromiseProxies.PromiseObject.create({ promise: promise, content: this.inverseRecord ? this.inverseRecord.getRecord() : null }); } else { if (this.inverseRecord === null) { return null; } var toReturn = this.inverseRecord.getRecord(); return toReturn; } }; BelongsToRelationship.prototype.reload = function () { // TODO handle case when reload() is triggered multiple times if (this.link) { return this.fetchLink(); } // reload record, if it is already loaded if (this.inverseRecord && this.inverseRecord.hasRecord) { return this.inverseRecord.record.reload(); } return this.findRecord(); }; BelongsToRelationship.prototype.updateData = function (data) { var internalModel = this.store._pushResourceIdentifier(this, data); this.setCanonicalRecord(internalModel); }; }); define("ember-data/-private/system/relationships/state/create", ["exports", "ember", "ember-data/-private/system/relationships/state/has-many", "ember-data/-private/system/relationships/state/belongs-to", "ember-data/-private/system/empty-object"], function (exports, _ember, _emberDataPrivateSystemRelationshipsStateHasMany, _emberDataPrivateSystemRelationshipsStateBelongsTo, _emberDataPrivateSystemEmptyObject) { exports.default = Relationships; var get = _ember.default.get; function shouldFindInverse(relationshipMeta) { var options = relationshipMeta.options; return !(options && options.inverse === null); } function createRelationshipFor(record, relationshipMeta, store) { var inverseKey = undefined; var inverse = null; if (shouldFindInverse(relationshipMeta)) { inverse = record.type.inverseFor(relationshipMeta.key, store); } if (inverse) { inverseKey = inverse.name; } if (relationshipMeta.kind === 'hasMany') { return new _emberDataPrivateSystemRelationshipsStateHasMany.default(store, record, inverseKey, relationshipMeta); } else { return new _emberDataPrivateSystemRelationshipsStateBelongsTo.default(store, record, inverseKey, relationshipMeta); } } function Relationships(record) { this.record = record; this.initializedRelationships = new _emberDataPrivateSystemEmptyObject.default(); } Relationships.prototype.has = function (key) { return !!this.initializedRelationships[key]; }; Relationships.prototype.get = function (key) { var relationships = this.initializedRelationships; var relationshipsByName = get(this.record.type, 'relationshipsByName'); if (!relationships[key] && relationshipsByName.get(key)) { relationships[key] = createRelationshipFor(this.record, relationshipsByName.get(key), this.record.store); } return relationships[key]; }; }); define("ember-data/-private/system/relationships/state/has-many", ["exports", "ember-data/-private/debug", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/relationships/state/relationship", "ember-data/-private/system/ordered-set", "ember-data/-private/system/many-array"], function (exports, _emberDataPrivateDebug, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemRelationshipsStateRelationship, _emberDataPrivateSystemOrderedSet, _emberDataPrivateSystemManyArray) { exports.default = ManyRelationship; function ManyRelationship(store, record, inverseKey, relationshipMeta) { this._super$constructor(store, record, inverseKey, relationshipMeta); this.belongsToType = relationshipMeta.type; this.canonicalState = []; this.isPolymorphic = relationshipMeta.options.polymorphic; } ManyRelationship.prototype = Object.create(_emberDataPrivateSystemRelationshipsStateRelationship.default.prototype); ManyRelationship.prototype.getManyArray = function () { if (!this._manyArray) { this._manyArray = _emberDataPrivateSystemManyArray.default.create({ canonicalState: this.canonicalState, store: this.store, relationship: this, type: this.store.modelFor(this.belongsToType), record: this.record, meta: this.meta, isPolymorphic: this.isPolymorphic }); } return this._manyArray; }; ManyRelationship.prototype.constructor = ManyRelationship; ManyRelationship.prototype._super$constructor = _emberDataPrivateSystemRelationshipsStateRelationship.default; ManyRelationship.prototype.destroy = function () { if (this._manyArray) { this._manyArray.destroy(); } }; ManyRelationship.prototype._super$updateMeta = _emberDataPrivateSystemRelationshipsStateRelationship.default.prototype.updateMeta; ManyRelationship.prototype.updateMeta = function (meta) { this._super$updateMeta(meta); if (this._manyArray) { this._manyArray.set('meta', meta); } }; ManyRelationship.prototype._super$addCanonicalRecord = _emberDataPrivateSystemRelationshipsStateRelationship.default.prototype.addCanonicalRecord; ManyRelationship.prototype.addCanonicalRecord = function (record, idx) { if (this.canonicalMembers.has(record)) { return; } if (idx !== undefined) { this.canonicalState.splice(idx, 0, record); } else { this.canonicalState.push(record); } this._super$addCanonicalRecord(record, idx); }; ManyRelationship.prototype._super$addRecord = _emberDataPrivateSystemRelationshipsStateRelationship.default.prototype.addRecord; ManyRelationship.prototype.addRecord = function (record, idx) { if (this.members.has(record)) { return; } this._super$addRecord(record, idx); // make lazy later this.getManyArray().internalAddRecords([record], idx); }; ManyRelationship.prototype._super$removeCanonicalRecordFromOwn = _emberDataPrivateSystemRelationshipsStateRelationship.default.prototype.removeCanonicalRecordFromOwn; ManyRelationship.prototype.removeCanonicalRecordFromOwn = function (record, idx) { var i = idx; if (!this.canonicalMembers.has(record)) { return; } if (i === undefined) { i = this.canonicalState.indexOf(record); } if (i > -1) { this.canonicalState.splice(i, 1); } this._super$removeCanonicalRecordFromOwn(record, idx); }; ManyRelationship.prototype._super$flushCanonical = _emberDataPrivateSystemRelationshipsStateRelationship.default.prototype.flushCanonical; ManyRelationship.prototype.flushCanonical = function () { if (this._manyArray) { this._manyArray.flushCanonical(); } this._super$flushCanonical(); }; ManyRelationship.prototype._super$removeRecordFromOwn = _emberDataPrivateSystemRelationshipsStateRelationship.default.prototype.removeRecordFromOwn; ManyRelationship.prototype.removeRecordFromOwn = function (record, idx) { if (!this.members.has(record)) { return; } this._super$removeRecordFromOwn(record, idx); var manyArray = this.getManyArray(); if (idx !== undefined) { //TODO(Igor) not used currently, fix manyArray.currentState.removeAt(idx); } else { manyArray.internalRemoveRecords([record]); } }; ManyRelationship.prototype.notifyRecordRelationshipAdded = function (record, idx) { this.record.notifyHasManyAdded(this.key, record, idx); }; ManyRelationship.prototype.reload = function () { var manyArray = this.getManyArray(); var manyArrayLoadedState = manyArray.get('isLoaded'); if (this._loadingPromise) { if (this._loadingPromise.get('isPending')) { return this._loadingPromise; } if (this._loadingPromise.get('isRejected')) { manyArray.set('isLoaded', manyArrayLoadedState); } } if (this.link) { this._loadingPromise = (0, _emberDataPrivateSystemPromiseProxies.promiseManyArray)(this.fetchLink(), 'Reload with link'); return this._loadingPromise; } else { this._loadingPromise = (0, _emberDataPrivateSystemPromiseProxies.promiseManyArray)(this.store._scheduleFetchMany(manyArray.currentState).then(function () { return manyArray; }), 'Reload with ids'); return this._loadingPromise; } }; ManyRelationship.prototype.computeChanges = function (records) { var members = this.canonicalMembers; var recordsToRemove = []; var length; var record; var i; records = setForArray(records); members.forEach(function (member) { if (records.has(member)) { return; } recordsToRemove.push(member); }); this.removeCanonicalRecords(recordsToRemove); // Using records.toArray() since currently using // removeRecord can modify length, messing stuff up // forEach since it directly looks at "length" each // iteration records = records.toArray(); length = records.length; for (i = 0; i < length; i++) { record = records[i]; this.removeCanonicalRecord(record); this.addCanonicalRecord(record, i); } }; ManyRelationship.prototype.fetchLink = function () { var _this = this; return this.store.findHasMany(this.record, this.link, this.relationshipMeta).then(function (records) { if (records.hasOwnProperty('meta')) { _this.updateMeta(records.meta); } _this.store._backburner.join(function () { _this.updateRecordsFromAdapter(records); _this.getManyArray().set('isLoaded', true); }); return _this.getManyArray(); }); }; ManyRelationship.prototype.findRecords = function () { var manyArray = this.getManyArray(); var array = manyArray.toArray(); var internalModels = new Array(array.length); for (var i = 0; i < array.length; i++) { internalModels[i] = array[i]._internalModel; } //TODO CLEANUP return this.store.findMany(internalModels).then(function () { if (!manyArray.get('isDestroyed')) { //Goes away after the manyArray refactor manyArray.set('isLoaded', true); } return manyArray; }); }; ManyRelationship.prototype.notifyHasManyChanged = function () { this.record.notifyHasManyAdded(this.key); }; ManyRelationship.prototype.getRecords = function () { var _this2 = this; //TODO(Igor) sync server here, once our syncing is not stupid var manyArray = this.getManyArray(); if (this.isAsync) { var promise; if (this.link) { if (this.hasLoaded) { promise = this.findRecords(); } else { promise = this.findLink().then(function () { return _this2.findRecords(); }); } } else { promise = this.findRecords(); } this._loadingPromise = _emberDataPrivateSystemPromiseProxies.PromiseManyArray.create({ content: manyArray, promise: promise }); return this._loadingPromise; } else { //TODO(Igor) WTF DO I DO HERE? if (!manyArray.get('isDestroyed')) { manyArray.set('isLoaded', true); } return manyArray; } }; ManyRelationship.prototype.updateData = function (data) { var internalModels = this.store._pushResourceIdentifiers(this, data); this.updateRecordsFromAdapter(internalModels); }; function setForArray(array) { var set = new _emberDataPrivateSystemOrderedSet.default(); if (array) { for (var i = 0, l = array.length; i < l; i++) { set.add(array[i]); } } return set; } }); define("ember-data/-private/system/relationships/state/relationship", ["exports", "ember-data/-private/debug", "ember-data/-private/system/ordered-set", "ember-data/-private/system/normalize-link"], function (exports, _emberDataPrivateDebug, _emberDataPrivateSystemOrderedSet, _emberDataPrivateSystemNormalizeLink) { exports.default = Relationship; function Relationship(store, record, inverseKey, relationshipMeta) { var async = relationshipMeta.options.async; this.members = new _emberDataPrivateSystemOrderedSet.default(); this.canonicalMembers = new _emberDataPrivateSystemOrderedSet.default(); this.store = store; this.key = relationshipMeta.key; this.inverseKey = inverseKey; this.record = record; this.isAsync = typeof async === 'undefined' ? true : async; this.relationshipMeta = relationshipMeta; //This probably breaks for polymorphic relationship in complex scenarios, due to //multiple possible modelNames this.inverseKeyForImplicit = this.record.constructor.modelName + this.key; this.linkPromise = null; this.meta = null; this.hasData = false; this.hasLoaded = false; } Relationship.prototype = { constructor: Relationship, destroy: function () {}, updateMeta: function (meta) { this.meta = meta; }, clear: function () { var members = this.members.list; var member; while (members.length > 0) { member = members[0]; this.removeRecord(member); } }, removeRecords: function (records) { var _this = this; records.forEach(function (record) { return _this.removeRecord(record); }); }, addRecords: function (records, idx) { var _this2 = this; records.forEach(function (record) { _this2.addRecord(record, idx); if (idx !== undefined) { idx++; } }); }, addCanonicalRecords: function (records, idx) { for (var i = 0; i < records.length; i++) { if (idx !== undefined) { this.addCanonicalRecord(records[i], i + idx); } else { this.addCanonicalRecord(records[i]); } } }, addCanonicalRecord: function (record, idx) { if (!this.canonicalMembers.has(record)) { this.canonicalMembers.add(record); if (this.inverseKey) { record._relationships.get(this.inverseKey).addCanonicalRecord(this.record); } else { if (!record._implicitRelationships[this.inverseKeyForImplicit]) { record._implicitRelationships[this.inverseKeyForImplicit] = new Relationship(this.store, record, this.key, { options: {} }); } record._implicitRelationships[this.inverseKeyForImplicit].addCanonicalRecord(this.record); } } this.flushCanonicalLater(); this.setHasData(true); }, removeCanonicalRecords: function (records, idx) { for (var i = 0; i < records.length; i++) { if (idx !== undefined) { this.removeCanonicalRecord(records[i], i + idx); } else { this.removeCanonicalRecord(records[i]); } } }, removeCanonicalRecord: function (record, idx) { if (this.canonicalMembers.has(record)) { this.removeCanonicalRecordFromOwn(record); if (this.inverseKey) { this.removeCanonicalRecordFromInverse(record); } else { if (record._implicitRelationships[this.inverseKeyForImplicit]) { record._implicitRelationships[this.inverseKeyForImplicit].removeCanonicalRecord(this.record); } } } this.flushCanonicalLater(); }, addRecord: function (record, idx) { if (!this.members.has(record)) { this.members.addWithIndex(record, idx); this.notifyRecordRelationshipAdded(record, idx); if (this.inverseKey) { record._relationships.get(this.inverseKey).addRecord(this.record); } else { if (!record._implicitRelationships[this.inverseKeyForImplicit]) { record._implicitRelationships[this.inverseKeyForImplicit] = new Relationship(this.store, record, this.key, { options: {} }); } record._implicitRelationships[this.inverseKeyForImplicit].addRecord(this.record); } this.record.updateRecordArraysLater(); } this.setHasData(true); }, removeRecord: function (record) { if (this.members.has(record)) { this.removeRecordFromOwn(record); if (this.inverseKey) { this.removeRecordFromInverse(record); } else { if (record._implicitRelationships[this.inverseKeyForImplicit]) { record._implicitRelationships[this.inverseKeyForImplicit].removeRecord(this.record); } } } }, removeRecordFromInverse: function (record) { var inverseRelationship = record._relationships.get(this.inverseKey); //Need to check for existence, as the record might unloading at the moment if (inverseRelationship) { inverseRelationship.removeRecordFromOwn(this.record); } }, removeRecordFromOwn: function (record) { this.members.delete(record); this.notifyRecordRelationshipRemoved(record); this.record.updateRecordArrays(); }, removeCanonicalRecordFromInverse: function (record) { var inverseRelationship = record._relationships.get(this.inverseKey); //Need to check for existence, as the record might unloading at the moment if (inverseRelationship) { inverseRelationship.removeCanonicalRecordFromOwn(this.record); } }, removeCanonicalRecordFromOwn: function (record) { this.canonicalMembers.delete(record); this.flushCanonicalLater(); }, flushCanonical: function () { this.willSync = false; //a hack for not removing new records //TODO remove once we have proper diffing var newRecords = []; for (var i = 0; i < this.members.list.length; i++) { if (this.members.list[i].isNew()) { newRecords.push(this.members.list[i]); } } //TODO(Igor) make this less abysmally slow this.members = this.canonicalMembers.copy(); for (i = 0; i < newRecords.length; i++) { this.members.add(newRecords[i]); } }, flushCanonicalLater: function () { var _this3 = this; if (this.willSync) { return; } this.willSync = true; this.store._backburner.join(function () { return _this3.store._backburner.schedule('syncRelationships', _this3, _this3.flushCanonical); }); }, updateLink: function (link) { this.link = link; this.linkPromise = null; this.record.notifyPropertyChange(this.key); }, findLink: function () { if (this.linkPromise) { return this.linkPromise; } else { var promise = this.fetchLink(); this.linkPromise = promise; return promise.then(function (result) { return result; }); } }, updateRecordsFromAdapter: function (records) { //TODO(Igor) move this to a proper place //TODO Once we have adapter support, we need to handle updated and canonical changes this.computeChanges(records); }, notifyRecordRelationshipAdded: function () {}, notifyRecordRelationshipRemoved: function () {}, /* `hasData` for a relationship is a flag to indicate if we consider the content of this relationship "known". Snapshots uses this to tell the difference between unknown (`undefined`) or empty (`null`). The reason for this is that we wouldn't want to serialize unknown relationships as `null` as that might overwrite remote state. All relationships for a newly created (`store.createRecord()`) are considered known (`hasData === true`). */ setHasData: function (value) { this.hasData = value; }, /* `hasLoaded` is a flag to indicate if we have gotten data from the adapter or not when the relationship has a link. This is used to be able to tell when to fetch the link and when to return the local data in scenarios where the local state is considered known (`hasData === true`). Updating the link will automatically set `hasLoaded` to `false`. */ setHasLoaded: function (value) { this.hasLoaded = value; }, /* `push` for a relationship allows the store to push a JSON API Relationship Object onto the relationship. The relationship will then extract and set the meta, data and links of that relationship. `push` use `updateMeta`, `updateData` and `updateLink` to update the state of the relationship. */ push: function (payload) { var hasData = false; var hasLink = false; if (payload.meta) { this.updateMeta(payload.meta); } if (payload.data !== undefined) { hasData = true; this.updateData(payload.data); } if (payload.links && payload.links.related) { var relatedLink = (0, _emberDataPrivateSystemNormalizeLink.default)(payload.links.related); if (relatedLink && relatedLink.href && relatedLink.href !== this.link) { hasLink = true; this.updateLink(relatedLink.href); } } /* Data being pushed into the relationship might contain only data or links, or a combination of both. If we got data we want to set both hasData and hasLoaded to true since this would indicate that we should prefer the local state instead of trying to fetch the link or call findRecord(). If we have no data but a link is present we want to set hasLoaded to false without modifying the hasData flag. This will ensure we fetch the updated link next time the relationship is accessed. */ if (hasData) { this.setHasData(true); this.setHasLoaded(true); } else if (hasLink) { this.setHasLoaded(false); } }, updateData: function () {} }; }); /* global heimdall */ define('ember-data/-private/system/snapshot-record-array', ['exports'], function (exports) { exports.default = SnapshotRecordArray; /** @module ember-data */ /** @class SnapshotRecordArray @namespace DS @private @constructor @param {Array} snapshots An array of snapshots @param {Object} meta */ function SnapshotRecordArray(recordArray, meta) { var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; /** An array of snapshots @private @property _snapshots @type {Array} */ this._snapshots = null; /** An array of records @private @property _recordArray @type {Array} */ this._recordArray = recordArray; /** Number of records in the array @property length @type {Number} */ this.length = recordArray.get('length'); /** The type of the underlying records for the snapshots in the array, as a DS.Model @property type @type {DS.Model} */ this.type = recordArray.get('type'); /** Meta object @property meta @type {Object} */ this.meta = meta; /** A hash of adapter options @property adapterOptions @type {Object} */ this.adapterOptions = options.adapterOptions; this.include = options.include; } /** Get snapshots of the underlying record array @method snapshots @return {Array} Array of snapshots */ SnapshotRecordArray.prototype.snapshots = function () { if (this._snapshots !== null) { return this._snapshots; } this._snapshots = this._recordArray._takeSnapshot(); return this._snapshots; }; }); define("ember-data/-private/system/snapshot", ["exports", "ember", "ember-data/-private/system/empty-object"], function (exports, _ember, _emberDataPrivateSystemEmptyObject) { exports.default = Snapshot; var get = _ember.default.get; /** @class Snapshot @namespace DS @private @constructor @param {DS.Model} internalModel The model to create a snapshot from */ function Snapshot(internalModel) { var _this = this; var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; this._attributes = new _emberDataPrivateSystemEmptyObject.default(); this._belongsToRelationships = new _emberDataPrivateSystemEmptyObject.default(); this._belongsToIds = new _emberDataPrivateSystemEmptyObject.default(); this._hasManyRelationships = new _emberDataPrivateSystemEmptyObject.default(); this._hasManyIds = new _emberDataPrivateSystemEmptyObject.default(); var record = internalModel.getRecord(); this.record = record; record.eachAttribute(function (keyName) { return _this._attributes[keyName] = get(record, keyName); }); this.id = internalModel.id; this._internalModel = internalModel; this.type = internalModel.type; this.modelName = internalModel.type.modelName; /** A hash of adapter options @property adapterOptions @type {Object} */ this.adapterOptions = options.adapterOptions; this.include = options.include; this._changedAttributes = record.changedAttributes(); } Snapshot.prototype = { constructor: Snapshot, /** The id of the snapshot's underlying record Example ```javascript // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); postSnapshot.id; // => '1' ``` @property id @type {String} */ id: null, /** The underlying record for this snapshot. Can be used to access methods and properties defined on the record. Example ```javascript var json = snapshot.record.toJSON(); ``` @property record @type {DS.Model} */ record: null, /** The type of the underlying record for this snapshot, as a DS.Model. @property type @type {DS.Model} */ type: null, /** The name of the type of the underlying record for this snapshot, as a string. @property modelName @type {String} */ modelName: null, /** Returns the value of an attribute. Example ```javascript // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); postSnapshot.attr('author'); // => 'Tomster' postSnapshot.attr('title'); // => 'Ember.js rocks' ``` Note: Values are loaded eagerly and cached when the snapshot is created. @method attr @param {String} keyName @return {Object} The attribute value or undefined */ attr: function (keyName) { if (keyName in this._attributes) { return this._attributes[keyName]; } throw new _ember.default.Error("Model '" + _ember.default.inspect(this.record) + "' has no attribute named '" + keyName + "' defined."); }, /** Returns all attributes and their corresponding values. Example ```javascript // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); postSnapshot.attributes(); // => { author: 'Tomster', title: 'Ember.js rocks' } ``` @method attributes @return {Object} All attributes of the current snapshot */ attributes: function () { return _ember.default.copy(this._attributes); }, /** Returns all changed attributes and their old and new values. Example ```javascript // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); postModel.set('title', 'Ember.js rocks!'); postSnapshot.changedAttributes(); // => { title: ['Ember.js rocks', 'Ember.js rocks!'] } ``` @method changedAttributes @return {Object} All changed attributes of the current snapshot */ changedAttributes: function () { var changedAttributes = new _emberDataPrivateSystemEmptyObject.default(); var changedAttributeKeys = Object.keys(this._changedAttributes); for (var i = 0, _length = changedAttributeKeys.length; i < _length; i++) { var key = changedAttributeKeys[i]; changedAttributes[key] = _ember.default.copy(this._changedAttributes[key]); } return changedAttributes; }, /** Returns the current value of a belongsTo relationship. `belongsTo` takes an optional hash of options as a second parameter, currently supported options are: - `id`: set to `true` if you only want the ID of the related record to be returned. Example ```javascript // store.push('post', { id: 1, title: 'Hello World' }); // store.createRecord('comment', { body: 'Lorem ipsum', post: post }); commentSnapshot.belongsTo('post'); // => DS.Snapshot commentSnapshot.belongsTo('post', { id: true }); // => '1' // store.push('comment', { id: 1, body: 'Lorem ipsum' }); commentSnapshot.belongsTo('post'); // => undefined ``` Calling `belongsTo` will return a new Snapshot as long as there's any known data for the relationship available, such as an ID. If the relationship is known but unset, `belongsTo` will return `null`. If the contents of the relationship is unknown `belongsTo` will return `undefined`. Note: Relationships are loaded lazily and cached upon first access. @method belongsTo @param {String} keyName @param {Object} [options] @return {(DS.Snapshot|String|null|undefined)} A snapshot or ID of a known relationship or null if the relationship is known but unset. undefined will be returned if the contents of the relationship is unknown. */ belongsTo: function (keyName, options) { var id = options && options.id; var relationship, inverseRecord, hasData; var result; if (id && keyName in this._belongsToIds) { return this._belongsToIds[keyName]; } if (!id && keyName in this._belongsToRelationships) { return this._belongsToRelationships[keyName]; } relationship = this._internalModel._relationships.get(keyName); if (!(relationship && relationship.relationshipMeta.kind === 'belongsTo')) { throw new _ember.default.Error("Model '" + _ember.default.inspect(this.record) + "' has no belongsTo relationship named '" + keyName + "' defined."); } hasData = get(relationship, 'hasData'); inverseRecord = get(relationship, 'inverseRecord'); if (hasData) { if (inverseRecord && !inverseRecord.isDeleted()) { if (id) { result = get(inverseRecord, 'id'); } else { result = inverseRecord.createSnapshot(); } } else { result = null; } } if (id) { this._belongsToIds[keyName] = result; } else { this._belongsToRelationships[keyName] = result; } return result; }, /** Returns the current value of a hasMany relationship. `hasMany` takes an optional hash of options as a second parameter, currently supported options are: - `ids`: set to `true` if you only want the IDs of the related records to be returned. Example ```javascript // store.push('post', { id: 1, title: 'Hello World', comments: [2, 3] }); postSnapshot.hasMany('comments'); // => [DS.Snapshot, DS.Snapshot] postSnapshot.hasMany('comments', { ids: true }); // => ['2', '3'] // store.push('post', { id: 1, title: 'Hello World' }); postSnapshot.hasMany('comments'); // => undefined ``` Note: Relationships are loaded lazily and cached upon first access. @method hasMany @param {String} keyName @param {Object} [options] @return {(Array|undefined)} An array of snapshots or IDs of a known relationship or an empty array if the relationship is known but unset. undefined will be returned if the contents of the relationship is unknown. */ hasMany: function (keyName, options) { var ids = options && options.ids; var relationship, members, hasData; var results; if (ids && keyName in this._hasManyIds) { return this._hasManyIds[keyName]; } if (!ids && keyName in this._hasManyRelationships) { return this._hasManyRelationships[keyName]; } relationship = this._internalModel._relationships.get(keyName); if (!(relationship && relationship.relationshipMeta.kind === 'hasMany')) { throw new _ember.default.Error("Model '" + _ember.default.inspect(this.record) + "' has no hasMany relationship named '" + keyName + "' defined."); } hasData = get(relationship, 'hasData'); members = get(relationship, 'members'); if (hasData) { results = []; members.forEach(function (member) { if (!member.isDeleted()) { if (ids) { results.push(member.id); } else { results.push(member.createSnapshot()); } } }); } if (ids) { this._hasManyIds[keyName] = results; } else { this._hasManyRelationships[keyName] = results; } return results; }, /** Iterates through all the attributes of the model, calling the passed function on each attribute. Example ```javascript snapshot.eachAttribute(function(name, meta) { // ... }); ``` @method eachAttribute @param {Function} callback the callback to execute @param {Object} [binding] the value to which the callback's `this` should be bound */ eachAttribute: function (callback, binding) { this.record.eachAttribute(callback, binding); }, /** Iterates through all the relationships of the model, calling the passed function on each relationship. Example ```javascript snapshot.eachRelationship(function(name, relationship) { // ... }); ``` @method eachRelationship @param {Function} callback the callback to execute @param {Object} [binding] the value to which the callback's `this` should be bound */ eachRelationship: function (callback, binding) { this.record.eachRelationship(callback, binding); }, /** @method serialize @param {Object} options @return {Object} an object whose values are primitive JSON values only */ serialize: function (options) { return this.record.store.serializerFor(this.modelName).serialize(this, options); } }; }); /** @module ember-data */ define('ember-data/-private/system/store', ['exports', 'ember', 'ember-data/model', 'ember-data/-private/debug', 'ember-data/-private/system/normalize-model-name', 'ember-data/adapters/errors', 'ember-data/-private/system/promise-proxies', 'ember-data/-private/system/store/common', 'ember-data/-private/system/store/serializer-response', 'ember-data/-private/system/store/serializers', 'ember-data/-private/system/store/finders', 'ember-data/-private/utils', 'ember-data/-private/system/coerce-id', 'ember-data/-private/system/record-array-manager', 'ember-data/-private/system/store/container-instance-cache', 'ember-data/-private/system/model/internal-model', 'ember-data/-private/system/empty-object', 'ember-data/-private/features'], function (exports, _ember, _emberDataModel, _emberDataPrivateDebug, _emberDataPrivateSystemNormalizeModelName, _emberDataAdaptersErrors, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemStoreCommon, _emberDataPrivateSystemStoreSerializerResponse, _emberDataPrivateSystemStoreSerializers, _emberDataPrivateSystemStoreFinders, _emberDataPrivateUtils, _emberDataPrivateSystemCoerceId, _emberDataPrivateSystemRecordArrayManager, _emberDataPrivateSystemStoreContainerInstanceCache, _emberDataPrivateSystemModelInternalModel, _emberDataPrivateSystemEmptyObject, _emberDataPrivateFeatures) { var badIdFormatAssertion = '`id` passed to `findRecord()` has to be non-empty string or number'; exports.badIdFormatAssertion = badIdFormatAssertion; var A = _ember.default.A; var Backburner = _ember.default._Backburner; var computed = _ember.default.computed; var copy = _ember.default.copy; var ENV = _ember.default.ENV; var EmberError = _ember.default.Error; var get = _ember.default.get; var guidFor = _ember.default.guidFor; var inspect = _ember.default.inspect; var isNone = _ember.default.isNone; var isPresent = _ember.default.isPresent; var MapWithDefault = _ember.default.MapWithDefault; var emberRun = _ember.default.run; var set = _ember.default.set; var RSVP = _ember.default.RSVP; var Service = _ember.default.Service; var typeOf = _ember.default.typeOf; var Promise = RSVP.Promise; //Get the materialized model from the internalModel/promise that returns //an internal model and return it in a promiseObject. Useful for returning //from find methods function promiseRecord(internalModelPromise, label) { var toReturn = internalModelPromise.then(function (internalModel) { return internalModel.getRecord(); }); return (0, _emberDataPrivateSystemPromiseProxies.promiseObject)(toReturn, label); } var Store = undefined; // Implementors Note: // // The variables in this file are consistently named according to the following // scheme: // // * +id+ means an identifier managed by an external source, provided inside // the data provided by that source. These are always coerced to be strings // before being used internally. // * +clientId+ means a transient numerical identifier generated at runtime by // the data store. It is important primarily because newly created objects may // not yet have an externally generated id. // * +internalModel+ means a record internalModel object, which holds metadata about a // record, even if it has not yet been fully materialized. // * +type+ means a DS.Model. /** The store contains all of the data for records loaded from the server. It is also responsible for creating instances of `DS.Model` that wrap the individual data for a record, so that they can be bound to in your Handlebars templates. Define your application's store like this: ```app/services/store.js import DS from 'ember-data'; export default DS.Store.extend({ }); ``` Most Ember.js applications will only have a single `DS.Store` that is automatically created by their `Ember.Application`. You can retrieve models from the store in several ways. To retrieve a record for a specific id, use `DS.Store`'s `findRecord()` method: ```javascript store.findRecord('person', 123).then(function (person) { }); ``` By default, the store will talk to your backend using a standard REST mechanism. You can customize how the store talks to your backend by specifying a custom adapter: ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ }); ``` You can learn more about writing a custom adapter by reading the `DS.Adapter` documentation. ### Store createRecord() vs. push() vs. pushPayload() The store provides multiple ways to create new record objects. They have some subtle differences in their use which are detailed below: [createRecord](#method_createRecord) is used for creating new records on the client side. This will return a new record in the `created.uncommitted` state. In order to persist this record to the backend you will need to call `record.save()`. [push](#method_push) is used to notify Ember Data's store of new or updated records that exist in the backend. This will return a record in the `loaded.saved` state. The primary use-case for `store#push` is to notify Ember Data about record updates (full or partial) that happen outside of the normal adapter methods (for example [SSE](http://dev.w3.org/html5/eventsource/) or [Web Sockets](http://www.w3.org/TR/2009/WD-websockets-20091222/)). [pushPayload](#method_pushPayload) is a convenience wrapper for `store#push` that will deserialize payloads if the Serializer implements a `pushPayload` method. Note: When creating a new record using any of the above methods Ember Data will update `DS.RecordArray`s such as those returned by `store#peekAll()`, `store#findAll()` or `store#filter()`. This means any data bindings or computed properties that depend on the RecordArray will automatically be synced to include the new or updated record values. @class Store @namespace DS @extends Ember.Service */ exports.Store = Store = Service.extend({ /** @method init @private */ init: function () { this._super.apply(this, arguments); this._backburner = new Backburner(['normalizeRelationships', 'syncRelationships', 'finished']); // internal bookkeeping; not observable this.typeMaps = {}; this.recordArrayManager = _emberDataPrivateSystemRecordArrayManager.default.create({ store: this }); this._pendingSave = []; this._instanceCache = new _emberDataPrivateSystemStoreContainerInstanceCache.default((0, _emberDataPrivateUtils.getOwner)(this), this); //Used to keep track of all the find requests that need to be coalesced this._pendingFetch = MapWithDefault.create({ defaultValue: function () { return []; } }); }, /** The default adapter to use to communicate to a backend server or other persistence layer. This will be overridden by an application adapter if present. If you want to specify `app/adapters/custom.js` as a string, do: ```js import DS from 'ember-data'; export default DS.Store.extend({ adapter: 'custom', }); ``` @property adapter @default '-json-api' @type {String} */ adapter: '-json-api', /** Returns a JSON representation of the record using a custom type-specific serializer, if one exists. The available options are: * `includeId`: `true` if the record's ID should be included in the JSON representation @method serialize @private @deprecated @param {DS.Model} record the record to serialize @param {Object} options an options hash */ serialize: function (record, options) { if (true) {} var snapshot = record._internalModel.createSnapshot(); return snapshot.serialize(options); }, /** This property returns the adapter, after resolving a possible string key. If the supplied `adapter` was a class, or a String property path resolved to a class, this property will instantiate the class. This property is cacheable, so the same instance of a specified adapter class should be used for the lifetime of the store. @property defaultAdapter @private @return DS.Adapter */ defaultAdapter: computed('adapter', function () { var adapter = get(this, 'adapter'); return this.adapterFor(adapter); }), // ..................... // . CREATE NEW RECORD . // ..................... /** Create a new record in the current store. The properties passed to this method are set on the newly created record. To create a new instance of a `Post`: ```js store.createRecord('post', { title: "Rails is omakase" }); ``` To create a new instance of a `Post` that has a relationship with a `User` record: ```js let user = this.store.peekRecord('user', 1); store.createRecord('post', { title: "Rails is omakase", user: user }); ``` @method createRecord @param {String} modelName @param {Object} inputProperties a hash of properties to set on the newly created record. @return {DS.Model} record */ createRecord: function (modelName, inputProperties) { var modelClass = this.modelFor(modelName); var properties = copy(inputProperties) || new _emberDataPrivateSystemEmptyObject.default(); // If the passed properties do not include a primary key, // give the adapter an opportunity to generate one. Typically, // client-side ID generators will use something like uuid.js // to avoid conflicts. if (isNone(properties.id)) { properties.id = this._generateId(modelName, properties); } // Coerce ID to a string properties.id = (0, _emberDataPrivateSystemCoerceId.default)(properties.id); var internalModel = this.buildInternalModel(modelClass, properties.id); var record = internalModel.getRecord(); // Move the record out of its initial `empty` state into // the `loaded` state. // TODO @runspired this seems really bad, store should not be changing the state internalModel.loadedData(); // Set the properties specified on the record. // TODO @runspired this is probably why we do the bad thing above record.setProperties(properties); // TODO @runspired this should also be coalesced into some form of internalModel.setState() internalModel.eachRelationship(function (key, descriptor) { internalModel._relationships.get(key).setHasData(true); }); return record; }, /** If possible, this method asks the adapter to generate an ID for a newly created record. @method _generateId @private @param {String} modelName @param {Object} properties from the new record @return {String} if the adapter can generate one, an ID */ _generateId: function (modelName, properties) { var adapter = this.adapterFor(modelName); if (adapter && adapter.generateIdForRecord) { return adapter.generateIdForRecord(this, modelName, properties); } return null; }, // ................. // . DELETE RECORD . // ................. /** For symmetry, a record can be deleted via the store. Example ```javascript let post = store.createRecord('post', { title: "Rails is omakase" }); store.deleteRecord(post); ``` @method deleteRecord @param {DS.Model} record */ deleteRecord: function (record) { record.deleteRecord(); }, /** For symmetry, a record can be unloaded via the store. Only non-dirty records can be unloaded. Example ```javascript store.findRecord('post', 1).then(function(post) { store.unloadRecord(post); }); ``` @method unloadRecord @param {DS.Model} record */ unloadRecord: function (record) { record.unloadRecord(); }, // ................ // . FIND RECORDS . // ................ /** @method find @param {String} modelName @param {String|Integer} id @param {Object} options @return {Promise} promise @private */ find: function (modelName, id, options) { // The default `model` hook in Ember.Route calls `find(modelName, id)`, // that's why we have to keep this method around even though `findRecord` is // the public way to get a record by modelName and id. if (arguments.length === 1) {} if (typeOf(id) === 'object') {} if (options) {} return this.findRecord(modelName, id); }, /** This method returns a record for a given type and id combination. The `findRecord` method will always resolve its promise with the same object for a given type and `id`. The `findRecord` method will always return a **promise** that will be resolved with the record. Example ```app/routes/post.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findRecord('post', params.post_id); } }); ``` If the record is not yet available, the store will ask the adapter's `find` method to find the necessary data. If the record is already present in the store, it depends on the reload behavior _when_ the returned promise resolves. ### Reloading The reload behavior is configured either via the passed `options` hash or the result of the adapter's `shouldReloadRecord`. If `{ reload: true }` is passed or `adapter.shouldReloadRecord` evaluates to `true`, then the returned promise resolves once the adapter returns data, regardless if the requested record is already in the store: ```js store.push({ data: { id: 1, type: 'post', revision: 1 } }); // adapter#findRecord resolves with // [ // { // id: 1, // type: 'post', // revision: 2 // } // ] store.findRecord('post', 1, { reload: true }).then(function(post) { post.get("revision"); // 2 }); ``` If no reload is indicated via the abovementioned ways, then the promise immediately resolves with the cached version in the store. ### Background Reloading Optionally, if `adapter.shouldBackgroundReloadRecord` evaluates to `true`, then a background reload is started, which updates the records' data, once it is available: ```js // app/adapters/post.js import ApplicationAdapter from "./application"; export default ApplicationAdapter.extend({ shouldReloadRecord(store, snapshot) { return false; }, shouldBackgroundReloadRecord(store, snapshot) { return true; } }); // ... store.push({ data: { id: 1, type: 'post', revision: 1 } }); let blogPost = store.findRecord('post', 1).then(function(post) { post.get('revision'); // 1 }); // later, once adapter#findRecord resolved with // [ // { // id: 1, // type: 'post', // revision: 2 // } // ] blogPost.get('revision'); // 2 ``` If you would like to force or prevent background reloading, you can set a boolean value for `backgroundReload` in the options object for `findRecord`. ```app/routes/post/edit.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findRecord('post', params.post_id, { backgroundReload: false }); } }); ``` If you pass an object on the `adapterOptions` property of the options argument it will be passed to you adapter via the snapshot ```app/routes/post/edit.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findRecord('post', params.post_id, { adapterOptions: { subscribe: false } }); } }); ``` ```app/adapters/post.js import MyCustomAdapter from './custom-adapter'; export default MyCustomAdapter.extend({ findRecord: function(store, type, id, snapshot) { if (snapshot.adapterOptions.subscribe) { // ... } // ... } }); ``` See [peekRecord](#method_peekRecord) to get the cached version of a record. ### Retrieving Related Model Records If you use an adapter such as Ember's default [`JSONAPIAdapter`](http://emberjs.com/api/data/classes/DS.JSONAPIAdapter.html) that supports the [JSON API specification](http://jsonapi.org/) and if your server endpoint supports the use of an ['include' query parameter](http://jsonapi.org/format/#fetching-includes), you can use `findRecord()` to automatically retrieve additional records related to the one you request by supplying an `include` parameter in the `options` object. For example, given a `post` model that has a `hasMany` relationship with a `comment` model, when we retrieve a specific post we can have the server also return that post's comments in the same request: ```app/routes/post.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findRecord('post', params.post_id, {include: 'comments'}); } }); ``` In this case, the post's comments would then be available in your template as `model.comments`. Multiple relationships can be requested using an `include` parameter consisting of a comma-separated list (without white-space) while nested relationships can be specified using a dot-separated sequence of relationship names. So to request both the post's comments and the authors of those comments the request would look like this: ```app/routes/post.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findRecord('post', params.post_id, {include: 'comments,comments.author'}); } }); ``` @since 1.13.0 @method findRecord @param {String} modelName @param {(String|Integer)} id @param {Object} options @return {Promise} promise */ findRecord: function (modelName, id, options) { var internalModel = this._internalModelForId(modelName, id); options = options || {}; if (!this.hasRecordForId(modelName, id)) { return this._findByInternalModel(internalModel, options); } var fetchedInternalModel = this._findRecord(internalModel, options); return promiseRecord(fetchedInternalModel, "DS: Store#findRecord " + internalModel.typeKey + " with id: " + get(internalModel, 'id')); }, _findRecord: function (internalModel, options) { // Refetch if the reload option is passed if (options.reload) { return this._scheduleFetch(internalModel, options); } var snapshot = internalModel.createSnapshot(options); var modelClass = internalModel.type; var adapter = this.adapterFor(modelClass.modelName); // Refetch the record if the adapter thinks the record is stale if (adapter.shouldReloadRecord(this, snapshot)) { return this._scheduleFetch(internalModel, options); } if (options.backgroundReload === false) { return Promise.resolve(internalModel); } // Trigger the background refetch if backgroundReload option is passed if (options.backgroundReload || adapter.shouldBackgroundReloadRecord(this, snapshot)) { this._scheduleFetch(internalModel, options); } // Return the cached record return Promise.resolve(internalModel); }, _findByInternalModel: function (internalModel, options) { options = options || {}; if (options.preload) { internalModel.preloadData(options.preload); } var fetchedInternalModel = this._findEmptyInternalModel(internalModel, options); return promiseRecord(fetchedInternalModel, "DS: Store#findRecord " + internalModel.typeKey + " with id: " + get(internalModel, 'id')); }, _findEmptyInternalModel: function (internalModel, options) { if (internalModel.isEmpty()) { return this._scheduleFetch(internalModel, options); } //TODO double check about reloading if (internalModel.isLoading()) { return internalModel._loadingPromise; } return Promise.resolve(internalModel); }, /** This method makes a series of requests to the adapter's `find` method and returns a promise that resolves once they are all loaded. @private @method findByIds @param {String} modelName @param {Array} ids @return {Promise} promise */ findByIds: function (modelName, ids) { var promises = new Array(ids.length); for (var i = 0; i < ids.length; i++) { promises[i] = this.findRecord(modelName, ids[i]); } return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)(RSVP.all(promises).then(A, null, "DS: Store#findByIds of " + modelName + " complete")); }, /** This method is called by `findRecord` if it discovers that a particular type/id pair hasn't been loaded yet to kick off a request to the adapter. @method _fetchRecord @private @param {InternalModel} internalModel model @return {Promise} promise */ _fetchRecord: function (internalModel, options) { var modelClass = internalModel.type; var id = internalModel.id; var adapter = this.adapterFor(modelClass.modelName); return (0, _emberDataPrivateSystemStoreFinders._find)(adapter, this, modelClass, id, internalModel, options); }, _scheduleFetchMany: function (internalModels) { var fetches = new Array(internalModels.length); for (var i = 0; i < internalModels.length; i++) { fetches[i] = this._scheduleFetch(internalModels[i]); } return Promise.all(fetches); }, _scheduleFetch: function (internalModel, options) { if (internalModel._loadingPromise) { return internalModel._loadingPromise; } var modelClass = internalModel.type; var resolver = RSVP.defer('Fetching ' + modelClass.modelName + ' with id: ' + internalModel.id); var pendingFetchItem = { internalModel: internalModel, resolver: resolver, options: options }; var promise = resolver.promise; internalModel.loadingData(promise); this._pendingFetch.get(modelClass).push(pendingFetchItem); emberRun.scheduleOnce('afterRender', this, this.flushAllPendingFetches); return promise; }, flushAllPendingFetches: function () { if (this.isDestroyed || this.isDestroying) { return; } this._pendingFetch.forEach(this._flushPendingFetchForType, this); this._pendingFetch.clear(); }, _flushPendingFetchForType: function (pendingFetchItems, modelClass) { var store = this; var adapter = store.adapterFor(modelClass.modelName); var shouldCoalesce = !!adapter.findMany && adapter.coalesceFindRequests; var totalItems = pendingFetchItems.length; var internalModels = new Array(totalItems); var seeking = new _emberDataPrivateSystemEmptyObject.default(); for (var i = 0; i < totalItems; i++) { var pendingItem = pendingFetchItems[i]; var internalModel = pendingItem.internalModel; internalModels[i] = internalModel; seeking[internalModel.id] = pendingItem; } function _fetchRecord(recordResolverPair) { var recordFetch = store._fetchRecord(recordResolverPair.internalModel, recordResolverPair.options); // TODO adapter options recordResolverPair.resolver.resolve(recordFetch); } function handleFoundRecords(foundInternalModels, expectedInternalModels) { // resolve found records var found = new _emberDataPrivateSystemEmptyObject.default(); for (var i = 0, l = foundInternalModels.length; i < l; i++) { var internalModel = foundInternalModels[i]; var pair = seeking[internalModel.id]; found[internalModel.id] = internalModel; if (pair) { var resolver = pair.resolver; resolver.resolve(internalModel); } } // reject missing records var missingInternalModels = []; for (var i = 0, l = expectedInternalModels.length; i < l; i++) { var internalModel = expectedInternalModels[i]; if (!found[internalModel.id]) { missingInternalModels.push(internalModel); } } if (missingInternalModels.length) { rejectInternalModels(missingInternalModels); } } function rejectInternalModels(internalModels, error) { for (var i = 0, l = internalModels.length; i < l; i++) { var pair = seeking[internalModels[i].id]; if (pair) { pair.resolver.reject(error); } } } if (shouldCoalesce) { // TODO: Improve records => snapshots => records => snapshots // // We want to provide records to all store methods and snapshots to all // adapter methods. To make sure we're doing that we're providing an array // of snapshots to adapter.groupRecordsForFindMany(), which in turn will // return grouped snapshots instead of grouped records. // // But since the _findMany() finder is a store method we need to get the // records from the grouped snapshots even though the _findMany() finder // will once again convert the records to snapshots for adapter.findMany() var snapshots = new Array(totalItems); for (var i = 0; i < totalItems; i++) { snapshots[i] = internalModels[i].createSnapshot(); } var groups = adapter.groupRecordsForFindMany(this, snapshots); var _loop = function (i, l) { var group = groups[i]; var totalInGroup = groups[i].length; var ids = new Array(totalInGroup); var groupedInternalModels = new Array(totalInGroup); for (var j = 0; j < totalInGroup; j++) { var internalModel = group[j]._internalModel; groupedInternalModels[j] = internalModel; ids[j] = internalModel.id; } if (totalInGroup > 1) { (0, _emberDataPrivateSystemStoreFinders._findMany)(adapter, store, modelClass, ids, groupedInternalModels).then(function (foundInternalModels) { handleFoundRecords(foundInternalModels, groupedInternalModels); }).catch(function (error) { rejectInternalModels(groupedInternalModels, error); }); } else if (ids.length === 1) { var pair = seeking[groupedInternalModels[0].id]; _fetchRecord(pair); } else {} }; for (var i = 0, l = groups.length; i < l; i++) { _loop(i, l); } } else { for (var i = 0; i < totalItems; i++) { _fetchRecord(pendingFetchItems[i]); } } }, /** Get the reference for the specified record. Example ```javascript let userRef = store.getReference('user', 1); // check if the user is loaded let isLoaded = userRef.value() !== null; // get the record of the reference (null if not yet available) let user = userRef.value(); // get the identifier of the reference if (userRef.remoteType() === "id") { let id = userRef.id(); } // load user (via store.find) userRef.load().then(...) // or trigger a reload userRef.reload().then(...) // provide data for reference userRef.push({ id: 1, username: "@user" }).then(function(user) { userRef.value() === user; }); ``` @method getReference @param {String} type @param {String|Integer} id @since 2.5.0 @return {RecordReference} */ getReference: function (type, id) { return this._internalModelForId(type, id).recordReference; }, /** Get a record by a given type and ID without triggering a fetch. This method will synchronously return the record if it is available in the store, otherwise it will return `null`. A record is available if it has been fetched earlier, or pushed manually into the store. _Note: This is an synchronous method and does not return a promise._ ```js let post = store.peekRecord('post', 1); post.get('id'); // 1 ``` @since 1.13.0 @method peekRecord @param {String} modelName @param {String|Integer} id @return {DS.Model|null} record */ peekRecord: function (modelName, id) { if (this.hasRecordForId(modelName, id)) { return this._internalModelForId(modelName, id).getRecord(); } else { return null; } }, /** This method is called by the record's `reload` method. This method calls the adapter's `find` method, which returns a promise. When **that** promise resolves, `reloadRecord` will resolve the promise returned by the record's `reload`. @method reloadRecord @private @param {DS.Model} internalModel @return {Promise} promise */ // TODO @runspired this should be underscored reloadRecord: function (internalModel) { var modelName = internalModel.type.modelName; var adapter = this.adapterFor(modelName); var id = internalModel.id; return this._scheduleFetch(internalModel); }, /** This method returns true if a record for a given modelName and id is already loaded in the store. Use this function to know beforehand if a findRecord() will result in a request or that it will be a cache hit. Example ```javascript store.hasRecordForId('post', 1); // false store.findRecord('post', 1).then(function() { store.hasRecordForId('post', 1); // true }); ``` @method hasRecordForId @param {String} modelName @param {(String|Integer)} id @return {Boolean} */ hasRecordForId: function (modelName, id) { var trueId = (0, _emberDataPrivateSystemCoerceId.default)(id); var modelClass = this.modelFor(modelName); var internalModel = this.typeMapFor(modelClass).idToRecord[trueId]; return !!internalModel && internalModel.isLoaded(); }, /** Returns id record for a given type and ID. If one isn't already loaded, it builds a new record and leaves it in the `empty` state. @method recordForId @private @param {String} modelName @param {(String|Integer)} id @return {DS.Model} record */ recordForId: function (modelName, id) { return this._internalModelForId(modelName, id).getRecord(); }, _internalModelForId: function (modelName, inputId) { var modelClass = this.modelFor(modelName); var id = (0, _emberDataPrivateSystemCoerceId.default)(inputId); var idToRecord = this.typeMapFor(modelClass).idToRecord; var internalModel = idToRecord[id]; if (!internalModel || !idToRecord[id]) { internalModel = this.buildInternalModel(modelClass, id); } return internalModel; }, /** @method findMany @private @param {Array} internalModels @return {Promise} promise */ findMany: function (internalModels) { var finds = new Array(internalModels.length); for (var i = 0; i < internalModels.length; i++) { finds[i] = this._findByInternalModel(internalModels[i]); } return Promise.all(finds); }, /** If a relationship was originally populated by the adapter as a link (as opposed to a list of IDs), this method is called when the relationship is fetched. The link (which is usually a URL) is passed through unchanged, so the adapter can make whatever request it wants. The usual use-case is for the server to register a URL as a link, and then use that URL in the future to make a request for the relationship. @method findHasMany @private @param {DS.Model} owner @param {any} link @param {(Relationship)} relationship @return {Promise} promise */ findHasMany: function (owner, link, relationship) { var adapter = this.adapterFor(owner.type.modelName); return (0, _emberDataPrivateSystemStoreFinders._findHasMany)(adapter, this, owner, link, relationship); }, /** @method findBelongsTo @private @param {DS.Model} owner @param {any} link @param {Relationship} relationship @return {Promise} promise */ findBelongsTo: function (owner, link, relationship) { var adapter = this.adapterFor(owner.type.modelName); return (0, _emberDataPrivateSystemStoreFinders._findBelongsTo)(adapter, this, owner, link, relationship); }, /** This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application. Exposing queries this way seems preferable to creating an abstract query language for all server-side queries, and then require all adapters to implement them. --- If you do something like this: ```javascript store.query('person', { page: 1 }); ``` The call made to the server, using a Rails backend, will look something like this: ``` Started GET "/api/v1/person?page=1" Processing by Api::V1::PersonsController#index as HTML Parameters: { "page"=>"1" } ``` --- If you do something like this: ```javascript store.query('person', { ids: [1, 2, 3] }); ``` The call to the server, using a Rails backend, will look something like this: ``` Started GET "/api/v1/person?ids%5B%5D=1&ids%5B%5D=2&ids%5B%5D=3" Processing by Api::V1::PersonsController#index as HTML Parameters: { "ids" => ["1", "2", "3"] } ``` This method returns a promise, which is resolved with an [`AdapterPopulatedRecordArray`](http://emberjs.com/api/data/classes/DS.AdapterPopulatedRecordArray.html) once the server returns. @since 1.13.0 @method query @param {String} modelName @param {any} query an opaque query to be used by the adapter @return {Promise} promise */ query: function (modelName, query) { return this._query(modelName, query); }, _query: function (modelName, query, array) { var modelClass = this.modelFor(modelName); array = array || this.recordArrayManager.createAdapterPopulatedRecordArray(modelClass, query); var adapter = this.adapterFor(modelName); var pA = (0, _emberDataPrivateSystemPromiseProxies.promiseArray)((0, _emberDataPrivateSystemStoreFinders._query)(adapter, this, modelClass, query, array)); return pA; }, /** This method makes a request for one record, where the `id` is not known beforehand (if the `id` is known, use [`findRecord`](#method_findRecord) instead). This method can be used when it is certain that the server will return a single object for the primary data. Let's assume our API provides an endpoint for the currently logged in user via: ``` // GET /api/current_user { user: { id: 1234, username: 'admin' } } ``` Since the specific `id` of the `user` is not known beforehand, we can use `queryRecord` to get the user: ```javascript store.queryRecord('user', {}).then(function(user) { let username = user.get('username'); console.log(`Currently logged in as ${username}`); }); ``` The request is made through the adapters' `queryRecord`: ```app/adapters/user.js import DS from "ember-data"; export default DS.Adapter.extend({ queryRecord(modelName, query) { return Ember.$.getJSON("/api/current_user"); } }); ``` Note: the primary use case for `store.queryRecord` is when a single record is queried and the `id` is not known beforehand. In all other cases `store.query` and using the first item of the array is likely the preferred way: ``` // GET /users?username=unique { data: [{ id: 1234, type: 'user', attributes: { username: "unique" } }] } ``` ```javascript store.query('user', { username: 'unique' }).then(function(users) { return users.get('firstObject'); }).then(function(user) { let id = user.get('id'); }); ``` This method returns a promise, which resolves with the found record. If the adapter returns no data for the primary data of the payload, then `queryRecord` resolves with `null`: ``` // GET /users?username=unique { data: null } ``` ```javascript store.queryRecord('user', { username: 'unique' }).then(function(user) { console.log(user); // null }); ``` @since 1.13.0 @method queryRecord @param {String} modelName @param {any} query an opaque query to be used by the adapter @return {Promise} promise which resolves with the found record or `null` */ queryRecord: function (modelName, query) { var modelClass = this.modelFor(modelName); var adapter = this.adapterFor(modelName); return (0, _emberDataPrivateSystemPromiseProxies.promiseObject)((0, _emberDataPrivateSystemStoreFinders._queryRecord)(adapter, this, modelClass, query).then(function (internalModel) { // the promise returned by store.queryRecord is expected to resolve with // an instance of DS.Model if (internalModel) { return internalModel.getRecord(); } return null; })); }, /** `findAll` asks the adapter's `findAll` method to find the records for the given type, and returns a promise which will resolve with all records of this type present in the store, even if the adapter only returns a subset of them. ```app/routes/authors.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findAll('author'); } }); ``` _When_ the returned promise resolves depends on the reload behavior, configured via the passed `options` hash and the result of the adapter's `shouldReloadAll` method. ### Reloading If `{ reload: true }` is passed or `adapter.shouldReloadAll` evaluates to `true`, then the returned promise resolves once the adapter returns data, regardless if there are already records in the store: ```js store.push({ data: { id: 'first', type: 'author' } }); // adapter#findAll resolves with // [ // { // id: 'second', // type: 'author' // } // ] store.findAll('author', { reload: true }).then(function(authors) { authors.getEach("id"); // ['first', 'second'] }); ``` If no reload is indicated via the abovementioned ways, then the promise immediately resolves with all the records currently loaded in the store. ### Background Reloading Optionally, if `adapter.shouldBackgroundReloadAll` evaluates to `true`, then a background reload is started. Once this resolves, the array with which the promise resolves, is updated automatically so it contains all the records in the store: ```js // app/adapters/application.js export default DS.Adapter.extend({ shouldReloadAll(store, snapshotsArray) { return false; }, shouldBackgroundReloadAll(store, snapshotsArray) { return true; } }); // ... store.push({ data: { id: 'first', type: 'author' } }); let allAuthors; store.findAll('author').then(function(authors) { authors.getEach('id'); // ['first'] allAuthors = authors; }); // later, once adapter#findAll resolved with // [ // { // id: 'second', // type: 'author' // } // ] allAuthors.getEach('id'); // ['first', 'second'] ``` If you would like to force or prevent background reloading, you can set a boolean value for `backgroundReload` in the options object for `findAll`. ```app/routes/post/edit.js import Ember from 'ember'; export default Ember.Route.extend({ model: function() { return this.store.findAll('post', { backgroundReload: false }); } }); ``` If you pass an object on the `adapterOptions` property of the options argument it will be passed to you adapter via the `snapshotRecordArray` ```app/routes/posts.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findAll('post', { adapterOptions: { subscribe: false } }); } }); ``` ```app/adapters/post.js import MyCustomAdapter from './custom-adapter'; export default MyCustomAdapter.extend({ findAll: function(store, type, sinceToken, snapshotRecordArray) { if (snapshotRecordArray.adapterOptions.subscribe) { // ... } // ... } }); ``` See [peekAll](#method_peekAll) to get an array of current records in the store, without waiting until a reload is finished. ### Retrieving Related Model Records If you use an adapter such as Ember's default [`JSONAPIAdapter`](http://emberjs.com/api/data/classes/DS.JSONAPIAdapter.html) that supports the [JSON API specification](http://jsonapi.org/) and if your server endpoint supports the use of an ['include' query parameter](http://jsonapi.org/format/#fetching-includes), you can use `findAll()` to automatically retrieve additional records related to those requested by supplying an `include` parameter in the `options` object. For example, given a `post` model that has a `hasMany` relationship with a `comment` model, when we retrieve all of the post records we can have the server also return all of the posts' comments in the same request: ```app/routes/posts.js import Ember from 'ember'; export default Ember.Route.extend({ model: function() { return this.store.findAll('post', {include: 'comments'}); } }); ``` Multiple relationships can be requested using an `include` parameter consisting of a comma-separated list (without white-space) while nested relationships can be specified using a dot-separated sequence of relationship names. So to request both the posts' comments and the authors of those comments the request would look like this: ```app/routes/posts.js import Ember from 'ember'; export default Ember.Route.extend({ model: function() { return this.store.findAll('post', {include: 'comments,comments.author'}); } }); ``` See [query](#method_query) to only get a subset of records from the server. @since 1.13.0 @method findAll @param {String} modelName @param {Object} options @return {Promise} promise */ findAll: function (modelName, options) { var modelClass = this.modelFor(modelName); var fetch = this._fetchAll(modelClass, this.peekAll(modelName), options); return fetch; }, /** @method _fetchAll @private @param {DS.Model} modelClass @param {DS.RecordArray} array @return {Promise} promise */ _fetchAll: function (modelClass, array, options) { options = options || {}; var adapter = this.adapterFor(modelClass.modelName); var sinceToken = this.typeMapFor(modelClass).metadata.since; if (options.reload) { set(array, 'isUpdating', true); return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)((0, _emberDataPrivateSystemStoreFinders._findAll)(adapter, this, modelClass, sinceToken, options)); } var snapshotArray = array._createSnapshot(options); if (adapter.shouldReloadAll(this, snapshotArray)) { set(array, 'isUpdating', true); return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)((0, _emberDataPrivateSystemStoreFinders._findAll)(adapter, this, modelClass, sinceToken, options)); } if (options.backgroundReload === false) { return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)(Promise.resolve(array)); } if (options.backgroundReload || adapter.shouldBackgroundReloadAll(this, snapshotArray)) { set(array, 'isUpdating', true); (0, _emberDataPrivateSystemStoreFinders._findAll)(adapter, this, modelClass, sinceToken, options); } return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)(Promise.resolve(array)); }, /** @method didUpdateAll @param {DS.Model} modelClass @private */ didUpdateAll: function (modelClass) { var liveRecordArray = this.recordArrayManager.liveRecordArrayFor(modelClass); set(liveRecordArray, 'isUpdating', false); }, /** This method returns a filtered array that contains all of the known records for a given type in the store. Note that because it's just a filter, the result will contain any locally created records of the type, however, it will not make a request to the backend to retrieve additional records. If you would like to request all the records from the backend please use [store.findAll](#method_findAll). Also note that multiple calls to `peekAll` for a given type will always return the same `RecordArray`. Example ```javascript let localPosts = store.peekAll('post'); ``` @since 1.13.0 @method peekAll @param {String} modelName @return {DS.RecordArray} */ peekAll: function (modelName) { var modelClass = this.modelFor(modelName); var liveRecordArray = this.recordArrayManager.liveRecordArrayFor(modelClass); this.recordArrayManager.syncLiveRecordArray(liveRecordArray, modelClass); return liveRecordArray; }, /** This method unloads all records in the store. It schedules unloading to happen during the next run loop. Optionally you can pass a type which unload all records for a given type. ```javascript store.unloadAll(); store.unloadAll('post'); ``` @method unloadAll @param {String} modelName */ unloadAll: function (modelName) { if (arguments.length === 0) { var typeMaps = this.typeMaps; var keys = Object.keys(typeMaps); var types = new Array(keys.length); for (var i = 0; i < keys.length; i++) { types[i] = typeMaps[keys[i]]['type'].modelName; } types.forEach(this.unloadAll, this); } else { var modelClass = this.modelFor(modelName); var typeMap = this.typeMapFor(modelClass); var records = typeMap.records.slice(); var record = undefined; for (var i = 0; i < records.length; i++) { record = records[i]; record.unloadRecord(); record.destroy(); // maybe within unloadRecord } typeMap.metadata = new _emberDataPrivateSystemEmptyObject.default(); } }, /** Takes a type and filter function, and returns a live RecordArray that remains up to date as new records are loaded into the store or created locally. The filter function takes a materialized record, and returns true if the record should be included in the filter and false if it should not. Example ```javascript store.filter('post', function(post) { return post.get('unread'); }); ``` The filter function is called once on all records for the type when it is created, and then once on each newly loaded or created record. If any of a record's properties change, or if it changes state, the filter function will be invoked again to determine whether it should still be in the array. Optionally you can pass a query, which is the equivalent of calling [query](#method_query) with that same query, to fetch additional records from the server. The results returned by the server could then appear in the filter if they match the filter function. The query itself is not used to filter records, it's only sent to your server for you to be able to do server-side filtering. The filter function will be applied on the returned results regardless. Example ```javascript store.filter('post', { unread: true }, function(post) { return post.get('unread'); }).then(function(unreadPosts) { unreadPosts.get('length'); // 5 let unreadPost = unreadPosts.objectAt(0); unreadPost.set('unread', false); unreadPosts.get('length'); // 4 }); ``` @method filter @private @param {String} modelName @param {Object} query optional query @param {Function} filter @return {DS.PromiseArray} @deprecated */ filter: function (modelName, query, filter) { if (!ENV.ENABLE_DS_FILTER) {} var promise = undefined; var length = arguments.length; var array = undefined; var hasQuery = length === 3; // allow an optional server query if (hasQuery) { promise = this.query(modelName, query); } else if (arguments.length === 2) { filter = query; } modelName = this.modelFor(modelName); if (hasQuery) { array = this.recordArrayManager.createFilteredRecordArray(modelName, filter, query); } else { array = this.recordArrayManager.createFilteredRecordArray(modelName, filter); } promise = promise || Promise.resolve(array); return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)(promise.then(function () { return array; }, null, 'DS: Store#filter of ' + modelName)); }, /** This method has been deprecated and is an alias for store.hasRecordForId, which should be used instead. @deprecated @method recordIsLoaded @param {String} modelName @param {string} id @return {boolean} */ recordIsLoaded: function (modelName, id) { return this.hasRecordForId(modelName, id); }, // ............ // . UPDATING . // ............ /** If the adapter updates attributes the record will notify the store to update its membership in any filters. To avoid thrashing, this method is invoked only once per run loop per record. @method dataWasUpdated @private @param {Class} type @param {InternalModel} internalModel */ dataWasUpdated: function (type, internalModel) { this.recordArrayManager.recordDidChange(internalModel); }, // .............. // . PERSISTING . // .............. /** This method is called by `record.save`, and gets passed a resolver for the promise that `record.save` returns. It schedules saving to happen at the end of the run loop. @method scheduleSave @private @param {InternalModel} internalModel @param {Resolver} resolver @param {Object} options */ scheduleSave: function (internalModel, resolver, options) { var snapshot = internalModel.createSnapshot(options); internalModel.flushChangedAttributes(); internalModel.adapterWillCommit(); this._pendingSave.push({ snapshot: snapshot, resolver: resolver }); emberRun.once(this, this.flushPendingSave); }, /** This method is called at the end of the run loop, and flushes any records passed into `scheduleSave` @method flushPendingSave @private */ flushPendingSave: function () { var _this = this; var pending = this._pendingSave.slice(); this._pendingSave = []; pending.forEach(function (pendingItem) { var snapshot = pendingItem.snapshot; var resolver = pendingItem.resolver; var record = snapshot._internalModel; var adapter = _this.adapterFor(record.modelClass.modelName); var operation = undefined; if (get(record, 'currentState.stateName') === 'root.deleted.saved') { return resolver.resolve(); } else if (record.isNew()) { operation = 'createRecord'; } else if (record.isDeleted()) { operation = 'deleteRecord'; } else { operation = 'updateRecord'; } resolver.resolve(_commit(adapter, _this, operation, snapshot)); }); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is resolved. If the data provides a server-generated ID, it will update the record and the store's indexes. @method didSaveRecord @private @param {InternalModel} internalModel the in-flight internal model @param {Object} data optional data (see above) */ didSaveRecord: function (internalModel, dataArg) { var data = undefined; if (dataArg) { data = dataArg.data; } if (data) { // normalize relationship IDs into records this._backburner.schedule('normalizeRelationships', this, this._setupRelationships, internalModel, data); this.updateId(internalModel, data); } else {} //We first make sure the primary data has been updated //TODO try to move notification to the user to the end of the runloop internalModel.adapterDidCommit(data); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected with a `DS.InvalidError`. @method recordWasInvalid @private @param {InternalModel} internalModel @param {Object} errors */ recordWasInvalid: function (internalModel, errors) { internalModel.adapterDidInvalidate(errors); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected (with anything other than a `DS.InvalidError`). @method recordWasError @private @param {InternalModel} internalModel @param {Error} error */ recordWasError: function (internalModel, error) { internalModel.adapterDidError(error); }, /** When an adapter's `createRecord`, `updateRecord` or `deleteRecord` resolves with data, this method extracts the ID from the supplied data. @method updateId @private @param {InternalModel} internalModel @param {Object} data */ updateId: function (internalModel, data) { var oldId = internalModel.id; var id = (0, _emberDataPrivateSystemCoerceId.default)(data.id); // ID absolutely can't be missing if the oldID is empty (missing Id in response for a new record) // ID absolutely can't be different than oldID if oldID is not null // ID can be null if oldID is not null (altered ID in response for a record) // however, this is more than likely a developer error. if (oldId !== null && id === null) { return; } this.typeMapFor(internalModel.type).idToRecord[id] = internalModel; internalModel.setId(id); }, /** Returns a map of IDs to client IDs for a given type. @method typeMapFor @private @param {DS.Model} modelClass @return {Object} typeMap */ typeMapFor: function (modelClass) { var typeMaps = get(this, 'typeMaps'); var guid = guidFor(modelClass); var typeMap = typeMaps[guid]; if (typeMap) { return typeMap; } typeMap = { idToRecord: new _emberDataPrivateSystemEmptyObject.default(), records: [], metadata: new _emberDataPrivateSystemEmptyObject.default(), type: modelClass }; typeMaps[guid] = typeMap; return typeMap; }, // ................ // . LOADING DATA . // ................ /** This internal method is used by `push`. @method _load @private @param {(String|DS.Model)} type @param {Object} data */ _load: function (data) { var internalModel = this._internalModelForId(data.type, data.id); internalModel.setupData(data); this.recordArrayManager.recordDidChange(internalModel); return internalModel; }, /* In case someone defined a relationship to a mixin, for example: ``` let Comment = DS.Model.extend({ owner: belongsTo('commentable'. { polymorphic: true}) }); let Commentable = Ember.Mixin.create({ comments: hasMany('comment') }); ``` we want to look up a Commentable class which has all the necessary relationship metadata. Thus, we look up the mixin and create a mock DS.Model, so we can access the relationship CPs of the mixin (`comments`) in this case */ _modelForMixin: function (modelName) { var normalizedModelName = (0, _emberDataPrivateSystemNormalizeModelName.default)(modelName); // container.registry = 2.1 // container._registry = 1.11 - 2.0 // container = < 1.11 var owner = (0, _emberDataPrivateUtils.getOwner)(this); var mixin = owner._lookupFactory('mixin:' + normalizedModelName); if (mixin) { //Cache the class as a model owner.register('model:' + normalizedModelName, _emberDataModel.default.extend(mixin)); } var factory = this.modelFactoryFor(normalizedModelName); if (factory) { factory.__isMixin = true; factory.__mixin = mixin; } return factory; }, /** Returns the model class for the particular `modelName`. The class of a model might be useful if you want to get a list of all the relationship names of the model, see [`relationshipNames`](http://emberjs.com/api/data/classes/DS.Model.html#property_relationshipNames) for example. @method modelFor @param {String} modelName @return {DS.Model} */ modelFor: function (modelName) { var factory = this.modelFactoryFor(modelName); if (!factory) { //Support looking up mixins as base types for polymorphic relationships factory = this._modelForMixin(modelName); } if (!factory) { throw new EmberError("No model was found for '" + modelName + "'"); } factory.modelName = factory.modelName || (0, _emberDataPrivateSystemNormalizeModelName.default)(modelName); return factory; }, modelFactoryFor: function (modelName) { var normalizedKey = (0, _emberDataPrivateSystemNormalizeModelName.default)(modelName); var owner = (0, _emberDataPrivateUtils.getOwner)(this); return owner._lookupFactory('model:' + normalizedKey); }, /** Push some data for a given type into the store. This method expects normalized [JSON API](http://jsonapi.org/) document. This means you have to follow [JSON API specification](http://jsonapi.org/format/) with few minor adjustments: - record's `type` should always be in singular, dasherized form - members (properties) should be camelCased [Your primary data should be wrapped inside `data` property](http://jsonapi.org/format/#document-top-level): ```js store.push({ data: { // primary data for single record of type `Person` id: '1', type: 'person', attributes: { firstName: 'Daniel', lastName: 'Kmak' } } }); ``` [Demo.](http://ember-twiddle.com/fb99f18cd3b4d3e2a4c7) `data` property can also hold an array (of records): ```js store.push({ data: [ // an array of records { id: '1', type: 'person', attributes: { firstName: 'Daniel', lastName: 'Kmak' } }, { id: '2', type: 'person', attributes: { firstName: 'Tom', lastName: 'Dale' } } ] }); ``` [Demo.](http://ember-twiddle.com/69cdbeaa3702159dc355) There are some typical properties for `JSONAPI` payload: * `id` - mandatory, unique record's key * `type` - mandatory string which matches `model`'s dasherized name in singular form * `attributes` - object which holds data for record attributes - `DS.attr`'s declared in model * `relationships` - object which must contain any of the following properties under each relationships' respective key (example path is `relationships.achievements.data`): - [`links`](http://jsonapi.org/format/#document-links) - [`data`](http://jsonapi.org/format/#document-resource-object-linkage) - place for primary data - [`meta`](http://jsonapi.org/format/#document-meta) - object which contains meta-information about relationship For this model: ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), children: DS.hasMany('person') }); ``` To represent the children as IDs: ```js { data: { id: '1', type: 'person', attributes: { firstName: 'Tom', lastName: 'Dale' }, relationships: { children: { data: [ { id: '2', type: 'person' }, { id: '3', type: 'person' }, { id: '4', type: 'person' } ] } } } } ``` [Demo.](http://ember-twiddle.com/343e1735e034091f5bde) To represent the children relationship as a URL: ```js { data: { id: '1', type: 'person', attributes: { firstName: 'Tom', lastName: 'Dale' }, relationships: { children: { links: { related: '/people/1/children' } } } } } ``` If you're streaming data or implementing an adapter, make sure that you have converted the incoming data into this form. The store's [normalize](#method_normalize) method is a convenience helper for converting a json payload into the form Ember Data expects. ```js store.push(store.normalize('person', data)); ``` This method can be used both to push in brand new records, as well as to update existing records. @method push @param {Object} data @return {DS.Model|Array} the record(s) that was created or updated. */ push: function (data) { var pushed = this._push(data); if (Array.isArray(pushed)) { var records = pushed.map(function (internalModel) { return internalModel.getRecord(); }); return records; } if (pushed === null) { return null; } var record = pushed.getRecord(); return record; }, /* Push some data into the store, without creating materialized records. @method _push @private @param {Object} data @return {DS.InternalModel|Array<DS.InternalModel>} pushed InternalModel(s) */ _push: function (data) { var included = data.included; var i = undefined, length = undefined; if (included) { for (i = 0, length = included.length; i < length; i++) { this._pushInternalModel(included[i]); } } if (Array.isArray(data.data)) { length = data.data.length; var internalModels = new Array(length); for (i = 0; i < length; i++) { internalModels[i] = this._pushInternalModel(data.data[i]); } return internalModels; } if (data.data === null) { return null; } var internalModel = this._pushInternalModel(data.data); return internalModel; }, _hasModelFor: function (modelName) { return !!(0, _emberDataPrivateUtils.getOwner)(this)._lookupFactory('model:' + modelName); }, _pushInternalModel: function (data) { var _this2 = this; var modelName = data.type; // Actually load the record into the store. var internalModel = this._load(data); this._backburner.join(function () { _this2._backburner.schedule('normalizeRelationships', _this2, _this2._setupRelationships, internalModel, data); }); return internalModel; }, _setupRelationships: function (record, data) { // This will convert relationships specified as IDs into DS.Model instances // (possibly unloaded) and also create the data structures used to track // relationships. setupRelationships(this, record, data); }, /** Push some raw data into the store. This method can be used both to push in brand new records, as well as to update existing records. You can push in more than one type of object at once. All objects should be in the format expected by the serializer. ```app/serializers/application.js import DS from 'ember-data'; export default DS.ActiveModelSerializer; ``` ```js let pushData = { posts: [ { id: 1, post_title: "Great post", comment_ids: [2] } ], comments: [ { id: 2, comment_body: "Insightful comment" } ] } store.pushPayload(pushData); ``` By default, the data will be deserialized using a default serializer (the application serializer if it exists). Alternatively, `pushPayload` will accept a model type which will determine which serializer will process the payload. ```app/serializers/application.js import DS from 'ember-data'; export default DS.ActiveModelSerializer; ``` ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer; ``` ```js store.pushPayload('comment', pushData); // Will use the application serializer store.pushPayload('post', pushData); // Will use the post serializer ``` @method pushPayload @param {String} modelName Optionally, a model type used to determine which serializer will be used @param {Object} inputPayload */ pushPayload: function (modelName, inputPayload) { var _this3 = this; var serializer = undefined; var payload = undefined; if (!inputPayload) { payload = modelName; serializer = defaultSerializer(this); } else { payload = inputPayload; serializer = this.serializerFor(modelName); } if (false) { return this._adapterRun(function () { return serializer.pushPayload(_this3, payload); }); } else { this._adapterRun(function () { return serializer.pushPayload(_this3, payload); }); } }, /** `normalize` converts a json payload into the normalized form that [push](#method_push) expects. Example ```js socket.on('message', function(message) { let modelName = message.model; let data = message.data; store.push(store.normalize(modelName, data)); }); ``` @method normalize @param {String} modelName The name of the model type for this payload @param {Object} payload @return {Object} The normalized payload */ normalize: function (modelName, payload) { var serializer = this.serializerFor(modelName); var model = this.modelFor(modelName); return serializer.normalize(model, payload); }, /** Build a brand new record for a given type, ID, and initial data. @method buildRecord @private @param {DS.Model} modelClass @param {String} id @param {Object} data @return {InternalModel} internal model */ buildInternalModel: function (modelClass, id, data) { var typeMap = this.typeMapFor(modelClass); var idToRecord = typeMap.idToRecord; // lookupFactory should really return an object that creates // instances with the injections applied var internalModel = new _emberDataPrivateSystemModelInternalModel.default(modelClass, id, this, data); // if we're creating an item, this process will be done // later, once the object has been persisted. if (id) { idToRecord[id] = internalModel; } typeMap.records.push(internalModel); return internalModel; }, //Called by the state machine to notify the store that the record is ready to be interacted with recordWasLoaded: function (record) { this.recordArrayManager.recordWasLoaded(record); }, // ............... // . DESTRUCTION . // ............... /** When a record is destroyed, this un-indexes it and removes it from any record arrays so it can be GCed. @method _dematerializeRecord @private @param {InternalModel} internalModel */ _dematerializeRecord: function (internalModel) { var modelClass = internalModel.type; var typeMap = this.typeMapFor(modelClass); var id = internalModel.id; internalModel.updateRecordArrays(); if (id) { delete typeMap.idToRecord[id]; } var loc = typeMap.records.indexOf(internalModel); typeMap.records.splice(loc, 1); }, // ...................... // . PER-TYPE ADAPTERS // ...................... /** Returns an instance of the adapter for a given type. For example, `adapterFor('person')` will return an instance of `App.PersonAdapter`. If no `App.PersonAdapter` is found, this method will look for an `App.ApplicationAdapter` (the default adapter for your entire application). If no `App.ApplicationAdapter` is found, it will return the value of the `defaultAdapter`. @method adapterFor @public @param {String} modelName @return DS.Adapter */ adapterFor: function (modelName) { var normalizedModelName = (0, _emberDataPrivateSystemNormalizeModelName.default)(modelName); return this._instanceCache.get('adapter', normalizedModelName); }, _adapterRun: function (fn) { return this._backburner.run(fn); }, // .............................. // . RECORD CHANGE NOTIFICATION . // .............................. /** Returns an instance of the serializer for a given type. For example, `serializerFor('person')` will return an instance of `App.PersonSerializer`. If no `App.PersonSerializer` is found, this method will look for an `App.ApplicationSerializer` (the default serializer for your entire application). if no `App.ApplicationSerializer` is found, it will attempt to get the `defaultSerializer` from the `PersonAdapter` (`adapterFor('person')`). If a serializer cannot be found on the adapter, it will fall back to an instance of `DS.JSONSerializer`. @method serializerFor @public @param {String} modelName the record to serialize @return {DS.Serializer} */ serializerFor: function (modelName) { var normalizedModelName = (0, _emberDataPrivateSystemNormalizeModelName.default)(modelName); return this._instanceCache.get('serializer', normalizedModelName); }, lookupAdapter: function (name) { return this.adapterFor(name); }, lookupSerializer: function (name) { return this.serializerFor(name); }, willDestroy: function () { this._super.apply(this, arguments); this.recordArrayManager.destroy(); this._instanceCache.destroy(); this.unloadAll(); }, _pushResourceIdentifier: function (relationship, resourceIdentifier) { if (isNone(resourceIdentifier)) { return; } //TODO:Better asserts return this._internalModelForId(resourceIdentifier.type, resourceIdentifier.id); }, _pushResourceIdentifiers: function (relationship, resourceIdentifiers) { if (isNone(resourceIdentifiers)) { return; } var _internalModels = new Array(resourceIdentifiers.length); for (var i = 0; i < resourceIdentifiers.length; i++) { _internalModels[i] = this._pushResourceIdentifier(relationship, resourceIdentifiers[i]); } return _internalModels; } }); // Delegation to the adapter and promise management function defaultSerializer(store) { return store.serializerFor('application'); } function _commit(adapter, store, operation, snapshot) { var internalModel = snapshot._internalModel; var modelName = snapshot.modelName; var modelClass = store.modelFor(modelName); var promise = adapter[operation](store, modelClass, snapshot); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, modelName); var label = 'DS: Extract and notify about ' + operation + ' completion of ' + internalModel; promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, internalModel)); return promise.then(function (adapterPayload) { store._adapterRun(function () { var payload = undefined, data = undefined; if (adapterPayload) { payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, modelClass, adapterPayload, snapshot.id, operation); if (payload.included) { store.push({ data: payload.included }); } data = payload.data; } store.didSaveRecord(internalModel, { data: data }); }); return internalModel; }, function (error) { if (error instanceof _emberDataAdaptersErrors.InvalidError) { var errors = serializer.extractErrors(store, modelClass, error, snapshot.id); store.recordWasInvalid(internalModel, errors); } else { store.recordWasError(internalModel, error); } throw error; }, label); } function setupRelationships(store, record, data) { if (!data.relationships) { return; } record.type.eachRelationship(function (key, descriptor) { if (!data.relationships[key]) { return; } var relationship = record._relationships.get(key); relationship.push(data.relationships[key]); }); } exports.Store = Store; exports.default = Store; }); /** @module ember-data */ // If ENV.DS_WARN_ON_UNKNOWN_KEYS is set to true and the payload // contains unknown attributes or relationships, log a warning. // Check unknown attributes // Check unknown relationships define('ember-data/-private/system/store/common', ['exports', 'ember'], function (exports, _ember) { exports._bind = _bind; exports._guard = _guard; exports._objectIsAlive = _objectIsAlive; var get = _ember.default.get; function _bind(fn) { var args = Array.prototype.slice.call(arguments, 1); return function () { return fn.apply(undefined, args); }; } function _guard(promise, test) { var guarded = promise['finally'](function () { if (!test()) { guarded._subscribers.length = 0; } }); return guarded; } function _objectIsAlive(object) { return !(get(object, "isDestroyed") || get(object, "isDestroying")); } }); define('ember-data/-private/system/store/container-instance-cache', ['exports', 'ember', 'ember-data/-private/system/empty-object'], function (exports, _ember, _emberDataPrivateSystemEmptyObject) { var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var set = _ember.default.set; /* * The `ContainerInstanceCache` serves as a lazy cache for looking up * instances of serializers and adapters. It has some additional logic for * finding the 'fallback' adapter or serializer. * * The 'fallback' adapter or serializer is an adapter or serializer that is looked up * when the preferred lookup fails. For example, say you try to look up `adapter:post`, * but there is no entry (app/adapters/post.js in EmberCLI) for `adapter:post` in the registry. * * When an adapter or serializer is unfound, getFallbacks will be invoked with the current namespace * ('adapter' or 'serializer') and the 'preferredKey' (usually a modelName). The method should return * an array of keys to check against. * * The first entry in the fallbacks array that exists in the container will then be cached for * `adapter:post`. So, the next time you look up `adapter:post`, you'll get the `adapter:application` * instance (or whatever the fallback was if `adapter:application` doesn't exist). * * @private * @class ContainerInstanceCache * */ var ContainerInstanceCache = (function () { function ContainerInstanceCache(owner, store) { this._owner = owner; this._store = store; this._namespaces = { adapter: new _emberDataPrivateSystemEmptyObject.default(), serializer: new _emberDataPrivateSystemEmptyObject.default() }; } _createClass(ContainerInstanceCache, [{ key: 'get', value: function get(namespace, preferredKey) { var cache = this._namespaces[namespace]; if (cache[preferredKey]) { return cache[preferredKey]; } var preferredLookupKey = namespace + ':' + preferredKey; var instance = this._instanceFor(preferredLookupKey) || this._findInstance(namespace, this._fallbacksFor(namespace, preferredKey)); if (instance) { cache[preferredKey] = instance; set(instance, 'store', this._store); } return cache[preferredKey]; } }, { key: '_fallbacksFor', value: function _fallbacksFor(namespace, preferredKey) { if (namespace === 'adapter') { return ['application', this._store.get('adapter'), '-json-api']; } // serializer return ['application', this.get('adapter', preferredKey).get('defaultSerializer'), '-default']; } }, { key: '_findInstance', value: function _findInstance(namespace, fallbacks) { var cache = this._namespaces[namespace]; for (var i = 0, _length = fallbacks.length; i < _length; i++) { var fallback = fallbacks[i]; if (cache[fallback]) { return cache[fallback]; } var lookupKey = namespace + ':' + fallback; var instance = this._instanceFor(lookupKey); if (instance) { cache[fallback] = instance; return instance; } } } }, { key: '_instanceFor', value: function _instanceFor(key) { return this._owner.lookup(key); } }, { key: 'destroyCache', value: function destroyCache(cache) { var cacheEntries = Object.keys(cache); for (var i = 0, _length2 = cacheEntries.length; i < _length2; i++) { var cacheKey = cacheEntries[i]; var cacheEntry = cache[cacheKey]; if (cacheEntry) { cacheEntry.destroy(); } } } }, { key: 'destroy', value: function destroy() { this.destroyCache(this._namespaces.adapter); this.destroyCache(this._namespaces.serializer); this._namespaces = null; this._store = null; this._owner = null; } }, { key: 'toString', value: function toString() { return 'ContainerInstanceCache'; } }]); return ContainerInstanceCache; })(); exports.default = ContainerInstanceCache; }); /* global heimdall */ define("ember-data/-private/system/store/finders", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/store/common", "ember-data/-private/system/store/serializer-response", "ember-data/-private/system/store/serializers"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemStoreCommon, _emberDataPrivateSystemStoreSerializerResponse, _emberDataPrivateSystemStoreSerializers) { exports._find = _find; exports._findMany = _findMany; exports._findHasMany = _findHasMany; exports._findBelongsTo = _findBelongsTo; exports._findAll = _findAll; exports._query = _query; exports._queryRecord = _queryRecord; var Promise = _ember.default.RSVP.Promise; function payloadIsNotBlank(adapterPayload) { if (Array.isArray(adapterPayload)) { return true; } else { return Object.keys(adapterPayload || {}).length; } } function _find(adapter, store, typeClass, id, internalModel, options) { var snapshot = internalModel.createSnapshot(options); var promise = adapter.findRecord(store, typeClass, id, snapshot); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, internalModel.type.modelName); var label = "DS: Handle Adapter#findRecord of " + typeClass + " with id: " + id; promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); return promise.then(function (adapterPayload) { return store._adapterRun(function () { var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, id, 'findRecord'); var internalModel = store._push(payload); return internalModel; }); }, function (error) { internalModel.notFound(); if (internalModel.isEmpty()) { internalModel.unloadRecord(); } throw error; }, "DS: Extract payload of '" + typeClass + "'"); } function _findMany(adapter, store, typeClass, ids, internalModels) { var snapshots = _ember.default.A(internalModels).invoke('createSnapshot'); var promise = adapter.findMany(store, typeClass, ids, snapshots); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, typeClass.modelName); var label = "DS: Handle Adapter#findMany of " + typeClass; if (promise === undefined) { throw new Error('adapter.findMany returned undefined, this was very likely a mistake'); } promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); return promise.then(function (adapterPayload) { return store._adapterRun(function () { var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'findMany'); var internalModels = store._push(payload); return internalModels; }); }, null, "DS: Extract payload of " + typeClass); } function _findHasMany(adapter, store, internalModel, link, relationship) { var snapshot = internalModel.createSnapshot(); var typeClass = store.modelFor(relationship.type); var promise = adapter.findHasMany(store, snapshot, link, relationship); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, relationship.type); var label = "DS: Handle Adapter#findHasMany of " + internalModel + " : " + relationship.type; promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, internalModel)); return promise.then(function (adapterPayload) { return store._adapterRun(function () { var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'findHasMany'); //TODO Use a non record creating push var records = store.push(payload); var recordArray = records.map(function (record) { return record._internalModel; }); recordArray.meta = payload.meta; return recordArray; }); }, null, "DS: Extract payload of " + internalModel + " : hasMany " + relationship.type); } function _findBelongsTo(adapter, store, internalModel, link, relationship) { var snapshot = internalModel.createSnapshot(); var typeClass = store.modelFor(relationship.type); var promise = adapter.findBelongsTo(store, snapshot, link, relationship); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, relationship.type); var label = "DS: Handle Adapter#findBelongsTo of " + internalModel + " : " + relationship.type; promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, internalModel)); return promise.then(function (adapterPayload) { return store._adapterRun(function () { var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'findBelongsTo'); if (!payload.data) { return null; } var internalModel = store._push(payload); return internalModel; }); }, null, "DS: Extract payload of " + internalModel + " : " + relationship.type); } function _findAll(adapter, store, typeClass, sinceToken, options) { var modelName = typeClass.modelName; var recordArray = store.peekAll(modelName); var snapshotArray = recordArray._createSnapshot(options); var promise = adapter.findAll(store, typeClass, sinceToken, snapshotArray); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, modelName); var label = "DS: Handle Adapter#findAll of " + typeClass; promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); return promise.then(function (adapterPayload) { store._adapterRun(function () { var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'findAll'); store._push(payload); }); store.didUpdateAll(typeClass); return store.peekAll(modelName); }, null, "DS: Extract payload of findAll " + typeClass); } function _query(adapter, store, typeClass, query, recordArray) { var modelName = typeClass.modelName; var promise = adapter.query(store, typeClass, query, recordArray); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, modelName); var label = 'DS: Handle Adapter#query of ' + typeClass; promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); return promise.then(function (adapterPayload) { var internalModels = undefined, payload = undefined; store._adapterRun(function () { payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'query'); internalModels = store._push(payload); }); recordArray._setInternalModels(internalModels, payload); return recordArray; }, null, 'DS: Extract payload of query ' + typeClass); } function _queryRecord(adapter, store, typeClass, query) { var modelName = typeClass.modelName; var promise = adapter.queryRecord(store, typeClass, query); var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, modelName); var label = "DS: Handle Adapter#queryRecord of " + typeClass; promise = Promise.resolve(promise, label); promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); return promise.then(function (adapterPayload) { var internalModel; store._adapterRun(function () { var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'queryRecord'); internalModel = store._push(payload); }); return internalModel; }, null, "DS: Extract payload of queryRecord " + typeClass); } }); define('ember-data/-private/system/store/serializer-response', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { exports.validateDocumentStructure = validateDocumentStructure; exports.normalizeResponseHelper = normalizeResponseHelper; /* This is a helper method that validates a JSON API top-level document The format of a document is described here: http://jsonapi.org/format/#document-top-level @method validateDocumentStructure @param {Object} doc JSON API document @return {array} An array of errors found in the document structure */ function validateDocumentStructure(doc) { var errors = []; if (!doc || typeof doc !== 'object') { errors.push('Top level of a JSON API document must be an object'); } else { if (!('data' in doc) && !('errors' in doc) && !('meta' in doc)) { errors.push('One or more of the following keys must be present: "data", "errors", "meta".'); } else { if ('data' in doc && 'errors' in doc) { errors.push('Top level keys "errors" and "data" cannot both be present in a JSON API document'); } } if ('data' in doc) { if (!(doc.data === null || Array.isArray(doc.data) || typeof doc.data === 'object')) { errors.push('data must be null, an object, or an array'); } } if ('meta' in doc) { if (typeof doc.meta !== 'object') { errors.push('meta must be an object'); } } if ('errors' in doc) { if (!Array.isArray(doc.errors)) { errors.push('errors must be an array'); } } if ('links' in doc) { if (typeof doc.links !== 'object') { errors.push('links must be an object'); } } if ('jsonapi' in doc) { if (typeof doc.jsonapi !== 'object') { errors.push('jsonapi must be an object'); } } if ('included' in doc) { if (typeof doc.included !== 'object') { errors.push('included must be an array'); } } } return errors; } /* This is a helper method that always returns a JSON-API Document. @method normalizeResponseHelper @param {DS.Serializer} serializer @param {DS.Store} store @param {subclass of DS.Model} modelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ function normalizeResponseHelper(serializer, store, modelClass, payload, id, requestType) { var normalizedResponse = serializer.normalizeResponse(store, modelClass, payload, id, requestType); var validationErrors = []; return normalizedResponse; } }); define("ember-data/-private/system/store/serializers", ["exports"], function (exports) { exports.serializerForAdapter = serializerForAdapter; function serializerForAdapter(store, adapter, type) { var serializer = adapter.serializer; if (serializer === undefined) { serializer = store.serializerFor(type); } if (serializer === null || serializer === undefined) { serializer = { extract: function (store, type, payload) { return payload; } }; } return serializer; } }); define("ember-data/-private/transforms", ["exports", "ember-data/transform", "ember-data/-private/transforms/number", "ember-data/-private/transforms/date", "ember-data/-private/transforms/string", "ember-data/-private/transforms/boolean"], function (exports, _emberDataTransform, _emberDataPrivateTransformsNumber, _emberDataPrivateTransformsDate, _emberDataPrivateTransformsString, _emberDataPrivateTransformsBoolean) { exports.Transform = _emberDataTransform.default; exports.NumberTransform = _emberDataPrivateTransformsNumber.default; exports.DateTransform = _emberDataPrivateTransformsDate.default; exports.StringTransform = _emberDataPrivateTransformsString.default; exports.BooleanTransform = _emberDataPrivateTransformsBoolean.default; }); define("ember-data/-private/transforms/boolean", ["exports", "ember", "ember-data/transform"], function (exports, _ember, _emberDataTransform) { var isNone = _ember.default.isNone; /** The `DS.BooleanTransform` class is used to serialize and deserialize boolean attributes on Ember Data record objects. This transform is used when `boolean` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ isAdmin: DS.attr('boolean'), name: DS.attr('string'), email: DS.attr('string') }); ``` By default the boolean transform only allows for values of `true` or `false`. You can opt into allowing `null` values for boolean attributes via `DS.attr('boolean', { allowNull: true })` ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ email: DS.attr('string'), username: DS.attr('string'), wantsWeeklyEmail: DS.attr('boolean', { allowNull: true }) }); ``` @class BooleanTransform @extends DS.Transform @namespace DS */ exports.default = _emberDataTransform.default.extend({ deserialize: function (serialized, options) { var type = typeof serialized; if (isNone(serialized) && options.allowNull === true) { return null; } if (type === "boolean") { return serialized; } else if (type === "string") { return serialized.match(/^true$|^t$|^1$/i) !== null; } else if (type === "number") { return serialized === 1; } else { return false; } }, serialize: function (deserialized, options) { if (isNone(deserialized) && options.allowNull === true) { return null; } return Boolean(deserialized); } }); }); define("ember-data/-private/transforms/date", ["exports", "ember-data/-private/ext/date", "ember-data/transform"], function (exports, _emberDataPrivateExtDate, _emberDataTransform) { exports.default = _emberDataTransform.default.extend({ deserialize: function (serialized) { var type = typeof serialized; if (type === "string") { return new Date((0, _emberDataPrivateExtDate.parseDate)(serialized)); } else if (type === "number") { return new Date(serialized); } else if (serialized === null || serialized === undefined) { // if the value is null return null // if the value is not present in the data return undefined return serialized; } else { return null; } }, serialize: function (date) { if (date instanceof Date && !isNaN(date)) { return date.toISOString(); } else { return null; } } }); }); /** The `DS.DateTransform` class is used to serialize and deserialize date attributes on Ember Data record objects. This transform is used when `date` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. It uses the [`ISO 8601`](https://en.wikipedia.org/wiki/ISO_8601) standard. ```app/models/score.js import DS from 'ember-data'; export default DS.Model.extend({ value: DS.attr('number'), player: DS.belongsTo('player'), date: DS.attr('date') }); ``` @class DateTransform @extends DS.Transform @namespace DS */ define("ember-data/-private/transforms/number", ["exports", "ember", "ember-data/transform"], function (exports, _ember, _emberDataTransform) { var empty = _ember.default.isEmpty; function isNumber(value) { return value === value && value !== Infinity && value !== -Infinity; } /** The `DS.NumberTransform` class is used to serialize and deserialize numeric attributes on Ember Data record objects. This transform is used when `number` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```app/models/score.js import DS from 'ember-data'; export default DS.Model.extend({ value: DS.attr('number'), player: DS.belongsTo('player'), date: DS.attr('date') }); ``` @class NumberTransform @extends DS.Transform @namespace DS */ exports.default = _emberDataTransform.default.extend({ deserialize: function (serialized) { var transformed; if (empty(serialized)) { return null; } else { transformed = Number(serialized); return isNumber(transformed) ? transformed : null; } }, serialize: function (deserialized) { var transformed; if (empty(deserialized)) { return null; } else { transformed = Number(deserialized); return isNumber(transformed) ? transformed : null; } } }); }); define("ember-data/-private/transforms/string", ["exports", "ember", "ember-data/transform"], function (exports, _ember, _emberDataTransform) { var none = _ember.default.isNone; /** The `DS.StringTransform` class is used to serialize and deserialize string attributes on Ember Data record objects. This transform is used when `string` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ isAdmin: DS.attr('boolean'), name: DS.attr('string'), email: DS.attr('string') }); ``` @class StringTransform @extends DS.Transform @namespace DS */ exports.default = _emberDataTransform.default.extend({ deserialize: function (serialized) { return none(serialized) ? null : String(serialized); }, serialize: function (deserialized) { return none(deserialized) ? null : String(deserialized); } }); }); define('ember-data/-private/utils', ['exports', 'ember'], function (exports, _ember) { var get = _ember.default.get; /* Check if the passed model has a `type` attribute or a relationship named `type`. @method modelHasAttributeOrRelationshipNamedType @param modelClass */ function modelHasAttributeOrRelationshipNamedType(modelClass) { return get(modelClass, 'attributes').has('type') || get(modelClass, 'relationshipsByName').has('type'); } /* ember-container-inject-owner is a new feature in Ember 2.3 that finally provides a public API for looking items up. This function serves as a super simple polyfill to avoid triggering deprecations. */ function getOwner(context) { var owner; if (_ember.default.getOwner) { owner = _ember.default.getOwner(context); } if (!owner && context.container) { owner = context.container; } if (owner && owner.lookupFactory && !owner._lookupFactory) { // `owner` is a container, we are just making this work owner._lookupFactory = owner.lookupFactory; owner.register = function () { var registry = owner.registry || owner._registry || owner; return registry.register.apply(registry, arguments); }; } return owner; } exports.modelHasAttributeOrRelationshipNamedType = modelHasAttributeOrRelationshipNamedType; exports.getOwner = getOwner; }); define('ember-data/-private/utils/parse-response-headers', ['exports', 'ember-data/-private/system/empty-object'], function (exports, _emberDataPrivateSystemEmptyObject) { exports.default = parseResponseHeaders; function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } var CLRF = '\u000d\u000a'; function parseResponseHeaders(headersString) { var headers = new _emberDataPrivateSystemEmptyObject.default(); if (!headersString) { return headers; } var headerPairs = headersString.split(CLRF); headerPairs.forEach(function (header) { var _header$split = header.split(':'); var _header$split2 = _toArray(_header$split); var field = _header$split2[0]; var value = _header$split2.slice(1); field = field.trim(); value = value.join(':').trim(); if (value) { headers[field] = value; } }); return headers; } }); define('ember-data/adapter', ['exports', 'ember'], function (exports, _ember) { /** An adapter is an object that receives requests from a store and translates them into the appropriate action to take against your persistence layer. The persistence layer is usually an HTTP API, but may be anything, such as the browser's local storage. Typically the adapter is not invoked directly instead its functionality is accessed through the `store`. ### Creating an Adapter Create a new subclass of `DS.Adapter` in the `app/adapters` folder: ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ // ...your code here }); ``` Model-specific adapters can be created by putting your adapter class in an `app/adapters/` + `model-name` + `.js` file of the application. ```app/adapters/post.js import DS from 'ember-data'; export default DS.Adapter.extend({ // ...Post-specific adapter code goes here }); ``` `DS.Adapter` is an abstract base class that you should override in your application to customize it for your backend. The minimum set of methods that you should implement is: * `findRecord()` * `createRecord()` * `updateRecord()` * `deleteRecord()` * `findAll()` * `query()` To improve the network performance of your application, you can optimize your adapter by overriding these lower-level methods: * `findMany()` For an example implementation, see `DS.RESTAdapter`, the included REST adapter. @class Adapter @namespace DS @extends Ember.Object */ exports.default = _ember.default.Object.extend({ /** If you would like your adapter to use a custom serializer you can set the `defaultSerializer` property to be the name of the custom serializer. Note the `defaultSerializer` serializer has a lower priority than a model specific serializer (i.e. `PostSerializer`) or the `application` serializer. ```app/adapters/django.js import DS from 'ember-data'; export default DS.Adapter.extend({ defaultSerializer: 'django' }); ``` @property defaultSerializer @type {String} */ defaultSerializer: '-default', /** The `findRecord()` method is invoked when the store is asked for a record that has not previously been loaded. In response to `findRecord()` being called, you should query your persistence layer for a record with the given ID. The `findRecord` method should return a promise that will resolve to a JavaScript object that will be normalized by the serializer. Here is an example `findRecord` implementation: ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ findRecord: function(store, type, id, snapshot) { return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.getJSON(`/${type.modelName}/${id}`).then(function(data) { resolve(data); }, function(jqXHR) { reject(jqXHR); }); }); } }); ``` @method findRecord @param {DS.Store} store @param {DS.Model} type @param {String} id @param {DS.Snapshot} snapshot @return {Promise} promise */ findRecord: null, /** The `findAll()` method is used to retrieve all records for a given type. Example ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ findAll: function(store, type, sinceToken) { var query = { since: sinceToken }; return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.getJSON(`/${type.modelName}`, query).then(function(data) { resolve(data); }, function(jqXHR) { reject(jqXHR); }); }); } }); ``` @method findAll @param {DS.Store} store @param {DS.Model} type @param {String} sinceToken @param {DS.SnapshotRecordArray} snapshotRecordArray @return {Promise} promise */ findAll: null, /** This method is called when you call `query` on the store. Example ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ query: function(store, type, query) { return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.getJSON(`/${type.modelName}`, query).then(function(data) { resolve(data); }, function(jqXHR) { reject(jqXHR); }); }); } }); ``` @method query @param {DS.Store} store @param {DS.Model} type @param {Object} query @param {DS.AdapterPopulatedRecordArray} recordArray @return {Promise} promise */ query: null, /** The `queryRecord()` method is invoked when the store is asked for a single record through a query object. In response to `queryRecord()` being called, you should always fetch fresh data. Once found, you can asynchronously call the store's `push()` method to push the record into the store. Here is an example `queryRecord` implementation: Example ```app/adapters/application.js import DS from 'ember-data'; import Ember from 'ember'; export default DS.Adapter.extend(DS.BuildURLMixin, { queryRecord: function(store, type, query) { return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.getJSON(`/${type.modelName}`, query).then(function(data) { resolve(data); }, function(jqXHR) { reject(jqXHR); }); }); } }); ``` @method queryRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @return {Promise} promise */ queryRecord: null, /** If the globally unique IDs for your records should be generated on the client, implement the `generateIdForRecord()` method. This method will be invoked each time you create a new record, and the value returned from it will be assigned to the record's `primaryKey`. Most traditional REST-like HTTP APIs will not use this method. Instead, the ID of the record will be set by the server, and your adapter will update the store with the new ID when it calls `didCreateRecord()`. Only implement this method if you intend to generate record IDs on the client-side. The `generateIdForRecord()` method will be invoked with the requesting store as the first parameter and the newly created record as the second parameter: ```javascript import DS from 'ember-data'; import { v4 } from 'uuid'; export default DS.Adapter.extend({ generateIdForRecord: function(store, inputProperties) { return v4(); } }); ``` @method generateIdForRecord @param {DS.Store} store @param {DS.Model} type the DS.Model class of the record @param {Object} inputProperties a hash of properties to set on the newly created record. @return {(String|Number)} id */ generateIdForRecord: null, /** Proxies to the serializer's `serialize` method. Example ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ createRecord: function(store, type, snapshot) { var data = this.serialize(snapshot, { includeId: true }); var url = `/${type.modelName}`; // ... } }); ``` @method serialize @param {DS.Snapshot} snapshot @param {Object} options @return {Object} serialized snapshot */ serialize: function (snapshot, options) { return snapshot.serialize(options); }, /** Implement this method in a subclass to handle the creation of new records. Serializes the record and sends it to the server. Example ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ createRecord: function(store, type, snapshot) { var data = this.serialize(snapshot, { includeId: true }); return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.ajax({ type: 'POST', url: `/${type.modelName}`, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method createRecord @param {DS.Store} store @param {DS.Model} type the DS.Model class of the record @param {DS.Snapshot} snapshot @return {Promise} promise */ createRecord: null, /** Implement this method in a subclass to handle the updating of a record. Serializes the record update and sends it to the server. The updateRecord method is expected to return a promise that will resolve with the serialized record. This allows the backend to inform the Ember Data store the current state of this record after the update. If it is not possible to return a serialized record the updateRecord promise can also resolve with `undefined` and the Ember Data store will assume all of the updates were successfully applied on the backend. Example ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ updateRecord: function(store, type, snapshot) { var data = this.serialize(snapshot, { includeId: true }); var id = snapshot.id; return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.ajax({ type: 'PUT', url: `/${type.modelName}/${id}`, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method updateRecord @param {DS.Store} store @param {DS.Model} type the DS.Model class of the record @param {DS.Snapshot} snapshot @return {Promise} promise */ updateRecord: null, /** Implement this method in a subclass to handle the deletion of a record. Sends a delete request for the record to the server. Example ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ deleteRecord: function(store, type, snapshot) { var data = this.serialize(snapshot, { includeId: true }); var id = snapshot.id; return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.ajax({ type: 'DELETE', url: `/${type.modelName}/${id}`, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method deleteRecord @param {DS.Store} store @param {DS.Model} type the DS.Model class of the record @param {DS.Snapshot} snapshot @return {Promise} promise */ deleteRecord: null, /** By default the store will try to coalesce all `fetchRecord` calls within the same runloop into as few requests as possible by calling groupRecordsForFindMany and passing it into a findMany call. You can opt out of this behaviour by either not implementing the findMany hook or by setting coalesceFindRequests to false. @property coalesceFindRequests @type {boolean} */ coalesceFindRequests: true, /** The store will call `findMany` instead of multiple `findRecord` requests to find multiple records at once if coalesceFindRequests is true. ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ findMany(store, type, ids, snapshots) { return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.ajax({ type: 'GET', url: `/${type.modelName}/`, dataType: 'json', data: { filter: { id: ids.join(',') } } }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method findMany @param {DS.Store} store @param {DS.Model} type the DS.Model class of the records @param {Array} ids @param {Array} snapshots @return {Promise} promise */ findMany: null, /** Organize records into groups, each of which is to be passed to separate calls to `findMany`. For example, if your api has nested URLs that depend on the parent, you will want to group records by their parent. The default implementation returns the records as a single group. @method groupRecordsForFindMany @param {DS.Store} store @param {Array} snapshots @return {Array} an array of arrays of records, each of which is to be loaded separately by `findMany`. */ groupRecordsForFindMany: function (store, snapshots) { return [snapshots]; }, /** This method is used by the store to determine if the store should reload a record from the adapter when a record is requested by `store.findRecord`. If this method returns `true`, the store will re-fetch a record from the adapter. If this method returns `false`, the store will resolve immediately using the cached record. For example, if you are building an events ticketing system, in which users can only reserve tickets for 20 minutes at a time, and want to ensure that in each route you have data that is no more than 20 minutes old you could write: ```javascript shouldReloadRecord: function(store, ticketSnapshot) { var timeDiff = moment().diff(ticketSnapshot.attr('lastAccessedAt'), 'minutes'); if (timeDiff > 20) { return true; } else { return false; } } ``` This method would ensure that whenever you do `store.findRecord('ticket', id)` you will always get a ticket that is no more than 20 minutes old. In case the cached version is more than 20 minutes old, `findRecord` will not resolve until you fetched the latest version. By default this hook returns `false`, as most UIs should not block user interactions while waiting on data update. Note that, with default settings, `shouldBackgroundReloadRecord` will always re-fetch the records in the background even if `shouldReloadRecord` returns `false`. You can override `shouldBackgroundReloadRecord` if this does not suit your use case. @since 1.13.0 @method shouldReloadRecord @param {DS.Store} store @param {DS.Snapshot} snapshot @return {Boolean} */ shouldReloadRecord: function (store, snapshot) { return false; }, /** This method is used by the store to determine if the store should reload all records from the adapter when records are requested by `store.findAll`. If this method returns `true`, the store will re-fetch all records from the adapter. If this method returns `false`, the store will resolve immediately using the cached records. For example, if you are building an events ticketing system, in which users can only reserve tickets for 20 minutes at a time, and want to ensure that in each route you have data that is no more than 20 minutes old you could write: ```javascript shouldReloadAll: function(store, snapshotArray) { var snapshots = snapshotArray.snapshots(); return snapshots.any(function(ticketSnapshot) { var timeDiff = moment().diff(ticketSnapshot.attr('lastAccessedAt'), 'minutes'); if (timeDiff > 20) { return true; } else { return false; } }); } ``` This method would ensure that whenever you do `store.findAll('ticket')` you will always get a list of tickets that are no more than 20 minutes old. In case a cached version is more than 20 minutes old, `findAll` will not resolve until you fetched the latest versions. By default this methods returns `true` if the passed `snapshotRecordArray` is empty (meaning that there are no records locally available yet), otherwise it returns `false`. Note that, with default settings, `shouldBackgroundReloadAll` will always re-fetch all the records in the background even if `shouldReloadAll` returns `false`. You can override `shouldBackgroundReloadAll` if this does not suit your use case. @since 1.13.0 @method shouldReloadAll @param {DS.Store} store @param {DS.SnapshotRecordArray} snapshotRecordArray @return {Boolean} */ shouldReloadAll: function (store, snapshotRecordArray) { return !snapshotRecordArray.length; }, /** This method is used by the store to determine if the store should reload a record after the `store.findRecord` method resolves a cached record. This method is *only* checked by the store when the store is returning a cached record. If this method returns `true` the store will re-fetch a record from the adapter. For example, if you do not want to fetch complex data over a mobile connection, or if the network is down, you can implement `shouldBackgroundReloadRecord` as follows: ```javascript shouldBackgroundReloadRecord: function(store, snapshot) { var connection = window.navigator.connection; if (connection === 'cellular' || connection === 'none') { return false; } else { return true; } } ``` By default this hook returns `true` so the data for the record is updated in the background. @since 1.13.0 @method shouldBackgroundReloadRecord @param {DS.Store} store @param {DS.Snapshot} snapshot @return {Boolean} */ shouldBackgroundReloadRecord: function (store, snapshot) { return true; }, /** This method is used by the store to determine if the store should reload a record array after the `store.findAll` method resolves with a cached record array. This method is *only* checked by the store when the store is returning a cached record array. If this method returns `true` the store will re-fetch all records from the adapter. For example, if you do not want to fetch complex data over a mobile connection, or if the network is down, you can implement `shouldBackgroundReloadAll` as follows: ```javascript shouldBackgroundReloadAll: function(store, snapshotArray) { var connection = window.navigator.connection; if (connection === 'cellular' || connection === 'none') { return false; } else { return true; } } ``` By default this method returns `true`, indicating that a background reload should always be triggered. @since 1.13.0 @method shouldBackgroundReloadAll @param {DS.Store} store @param {DS.SnapshotRecordArray} snapshotRecordArray @return {Boolean} */ shouldBackgroundReloadAll: function (store, snapshotRecordArray) { return true; } }); }); /** @module ember-data */ define('ember-data/adapters/errors', ['exports', 'ember', 'ember-data/-private/debug', 'ember-data/-private/features'], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateFeatures) { exports.AdapterError = AdapterError; exports.errorsHashToArray = errorsHashToArray; exports.errorsArrayToHash = errorsArrayToHash; var EmberError = _ember.default.Error; var SOURCE_POINTER_REGEXP = /^\/?data\/(attributes|relationships)\/(.*)/; var SOURCE_POINTER_PRIMARY_REGEXP = /^\/?data/; var PRIMARY_ATTRIBUTE_KEY = 'base'; /** A `DS.AdapterError` is used by an adapter to signal that an error occurred during a request to an external API. It indicates a generic error, and subclasses are used to indicate specific error states. The following subclasses are provided: - `DS.InvalidError` - `DS.TimeoutError` - `DS.AbortError` - `DS.UnauthorizedError` - `DS.ForbiddenError` - `DS.NotFoundError` - `DS.ConflictError` - `DS.ServerError` To create a custom error to signal a specific error state in communicating with an external API, extend the `DS.AdapterError`. For example if the external API exclusively used HTTP `503 Service Unavailable` to indicate it was closed for maintenance: ```app/adapters/maintenance-error.js import DS from 'ember-data'; export default DS.AdapterError.extend({ message: "Down for maintenance." }); ``` This error would then be returned by an adapter's `handleResponse` method: ```app/adapters/application.js import DS from 'ember-data'; import MaintenanceError from './maintenance-error'; export default DS.JSONAPIAdapter.extend({ handleResponse(status) { if (503 === status) { return new MaintenanceError(); } return this._super(...arguments); } }); ``` And can then be detected in an application and used to send the user to an `under-maintenance` route: ```app/routes/application.js import Ember from 'ember'; import MaintenanceError from '../adapters/maintenance-error'; export default Ember.Route.extend({ actions: { error(error, transition) { if (error instanceof MaintenanceError) { this.transitionTo('under-maintenance'); return; } // ...other error handling logic } } }); ``` @class AdapterError @namespace DS */ function AdapterError(errors) { var message = arguments.length <= 1 || arguments[1] === undefined ? 'Adapter operation failed' : arguments[1]; this.isAdapterError = true; EmberError.call(this, message); this.errors = errors || [{ title: 'Adapter Error', detail: message }]; } var extendedErrorsEnabled = false; if (false) { extendedErrorsEnabled = true; } function extendFn(ErrorClass) { return function () { var _ref = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var defaultMessage = _ref.message; return extend(ErrorClass, defaultMessage); }; } function extend(ParentErrorClass, defaultMessage) { var ErrorClass = function (errors, message) { ParentErrorClass.call(this, errors, message || defaultMessage); }; ErrorClass.prototype = Object.create(ParentErrorClass.prototype); if (extendedErrorsEnabled) { ErrorClass.extend = extendFn(ErrorClass); } return ErrorClass; } AdapterError.prototype = Object.create(EmberError.prototype); if (extendedErrorsEnabled) { AdapterError.extend = extendFn(AdapterError); } /** A `DS.InvalidError` is used by an adapter to signal the external API was unable to process a request because the content was not semantically correct or meaningful per the API. Usually this means a record failed some form of server side validation. When a promise from an adapter is rejected with a `DS.InvalidError` the record will transition to the `invalid` state and the errors will be set to the `errors` property on the record. For Ember Data to correctly map errors to their corresponding properties on the model, Ember Data expects each error to be a valid json-api error object with a `source/pointer` that matches the property name. For example if you had a Post model that looked like this. ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ title: DS.attr('string'), content: DS.attr('string') }); ``` To show an error from the server related to the `title` and `content` properties your adapter could return a promise that rejects with a `DS.InvalidError` object that looks like this: ```app/adapters/post.js import Ember from 'ember'; import DS from 'ember-data'; export default DS.RESTAdapter.extend({ updateRecord: function() { // Fictional adapter that always rejects return Ember.RSVP.reject(new DS.InvalidError([ { detail: 'Must be unique', source: { pointer: '/data/attributes/title' } }, { detail: 'Must not be blank', source: { pointer: '/data/attributes/content'} } ])); } }); ``` Your backend may use different property names for your records the store will attempt extract and normalize the errors using the serializer's `extractErrors` method before the errors get added to the the model. As a result, it is safe for the `InvalidError` to wrap the error payload unaltered. @class InvalidError @namespace DS */ var InvalidError = extend(AdapterError, 'The adapter rejected the commit because it was invalid'); exports.InvalidError = InvalidError; /** A `DS.TimeoutError` is used by an adapter to signal that a request to the external API has timed out. I.e. no response was received from the external API within an allowed time period. An example use case would be to warn the user to check their internet connection if an adapter operation has timed out: ```app/routes/application.js import Ember from 'ember'; import DS from 'ember-data'; const { TimeoutError } = DS; export default Ember.Route.extend({ actions: { error(error, transition) { if (error instanceof TimeoutError) { // alert the user alert('Are you still connected to the internet?'); return; } // ...other error handling logic } } }); ``` @class TimeoutError @namespace DS */ var TimeoutError = extend(AdapterError, 'The adapter operation timed out'); exports.TimeoutError = TimeoutError; /** A `DS.AbortError` is used by an adapter to signal that a request to the external API was aborted. For example, this can occur if the user navigates away from the current page after a request to the external API has been initiated but before a response has been received. @class AbortError @namespace DS */ var AbortError = extend(AdapterError, 'The adapter operation was aborted'); exports.AbortError = AbortError; /** A `DS.UnauthorizedError` equates to a HTTP `401 Unauthorized` response status. It is used by an adapter to signal that a request to the external API was rejected because authorization is required and has failed or has not yet been provided. An example use case would be to redirect the user to a log in route if a request is unauthorized: ```app/routes/application.js import Ember from 'ember'; import DS from 'ember-data'; const { UnauthorizedError } = DS; export default Ember.Route.extend({ actions: { error(error, transition) { if (error instanceof UnauthorizedError) { // go to the sign in route this.transitionTo('login'); return; } // ...other error handling logic } } }); ``` @class UnauthorizedError @namespace DS */ var UnauthorizedError = extendedErrorsEnabled ? extend(AdapterError, 'The adapter operation is unauthorized') : null; exports.UnauthorizedError = UnauthorizedError; /** A `DS.ForbiddenError` equates to a HTTP `403 Forbidden` response status. It is used by an adapter to signal that a request to the external API was valid but the server is refusing to respond to it. If authorization was provided and is valid, then the authenticated user does not have the necessary permissions for the request. @class ForbiddenError @namespace DS */ var ForbiddenError = extendedErrorsEnabled ? extend(AdapterError, 'The adapter operation is forbidden') : null; exports.ForbiddenError = ForbiddenError; /** A `DS.NotFoundError` equates to a HTTP `404 Not Found` response status. It is used by an adapter to signal that a request to the external API was rejected because the resource could not be found on the API. An example use case would be to detect if the user has entered a route for a specific model that does not exist. For example: ```app/routes/post.js import Ember from 'ember'; import DS from 'ember-data'; const { NotFoundError } = DS; export default Ember.Route.extend({ model(params) { return this.get('store').findRecord('post', params.post_id); }, actions: { error(error, transition) { if (error instanceof NotFoundError) { // redirect to a list of all posts instead this.transitionTo('posts'); } else { // otherwise let the error bubble return true; } } } }); ``` @class NotFoundError @namespace DS */ var NotFoundError = extendedErrorsEnabled ? extend(AdapterError, 'The adapter could not find the resource') : null; exports.NotFoundError = NotFoundError; /** A `DS.ConflictError` equates to a HTTP `409 Conflict` response status. It is used by an adapter to indicate that the request could not be processed because of a conflict in the request. An example scenario would be when creating a record with a client generated id but that id is already known to the external API. @class ConflictError @namespace DS */ var ConflictError = extendedErrorsEnabled ? extend(AdapterError, 'The adapter operation failed due to a conflict') : null; exports.ConflictError = ConflictError; /** A `DS.ServerError` equates to a HTTP `500 Internal Server Error` response status. It is used by the adapter to indicate that a request has failed because of an error in the external API. @class ServerError @namespace DS */ var ServerError = extendedErrorsEnabled ? extend(AdapterError, 'The adapter operation failed due to a server error') : null; exports.ServerError = ServerError; /** Convert an hash of errors into an array with errors in JSON-API format. ```javascript import DS from 'ember-data'; const { errorsHashToArray } = DS; let errors = { base: "Invalid attributes on saving this record", name: "Must be present", age: ["Must be present", "Must be a number"] }; let errorsArray = errorsHashToArray(errors); // [ // { // title: "Invalid Document", // detail: "Invalid attributes on saving this record", // source: { pointer: "/data" } // }, // { // title: "Invalid Attribute", // detail: "Must be present", // source: { pointer: "/data/attributes/name" } // }, // { // title: "Invalid Attribute", // detail: "Must be present", // source: { pointer: "/data/attributes/age" } // }, // { // title: "Invalid Attribute", // detail: "Must be a number", // source: { pointer: "/data/attributes/age" } // } // ] ``` @method errorsHashToArray @public @namespace @for DS @param {Object} errors hash with errors as properties @return {Array} array of errors in JSON-API format */ function errorsHashToArray(errors) { var out = []; if (_ember.default.isPresent(errors)) { Object.keys(errors).forEach(function (key) { var messages = _ember.default.makeArray(errors[key]); for (var i = 0; i < messages.length; i++) { var title = 'Invalid Attribute'; var pointer = '/data/attributes/' + key; if (key === PRIMARY_ATTRIBUTE_KEY) { title = 'Invalid Document'; pointer = '/data'; } out.push({ title: title, detail: messages[i], source: { pointer: pointer } }); } }); } return out; } /** Convert an array of errors in JSON-API format into an object. ```javascript import DS from 'ember-data'; const { errorsArrayToHash } = DS; let errorsArray = [ { title: "Invalid Attribute", detail: "Must be present", source: { pointer: "/data/attributes/name" } }, { title: "Invalid Attribute", detail: "Must be present", source: { pointer: "/data/attributes/age" } }, { title: "Invalid Attribute", detail: "Must be a number", source: { pointer: "/data/attributes/age" } } ]; let errors = errorsArrayToHash(errorsArray); // { // "name": ["Must be present"], // "age": ["Must be present", "must be a number"] // } ``` @method errorsArrayToHash @public @namespace @for DS @param {Array} errors array of errors in JSON-API format @return {Object} */ function errorsArrayToHash(errors) { var out = {}; if (_ember.default.isPresent(errors)) { errors.forEach(function (error) { if (error.source && error.source.pointer) { var key = error.source.pointer.match(SOURCE_POINTER_REGEXP); if (key) { key = key[2]; } else if (error.source.pointer.search(SOURCE_POINTER_PRIMARY_REGEXP) !== -1) { key = PRIMARY_ATTRIBUTE_KEY; } if (key) { out[key] = out[key] || []; out[key].push(error.detail || error.title); } } }); } return out; } }); define('ember-data/adapters/json-api', ['exports', 'ember', 'ember-data/adapters/rest', 'ember-data/-private/features', 'ember-data/-private/debug'], function (exports, _ember, _emberDataAdaptersRest, _emberDataPrivateFeatures, _emberDataPrivateDebug) { /** The `JSONAPIAdapter` is the default adapter used by Ember Data. It is responsible for transforming the store's requests into HTTP requests that follow the [JSON API](http://jsonapi.org/format/) format. ## JSON API Conventions The JSONAPIAdapter uses JSON API conventions for building the url for a record and selecting the HTTP verb to use with a request. The actions you can take on a record map onto the following URLs in the JSON API adapter: <table> <tr> <th> Action </th> <th> HTTP Verb </th> <th> URL </th> </tr> <tr> <th> `store.findRecord('post', 123)` </th> <td> GET </td> <td> /posts/123 </td> </tr> <tr> <th> `store.findAll('post')` </th> <td> GET </td> <td> /posts </td> </tr> <tr> <th> Update `postRecord.save()` </th> <td> PATCH </td> <td> /posts/123 </td> </tr> <tr> <th> Create `store.createRecord('post').save()` </th> <td> POST </td> <td> /posts </td> </tr> <tr> <th> Delete `postRecord.destroyRecord()` </th> <td> DELETE </td> <td> /posts/123 </td> </tr> </table> ## Success and failure The JSONAPIAdapter will consider a success any response with a status code of the 2xx family ("Success"), as well as 304 ("Not Modified"). Any other status code will be considered a failure. On success, the request promise will be resolved with the full response payload. Failed responses with status code 422 ("Unprocessable Entity") will be considered "invalid". The response will be discarded, except for the `errors` key. The request promise will be rejected with a `DS.InvalidError`. This error object will encapsulate the saved `errors` value. Any other status codes will be treated as an adapter error. The request promise will be rejected, similarly to the invalid case, but with an instance of `DS.AdapterError` instead. ### Endpoint path customization Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```app/adapters/application.js import DS from 'ember-data'; export default DS.JSONAPIAdapter.extend({ namespace: 'api/1' }); ``` Requests for the `person` model would now target `/api/1/people/1`. ### Host customization An adapter can target other hosts by setting the `host` property. ```app/adapters/application.js import DS from 'ember-data'; export default DS.JSONAPIAdapter.extend({ host: 'https://api.example.com' }); ``` Requests for the `person` model would now target `https://api.example.com/people/1`. @since 1.13.0 @class JSONAPIAdapter @constructor @namespace DS @extends DS.RESTAdapter */ var JSONAPIAdapter = _emberDataAdaptersRest.default.extend({ defaultSerializer: '-json-api', /** @method ajaxOptions @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} options @return {Object} */ ajaxOptions: function (url, type, options) { var hash = this._super.apply(this, arguments); if (hash.contentType) { hash.contentType = 'application/vnd.api+json'; } var beforeSend = hash.beforeSend; hash.beforeSend = function (xhr) { xhr.setRequestHeader('Accept', 'application/vnd.api+json'); if (beforeSend) { beforeSend(xhr); } }; return hash; }, /** By default the JSONAPIAdapter will send each find request coming from a `store.find` or from accessing a relationship separately to the server. If your server supports passing ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests within a single runloop. For example, if you have an initial payload of: ```javascript { data: { id: 1, type: 'post', relationship: { comments: { data: [ { id: 1, type: 'comment' }, { id: 2, type: 'comment' } ] } } } } ``` By default calling `post.get('comments')` will trigger the following requests(assuming the comments haven't been loaded before): ``` GET /comments/1 GET /comments/2 ``` If you set coalesceFindRequests to `true` it will instead trigger the following request: ``` GET /comments?filter[id]=1,2 ``` Setting coalesceFindRequests to `true` also works for `store.find` requests and `belongsTo` relationships accessed within the same runloop. If you set `coalesceFindRequests: true` ```javascript store.findRecord('comment', 1); store.findRecord('comment', 2); ``` will also send a request to: `GET /comments?filter[id]=1,2` Note: Requests coalescing rely on URL building strategy. So if you override `buildURL` in your app `groupRecordsForFindMany` more likely should be overridden as well in order for coalescing to work. @property coalesceFindRequests @type {boolean} */ coalesceFindRequests: false, findMany: function (store, type, ids, snapshots) { if (false && !this._hasCustomizedAjax()) { return this._super.apply(this, arguments); } else { var url = this.buildURL(type.modelName, ids, snapshots, 'findMany'); return this.ajax(url, 'GET', { data: { filter: { id: ids.join(',') } } }); } }, pathForType: function (modelName) { var dasherized = _ember.default.String.dasherize(modelName); return _ember.default.String.pluralize(dasherized); }, // TODO: Remove this once we have a better way to override HTTP verbs. updateRecord: function (store, type, snapshot) { if (false && !this._hasCustomizedAjax()) { return this._super.apply(this, arguments); } else { var data = {}; var serializer = store.serializerFor(type.modelName); serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); var id = snapshot.id; var url = this.buildURL(type.modelName, id, snapshot, 'updateRecord'); return this.ajax(url, 'PATCH', { data: data }); } }, _hasCustomizedAjax: function () { if (this.ajax !== JSONAPIAdapter.prototype.ajax) { return true; } if (this.ajaxOptions !== JSONAPIAdapter.prototype.ajaxOptions) { return true; } return false; } }); if (false) { JSONAPIAdapter.reopen({ methodForRequest: function (params) { if (params.requestType === 'updateRecord') { return 'PATCH'; } return this._super.apply(this, arguments); }, dataForRequest: function (params) { var requestType = params.requestType; var ids = params.ids; if (requestType === 'findMany') { return { filter: { id: ids.join(',') } }; } if (requestType === 'updateRecord') { var store = params.store; var type = params.type; var snapshot = params.snapshot; var data = {}; var serializer = store.serializerFor(type.modelName); serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); return data; } return this._super.apply(this, arguments); }, headersForRequest: function () { var headers = this._super.apply(this, arguments) || {}; headers['Accept'] = 'application/vnd.api+json'; return headers; }, _requestToJQueryAjaxHash: function () { var hash = this._super.apply(this, arguments); if (hash.contentType) { hash.contentType = 'application/vnd.api+json'; } return hash; } }); } exports.default = JSONAPIAdapter; }); /* global heimdall */ /** @module ember-data */ define('ember-data/adapters/rest', ['exports', 'ember', 'ember-data/adapter', 'ember-data/adapters/errors', 'ember-data/-private/adapters/build-url-mixin', 'ember-data/-private/features', 'ember-data/-private/debug', 'ember-data/-private/utils/parse-response-headers'], function (exports, _ember, _emberDataAdapter, _emberDataAdaptersErrors, _emberDataPrivateAdaptersBuildUrlMixin, _emberDataPrivateFeatures, _emberDataPrivateDebug, _emberDataPrivateUtilsParseResponseHeaders) { var MapWithDefault = _ember.default.MapWithDefault; var get = _ember.default.get; var Promise = _ember.default.RSVP.Promise; /** The REST adapter allows your store to communicate with an HTTP server by transmitting JSON via XHR. Most Ember.js apps that consume a JSON API should use the REST adapter. This adapter is designed around the idea that the JSON exchanged with the server should be conventional. ## Success and failure The REST adapter will consider a success any response with a status code of the 2xx family ("Success"), as well as 304 ("Not Modified"). Any other status code will be considered a failure. On success, the request promise will be resolved with the full response payload. Failed responses with status code 422 ("Unprocessable Entity") will be considered "invalid". The response will be discarded, except for the `errors` key. The request promise will be rejected with a `DS.InvalidError`. This error object will encapsulate the saved `errors` value. Any other status codes will be treated as an "adapter error". The request promise will be rejected, similarly to the "invalid" case, but with an instance of `DS.AdapterError` instead. ## JSON Structure The REST adapter expects the JSON returned from your server to follow these conventions. ### Object Root The JSON payload should be an object that contains the record inside a root property. For example, in response to a `GET` request for `/posts/1`, the JSON should look like this: ```js { "posts": { "id": 1, "title": "I'm Running to Reform the W3C's Tag", "author": "Yehuda Katz" } } ``` Similarly, in response to a `GET` request for `/posts`, the JSON should look like this: ```js { "posts": [ { "id": 1, "title": "I'm Running to Reform the W3C's Tag", "author": "Yehuda Katz" }, { "id": 2, "title": "Rails is omakase", "author": "D2H" } ] } ``` Note that the object root can be pluralized for both a single-object response and an array response: the REST adapter is not strict on this. Further, if the HTTP server responds to a `GET` request to `/posts/1` (e.g. the response to a `findRecord` query) with more than one object in the array, Ember Data will only display the object with the matching ID. ### Conventional Names Attribute names in your JSON payload should be the camelCased versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "people": { "id": 5, "firstName": "Barack", "lastName": "Obama", "occupation": "President" } } ``` #### Relationships Relationships are usually represented by ids to the record in the relationship. The related records can then be sideloaded in the response under a key for the type. ```js { "posts": { "id": 5, "title": "I'm Running to Reform the W3C's Tag", "author": "Yehuda Katz", "comments": [1, 2] }, "comments": [{ "id": 1, "author": "User 1", "message": "First!", }, { "id": 2, "author": "User 2", "message": "Good Luck!", }] } ``` If the records in the relationship are not known when the response is serialized its also possible to represent the relationship as a url using the `links` key in the response. Ember Data will fetch this url to resolve the relationship when it is accessed for the first time. ```js { "posts": { "id": 5, "title": "I'm Running to Reform the W3C's Tag", "author": "Yehuda Katz", "links": { "comments": "/posts/5/comments" } } } ``` ### Errors If a response is considered a failure, the JSON payload is expected to include a top-level key `errors`, detailing any specific issues. For example: ```js { "errors": { "msg": "Something went wrong" } } ``` This adapter does not make any assumptions as to the format of the `errors` object. It will simply be passed along as is, wrapped in an instance of `DS.InvalidError` or `DS.AdapterError`. The serializer can interpret it afterwards. ## Customization ### Endpoint path customization Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ namespace: 'api/1' }); ``` Requests for the `Person` model would now target `/api/1/people/1`. ### Host customization An adapter can target other hosts by setting the `host` property. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ host: 'https://api.example.com' }); ``` ### Headers customization Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary headers can be set as key/value pairs on the `RESTAdapter`'s `headers` object and Ember Data will send them along with each ajax request. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ headers: { "API_KEY": "secret key", "ANOTHER_HEADER": "Some header value" } }); ``` `headers` can also be used as a computed property to support dynamic headers. In the example below, the `session` object has been injected into an adapter by Ember's container. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ headers: Ember.computed('session.authToken', function() { return { "API_KEY": this.get("session.authToken"), "ANOTHER_HEADER": "Some header value" }; }) }); ``` In some cases, your dynamic headers may require data from some object outside of Ember's observer system (for example `document.cookie`). You can use the [volatile](/api/classes/Ember.ComputedProperty.html#method_volatile) function to set the property into a non-cached mode causing the headers to be recomputed with every request. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ headers: Ember.computed(function() { return { "API_KEY": Ember.get(document.cookie.match(/apiKey\=([^;]*)/), "1"), "ANOTHER_HEADER": "Some header value" }; }).volatile() }); ``` @class RESTAdapter @constructor @namespace DS @extends DS.Adapter @uses DS.BuildURLMixin */ var RESTAdapter = _emberDataAdapter.default.extend(_emberDataPrivateAdaptersBuildUrlMixin.default, { defaultSerializer: '-rest', /** By default, the RESTAdapter will send the query params sorted alphabetically to the server. For example: ```js store.query('posts', { sort: 'price', category: 'pets' }); ``` will generate a requests like this `/posts?category=pets&sort=price`, even if the parameters were specified in a different order. That way the generated URL will be deterministic and that simplifies caching mechanisms in the backend. Setting `sortQueryParams` to a falsey value will respect the original order. In case you want to sort the query parameters with a different criteria, set `sortQueryParams` to your custom sort function. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ sortQueryParams: function(params) { var sortedKeys = Object.keys(params).sort().reverse(); var len = sortedKeys.length, newParams = {}; for (var i = 0; i < len; i++) { newParams[sortedKeys[i]] = params[sortedKeys[i]]; } return newParams; } }); ``` @method sortQueryParams @param {Object} obj @return {Object} */ sortQueryParams: function (obj) { var keys = Object.keys(obj); var len = keys.length; if (len < 2) { return obj; } var newQueryParams = {}; var sortedKeys = keys.sort(); for (var i = 0; i < len; i++) { newQueryParams[sortedKeys[i]] = obj[sortedKeys[i]]; } return newQueryParams; }, /** By default the RESTAdapter will send each find request coming from a `store.find` or from accessing a relationship separately to the server. If your server supports passing ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests within a single runloop. For example, if you have an initial payload of: ```javascript { post: { id: 1, comments: [1, 2] } } ``` By default calling `post.get('comments')` will trigger the following requests(assuming the comments haven't been loaded before): ``` GET /comments/1 GET /comments/2 ``` If you set coalesceFindRequests to `true` it will instead trigger the following request: ``` GET /comments?ids[]=1&ids[]=2 ``` Setting coalesceFindRequests to `true` also works for `store.find` requests and `belongsTo` relationships accessed within the same runloop. If you set `coalesceFindRequests: true` ```javascript store.findRecord('comment', 1); store.findRecord('comment', 2); ``` will also send a request to: `GET /comments?ids[]=1&ids[]=2` Note: Requests coalescing rely on URL building strategy. So if you override `buildURL` in your app `groupRecordsForFindMany` more likely should be overridden as well in order for coalescing to work. @property coalesceFindRequests @type {boolean} */ coalesceFindRequests: false, /** Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ namespace: 'api/1' }); ``` Requests for the `Post` model would now target `/api/1/post/`. @property namespace @type {String} */ /** An adapter can target other hosts by setting the `host` property. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ host: 'https://api.example.com' }); ``` Requests for the `Post` model would now target `https://api.example.com/post/`. @property host @type {String} */ /** Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary headers can be set as key/value pairs on the `RESTAdapter`'s `headers` object and Ember Data will send them along with each ajax request. For dynamic headers see [headers customization](/api/data/classes/DS.RESTAdapter.html#toc_headers-customization). ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ headers: { "API_KEY": "secret key", "ANOTHER_HEADER": "Some header value" } }); ``` @property headers @type {Object} */ /** Called by the store in order to fetch the JSON for a given type and ID. The `findRecord` method makes an Ajax request to a URL computed by `buildURL`, and returns a promise for the resulting payload. This method performs an HTTP `GET` request with the id provided as part of the query string. @since 1.13.0 @method findRecord @param {DS.Store} store @param {DS.Model} type @param {String} id @param {DS.Snapshot} snapshot @return {Promise} promise */ findRecord: function (store, type, id, snapshot) { if (false && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, id: id, snapshot: snapshot, requestType: 'findRecord' }); return this._makeRequest(request); } else { var url = this.buildURL(type.modelName, id, snapshot, 'findRecord'); var query = this.buildQuery(snapshot); return this.ajax(url, 'GET', { data: query }); } }, /** Called by the store in order to fetch a JSON array for all of the records for a given type. The `findAll` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @method findAll @param {DS.Store} store @param {DS.Model} type @param {String} sinceToken @param {DS.SnapshotRecordArray} snapshotRecordArray @return {Promise} promise */ findAll: function (store, type, sinceToken, snapshotRecordArray) { var query = this.buildQuery(snapshotRecordArray); if (false && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, sinceToken: sinceToken, query: query, snapshots: snapshotRecordArray, requestType: 'findAll' }); return this._makeRequest(request); } else { var url = this.buildURL(type.modelName, null, snapshotRecordArray, 'findAll'); if (sinceToken) { query.since = sinceToken; } return this.ajax(url, 'GET', { data: query }); } }, /** Called by the store in order to fetch a JSON array for the records that match a particular query. The `query` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. The `query` argument is a simple JavaScript object that will be passed directly to the server as parameters. @method query @param {DS.Store} store @param {DS.Model} type @param {Object} query @return {Promise} promise */ query: function (store, type, query) { if (false && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, query: query, requestType: 'query' }); return this._makeRequest(request); } else { var url = this.buildURL(type.modelName, null, null, 'query', query); if (this.sortQueryParams) { query = this.sortQueryParams(query); } return this.ajax(url, 'GET', { data: query }); } }, /** Called by the store in order to fetch a JSON object for the record that matches a particular query. The `queryRecord` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. The `query` argument is a simple JavaScript object that will be passed directly to the server as parameters. @since 1.13.0 @method queryRecord @param {DS.Store} store @param {DS.Model} type @param {Object} query @return {Promise} promise */ queryRecord: function (store, type, query) { if (false && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, query: query, requestType: 'queryRecord' }); return this._makeRequest(request); } else { var url = this.buildURL(type.modelName, null, null, 'queryRecord', query); if (this.sortQueryParams) { query = this.sortQueryParams(query); } return this.ajax(url, 'GET', { data: query }); } }, /** Called by the store in order to fetch several records together if `coalesceFindRequests` is true For example, if the original payload looks like: ```js { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2, 3 ] } ``` The IDs will be passed as a URL-encoded Array of IDs, in this form: ``` ids[]=1&ids[]=2&ids[]=3 ``` Many servers, such as Rails and PHP, will automatically convert this URL-encoded array into an Array for you on the server-side. If you want to encode the IDs, differently, just override this (one-line) method. The `findMany` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @method findMany @param {DS.Store} store @param {DS.Model} type @param {Array} ids @param {Array} snapshots @return {Promise} promise */ findMany: function (store, type, ids, snapshots) { if (false && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, ids: ids, snapshots: snapshots, requestType: 'findMany' }); return this._makeRequest(request); } else { var url = this.buildURL(type.modelName, ids, snapshots, 'findMany'); return this.ajax(url, 'GET', { data: { ids: ids } }); } }, /** Called by the store in order to fetch a JSON array for the unloaded records in a has-many relationship that were originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "comments": "/posts/1/comments" } } } ``` This method will be called with the parent record and `/posts/1/comments`. The `findHasMany` method will make an Ajax (HTTP GET) request to the originally specified URL. The format of your `links` value will influence the final request URL via the `urlPrefix` method: * Links beginning with `//`, `http://`, `https://`, will be used as is, with no further manipulation. * Links beginning with a single `/` will have the current adapter's `host` value prepended to it. * Links with no beginning `/` will have a parentURL prepended to it, via the current adapter's `buildURL`. @method findHasMany @param {DS.Store} store @param {DS.Snapshot} snapshot @param {Object} relationship meta object describing the relationship @param {String} url @return {Promise} promise */ findHasMany: function (store, snapshot, url, relationship) { if (false && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, snapshot: snapshot, url: url, relationship: relationship, requestType: 'findHasMany' }); return this._makeRequest(request); } else { var id = snapshot.id; var type = snapshot.modelName; url = this.urlPrefix(url, this.buildURL(type, id, snapshot, 'findHasMany')); return this.ajax(url, 'GET'); } }, /** Called by the store in order to fetch the JSON for the unloaded record in a belongs-to relationship that was originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "person": { "id": 1, "name": "Tom Dale", "links": { "group": "/people/1/group" } } } ``` This method will be called with the parent record and `/people/1/group`. The `findBelongsTo` method will make an Ajax (HTTP GET) request to the originally specified URL. The format of your `links` value will influence the final request URL via the `urlPrefix` method: * Links beginning with `//`, `http://`, `https://`, will be used as is, with no further manipulation. * Links beginning with a single `/` will have the current adapter's `host` value prepended to it. * Links with no beginning `/` will have a parentURL prepended to it, via the current adapter's `buildURL`. @method findBelongsTo @param {DS.Store} store @param {DS.Snapshot} snapshot @param {String} url @return {Promise} promise */ findBelongsTo: function (store, snapshot, url, relationship) { if (false && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, snapshot: snapshot, url: url, relationship: relationship, requestType: 'findBelongsTo' }); return this._makeRequest(request); } else { var id = snapshot.id; var type = snapshot.modelName; url = this.urlPrefix(url, this.buildURL(type, id, snapshot, 'findBelongsTo')); return this.ajax(url, 'GET'); } }, /** Called by the store when a newly created record is saved via the `save` method on a model record instance. The `createRecord` method serializes the record and makes an Ajax (HTTP POST) request to a URL computed by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method createRecord @param {DS.Store} store @param {DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ createRecord: function (store, type, snapshot) { if (false && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, snapshot: snapshot, requestType: 'createRecord' }); return this._makeRequest(request); } else { var data = {}; var serializer = store.serializerFor(type.modelName); var url = this.buildURL(type.modelName, null, snapshot, 'createRecord'); serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); return this.ajax(url, "POST", { data: data }); } }, /** Called by the store when an existing record is saved via the `save` method on a model record instance. The `updateRecord` method serializes the record and makes an Ajax (HTTP PUT) request to a URL computed by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method updateRecord @param {DS.Store} store @param {DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ updateRecord: function (store, type, snapshot) { if (false && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, snapshot: snapshot, requestType: 'updateRecord' }); return this._makeRequest(request); } else { var data = {}; var serializer = store.serializerFor(type.modelName); serializer.serializeIntoHash(data, type, snapshot); var id = snapshot.id; var url = this.buildURL(type.modelName, id, snapshot, 'updateRecord'); return this.ajax(url, "PUT", { data: data }); } }, /** Called by the store when a record is deleted. The `deleteRecord` method makes an Ajax (HTTP DELETE) request to a URL computed by `buildURL`. @method deleteRecord @param {DS.Store} store @param {DS.Model} type @param {DS.Snapshot} snapshot @return {Promise} promise */ deleteRecord: function (store, type, snapshot) { if (false && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, snapshot: snapshot, requestType: 'deleteRecord' }); return this._makeRequest(request); } else { var id = snapshot.id; return this.ajax(this.buildURL(type.modelName, id, snapshot, 'deleteRecord'), "DELETE"); } }, _stripIDFromURL: function (store, snapshot) { var url = this.buildURL(snapshot.modelName, snapshot.id, snapshot); var expandedURL = url.split('/'); // Case when the url is of the format ...something/:id // We are decodeURIComponent-ing the lastSegment because if it represents // the id, it has been encodeURIComponent-ified within `buildURL`. If we // don't do this, then records with id having special characters are not // coalesced correctly (see GH #4190 for the reported bug) var lastSegment = expandedURL[expandedURL.length - 1]; var id = snapshot.id; if (decodeURIComponent(lastSegment) === id) { expandedURL[expandedURL.length - 1] = ""; } else if (endsWith(lastSegment, '?id=' + id)) { //Case when the url is of the format ...something?id=:id expandedURL[expandedURL.length - 1] = lastSegment.substring(0, lastSegment.length - id.length - 1); } return expandedURL.join('/'); }, // http://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers maxURLLength: 2048, /** Organize records into groups, each of which is to be passed to separate calls to `findMany`. This implementation groups together records that have the same base URL but differing ids. For example `/comments/1` and `/comments/2` will be grouped together because we know findMany can coalesce them together as `/comments?ids[]=1&ids[]=2` It also supports urls where ids are passed as a query param, such as `/comments?id=1` but not those where there is more than 1 query param such as `/comments?id=2&name=David` Currently only the query param of `id` is supported. If you need to support others, please override this or the `_stripIDFromURL` method. It does not group records that have differing base urls, such as for example: `/posts/1/comments/2` and `/posts/2/comments/3` @method groupRecordsForFindMany @param {DS.Store} store @param {Array} snapshots @return {Array} an array of arrays of records, each of which is to be loaded separately by `findMany`. */ groupRecordsForFindMany: function (store, snapshots) { var groups = MapWithDefault.create({ defaultValue: function () { return []; } }); var adapter = this; var maxURLLength = this.maxURLLength; snapshots.forEach(function (snapshot) { var baseUrl = adapter._stripIDFromURL(store, snapshot); groups.get(baseUrl).push(snapshot); }); function splitGroupToFitInUrl(group, maxURLLength, paramNameLength) { var baseUrl = adapter._stripIDFromURL(store, group[0]); var idsSize = 0; var splitGroups = [[]]; group.forEach(function (snapshot) { var additionalLength = encodeURIComponent(snapshot.id).length + paramNameLength; if (baseUrl.length + idsSize + additionalLength >= maxURLLength) { idsSize = 0; splitGroups.push([]); } idsSize += additionalLength; var lastGroupIndex = splitGroups.length - 1; splitGroups[lastGroupIndex].push(snapshot); }); return splitGroups; } var groupsArray = []; groups.forEach(function (group, key) { var paramNameLength = '&ids%5B%5D='.length; var splitGroups = splitGroupToFitInUrl(group, maxURLLength, paramNameLength); splitGroups.forEach(function (splitGroup) { return groupsArray.push(splitGroup); }); }); return groupsArray; }, /** Takes an ajax response, and returns the json payload or an error. By default this hook just returns the json payload passed to it. You might want to override it in two cases: 1. Your API might return useful results in the response headers. Response headers are passed in as the second argument. 2. Your API might return errors as successful responses with status code 200 and an Errors text or object. You can return a `DS.InvalidError` or a `DS.AdapterError` (or a sub class) from this hook and it will automatically reject the promise and put your record into the invalid or error state. Returning a `DS.InvalidError` from this method will cause the record to transition into the `invalid` state and make the `errors` object available on the record. When returning an `DS.InvalidError` the store will attempt to normalize the error data returned from the server using the serializer's `extractErrors` method. @since 1.13.0 @method handleResponse @param {Number} status @param {Object} headers @param {Object} payload @param {Object} requestData - the original request information @return {Object | DS.AdapterError} response */ handleResponse: function (status, headers, payload, requestData) { if (this.isSuccess(status, headers, payload)) { return payload; } else if (this.isInvalid(status, headers, payload)) { return new _emberDataAdaptersErrors.InvalidError(payload.errors); } var errors = this.normalizeErrorResponse(status, headers, payload); var detailedMessage = this.generatedDetailedMessage(status, headers, payload, requestData); if (false) { switch (status) { case 401: return new _emberDataAdaptersErrors.UnauthorizedError(errors, detailedMessage); case 403: return new _emberDataAdaptersErrors.ForbiddenError(errors, detailedMessage); case 404: return new _emberDataAdaptersErrors.NotFoundError(errors, detailedMessage); case 409: return new _emberDataAdaptersErrors.ConflictError(errors, detailedMessage); default: if (status >= 500) { return new _emberDataAdaptersErrors.ServerError(errors, detailedMessage); } } } return new _emberDataAdaptersErrors.AdapterError(errors, detailedMessage); }, /** Default `handleResponse` implementation uses this hook to decide if the response is a success. @since 1.13.0 @method isSuccess @param {Number} status @param {Object} headers @param {Object} payload @return {Boolean} */ isSuccess: function (status, headers, payload) { return status >= 200 && status < 300 || status === 304; }, /** Default `handleResponse` implementation uses this hook to decide if the response is a an invalid error. @since 1.13.0 @method isInvalid @param {Number} status @param {Object} headers @param {Object} payload @return {Boolean} */ isInvalid: function (status, headers, payload) { return status === 422; }, /** Takes a URL, an HTTP method and a hash of data, and makes an HTTP request. When the server responds with a payload, Ember Data will call into `extractSingle` or `extractArray` (depending on whether the original query was for one record or many records). By default, `ajax` method has the following behavior: * It sets the response `dataType` to `"json"` * If the HTTP method is not `"GET"`, it sets the `Content-Type` to be `application/json; charset=utf-8` * If the HTTP method is not `"GET"`, it stringifies the data passed in. The data is the serialized record in the case of a save. * Registers success and failure handlers. @method ajax @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} options @return {Promise} promise */ ajax: function (url, type, options) { var adapter = this; var requestData = { url: url, method: type }; return new Promise(function (resolve, reject) { var hash = adapter.ajaxOptions(url, type, options); hash.success = function (payload, textStatus, jqXHR) { var response = ajaxSuccess(adapter, jqXHR, payload, requestData); _ember.default.run.join(null, resolve, response); }; hash.error = function (jqXHR, textStatus, errorThrown) { var responseData = { textStatus: textStatus, errorThrown: errorThrown }; var error = ajaxError(adapter, jqXHR, requestData, responseData); _ember.default.run.join(null, reject, error); }; adapter._ajaxRequest(hash); }, 'DS: RESTAdapter#ajax ' + type + ' to ' + url); }, /** @method _ajaxRequest @private @param {Object} options jQuery ajax options to be used for the ajax request */ _ajaxRequest: function (options) { _ember.default.$.ajax(options); }, /** @method ajaxOptions @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} options @return {Object} */ ajaxOptions: function (url, type, options) { var hash = options || {}; hash.url = url; hash.type = type; hash.dataType = 'json'; hash.context = this; if (hash.data && type !== 'GET') { hash.contentType = 'application/json; charset=utf-8'; hash.data = JSON.stringify(hash.data); } var headers = get(this, 'headers'); if (headers !== undefined) { hash.beforeSend = function (xhr) { Object.keys(headers).forEach(function (key) { return xhr.setRequestHeader(key, headers[key]); }); }; } return hash; }, /** @method parseErrorResponse @private @param {String} responseText @return {Object} */ parseErrorResponse: function (responseText) { var json = responseText; try { json = _ember.default.$.parseJSON(responseText); } catch (e) { // ignored } return json; }, /** @method normalizeErrorResponse @private @param {Number} status @param {Object} headers @param {Object} payload @return {Array} errors payload */ normalizeErrorResponse: function (status, headers, payload) { if (payload && typeof payload === 'object' && payload.errors) { return payload.errors; } else { return [{ status: '' + status, title: "The backend responded with an error", detail: '' + payload }]; } }, /** Generates a detailed ("friendly") error message, with plenty of information for debugging (good luck!) @method generatedDetailedMessage @private @param {Number} status @param {Object} headers @param {Object} payload @param {Object} requestData @return {String} detailed error message */ generatedDetailedMessage: function (status, headers, payload, requestData) { var shortenedPayload; var payloadContentType = headers["Content-Type"] || "Empty Content-Type"; if (payloadContentType === "text/html" && payload.length > 250) { shortenedPayload = "[Omitted Lengthy HTML]"; } else { shortenedPayload = payload; } var requestDescription = requestData.method + ' ' + requestData.url; var payloadDescription = 'Payload (' + payloadContentType + ')'; return ['Ember Data Request ' + requestDescription + ' returned a ' + status, payloadDescription, shortenedPayload].join('\n'); }, // @since 2.5.0 buildQuery: function (snapshot) { var query = {}; if (snapshot) { var include = snapshot.include; if (include) { query.include = include; } } return query; }, _hasCustomizedAjax: function () { if (this.ajax !== RESTAdapter.prototype.ajax) { return true; } if (this.ajaxOptions !== RESTAdapter.prototype.ajaxOptions) { return true; } return false; } }); if (false) { RESTAdapter.reopen({ /** * Get the data (body or query params) for a request. * * @public * @method dataForRequest * @param {Object} params * @return {Object} data */ dataForRequest: function (params) { var store = params.store; var type = params.type; var snapshot = params.snapshot; var requestType = params.requestType; var query = params.query; // type is not passed to findBelongsTo and findHasMany type = type || snapshot && snapshot.type; var serializer = store.serializerFor(type.modelName); var data = {}; switch (requestType) { case 'createRecord': serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); break; case 'updateRecord': serializer.serializeIntoHash(data, type, snapshot); break; case 'findRecord': data = this.buildQuery(snapshot); break; case 'findAll': if (params.sinceToken) { query = query || {}; query.since = params.sinceToken; } data = query; break; case 'query': case 'queryRecord': if (this.sortQueryParams) { query = this.sortQueryParams(query); } data = query; break; case 'findMany': data = { ids: params.ids }; break; default: data = undefined; break; } return data; }, /** * Get the HTTP method for a request. * * @public * @method methodForRequest * @param {Object} params * @return {String} HTTP method */ methodForRequest: function (params) { var requestType = params.requestType; switch (requestType) { case 'createRecord': return 'POST'; case 'updateRecord': return 'PUT'; case 'deleteRecord': return 'DELETE'; } return 'GET'; }, /** * Get the URL for a request. * * @public * @method urlForRequest * @param {Object} params * @return {String} URL */ urlForRequest: function (params) { var type = params.type; var id = params.id; var ids = params.ids; var snapshot = params.snapshot; var snapshots = params.snapshots; var requestType = params.requestType; var query = params.query; // type and id are not passed from updateRecord and deleteRecord, hence they // are defined if not set type = type || snapshot && snapshot.type; id = id || snapshot && snapshot.id; switch (requestType) { case 'findAll': return this.buildURL(type.modelName, null, snapshots, requestType); case 'query': case 'queryRecord': return this.buildURL(type.modelName, null, null, requestType, query); case 'findMany': return this.buildURL(type.modelName, ids, snapshots, requestType); case 'findHasMany': case 'findBelongsTo': { var url = this.buildURL(type.modelName, id, snapshot, requestType); return this.urlPrefix(params.url, url); } } return this.buildURL(type.modelName, id, snapshot, requestType, query); }, /** * Get the headers for a request. * * By default the value of the `headers` property of the adapter is * returned. * * @public * @method headersForRequest * @param {Object} params * @return {Object} headers */ headersForRequest: function (params) { return this.get('headers'); }, /** * Get an object which contains all properties for a request which should * be made. * * @private * @method _requestFor * @param {Object} params * @return {Object} request object */ _requestFor: function (params) { var method = this.methodForRequest(params); var url = this.urlForRequest(params); var headers = this.headersForRequest(params); var data = this.dataForRequest(params); return { method: method, url: url, headers: headers, data: data }; }, /** * Convert a request object into a hash which can be passed to `jQuery.ajax`. * * @private * @method _requestToJQueryAjaxHash * @param {Object} request * @return {Object} jQuery ajax hash */ _requestToJQueryAjaxHash: function (request) { var hash = {}; hash.type = request.method; hash.url = request.url; hash.dataType = 'json'; hash.context = this; if (request.data) { if (request.method !== 'GET') { hash.contentType = 'application/json; charset=utf-8'; hash.data = JSON.stringify(request.data); } else { hash.data = request.data; } } var headers = request.headers; if (headers !== undefined) { hash.beforeSend = function (xhr) { Object.keys(headers).forEach(function (key) { return xhr.setRequestHeader(key, headers[key]); }); }; } return hash; }, /** * Make a request using `jQuery.ajax`. * * @private * @method _makeRequest * @param {Object} request * @return {Promise} promise */ _makeRequest: function (request) { var adapter = this; var hash = this._requestToJQueryAjaxHash(request); var method = request.method; var url = request.url; var requestData = { method: method, url: url }; return new _ember.default.RSVP.Promise(function (resolve, reject) { hash.success = function (payload, textStatus, jqXHR) { var response = ajaxSuccess(adapter, jqXHR, payload, requestData); _ember.default.run.join(null, resolve, response); }; hash.error = function (jqXHR, textStatus, errorThrown) { var responseData = { textStatus: textStatus, errorThrown: errorThrown }; var error = ajaxError(adapter, jqXHR, requestData, responseData); _ember.default.run.join(null, reject, error); }; adapter._ajaxRequest(hash); }, 'DS: RESTAdapter#makeRequest: ' + method + ' ' + url); } }); } function ajaxSuccess(adapter, jqXHR, payload, requestData) { var response = undefined; try { response = adapter.handleResponse(jqXHR.status, (0, _emberDataPrivateUtilsParseResponseHeaders.default)(jqXHR.getAllResponseHeaders()), payload, requestData); } catch (error) { return Promise.reject(error); } if (response && response.isAdapterError) { return Promise.reject(response); } else { return response; } } function ajaxError(adapter, jqXHR, requestData, responseData) { var error = undefined; if (responseData.errorThrown instanceof Error) { error = responseData.errorThrown; } else if (responseData.textStatus === 'timeout') { error = new _emberDataAdaptersErrors.TimeoutError(); } else if (responseData.textStatus === 'abort' || jqXHR.status === 0) { error = new _emberDataAdaptersErrors.AbortError(); } else { try { error = adapter.handleResponse(jqXHR.status, (0, _emberDataPrivateUtilsParseResponseHeaders.default)(jqXHR.getAllResponseHeaders()), adapter.parseErrorResponse(jqXHR.responseText) || responseData.errorThrown, requestData); } catch (e) { error = e; } } return error; } //From http://stackoverflow.com/questions/280634/endswith-in-javascript function endsWith(string, suffix) { if (typeof String.prototype.endsWith !== 'function') { return string.indexOf(suffix, string.length - suffix.length) !== -1; } else { return string.endsWith(suffix); } } exports.default = RESTAdapter; }); /* global heimdall */ /** @module ember-data */ define('ember-data/attr', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { exports.default = attr; /** @module ember-data */ function getDefaultValue(record, options, key) { if (typeof options.defaultValue === 'function') { return options.defaultValue.apply(null, arguments); } else { var defaultValue = options.defaultValue; return defaultValue; } } function hasValue(record, key) { return key in record._attributes || key in record._inFlightAttributes || key in record._data; } function getValue(record, key) { if (key in record._attributes) { return record._attributes[key]; } else if (key in record._inFlightAttributes) { return record._inFlightAttributes[key]; } else { return record._data[key]; } } /** `DS.attr` defines an attribute on a [DS.Model](/api/data/classes/DS.Model.html). By default, attributes are passed through as-is, however you can specify an optional type to have the value automatically transformed. Ember Data ships with four basic transform types: `string`, `number`, `boolean` and `date`. You can define your own transforms by subclassing [DS.Transform](/api/data/classes/DS.Transform.html). Note that you cannot use `attr` to define an attribute of `id`. `DS.attr` takes an optional hash as a second parameter, currently supported options are: - `defaultValue`: Pass a string or a function to be called to set the attribute to a default value if none is supplied. Example ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ username: DS.attr('string'), email: DS.attr('string'), verified: DS.attr('boolean', { defaultValue: false }) }); ``` Default value can also be a function. This is useful it you want to return a new object for each attribute. ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ username: attr('string'), email: attr('string'), settings: attr({defaultValue: function() { return {}; }}) }); ``` The `options` hash is passed as second argument to a transforms' `serialize` and `deserialize` method. This allows to configure a transformation and adapt the corresponding value, based on the config: ```app/models/post.js export default DS.Model.extend({ text: DS.attr('text', { uppercase: true }) }); ``` ```app/transforms/text.js export default DS.Transform.extend({ serialize: function(value, options) { if (options.uppercase) { return value.toUpperCase(); } return value; }, deserialize: function(value) { return value; } }) ``` @namespace @method attr @for DS @param {String} type the attribute type @param {Object} options a hash of options @return {Attribute} */ function attr(type, options) { if (typeof type === 'object') { options = type; type = undefined; } else { options = options || {}; } var meta = { type: type, isAttribute: true, options: options }; return _ember.default.computed({ get: function (key) { var internalModel = this._internalModel; if (hasValue(internalModel, key)) { return getValue(internalModel, key); } else { return getDefaultValue(this, options, key); } }, set: function (key, value) { var internalModel = this._internalModel; var oldValue = getValue(internalModel, key); var originalValue; if (value !== oldValue) { // Add the new value to the changed attributes hash; it will get deleted by // the 'didSetProperty' handler if it is no different from the original value internalModel._attributes[key] = value; if (key in internalModel._inFlightAttributes) { originalValue = internalModel._inFlightAttributes[key]; } else { originalValue = internalModel._data[key]; } this._internalModel.send('didSetProperty', { name: key, oldValue: oldValue, originalValue: originalValue, value: value }); } return value; } }).meta(meta); } }); define("ember-data", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/features", "ember-data/-private/global", "ember-data/-private/core", "ember-data/-private/system/normalize-model-name", "ember-data/-private/system/model/internal-model", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/store", "ember-data/-private/system/model", "ember-data/model", "ember-data/-private/system/snapshot", "ember-data/adapter", "ember-data/serializer", "ember-data/-private/system/debug", "ember-data/adapters/errors", "ember-data/-private/system/record-arrays", "ember-data/-private/system/many-array", "ember-data/-private/system/record-array-manager", "ember-data/-private/adapters", "ember-data/-private/adapters/build-url-mixin", "ember-data/-private/serializers", "ember-inflector", "ember-data/serializers/embedded-records-mixin", "ember-data/-private/transforms", "ember-data/relationships", "ember-data/setup-container", "ember-data/-private/instance-initializers/initialize-store-service", "ember-data/-private/system/relationships/state/relationship"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateFeatures, _emberDataPrivateGlobal, _emberDataPrivateCore, _emberDataPrivateSystemNormalizeModelName, _emberDataPrivateSystemModelInternalModel, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemStore, _emberDataPrivateSystemModel, _emberDataModel, _emberDataPrivateSystemSnapshot, _emberDataAdapter, _emberDataSerializer, _emberDataPrivateSystemDebug, _emberDataAdaptersErrors, _emberDataPrivateSystemRecordArrays, _emberDataPrivateSystemManyArray, _emberDataPrivateSystemRecordArrayManager, _emberDataPrivateAdapters, _emberDataPrivateAdaptersBuildUrlMixin, _emberDataPrivateSerializers, _emberInflector, _emberDataSerializersEmbeddedRecordsMixin, _emberDataPrivateTransforms, _emberDataRelationships, _emberDataSetupContainer, _emberDataPrivateInstanceInitializersInitializeStoreService, _emberDataPrivateSystemRelationshipsStateRelationship) { /** Ember Data @module ember-data @main ember-data */ if (_ember.default.VERSION.match(/^1\.([0-9]|1[0-2])\./)) { throw new _ember.default.Error("Ember Data requires at least Ember 1.13.0, but you have " + _ember.default.VERSION + ". Please upgrade your version of Ember, then upgrade Ember Data."); } _emberDataPrivateCore.default.Store = _emberDataPrivateSystemStore.Store; _emberDataPrivateCore.default.PromiseArray = _emberDataPrivateSystemPromiseProxies.PromiseArray; _emberDataPrivateCore.default.PromiseObject = _emberDataPrivateSystemPromiseProxies.PromiseObject; _emberDataPrivateCore.default.PromiseManyArray = _emberDataPrivateSystemPromiseProxies.PromiseManyArray; _emberDataPrivateCore.default.Model = _emberDataModel.default; _emberDataPrivateCore.default.RootState = _emberDataPrivateSystemModel.RootState; _emberDataPrivateCore.default.attr = _emberDataPrivateSystemModel.attr; _emberDataPrivateCore.default.Errors = _emberDataPrivateSystemModel.Errors; _emberDataPrivateCore.default.InternalModel = _emberDataPrivateSystemModelInternalModel.default; _emberDataPrivateCore.default.Snapshot = _emberDataPrivateSystemSnapshot.default; _emberDataPrivateCore.default.Adapter = _emberDataAdapter.default; _emberDataPrivateCore.default.AdapterError = _emberDataAdaptersErrors.AdapterError; _emberDataPrivateCore.default.InvalidError = _emberDataAdaptersErrors.InvalidError; _emberDataPrivateCore.default.TimeoutError = _emberDataAdaptersErrors.TimeoutError; _emberDataPrivateCore.default.AbortError = _emberDataAdaptersErrors.AbortError; if (false) { _emberDataPrivateCore.default.UnauthorizedError = _emberDataAdaptersErrors.UnauthorizedError; _emberDataPrivateCore.default.ForbiddenError = _emberDataAdaptersErrors.ForbiddenError; _emberDataPrivateCore.default.NotFoundError = _emberDataAdaptersErrors.NotFoundError; _emberDataPrivateCore.default.ConflictError = _emberDataAdaptersErrors.ConflictError; _emberDataPrivateCore.default.ServerError = _emberDataAdaptersErrors.ServerError; } _emberDataPrivateCore.default.errorsHashToArray = _emberDataAdaptersErrors.errorsHashToArray; _emberDataPrivateCore.default.errorsArrayToHash = _emberDataAdaptersErrors.errorsArrayToHash; _emberDataPrivateCore.default.Serializer = _emberDataSerializer.default; _emberDataPrivateCore.default.DebugAdapter = _emberDataPrivateSystemDebug.default; _emberDataPrivateCore.default.RecordArray = _emberDataPrivateSystemRecordArrays.RecordArray; _emberDataPrivateCore.default.FilteredRecordArray = _emberDataPrivateSystemRecordArrays.FilteredRecordArray; _emberDataPrivateCore.default.AdapterPopulatedRecordArray = _emberDataPrivateSystemRecordArrays.AdapterPopulatedRecordArray; _emberDataPrivateCore.default.ManyArray = _emberDataPrivateSystemManyArray.default; _emberDataPrivateCore.default.RecordArrayManager = _emberDataPrivateSystemRecordArrayManager.default; _emberDataPrivateCore.default.RESTAdapter = _emberDataPrivateAdapters.RESTAdapter; _emberDataPrivateCore.default.BuildURLMixin = _emberDataPrivateAdaptersBuildUrlMixin.default; _emberDataPrivateCore.default.RESTSerializer = _emberDataPrivateSerializers.RESTSerializer; _emberDataPrivateCore.default.JSONSerializer = _emberDataPrivateSerializers.JSONSerializer; _emberDataPrivateCore.default.JSONAPIAdapter = _emberDataPrivateAdapters.JSONAPIAdapter; _emberDataPrivateCore.default.JSONAPISerializer = _emberDataPrivateSerializers.JSONAPISerializer; _emberDataPrivateCore.default.Transform = _emberDataPrivateTransforms.Transform; _emberDataPrivateCore.default.DateTransform = _emberDataPrivateTransforms.DateTransform; _emberDataPrivateCore.default.StringTransform = _emberDataPrivateTransforms.StringTransform; _emberDataPrivateCore.default.NumberTransform = _emberDataPrivateTransforms.NumberTransform; _emberDataPrivateCore.default.BooleanTransform = _emberDataPrivateTransforms.BooleanTransform; _emberDataPrivateCore.default.EmbeddedRecordsMixin = _emberDataSerializersEmbeddedRecordsMixin.default; _emberDataPrivateCore.default.belongsTo = _emberDataRelationships.belongsTo; _emberDataPrivateCore.default.hasMany = _emberDataRelationships.hasMany; _emberDataPrivateCore.default.Relationship = _emberDataPrivateSystemRelationshipsStateRelationship.default; _emberDataPrivateCore.default._setupContainer = _emberDataSetupContainer.default; _emberDataPrivateCore.default._initializeStoreService = _emberDataPrivateInstanceInitializersInitializeStoreService.default; Object.defineProperty(_emberDataPrivateCore.default, 'normalizeModelName', { enumerable: true, writable: false, configurable: false, value: _emberDataPrivateSystemNormalizeModelName.default }); Object.defineProperty(_emberDataPrivateGlobal.default, 'DS', { configurable: true, get: function () { return _emberDataPrivateCore.default; } }); exports.default = _emberDataPrivateCore.default; }); define('ember-data/initializers/data-adapter', ['exports', 'ember'], function (exports, _ember) { /* This initializer is here to keep backwards compatibility with code depending on the `data-adapter` initializer (before Ember Data was an addon). Should be removed for Ember Data 3.x */ exports.default = { name: 'data-adapter', before: 'store', initialize: function () {} }; }); define('ember-data/initializers/ember-data', ['exports', 'ember-data/setup-container', 'ember-data/-private/core'], function (exports, _emberDataSetupContainer, _emberDataPrivateCore) { /* This code initializes Ember-Data onto an Ember application. If an Ember.js developer defines a subclass of DS.Store on their application, as `App.StoreService` (or via a module system that resolves to `service:store`) this code will automatically instantiate it and make it available on the router. Additionally, after an application's controllers have been injected, they will each have the store made available to them. For example, imagine an Ember.js application with the following classes: App.StoreService = DS.Store.extend({ adapter: 'custom' }); App.PostsController = Ember.Controller.extend({ // ... }); When the application is initialized, `App.ApplicationStore` will automatically be instantiated, and the instance of `App.PostsController` will have its `store` property set to that instance. Note that this code will only be run if the `ember-application` package is loaded. If Ember Data is being used in an environment other than a typical application (e.g., node.js where only `ember-runtime` is available), this code will be ignored. */ exports.default = { name: 'ember-data', initialize: _emberDataSetupContainer.default }; }); define('ember-data/initializers/injectStore', ['exports', 'ember'], function (exports, _ember) { /* This initializer is here to keep backwards compatibility with code depending on the `injectStore` initializer (before Ember Data was an addon). Should be removed for Ember Data 3.x */ exports.default = { name: 'injectStore', before: 'store', initialize: function () {} }; }); define('ember-data/initializers/store', ['exports', 'ember'], function (exports, _ember) { /* This initializer is here to keep backwards compatibility with code depending on the `store` initializer (before Ember Data was an addon). Should be removed for Ember Data 3.x */ exports.default = { name: 'store', after: 'ember-data', initialize: function () {} }; }); define('ember-data/initializers/transforms', ['exports', 'ember'], function (exports, _ember) { /* This initializer is here to keep backwards compatibility with code depending on the `transforms` initializer (before Ember Data was an addon). Should be removed for Ember Data 3.x */ exports.default = { name: 'transforms', before: 'store', initialize: function () {} }; }); define("ember-data/instance-initializers/ember-data", ["exports", "ember-data/-private/instance-initializers/initialize-store-service"], function (exports, _emberDataPrivateInstanceInitializersInitializeStoreService) { exports.default = { name: "ember-data", initialize: _emberDataPrivateInstanceInitializersInitializeStoreService.default }; }); define("ember-data/model", ["exports", "ember-data/-private/system/model"], function (exports, _emberDataPrivateSystemModel) { exports.default = _emberDataPrivateSystemModel.default; }); define("ember-data/relationships", ["exports", "ember-data/-private/system/relationships/belongs-to", "ember-data/-private/system/relationships/has-many"], function (exports, _emberDataPrivateSystemRelationshipsBelongsTo, _emberDataPrivateSystemRelationshipsHasMany) { exports.belongsTo = _emberDataPrivateSystemRelationshipsBelongsTo.default; exports.hasMany = _emberDataPrivateSystemRelationshipsHasMany.default; }); /** @module ember-data */ define('ember-data/serializer', ['exports', 'ember'], function (exports, _ember) { /** `DS.Serializer` is an abstract base class that you should override in your application to customize it for your backend. The minimum set of methods that you should implement is: * `normalizeResponse()` * `serialize()` And you can optionally override the following methods: * `normalize()` For an example implementation, see [DS.JSONSerializer](DS.JSONSerializer.html), the included JSON serializer. @class Serializer @namespace DS @extends Ember.Object */ exports.default = _ember.default.Object.extend({ /** The `store` property is the application's `store` that contains all records. It can be used to look up serializers for other model types that may be nested inside the payload response. Example: ```js Serializer.extend({ extractRelationship: function(relationshipModelName, relationshipHash) { var modelClass = this.store.modelFor(relationshipModelName); var relationshipSerializer = this.store.serializerFor(relationshipModelName); return relationshipSerializer.normalize(modelClass, relationshipHash); } }); ``` @property store @type {DS.Store} @public */ /** The `normalizeResponse` method is used to normalize a payload from the server to a JSON-API Document. http://jsonapi.org/format/#document-structure Example: ```js Serializer.extend({ normalizeResponse(store, primaryModelClass, payload, id, requestType) { if (requestType === 'findRecord') { return this.normalize(primaryModelClass, payload); } else { return payload.reduce(function(documentHash, item) { let { data, included } = this.normalize(primaryModelClass, item); documentHash.included.push(...included); documentHash.data.push(data); return documentHash; }, { data: [], included: [] }) } } }); ``` @since 1.13.0 @method normalizeResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeResponse: null, /** The `serialize` method is used when a record is saved in order to convert the record into the form that your external data source expects. `serialize` takes an optional `options` hash with a single option: - `includeId`: If this is `true`, `serialize` should include the ID in the serialized object it builds. Example: ```js Serializer.extend({ serialize(snapshot, options) { var json = { id: snapshot.id }; snapshot.eachAttribute((key, attribute) => { json[key] = snapshot.attr(key); }); snapshot.eachRelationship((key, relationship) => { if (relationship.kind === 'belongsTo') { json[key] = snapshot.belongsTo(key, { id: true }); } else if (relationship.kind === 'hasMany') { json[key] = snapshot.hasMany(key, { ids: true }); } }); return json; }, }); ``` @method serialize @param {DS.Snapshot} snapshot @param {Object} [options] @return {Object} */ serialize: null, /** The `normalize` method is used to convert a payload received from your external data source into the normalized form `store.push()` expects. You should override this method, munge the hash and return the normalized payload. Example: ```js Serializer.extend({ normalize(modelClass, resourceHash) { var data = { id: resourceHash.id, type: modelClass.modelName, attributes: resourceHash }; return { data: data }; } }) ``` @method normalize @param {DS.Model} typeClass @param {Object} hash @return {Object} */ normalize: function (typeClass, hash) { return hash; } }); }); /** @module ember-data */ define('ember-data/serializers/embedded-records-mixin', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } } var get = _ember.default.get; var set = _ember.default.set; var camelize = _ember.default.String.camelize; /** ## Using Embedded Records `DS.EmbeddedRecordsMixin` supports serializing embedded records. To set up embedded records, include the mixin when extending a serializer, then define and configure embedded (model) relationships. Below is an example of a per-type serializer (`post` type). ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { author: { embedded: 'always' }, comments: { serialize: 'ids' } } }); ``` Note that this use of `{ embedded: 'always' }` is unrelated to the `{ embedded: 'always' }` that is defined as an option on `DS.attr` as part of defining a model while working with the `ActiveModelSerializer`. Nevertheless, using `{ embedded: 'always' }` as an option to `DS.attr` is not a valid way to setup embedded records. The `attrs` option for a resource `{ embedded: 'always' }` is shorthand for: ```js { serialize: 'records', deserialize: 'records' } ``` ### Configuring Attrs A resource's `attrs` option may be set to use `ids`, `records` or false for the `serialize` and `deserialize` settings. The `attrs` property can be set on the `ApplicationSerializer` or a per-type serializer. In the case where embedded JSON is expected while extracting a payload (reading) the setting is `deserialize: 'records'`, there is no need to use `ids` when extracting as that is the default behavior without this mixin if you are using the vanilla `EmbeddedRecordsMixin`. Likewise, to embed JSON in the payload while serializing `serialize: 'records'` is the setting to use. There is an option of not embedding JSON in the serialized payload by using `serialize: 'ids'`. If you do not want the relationship sent at all, you can use `serialize: false`. ### EmbeddedRecordsMixin defaults If you do not overwrite `attrs` for a specific relationship, the `EmbeddedRecordsMixin` will behave in the following way: BelongsTo: `{ serialize: 'id', deserialize: 'id' }` HasMany: `{ serialize: false, deserialize: 'ids' }` ### Model Relationships Embedded records must have a model defined to be extracted and serialized. Note that when defining any relationships on your model such as `belongsTo` and `hasMany`, you should not both specify `async: true` and also indicate through the serializer's `attrs` attribute that the related model should be embedded for deserialization. If a model is declared embedded for deserialization (`embedded: 'always'` or `deserialize: 'records'`), then do not use `async: true`. To successfully extract and serialize embedded records the model relationships must be setup correcty. See the [defining relationships](/guides/models/defining-models/#toc_defining-relationships) section of the **Defining Models** guide page. Records without an `id` property are not considered embedded records, model instances must have an `id` property to be used with Ember Data. ### Example JSON payloads, Models and Serializers **When customizing a serializer it is important to grok what the customizations are. Please read the docs for the methods this mixin provides, in case you need to modify it to fit your specific needs.** For example review the docs for each method of this mixin: * [normalize](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_normalize) * [serializeBelongsTo](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeBelongsTo) * [serializeHasMany](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeHasMany) @class EmbeddedRecordsMixin @namespace DS */ exports.default = _ember.default.Mixin.create({ /** Normalize the record and recursively normalize/extract all the embedded records while pushing them into the store as they are encountered A payload with an attr configured for embedded records needs to be extracted: ```js { "post": { "id": "1" "title": "Rails is omakase", "comments": [{ "id": "1", "body": "Rails is unagi" }, { "id": "2", "body": "Omakase O_o" }] } } ``` @method normalize @param {DS.Model} typeClass @param {Object} hash to be normalized @param {String} prop the hash has been referenced by @return {Object} the normalized hash **/ normalize: function (typeClass, hash, prop) { var normalizedHash = this._super(typeClass, hash, prop); return this._extractEmbeddedRecords(this, this.store, typeClass, normalizedHash); }, keyForRelationship: function (key, typeClass, method) { if (method === 'serialize' && this.hasSerializeRecordsOption(key) || method === 'deserialize' && this.hasDeserializeRecordsOption(key)) { return this.keyForAttribute(key, method); } else { return this._super(key, typeClass, method) || key; } }, /** Serialize `belongsTo` relationship when it is configured as an embedded object. This example of an author model belongs to a post model: ```js Post = DS.Model.extend({ title: DS.attr('string'), body: DS.attr('string'), author: DS.belongsTo('author') }); Author = DS.Model.extend({ name: DS.attr('string'), post: DS.belongsTo('post') }); ``` Use a custom (type) serializer for the post model to configure embedded author ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { author: { embedded: 'always' } } }) ``` A payload with an attribute configured for embedded records can serialize the records together under the root attribute's payload: ```js { "post": { "id": "1" "title": "Rails is omakase", "author": { "id": "2" "name": "dhh" } } } ``` @method serializeBelongsTo @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeBelongsTo: function (snapshot, json, relationship) { var attr = relationship.key; if (this.noSerializeOptionSpecified(attr)) { this._super(snapshot, json, relationship); return; } var includeIds = this.hasSerializeIdsOption(attr); var includeRecords = this.hasSerializeRecordsOption(attr); var embeddedSnapshot = snapshot.belongsTo(attr); if (includeIds) { var serializedKey = this._getMappedKey(relationship.key, snapshot.type); if (serializedKey === relationship.key && this.keyForRelationship) { serializedKey = this.keyForRelationship(relationship.key, relationship.kind, "serialize"); } if (!embeddedSnapshot) { json[serializedKey] = null; } else { json[serializedKey] = embeddedSnapshot.id; if (relationship.options.polymorphic) { this.serializePolymorphicType(snapshot, json, relationship); } } } else if (includeRecords) { this._serializeEmbeddedBelongsTo(snapshot, json, relationship); } }, _serializeEmbeddedBelongsTo: function (snapshot, json, relationship) { var embeddedSnapshot = snapshot.belongsTo(relationship.key); var serializedKey = this._getMappedKey(relationship.key, snapshot.type); if (serializedKey === relationship.key && this.keyForRelationship) { serializedKey = this.keyForRelationship(relationship.key, relationship.kind, "serialize"); } if (!embeddedSnapshot) { json[serializedKey] = null; } else { json[serializedKey] = embeddedSnapshot.serialize({ includeId: true }); this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, json[serializedKey]); if (relationship.options.polymorphic) { this.serializePolymorphicType(snapshot, json, relationship); } } }, /** Serializes `hasMany` relationships when it is configured as embedded objects. This example of a post model has many comments: ```js Post = DS.Model.extend({ title: DS.attr('string'), body: DS.attr('string'), comments: DS.hasMany('comment') }); Comment = DS.Model.extend({ body: DS.attr('string'), post: DS.belongsTo('post') }); ``` Use a custom (type) serializer for the post model to configure embedded comments ```app/serializers/post.js import DS from 'ember-data; export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { comments: { embedded: 'always' } } }) ``` A payload with an attribute configured for embedded records can serialize the records together under the root attribute's payload: ```js { "post": { "id": "1" "title": "Rails is omakase", "body": "I want this for my ORM, I want that for my template language..." "comments": [{ "id": "1", "body": "Rails is unagi" }, { "id": "2", "body": "Omakase O_o" }] } } ``` The attrs options object can use more specific instruction for extracting and serializing. When serializing, an option to embed `ids`, `ids-and-types` or `records` can be set. When extracting the only option is `records`. So `{ embedded: 'always' }` is shorthand for: `{ serialize: 'records', deserialize: 'records' }` To embed the `ids` for a related object (using a hasMany relationship): ```app/serializers/post.js import DS from 'ember-data; export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { comments: { serialize: 'ids', deserialize: 'records' } } }) ``` ```js { "post": { "id": "1" "title": "Rails is omakase", "body": "I want this for my ORM, I want that for my template language..." "comments": ["1", "2"] } } ``` To embed the relationship as a collection of objects with `id` and `type` keys, set `ids-and-types` for the related object. This is particularly useful for polymorphic relationships where records don't share the same table and the `id` is not enough information. By example having a user that has many pets: ```js User = DS.Model.extend({ name: DS.attr('string'), pets: DS.hasMany('pet', { polymorphic: true }) }); Pet = DS.Model.extend({ name: DS.attr('string'), }); Cat = Pet.extend({ // ... }); Parrot = Pet.extend({ // ... }); ``` ```app/serializers/user.js import DS from 'ember-data; export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { pets: { serialize: 'ids-and-types', deserialize: 'records' } } }); ``` ```js { "user": { "id": "1" "name": "Bertin Osborne", "pets": [ { "id": "1", "type": "Cat" }, { "id": "1", "type": "Parrot"} ] } } ``` @method serializeHasMany @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeHasMany: function (snapshot, json, relationship) { var attr = relationship.key; if (this.noSerializeOptionSpecified(attr)) { this._super(snapshot, json, relationship); return; } if (this.hasSerializeIdsOption(attr)) { var serializedKey = this._getMappedKey(relationship.key, snapshot.type); if (serializedKey === relationship.key && this.keyForRelationship) { serializedKey = this.keyForRelationship(relationship.key, relationship.kind, "serialize"); } json[serializedKey] = snapshot.hasMany(attr, { ids: true }); } else if (this.hasSerializeRecordsOption(attr)) { this._serializeEmbeddedHasMany(snapshot, json, relationship); } else { if (this.hasSerializeIdsAndTypesOption(attr)) { this._serializeHasManyAsIdsAndTypes(snapshot, json, relationship); } } }, /* Serializes a hasMany relationship as an array of objects containing only `id` and `type` keys. This has its use case on polymorphic hasMany relationships where the server is not storing all records in the same table using STI, and therefore the `id` is not enough information TODO: Make the default in Ember-data 3.0?? */ _serializeHasManyAsIdsAndTypes: function (snapshot, json, relationship) { var serializedKey = this.keyForAttribute(relationship.key, 'serialize'); var hasMany = snapshot.hasMany(relationship.key); json[serializedKey] = _ember.default.A(hasMany).map(function (recordSnapshot) { // // I'm sure I'm being utterly naive here. Propably id is a configurate property and // type too, and the modelName has to be normalized somehow. // return { id: recordSnapshot.id, type: recordSnapshot.modelName }; }); }, _serializeEmbeddedHasMany: function (snapshot, json, relationship) { var serializedKey = this._getMappedKey(relationship.key, snapshot.type); if (serializedKey === relationship.key && this.keyForRelationship) { serializedKey = this.keyForRelationship(relationship.key, relationship.kind, "serialize"); } json[serializedKey] = this._generateSerializedHasMany(snapshot, relationship); }, /* Returns an array of embedded records serialized to JSON */ _generateSerializedHasMany: function (snapshot, relationship) { var hasMany = snapshot.hasMany(relationship.key); var manyArray = _ember.default.A(hasMany); var ret = new Array(manyArray.length); for (var i = 0; i < manyArray.length; i++) { var embeddedSnapshot = manyArray[i]; var embeddedJson = embeddedSnapshot.serialize({ includeId: true }); this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, embeddedJson); ret[i] = embeddedJson; } return ret; }, /** When serializing an embedded record, modify the property (in the json payload) that refers to the parent record (foreign key for relationship). Serializing a `belongsTo` relationship removes the property that refers to the parent record Serializing a `hasMany` relationship does not remove the property that refers to the parent record. @method removeEmbeddedForeignKey @param {DS.Snapshot} snapshot @param {DS.Snapshot} embeddedSnapshot @param {Object} relationship @param {Object} json */ removeEmbeddedForeignKey: function (snapshot, embeddedSnapshot, relationship, json) { if (relationship.kind === 'hasMany') { return; } else if (relationship.kind === 'belongsTo') { var parentRecord = snapshot.type.inverseFor(relationship.key, this.store); if (parentRecord) { var name = parentRecord.name; var embeddedSerializer = this.store.serializerFor(embeddedSnapshot.modelName); var parentKey = embeddedSerializer.keyForRelationship(name, parentRecord.kind, 'deserialize'); if (parentKey) { delete json[parentKey]; } } } }, // checks config for attrs option to embedded (always) - serialize and deserialize hasEmbeddedAlwaysOption: function (attr) { var option = this.attrsOption(attr); return option && option.embedded === 'always'; }, // checks config for attrs option to serialize ids hasSerializeRecordsOption: function (attr) { var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr); var option = this.attrsOption(attr); return alwaysEmbed || option && option.serialize === 'records'; }, // checks config for attrs option to serialize records hasSerializeIdsOption: function (attr) { var option = this.attrsOption(attr); return option && (option.serialize === 'ids' || option.serialize === 'id'); }, // checks config for attrs option to serialize records as objects containing id and types hasSerializeIdsAndTypesOption: function (attr) { var option = this.attrsOption(attr); return option && (option.serialize === 'ids-and-types' || option.serialize === 'id-and-type'); }, // checks config for attrs option to serialize records noSerializeOptionSpecified: function (attr) { var option = this.attrsOption(attr); return !(option && (option.serialize || option.embedded)); }, // checks config for attrs option to deserialize records // a defined option object for a resource is treated the same as // `deserialize: 'records'` hasDeserializeRecordsOption: function (attr) { var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr); var option = this.attrsOption(attr); return alwaysEmbed || option && option.deserialize === 'records'; }, attrsOption: function (attr) { var attrs = this.get('attrs'); return attrs && (attrs[camelize(attr)] || attrs[attr]); }, /** @method _extractEmbeddedRecords @private */ _extractEmbeddedRecords: function (serializer, store, typeClass, partial) { var _this = this; typeClass.eachRelationship(function (key, relationship) { if (serializer.hasDeserializeRecordsOption(key)) { if (relationship.kind === "hasMany") { _this._extractEmbeddedHasMany(store, key, partial, relationship); } if (relationship.kind === "belongsTo") { _this._extractEmbeddedBelongsTo(store, key, partial, relationship); } } }); return partial; }, /** @method _extractEmbeddedHasMany @private */ _extractEmbeddedHasMany: function (store, key, hash, relationshipMeta) { var relationshipHash = get(hash, 'data.relationships.' + key + '.data'); if (!relationshipHash) { return; } var hasMany = new Array(relationshipHash.length); for (var i = 0; i < relationshipHash.length; i++) { var item = relationshipHash[i]; var _normalizeEmbeddedRelationship = this._normalizeEmbeddedRelationship(store, relationshipMeta, item); var data = _normalizeEmbeddedRelationship.data; var included = _normalizeEmbeddedRelationship.included; hash.included = hash.included || []; hash.included.push(data); if (included) { var _hash$included; (_hash$included = hash.included).push.apply(_hash$included, _toConsumableArray(included)); } hasMany[i] = { id: data.id, type: data.type }; } var relationship = { data: hasMany }; set(hash, 'data.relationships.' + key, relationship); }, /** @method _extractEmbeddedBelongsTo @private */ _extractEmbeddedBelongsTo: function (store, key, hash, relationshipMeta) { var relationshipHash = get(hash, 'data.relationships.' + key + '.data'); if (!relationshipHash) { return; } var _normalizeEmbeddedRelationship2 = this._normalizeEmbeddedRelationship(store, relationshipMeta, relationshipHash); var data = _normalizeEmbeddedRelationship2.data; var included = _normalizeEmbeddedRelationship2.included; hash.included = hash.included || []; hash.included.push(data); if (included) { var _hash$included2; (_hash$included2 = hash.included).push.apply(_hash$included2, _toConsumableArray(included)); } var belongsTo = { id: data.id, type: data.type }; var relationship = { data: belongsTo }; set(hash, 'data.relationships.' + key, relationship); }, /** @method _normalizeEmbeddedRelationship @private */ _normalizeEmbeddedRelationship: function (store, relationshipMeta, relationshipHash) { var modelName = relationshipMeta.type; if (relationshipMeta.options.polymorphic) { modelName = relationshipHash.type; } var modelClass = store.modelFor(modelName); var serializer = store.serializerFor(modelName); return serializer.normalize(modelClass, relationshipHash, null); }, isEmbeddedRecordsMixin: true }); }); define('ember-data/serializers/json-api', ['exports', 'ember', 'ember-data/-private/debug', 'ember-data/serializers/json', 'ember-data/-private/system/normalize-model-name', 'ember-inflector', 'ember-data/-private/features'], function (exports, _ember, _emberDataPrivateDebug, _emberDataSerializersJson, _emberDataPrivateSystemNormalizeModelName, _emberInflector, _emberDataPrivateFeatures) { var dasherize = _ember.default.String.dasherize; /** Ember Data 2.0 Serializer: In Ember Data a Serializer is used to serialize and deserialize records when they are transferred in and out of an external source. This process involves normalizing property names, transforming attribute values and serializing relationships. `JSONAPISerializer` supports the http://jsonapi.org/ spec and is the serializer recommended by Ember Data. This serializer normalizes a JSON API payload that looks like: ```js // models/player.js import DS from "ember-data"; export default DS.Model.extend({ name: DS.attr(), skill: DS.attr(), gamesPlayed: DS.attr(), club: DS.belongsTo('club') }); // models/club.js import DS from "ember-data"; export default DS.Model.extend({ name: DS.attr(), location: DS.attr(), players: DS.hasMany('player') }); ``` ```js { "data": [ { "attributes": { "name": "Benfica", "location": "Portugal" }, "id": "1", "relationships": { "players": { "data": [ { "id": "3", "type": "players" } ] } }, "type": "clubs" } ], "included": [ { "attributes": { "name": "Eusebio Silva Ferreira", "skill": "Rocket shot", "games-played": 431 }, "id": "3", "relationships": { "club": { "data": { "id": "1", "type": "clubs" } } }, "type": "players" } ] } ``` to the format that the Ember Data store expects. ### Customizing meta Since a JSON API Document can have meta defined in multiple locations you can use the specific serializer hooks if you need to customize the meta. One scenario would be to camelCase the meta keys of your payload. The example below shows how this could be done using `normalizeArrayResponse` and `extractRelationship`. ```app/serializers/application.js export default JSONAPISerializer.extend({ normalizeArrayResponse(store, primaryModelClass, payload, id, requestType) { let normalizedDocument = this._super(...arguments); // Customize document meta normalizedDocument.meta = camelCaseKeys(normalizedDocument.meta); return normalizedDocument; }, extractRelationship(relationshipHash) { let normalizedRelationship = this._super(...arguments); // Customize relationship meta normalizedRelationship.meta = camelCaseKeys(normalizedRelationship.meta); return normalizedRelationship; } }); ``` @since 1.13.0 @class JSONAPISerializer @namespace DS @extends DS.JSONSerializer */ var JSONAPISerializer = _emberDataSerializersJson.default.extend({ /** @method _normalizeDocumentHelper @param {Object} documentHash @return {Object} @private */ _normalizeDocumentHelper: function (documentHash) { if (_ember.default.typeOf(documentHash.data) === 'object') { documentHash.data = this._normalizeResourceHelper(documentHash.data); } else if (Array.isArray(documentHash.data)) { var ret = new Array(documentHash.data.length); for (var i = 0; i < documentHash.data.length; i++) { var data = documentHash.data[i]; ret[i] = this._normalizeResourceHelper(data); } documentHash.data = ret; } if (Array.isArray(documentHash.included)) { var ret = new Array(documentHash.included.length); for (var i = 0; i < documentHash.included.length; i++) { var included = documentHash.included[i]; ret[i] = this._normalizeResourceHelper(included); } documentHash.included = ret; } return documentHash; }, /** @method _normalizeRelationshipDataHelper @param {Object} relationshipDataHash @return {Object} @private */ _normalizeRelationshipDataHelper: function (relationshipDataHash) { if (false) { var modelName = this.modelNameFromPayloadType(relationshipDataHash.type); var deprecatedModelNameLookup = this.modelNameFromPayloadKey(relationshipDataHash.type); if (modelName !== deprecatedModelNameLookup && this._hasCustomModelNameFromPayloadKey()) { modelName = deprecatedModelNameLookup; } relationshipDataHash.type = modelName; } else { var type = this.modelNameFromPayloadKey(relationshipDataHash.type); relationshipDataHash.type = type; } return relationshipDataHash; }, /** @method _normalizeResourceHelper @param {Object} resourceHash @return {Object} @private */ _normalizeResourceHelper: function (resourceHash) { var modelName = undefined, usedLookup = undefined; if (false) { modelName = this.modelNameFromPayloadType(resourceHash.type); var deprecatedModelNameLookup = this.modelNameFromPayloadKey(resourceHash.type); usedLookup = 'modelNameFromPayloadType'; if (modelName !== deprecatedModelNameLookup && this._hasCustomModelNameFromPayloadKey()) { modelName = deprecatedModelNameLookup; usedLookup = 'modelNameFromPayloadKey'; } } else { modelName = this.modelNameFromPayloadKey(resourceHash.type); usedLookup = 'modelNameFromPayloadKey'; } if (!this.store._hasModelFor(modelName)) { return null; } var modelClass = this.store.modelFor(modelName); var serializer = this.store.serializerFor(modelName); var _serializer$normalize = serializer.normalize(modelClass, resourceHash); var data = _serializer$normalize.data; return data; }, /** @method pushPayload @param {DS.Store} store @param {Object} payload */ pushPayload: function (store, payload) { var normalizedPayload = this._normalizeDocumentHelper(payload); if (false) { return store.push(normalizedPayload); } else { store.push(normalizedPayload); } }, /** @method _normalizeResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @param {Boolean} isSingle @return {Object} JSON-API Document @private */ _normalizeResponse: function (store, primaryModelClass, payload, id, requestType, isSingle) { var normalizedPayload = this._normalizeDocumentHelper(payload); return normalizedPayload; }, normalizeQueryRecordResponse: function () { var normalized = this._super.apply(this, arguments); return normalized; }, extractAttributes: function (modelClass, resourceHash) { var _this = this; var attributes = {}; if (resourceHash.attributes) { modelClass.eachAttribute(function (key) { var attributeKey = _this.keyForAttribute(key, 'deserialize'); if (resourceHash.attributes[attributeKey] !== undefined) { attributes[key] = resourceHash.attributes[attributeKey]; } }); } return attributes; }, extractRelationship: function (relationshipHash) { if (_ember.default.typeOf(relationshipHash.data) === 'object') { relationshipHash.data = this._normalizeRelationshipDataHelper(relationshipHash.data); } if (Array.isArray(relationshipHash.data)) { var ret = new Array(relationshipHash.data.length); for (var i = 0; i < relationshipHash.data.length; i++) { var data = relationshipHash.data[i]; ret[i] = this._normalizeRelationshipDataHelper(data); } relationshipHash.data = ret; } return relationshipHash; }, extractRelationships: function (modelClass, resourceHash) { var _this2 = this; var relationships = {}; if (resourceHash.relationships) { modelClass.eachRelationship(function (key, relationshipMeta) { var relationshipKey = _this2.keyForRelationship(key, relationshipMeta.kind, 'deserialize'); if (resourceHash.relationships[relationshipKey] !== undefined) { var relationshipHash = resourceHash.relationships[relationshipKey]; relationships[key] = _this2.extractRelationship(relationshipHash); } }); } return relationships; }, /** @method _extractType @param {DS.Model} modelClass @param {Object} resourceHash @return {String} @private */ _extractType: function (modelClass, resourceHash) { if (false) { var modelName = this.modelNameFromPayloadType(resourceHash.type); var deprecatedModelNameLookup = this.modelNameFromPayloadKey(resourceHash.type); if (modelName !== deprecatedModelNameLookup && this._hasCustomModelNameFromPayloadKey()) { modelName = deprecatedModelNameLookup; } return modelName; } else { return this.modelNameFromPayloadKey(resourceHash.type); } }, /** Dasherizes and singularizes the model name in the payload to match the format Ember Data uses internally for the model name. For example the key `posts` would be converted to `post` and the key `studentAssesments` would be converted to `student-assesment`. @method modelNameFromPayloadKey @param {String} key @return {String} the model's modelName */ // TODO @deprecated Use modelNameFromPayloadType instead modelNameFromPayloadKey: function (key) { return (0, _emberInflector.singularize)((0, _emberDataPrivateSystemNormalizeModelName.default)(key)); }, /** Converts the model name to a pluralized version of the model name. For example `post` would be converted to `posts` and `student-assesment` would be converted to `student-assesments`. @method payloadKeyFromModelName @param {String} modelName @return {String} */ // TODO @deprecated Use payloadTypeFromModelName instead payloadKeyFromModelName: function (modelName) { return (0, _emberInflector.pluralize)(modelName); }, normalize: function (modelClass, resourceHash) { if (resourceHash.attributes) { this.normalizeUsingDeclaredMapping(modelClass, resourceHash.attributes); } if (resourceHash.relationships) { this.normalizeUsingDeclaredMapping(modelClass, resourceHash.relationships); } var data = { id: this.extractId(modelClass, resourceHash), type: this._extractType(modelClass, resourceHash), attributes: this.extractAttributes(modelClass, resourceHash), relationships: this.extractRelationships(modelClass, resourceHash) }; this.applyTransforms(modelClass, data.attributes); return { data: data }; }, /** `keyForAttribute` can be used to define rules for how to convert an attribute name in your model to a key in your JSON. By default `JSONAPISerializer` follows the format used on the examples of http://jsonapi.org/format and uses dashes as the word separator in the JSON attribute keys. This behaviour can be easily customized by extending this method. Example ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONAPISerializer.extend({ keyForAttribute: function(attr, method) { return Ember.String.dasherize(attr).toUpperCase(); } }); ``` @method keyForAttribute @param {String} key @param {String} method @return {String} normalized key */ keyForAttribute: function (key, method) { return dasherize(key); }, /** `keyForRelationship` can be used to define a custom key when serializing and deserializing relationship properties. By default `JSONAPISerializer` follows the format used on the examples of http://jsonapi.org/format and uses dashes as word separators in relationship properties. This behaviour can be easily customized by extending this method. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONAPISerializer.extend({ keyForRelationship: function(key, relationship, method) { return Ember.String.underscore(key); } }); ``` @method keyForRelationship @param {String} key @param {String} typeClass @param {String} method @return {String} normalized key */ keyForRelationship: function (key, typeClass, method) { return dasherize(key); }, serialize: function (snapshot, options) { var data = this._super.apply(this, arguments); var payloadType = undefined; if (false) { payloadType = this.payloadTypeFromModelName(snapshot.modelName); var deprecatedPayloadTypeLookup = this.payloadKeyFromModelName(snapshot.modelName); if (payloadType !== deprecatedPayloadTypeLookup && this._hasCustomPayloadKeyFromModelName()) { payloadType = deprecatedPayloadTypeLookup; } } else { payloadType = this.payloadKeyFromModelName(snapshot.modelName); } data.type = payloadType; return { data: data }; }, serializeAttribute: function (snapshot, json, key, attribute) { var type = attribute.type; if (this._canSerialize(key)) { json.attributes = json.attributes || {}; var value = snapshot.attr(key); if (type) { var transform = this.transformFor(type); value = transform.serialize(value, attribute.options); } var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key) { payloadKey = this.keyForAttribute(key, 'serialize'); } json.attributes[payloadKey] = value; } }, serializeBelongsTo: function (snapshot, json, relationship) { var key = relationship.key; if (this._canSerialize(key)) { var belongsTo = snapshot.belongsTo(key); if (belongsTo !== undefined) { json.relationships = json.relationships || {}; var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key) { payloadKey = this.keyForRelationship(key, 'belongsTo', 'serialize'); } var data = null; if (belongsTo) { var payloadType = undefined; if (false) { payloadType = this.payloadTypeFromModelName(belongsTo.modelName); var deprecatedPayloadTypeLookup = this.payloadKeyFromModelName(belongsTo.modelName); if (payloadType !== deprecatedPayloadTypeLookup && this._hasCustomPayloadKeyFromModelName()) { payloadType = deprecatedPayloadTypeLookup; } } else { payloadType = this.payloadKeyFromModelName(belongsTo.modelName); } data = { type: payloadType, id: belongsTo.id }; } json.relationships[payloadKey] = { data: data }; } } }, serializeHasMany: function (snapshot, json, relationship) { var key = relationship.key; var shouldSerializeHasMany = '_shouldSerializeHasMany'; if (false) { shouldSerializeHasMany = 'shouldSerializeHasMany'; } if (this[shouldSerializeHasMany](snapshot, key, relationship)) { var hasMany = snapshot.hasMany(key); if (hasMany !== undefined) { json.relationships = json.relationships || {}; var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key && this.keyForRelationship) { payloadKey = this.keyForRelationship(key, 'hasMany', 'serialize'); } var data = new Array(hasMany.length); for (var i = 0; i < hasMany.length; i++) { var item = hasMany[i]; var payloadType = undefined; if (false) { payloadType = this.payloadTypeFromModelName(item.modelName); var deprecatedPayloadTypeLookup = this.payloadKeyFromModelName(item.modelName); if (payloadType !== deprecatedPayloadTypeLookup && this._hasCustomPayloadKeyFromModelName()) { payloadType = deprecatedPayloadTypeLookup; } } else { payloadType = this.payloadKeyFromModelName(item.modelName); } data[i] = { type: payloadType, id: item.id }; } json.relationships[payloadKey] = { data: data }; } } } }); if (false) { JSONAPISerializer.reopen({ /** `modelNameFromPayloadType` can be used to change the mapping for a DS model name, taken from the value in the payload. Say your API namespaces the type of a model and returns the following payload for the `post` model: ```javascript // GET /api/posts/1 { "data": { "id": 1, "type: "api::v1::post" } } ``` By overwriting `modelNameFromPayloadType` you can specify that the `post` model should be used: ```app/serializers/application.js import DS from "ember-data"; export default DS.JSONAPISerializer.extend({ modelNameFromPayloadType(payloadType) { return payloadType.replace('api::v1::', ''); } }); ``` By default the modelName for a model is its singularized name in dasherized form. Usually, Ember Data can use the correct inflection to do this for you. Most of the time, you won't need to override `modelNameFromPayloadType` for this purpose. Also take a look at [payloadTypeFromModelName](#method_payloadTypeFromModelName) to customize how the type of a record should be serialized. @method modelNameFromPayloadType @public @param {String} payloadType type from payload @return {String} modelName */ modelNameFromPayloadType: function (type) { return (0, _emberInflector.singularize)((0, _emberDataPrivateSystemNormalizeModelName.default)(type)); }, /** `payloadTypeFromModelName` can be used to change the mapping for the type in the payload, taken from the model name. Say your API namespaces the type of a model and expects the following payload when you update the `post` model: ```javascript // POST /api/posts/1 { "data": { "id": 1, "type": "api::v1::post" } } ``` By overwriting `payloadTypeFromModelName` you can specify that the namespaces model name for the `post` should be used: ```app/serializers/application.js import DS from "ember-data"; export default JSONAPISerializer.extend({ payloadTypeFromModelName(modelName) { return "api::v1::" + modelName; } }); ``` By default the payload type is the pluralized model name. Usually, Ember Data can use the correct inflection to do this for you. Most of the time, you won't need to override `payloadTypeFromModelName` for this purpose. Also take a look at [modelNameFromPayloadType](#method_modelNameFromPayloadType) to customize how the model name from should be mapped from the payload. @method payloadTypeFromModelName @public @param {String} modelname modelName from the record @return {String} payloadType */ payloadTypeFromModelName: function (modelName) { return (0, _emberInflector.pluralize)(modelName); }, _hasCustomModelNameFromPayloadKey: function () { return this.modelNameFromPayloadKey !== JSONAPISerializer.prototype.modelNameFromPayloadKey; }, _hasCustomPayloadKeyFromModelName: function () { return this.payloadKeyFromModelName !== JSONAPISerializer.prototype.payloadKeyFromModelName; } }); } exports.default = JSONAPISerializer; }); /** @module ember-data */ define('ember-data/serializers/json', ['exports', 'ember', 'ember-data/-private/debug', 'ember-data/serializer', 'ember-data/-private/system/coerce-id', 'ember-data/-private/system/normalize-model-name', 'ember-data/-private/utils', 'ember-data/-private/features', 'ember-data/adapters/errors'], function (exports, _ember, _emberDataPrivateDebug, _emberDataSerializer, _emberDataPrivateSystemCoerceId, _emberDataPrivateSystemNormalizeModelName, _emberDataPrivateUtils, _emberDataPrivateFeatures, _emberDataAdaptersErrors) { function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } } var get = _ember.default.get; var isNone = _ember.default.isNone; var assign = _ember.default.assign || _ember.default.merge; /** Ember Data 2.0 Serializer: In Ember Data a Serializer is used to serialize and deserialize records when they are transferred in and out of an external source. This process involves normalizing property names, transforming attribute values and serializing relationships. By default, Ember Data uses and recommends the `JSONAPISerializer`. `JSONSerializer` is useful for simpler or legacy backends that may not support the http://jsonapi.org/ spec. For example, given the following `User` model and JSON payload: ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ friends: DS.hasMany('user'), house: DS.belongsTo('location'), name: DS.attr('string') }); ``` ```js { id: 1, name: 'Sebastian', friends: [3, 4], links: { house: '/houses/lefkada' } } ``` `JSONSerializer` will normalize the JSON payload to the JSON API format that the Ember Data store expects. You can customize how JSONSerializer processes its payload by passing options in the `attrs` hash or by subclassing the `JSONSerializer` and overriding hooks: - To customize how a single record is normalized, use the `normalize` hook. - To customize how `JSONSerializer` normalizes the whole server response, use the `normalizeResponse` hook. - To customize how `JSONSerializer` normalizes a specific response from the server, use one of the many specific `normalizeResponse` hooks. - To customize how `JSONSerializer` normalizes your id, attributes or relationships, use the `extractId`, `extractAttributes` and `extractRelationships` hooks. The `JSONSerializer` normalization process follows these steps: - `normalizeResponse` - entry method to the serializer. - `normalizeCreateRecordResponse` - a `normalizeResponse` for a specific operation is called. - `normalizeSingleResponse`|`normalizeArrayResponse` - for methods like `createRecord` we expect a single record back, while for methods like `findAll` we expect multiple methods back. - `normalize` - `normalizeArray` iterates and calls `normalize` for each of its records while `normalizeSingle` calls it once. This is the method you most likely want to subclass. - `extractId` | `extractAttributes` | `extractRelationships` - `normalize` delegates to these methods to turn the record payload into the JSON API format. @class JSONSerializer @namespace DS @extends DS.Serializer */ var JSONSerializer = _emberDataSerializer.default.extend({ /** The `primaryKey` is used when serializing and deserializing data. Ember Data always uses the `id` property to store the id of the record. The external source may not always follow this convention. In these cases it is useful to override the `primaryKey` property to match the `primaryKey` of your external store. Example ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ primaryKey: '_id' }); ``` @property primaryKey @type {String} @default 'id' */ primaryKey: 'id', /** The `attrs` object can be used to declare a simple mapping between property names on `DS.Model` records and payload keys in the serialized JSON object representing the record. An object with the property `key` can also be used to designate the attribute's key on the response payload. Example ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string'), admin: DS.attr('boolean') }); ``` ```app/serializers/person.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ attrs: { admin: 'is_admin', occupation: { key: 'career' } } }); ``` You can also remove attributes by setting the `serialize` key to `false` in your mapping object. Example ```app/serializers/person.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ attrs: { admin: { serialize: false }, occupation: { key: 'career' } } }); ``` When serialized: ```javascript { "firstName": "Harry", "lastName": "Houdini", "career": "magician" } ``` Note that the `admin` is now not included in the payload. @property attrs @type {Object} */ mergedProperties: ['attrs'], /** Given a subclass of `DS.Model` and a JSON object this method will iterate through each attribute of the `DS.Model` and invoke the `DS.Transform#deserialize` method on the matching property of the JSON object. This method is typically called after the serializer's `normalize` method. @method applyTransforms @private @param {DS.Model} typeClass @param {Object} data The data to transform @return {Object} data The transformed data object */ applyTransforms: function (typeClass, data) { var _this = this; var attributes = get(typeClass, 'attributes'); typeClass.eachTransformedAttribute(function (key, typeClass) { if (data[key] === undefined) { return; } var transform = _this.transformFor(typeClass); var transformMeta = attributes.get(key); data[key] = transform.deserialize(data[key], transformMeta.options); }); return data; }, /** The `normalizeResponse` method is used to normalize a payload from the server to a JSON-API Document. http://jsonapi.org/format/#document-structure This method delegates to a more specific normalize method based on the `requestType`. To override this method with a custom one, make sure to call `return this._super(store, primaryModelClass, payload, id, requestType)` with your pre-processed data. Here's an example of using `normalizeResponse` manually: ```javascript socket.on('message', function(message) { var data = message.data; var modelClass = store.modelFor(data.modelName); var serializer = store.serializerFor(data.modelName); var normalized = serializer.normalizeSingleResponse(store, modelClass, data, data.id); store.push(normalized); }); ``` @since 1.13.0 @method normalizeResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeResponse: function (store, primaryModelClass, payload, id, requestType) { switch (requestType) { case 'findRecord': return this.normalizeFindRecordResponse.apply(this, arguments); case 'queryRecord': return this.normalizeQueryRecordResponse.apply(this, arguments); case 'findAll': return this.normalizeFindAllResponse.apply(this, arguments); case 'findBelongsTo': return this.normalizeFindBelongsToResponse.apply(this, arguments); case 'findHasMany': return this.normalizeFindHasManyResponse.apply(this, arguments); case 'findMany': return this.normalizeFindManyResponse.apply(this, arguments); case 'query': return this.normalizeQueryResponse.apply(this, arguments); case 'createRecord': return this.normalizeCreateRecordResponse.apply(this, arguments); case 'deleteRecord': return this.normalizeDeleteRecordResponse.apply(this, arguments); case 'updateRecord': return this.normalizeUpdateRecordResponse.apply(this, arguments); } }, /** @since 1.13.0 @method normalizeFindRecordResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeFindRecordResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSingleResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeQueryRecordResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeQueryRecordResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSingleResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeFindAllResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeFindAllResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeArrayResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeFindBelongsToResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeFindBelongsToResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSingleResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeFindHasManyResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeFindHasManyResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeArrayResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeFindManyResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeFindManyResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeArrayResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeQueryResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeQueryResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeArrayResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeCreateRecordResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeCreateRecordResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSaveResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeDeleteRecordResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeDeleteRecordResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSaveResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeUpdateRecordResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeUpdateRecordResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSaveResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeSaveResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeSaveResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSingleResponse.apply(this, arguments); }, /** @since 1.13.0 @method normalizeSingleResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeSingleResponse: function (store, primaryModelClass, payload, id, requestType) { return this._normalizeResponse(store, primaryModelClass, payload, id, requestType, true); }, /** @since 1.13.0 @method normalizeArrayResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeArrayResponse: function (store, primaryModelClass, payload, id, requestType) { return this._normalizeResponse(store, primaryModelClass, payload, id, requestType, false); }, /** @method _normalizeResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @param {Boolean} isSingle @return {Object} JSON-API Document @private */ _normalizeResponse: function (store, primaryModelClass, payload, id, requestType, isSingle) { var documentHash = { data: null, included: [] }; var meta = this.extractMeta(store, primaryModelClass, payload); if (meta) { documentHash.meta = meta; } if (isSingle) { var _normalize = this.normalize(primaryModelClass, payload); var data = _normalize.data; var included = _normalize.included; documentHash.data = data; if (included) { documentHash.included = included; } } else { var ret = new Array(payload.length); for (var i = 0, l = payload.length; i < l; i++) { var item = payload[i]; var _normalize2 = this.normalize(primaryModelClass, item); var data = _normalize2.data; var included = _normalize2.included; if (included) { var _documentHash$included; (_documentHash$included = documentHash.included).push.apply(_documentHash$included, _toConsumableArray(included)); } ret[i] = data; } documentHash.data = ret; } return documentHash; }, /** Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do. It takes the type of the record that is being normalized (as a DS.Model class), the property where the hash was originally found, and the hash to normalize. You can use this method, for example, to normalize underscored keys to camelized or other general-purpose normalizations. Example ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ normalize: function(typeClass, hash) { var fields = Ember.get(typeClass, 'fields'); fields.forEach(function(field) { var payloadField = Ember.String.underscore(field); if (field === payloadField) { return; } hash[field] = hash[payloadField]; delete hash[payloadField]; }); return this._super.apply(this, arguments); } }); ``` @method normalize @param {DS.Model} typeClass @param {Object} hash @return {Object} */ normalize: function (modelClass, resourceHash) { var data = null; if (resourceHash) { this.normalizeUsingDeclaredMapping(modelClass, resourceHash); if (_ember.default.typeOf(resourceHash.links) === 'object') { this.normalizeUsingDeclaredMapping(modelClass, resourceHash.links); } data = { id: this.extractId(modelClass, resourceHash), type: modelClass.modelName, attributes: this.extractAttributes(modelClass, resourceHash), relationships: this.extractRelationships(modelClass, resourceHash) }; this.applyTransforms(modelClass, data.attributes); } return { data: data }; }, /** Returns the resource's ID. @method extractId @param {Object} modelClass @param {Object} resourceHash @return {String} */ extractId: function (modelClass, resourceHash) { var primaryKey = get(this, 'primaryKey'); var id = resourceHash[primaryKey]; return (0, _emberDataPrivateSystemCoerceId.default)(id); }, /** Returns the resource's attributes formatted as a JSON-API "attributes object". http://jsonapi.org/format/#document-resource-object-attributes @method extractAttributes @param {Object} modelClass @param {Object} resourceHash @return {Object} */ extractAttributes: function (modelClass, resourceHash) { var _this2 = this; var attributeKey; var attributes = {}; modelClass.eachAttribute(function (key) { attributeKey = _this2.keyForAttribute(key, 'deserialize'); if (resourceHash[attributeKey] !== undefined) { attributes[key] = resourceHash[attributeKey]; } }); return attributes; }, /** Returns a relationship formatted as a JSON-API "relationship object". http://jsonapi.org/format/#document-resource-object-relationships @method extractRelationship @param {Object} relationshipModelName @param {Object} relationshipHash @return {Object} */ extractRelationship: function (relationshipModelName, relationshipHash) { if (_ember.default.isNone(relationshipHash)) { return null; } /* When `relationshipHash` is an object it usually means that the relationship is polymorphic. It could however also be embedded resources that the EmbeddedRecordsMixin has be able to process. */ if (_ember.default.typeOf(relationshipHash) === 'object') { if (relationshipHash.id) { relationshipHash.id = (0, _emberDataPrivateSystemCoerceId.default)(relationshipHash.id); } var modelClass = this.store.modelFor(relationshipModelName); if (relationshipHash.type && !(0, _emberDataPrivateUtils.modelHasAttributeOrRelationshipNamedType)(modelClass)) { if (false) { var modelName = this.modelNameFromPayloadType(relationshipHash.type); var deprecatedModelNameLookup = this.modelNameFromPayloadKey(relationshipHash.type); if (modelName !== deprecatedModelNameLookup && this._hasCustomModelNameFromPayloadKey()) { modelName = deprecatedModelNameLookup; } relationshipHash.type = modelName; } else { relationshipHash.type = this.modelNameFromPayloadKey(relationshipHash.type); } } return relationshipHash; } return { id: (0, _emberDataPrivateSystemCoerceId.default)(relationshipHash), type: relationshipModelName }; }, /** Returns a polymorphic relationship formatted as a JSON-API "relationship object". http://jsonapi.org/format/#document-resource-object-relationships `relationshipOptions` is a hash which contains more information about the polymorphic relationship which should be extracted: - `resourceHash` complete hash of the resource the relationship should be extracted from - `relationshipKey` key under which the value for the relationship is extracted from the resourceHash - `relationshipMeta` meta information about the relationship @method extractPolymorphicRelationship @param {Object} relationshipModelName @param {Object} relationshipHash @param {Object} relationshipOptions @return {Object} */ extractPolymorphicRelationship: function (relationshipModelName, relationshipHash, relationshipOptions) { return this.extractRelationship(relationshipModelName, relationshipHash); }, /** Returns the resource's relationships formatted as a JSON-API "relationships object". http://jsonapi.org/format/#document-resource-object-relationships @method extractRelationships @param {Object} modelClass @param {Object} resourceHash @return {Object} */ extractRelationships: function (modelClass, resourceHash) { var _this3 = this; var relationships = {}; modelClass.eachRelationship(function (key, relationshipMeta) { var relationship = null; var relationshipKey = _this3.keyForRelationship(key, relationshipMeta.kind, 'deserialize'); if (resourceHash[relationshipKey] !== undefined) { var data = null; var relationshipHash = resourceHash[relationshipKey]; if (relationshipMeta.kind === 'belongsTo') { if (relationshipMeta.options.polymorphic) { // extracting a polymorphic belongsTo may need more information // than the type and the hash (which might only be an id) for the // relationship, hence we pass the key, resource and // relationshipMeta too data = _this3.extractPolymorphicRelationship(relationshipMeta.type, relationshipHash, { key: key, resourceHash: resourceHash, relationshipMeta: relationshipMeta }); } else { data = _this3.extractRelationship(relationshipMeta.type, relationshipHash); } } else if (relationshipMeta.kind === 'hasMany') { if (!_ember.default.isNone(relationshipHash)) { data = new Array(relationshipHash.length); for (var i = 0, l = relationshipHash.length; i < l; i++) { var item = relationshipHash[i]; data[i] = _this3.extractRelationship(relationshipMeta.type, item); } } } relationship = { data: data }; } var linkKey = _this3.keyForLink(key, relationshipMeta.kind); if (resourceHash.links && resourceHash.links[linkKey] !== undefined) { var related = resourceHash.links[linkKey]; relationship = relationship || {}; relationship.links = { related: related }; } if (relationship) { relationships[key] = relationship; } }); return relationships; }, /** @method modelNameFromPayloadKey @param {String} key @return {String} the model's modelName */ // TODO @deprecated Use modelNameFromPayloadType instead modelNameFromPayloadKey: function (key) { return (0, _emberDataPrivateSystemNormalizeModelName.default)(key); }, /** @method normalizeRelationships @private */ normalizeRelationships: function (typeClass, hash) { var _this4 = this; var payloadKey; if (this.keyForRelationship) { typeClass.eachRelationship(function (key, relationship) { payloadKey = _this4.keyForRelationship(key, relationship.kind, 'deserialize'); if (key === payloadKey) { return; } if (hash[payloadKey] === undefined) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }); } }, /** @method normalizeUsingDeclaredMapping @private */ normalizeUsingDeclaredMapping: function (modelClass, hash) { var attrs = get(this, 'attrs'); var normalizedKey, payloadKey, key; if (attrs) { for (key in attrs) { normalizedKey = payloadKey = this._getMappedKey(key, modelClass); if (hash[payloadKey] === undefined) { continue; } if (get(modelClass, 'attributes').has(key)) { normalizedKey = this.keyForAttribute(key); } if (get(modelClass, 'relationshipsByName').has(key)) { normalizedKey = this.keyForRelationship(key); } if (payloadKey !== normalizedKey) { hash[normalizedKey] = hash[payloadKey]; delete hash[payloadKey]; } } } }, /** Looks up the property key that was set by the custom `attr` mapping passed to the serializer. @method _getMappedKey @private @param {String} key @return {String} key */ _getMappedKey: function (key, modelClass) { var attrs = get(this, 'attrs'); var mappedKey; if (attrs && attrs[key]) { mappedKey = attrs[key]; //We need to account for both the { title: 'post_title' } and //{ title: { key: 'post_title' }} forms if (mappedKey.key) { mappedKey = mappedKey.key; } if (typeof mappedKey === 'string') { key = mappedKey; } } return key; }, /** Check attrs.key.serialize property to inform if the `key` can be serialized @method _canSerialize @private @param {String} key @return {boolean} true if the key can be serialized */ _canSerialize: function (key) { var attrs = get(this, 'attrs'); return !attrs || !attrs[key] || attrs[key].serialize !== false; }, /** When attrs.key.serialize is set to true then it takes priority over the other checks and the related attribute/relationship will be serialized @method _mustSerialize @private @param {String} key @return {boolean} true if the key must be serialized */ _mustSerialize: function (key) { var attrs = get(this, 'attrs'); return attrs && attrs[key] && attrs[key].serialize === true; }, /** Check if the given hasMany relationship should be serialized @method shouldSerializeHasMany @param {DS.Snapshot} snapshot @param {String} key @param {String} relationshipType @return {boolean} true if the hasMany relationship should be serialized */ shouldSerializeHasMany: function (snapshot, key, relationship) { if (this._shouldSerializeHasMany !== JSONSerializer.prototype._shouldSerializeHasMany) {} return this._shouldSerializeHasMany(snapshot, key, relationship); }, /** Check if the given hasMany relationship should be serialized @method _shouldSerializeHasMany @private @param {DS.Snapshot} snapshot @param {String} key @param {String} relationshipType @return {boolean} true if the hasMany relationship should be serialized */ _shouldSerializeHasMany: function (snapshot, key, relationship) { var relationshipType = snapshot.type.determineRelationshipType(relationship, this.store); if (this._mustSerialize(key)) { return true; } return this._canSerialize(key) && (relationshipType === 'manyToNone' || relationshipType === 'manyToMany'); }, // SERIALIZE /** Called when a record is saved in order to convert the record into JSON. By default, it creates a JSON object with a key for each attribute and belongsTo relationship. For example, consider this model: ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.belongsTo('user') }); ``` The default serialization would create a JSON object like: ```javascript { "title": "Rails is unagi", "body": "Rails? Omakase? O_O", "author": 12 } ``` By default, attributes are passed through as-is, unless you specified an attribute type (`DS.attr('date')`). If you specify a transform, the JavaScript value will be serialized when inserted into the JSON hash. By default, belongs-to relationships are converted into IDs when inserted into the JSON hash. ## IDs `serialize` takes an options hash with a single option: `includeId`. If this option is `true`, `serialize` will, by default include the ID in the JSON object it builds. The adapter passes in `includeId: true` when serializing a record for `createRecord`, but not for `updateRecord`. ## Customization Your server may expect a different JSON format than the built-in serialization format. In that case, you can implement `serialize` yourself and return a JSON hash of your choosing. ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serialize: function(snapshot, options) { var json = { POST_TTL: snapshot.attr('title'), POST_BDY: snapshot.attr('body'), POST_CMS: snapshot.hasMany('comments', { ids: true }) } if (options.includeId) { json.POST_ID_ = snapshot.id; } return json; } }); ``` ## Customizing an App-Wide Serializer If you want to define a serializer for your entire application, you'll probably want to use `eachAttribute` and `eachRelationship` on the record. ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serialize: function(snapshot, options) { var json = {}; snapshot.eachAttribute(function(name) { json[serverAttributeName(name)] = snapshot.attr(name); }) snapshot.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true }); } }); if (options.includeId) { json.ID_ = snapshot.id; } return json; } }); function serverAttributeName(attribute) { return attribute.underscore().toUpperCase(); } function serverHasManyName(name) { return serverAttributeName(name.singularize()) + "_IDS"; } ``` This serializer will generate JSON that looks like this: ```javascript { "TITLE": "Rails is omakase", "BODY": "Yep. Omakase.", "COMMENT_IDS": [ 1, 2, 3 ] } ``` ## Tweaking the Default JSON If you just want to do some small tweaks on the default JSON, you can call super first and make the tweaks on the returned JSON. ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serialize: function(snapshot, options) { var json = this._super.apply(this, arguments); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param {DS.Snapshot} snapshot @param {Object} options @return {Object} json */ serialize: function (snapshot, options) { var _this5 = this; var json = {}; if (options && options.includeId) { if (false) { this.serializeId(snapshot, json, get(this, 'primaryKey')); } else { var id = snapshot.id; if (id) { json[get(this, 'primaryKey')] = id; } } } snapshot.eachAttribute(function (key, attribute) { _this5.serializeAttribute(snapshot, json, key, attribute); }); snapshot.eachRelationship(function (key, relationship) { if (relationship.kind === 'belongsTo') { _this5.serializeBelongsTo(snapshot, json, relationship); } else if (relationship.kind === 'hasMany') { _this5.serializeHasMany(snapshot, json, relationship); } }); return json; }, /** You can use this method to customize how a serialized record is added to the complete JSON hash to be sent to the server. By default the JSON Serializer does not namespace the payload and just sends the raw serialized JSON object. If your server expects namespaced keys, you should consider using the RESTSerializer. Otherwise you can override this method to customize how the record is added to the hash. The hash property should be modified by reference. For example, your server may expect underscored root objects. ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ serializeIntoHash: function(data, type, snapshot, options) { var root = Ember.String.decamelize(type.modelName); data[root] = this.serialize(snapshot, options); } }); ``` @method serializeIntoHash @param {Object} hash @param {DS.Model} typeClass @param {DS.Snapshot} snapshot @param {Object} options */ serializeIntoHash: function (hash, typeClass, snapshot, options) { assign(hash, this.serialize(snapshot, options)); }, /** `serializeAttribute` can be used to customize how `DS.attr` properties are serialized For example if you wanted to ensure all your attributes were always serialized as properties on an `attributes` object you could write: ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serializeAttribute: function(snapshot, json, key, attributes) { json.attributes = json.attributes || {}; this._super(snapshot, json.attributes, key, attributes); } }); ``` @method serializeAttribute @param {DS.Snapshot} snapshot @param {Object} json @param {String} key @param {Object} attribute */ serializeAttribute: function (snapshot, json, key, attribute) { var type = attribute.type; if (this._canSerialize(key)) { var value = snapshot.attr(key); if (type) { var transform = this.transformFor(type); value = transform.serialize(value, attribute.options); } // if provided, use the mapping provided by `attrs` in // the serializer var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key && this.keyForAttribute) { payloadKey = this.keyForAttribute(key, 'serialize'); } json[payloadKey] = value; } }, /** `serializeBelongsTo` can be used to customize how `DS.belongsTo` properties are serialized. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serializeBelongsTo: function(snapshot, json, relationship) { var key = relationship.key; var belongsTo = snapshot.belongsTo(key); key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo", "serialize") : key; json[key] = Ember.isNone(belongsTo) ? belongsTo : belongsTo.record.toJSON(); } }); ``` @method serializeBelongsTo @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeBelongsTo: function (snapshot, json, relationship) { var key = relationship.key; if (this._canSerialize(key)) { var belongsToId = snapshot.belongsTo(key, { id: true }); // if provided, use the mapping provided by `attrs` in // the serializer var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key && this.keyForRelationship) { payloadKey = this.keyForRelationship(key, "belongsTo", "serialize"); } //Need to check whether the id is there for new&async records if (isNone(belongsToId)) { json[payloadKey] = null; } else { json[payloadKey] = belongsToId; } if (relationship.options.polymorphic) { this.serializePolymorphicType(snapshot, json, relationship); } } }, /** `serializeHasMany` can be used to customize how `DS.hasMany` properties are serialized. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serializeHasMany: function(snapshot, json, relationship) { var key = relationship.key; if (key === 'comments') { return; } else { this._super.apply(this, arguments); } } }); ``` @method serializeHasMany @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeHasMany: function (snapshot, json, relationship) { var key = relationship.key; var shouldSerializeHasMany = '_shouldSerializeHasMany'; if (false) { shouldSerializeHasMany = 'shouldSerializeHasMany'; } if (this[shouldSerializeHasMany](snapshot, key, relationship)) { var hasMany = snapshot.hasMany(key, { ids: true }); if (hasMany !== undefined) { // if provided, use the mapping provided by `attrs` in // the serializer var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key && this.keyForRelationship) { payloadKey = this.keyForRelationship(key, "hasMany", "serialize"); } json[payloadKey] = hasMany; // TODO support for polymorphic manyToNone and manyToMany relationships } } }, /** You can use this method to customize how polymorphic objects are serialized. Objects are considered to be polymorphic if `{ polymorphic: true }` is pass as the second argument to the `DS.belongsTo` function. Example ```app/serializers/comment.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serializePolymorphicType: function(snapshot, json, relationship) { var key = relationship.key, belongsTo = snapshot.belongsTo(key); key = this.keyForAttribute ? this.keyForAttribute(key, "serialize") : key; if (Ember.isNone(belongsTo)) { json[key + "_type"] = null; } else { json[key + "_type"] = belongsTo.modelName; } } }); ``` @method serializePolymorphicType @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializePolymorphicType: function () {}, /** `extractMeta` is used to deserialize any meta information in the adapter payload. By default Ember Data expects meta information to be located on the `meta` property of the payload object. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ extractMeta: function(store, typeClass, payload) { if (payload && payload.hasOwnProperty('_pagination')) { let meta = payload._pagination; delete payload._pagination; return meta; } } }); ``` @method extractMeta @param {DS.Store} store @param {DS.Model} modelClass @param {Object} payload */ extractMeta: function (store, modelClass, payload) { if (payload && payload['meta'] !== undefined) { var meta = payload.meta; delete payload.meta; return meta; } }, /** `extractErrors` is used to extract model errors when a call to `DS.Model#save` fails with an `InvalidError`. By default Ember Data expects error information to be located on the `errors` property of the payload object. This serializer expects this `errors` object to be an Array similar to the following, compliant with the JSON-API specification: ```js { "errors": [ { "detail": "This username is already taken!", "source": { "pointer": "data/attributes/username" } }, { "detail": "Doesn't look like a valid email.", "source": { "pointer": "data/attributes/email" } } ] } ``` The key `detail` provides a textual description of the problem. Alternatively, the key `title` can be used for the same purpose. The nested keys `source.pointer` detail which specific element of the request data was invalid. Note that JSON-API also allows for object-level errors to be placed in an object with pointer `data`, signifying that the problem cannot be traced to a specific attribute: ```javascript { "errors": [ { "detail": "Some generic non property error message", "source": { "pointer": "data" } } ] } ``` When turn into a `DS.Errors` object, you can read these errors through the property `base`: ```handlebars {{#each model.errors.base as |error|}} <div class="error"> {{error.message}} </div> {{/each}} ``` Example of alternative implementation, overriding the default behavior to deal with a different format of errors: ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ extractErrors: function(store, typeClass, payload, id) { if (payload && typeof payload === 'object' && payload._problems) { payload = payload._problems; this.normalizeErrors(typeClass, payload); } return payload; } }); ``` @method extractErrors @param {DS.Store} store @param {DS.Model} typeClass @param {Object} payload @param {(String|Number)} id @return {Object} json The deserialized errors */ extractErrors: function (store, typeClass, payload, id) { var _this6 = this; if (payload && typeof payload === 'object' && payload.errors) { payload = (0, _emberDataAdaptersErrors.errorsArrayToHash)(payload.errors); this.normalizeUsingDeclaredMapping(typeClass, payload); typeClass.eachAttribute(function (name) { var key = _this6.keyForAttribute(name, 'deserialize'); if (key !== name && payload[key] !== undefined) { payload[name] = payload[key]; delete payload[key]; } }); typeClass.eachRelationship(function (name) { var key = _this6.keyForRelationship(name, 'deserialize'); if (key !== name && payload[key] !== undefined) { payload[name] = payload[key]; delete payload[key]; } }); } return payload; }, /** `keyForAttribute` can be used to define rules for how to convert an attribute name in your model to a key in your JSON. Example ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ keyForAttribute: function(attr, method) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` @method keyForAttribute @param {String} key @param {String} method @return {String} normalized key */ keyForAttribute: function (key, method) { return key; }, /** `keyForRelationship` can be used to define a custom key when serializing and deserializing relationship properties. By default `JSONSerializer` does not provide an implementation of this method. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ keyForRelationship: function(key, relationship, method) { return 'rel_' + Ember.String.underscore(key); } }); ``` @method keyForRelationship @param {String} key @param {String} typeClass @param {String} method @return {String} normalized key */ keyForRelationship: function (key, typeClass, method) { return key; }, /** `keyForLink` can be used to define a custom key when deserializing link properties. @method keyForLink @param {String} key @param {String} kind `belongsTo` or `hasMany` @return {String} normalized key */ keyForLink: function (key, kind) { return key; }, // HELPERS /** @method transformFor @private @param {String} attributeType @param {Boolean} skipAssertion @return {DS.Transform} transform */ transformFor: function (attributeType, skipAssertion) { var transform = (0, _emberDataPrivateUtils.getOwner)(this).lookup('transform:' + attributeType); return transform; } }); if (false) { JSONSerializer.reopen({ /** @method modelNameFromPayloadType @public @param {String} type @return {String} the model's modelName */ modelNameFromPayloadType: function (type) { return (0, _emberDataPrivateSystemNormalizeModelName.default)(type); }, _hasCustomModelNameFromPayloadKey: function () { return this.modelNameFromPayloadKey !== JSONSerializer.prototype.modelNameFromPayloadKey; } }); } if (false) { JSONSerializer.reopen({ /** serializeId can be used to customize how id is serialized For example, your server may expect integer datatype of id By default the snapshot's id (String) is set on the json hash via json[primaryKey] = snapshot.id. ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ serializeId(snapshot, json, primaryKey) { var id = snapshot.id; json[primaryKey] = parseInt(id, 10); } }); ``` @method serializeId @public @param {DS.Snapshot} snapshot @param {Object} json @param {String} primaryKey */ serializeId: function (snapshot, json, primaryKey) { var id = snapshot.id; if (id) { json[primaryKey] = id; } } }); } exports.default = JSONSerializer; }); define("ember-data/serializers/rest", ["exports", "ember", "ember-data/-private/debug", "ember-data/serializers/json", "ember-data/-private/system/normalize-model-name", "ember-inflector", "ember-data/-private/system/coerce-id", "ember-data/-private/utils", "ember-data/-private/features"], function (exports, _ember, _emberDataPrivateDebug, _emberDataSerializersJson, _emberDataPrivateSystemNormalizeModelName, _emberInflector, _emberDataPrivateSystemCoerceId, _emberDataPrivateUtils, _emberDataPrivateFeatures) { function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } } var camelize = _ember.default.String.camelize; /** Normally, applications will use the `RESTSerializer` by implementing the `normalize` method. This allows you to do whatever kind of munging you need, and is especially useful if your server is inconsistent and you need to do munging differently for many different kinds of responses. See the `normalize` documentation for more information. ## Across the Board Normalization There are also a number of hooks that you might find useful to define across-the-board rules for your payload. These rules will be useful if your server is consistent, or if you're building an adapter for an infrastructure service, like Firebase, and want to encode service conventions. For example, if all of your keys are underscored and all-caps, but otherwise consistent with the names you use in your models, you can implement across-the-board rules for how to convert an attribute name in your model to a key in your JSON. ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ keyForAttribute: function(attr, method) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` You can also implement `keyForRelationship`, which takes the name of the relationship as the first parameter, the kind of relationship (`hasMany` or `belongsTo`) as the second parameter, and the method (`serialize` or `deserialize`) as the third parameter. @class RESTSerializer @namespace DS @extends DS.JSONSerializer */ var RESTSerializer = _emberDataSerializersJson.default.extend({ /** `keyForPolymorphicType` can be used to define a custom key when serializing and deserializing a polymorphic type. By default, the returned key is `${key}Type`. Example ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ keyForPolymorphicType: function(key, relationship) { var relationshipKey = this.keyForRelationship(key); return 'type-' + relationshipKey; } }); ``` @method keyForPolymorphicType @param {String} key @param {String} typeClass @param {String} method @return {String} normalized key */ keyForPolymorphicType: function (key, typeClass, method) { var relationshipKey = this.keyForRelationship(key); return relationshipKey + "Type"; }, /** Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do. It takes the type of the record that is being normalized (as a DS.Model class), the property where the hash was originally found, and the hash to normalize. For example, if you have a payload that looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2 ] }, "comments": [{ "id": 1, "body": "FIRST" }, { "id": 2, "body": "Rails is unagi" }] } ``` The `normalize` method will be called three times: * With `App.Post`, `"posts"` and `{ id: 1, title: "Rails is omakase", ... }` * With `App.Comment`, `"comments"` and `{ id: 1, body: "FIRST" }` * With `App.Comment`, `"comments"` and `{ id: 2, body: "Rails is unagi" }` You can use this method, for example, to normalize underscored keys to camelized or other general-purpose normalizations. You will only need to implement `normalize` and manipulate the payload as desired. For example, if the `IDs` under `"comments"` are provided as `_id` instead of `id`, you can specify how to normalize just the comments: ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ normalize(model, hash, prop) { if (prop === 'comments') { hash.id = hash._id; delete hash._id; } return this._super(...arguments); } }); ``` On each call to the `normalize` method, the third parameter (`prop`) is always one of the keys that were in the original payload or in the result of another normalization as `normalizeResponse`. @method normalize @param {DS.Model} modelClass @param {Object} resourceHash @param {String} prop @return {Object} */ normalize: function (modelClass, resourceHash, prop) { if (this.normalizeHash && this.normalizeHash[prop]) { this.normalizeHash[prop](resourceHash); } return this._super(modelClass, resourceHash); }, /** Normalizes an array of resource payloads and returns a JSON-API Document with primary data and, if any, included data as `{ data, included }`. @method _normalizeArray @param {DS.Store} store @param {String} modelName @param {Object} arrayHash @param {String} prop @return {Object} @private */ _normalizeArray: function (store, modelName, arrayHash, prop) { var _this = this; var documentHash = { data: [], included: [] }; var modelClass = store.modelFor(modelName); var serializer = store.serializerFor(modelName); _ember.default.makeArray(arrayHash).forEach(function (hash) { var _normalizePolymorphicRecord = _this._normalizePolymorphicRecord(store, hash, prop, modelClass, serializer); var data = _normalizePolymorphicRecord.data; var included = _normalizePolymorphicRecord.included; documentHash.data.push(data); if (included) { var _documentHash$included; (_documentHash$included = documentHash.included).push.apply(_documentHash$included, _toConsumableArray(included)); } }); return documentHash; }, _normalizePolymorphicRecord: function (store, hash, prop, primaryModelClass, primarySerializer) { var serializer = primarySerializer; var modelClass = primaryModelClass; var primaryHasTypeAttribute = (0, _emberDataPrivateUtils.modelHasAttributeOrRelationshipNamedType)(primaryModelClass); if (!primaryHasTypeAttribute && hash.type) { // Support polymorphic records in async relationships var modelName = undefined; if (false) { modelName = this.modelNameFromPayloadType(hash.type); var deprecatedModelNameLookup = this.modelNameFromPayloadKey(hash.type); if (modelName !== deprecatedModelNameLookup && !this._hasCustomModelNameFromPayloadType() && this._hasCustomModelNameFromPayloadKey()) { modelName = deprecatedModelNameLookup; } } else { modelName = this.modelNameFromPayloadKey(hash.type); } if (store._hasModelFor(modelName)) { serializer = store.serializerFor(modelName); modelClass = store.modelFor(modelName); } } return serializer.normalize(modelClass, hash, prop); }, /* @method _normalizeResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @param {Boolean} isSingle @return {Object} JSON-API Document @private */ _normalizeResponse: function (store, primaryModelClass, payload, id, requestType, isSingle) { var documentHash = { data: null, included: [] }; var meta = this.extractMeta(store, primaryModelClass, payload); if (meta) { documentHash.meta = meta; } var keys = Object.keys(payload); for (var i = 0, _length = keys.length; i < _length; i++) { var prop = keys[i]; var modelName = prop; var forcedSecondary = false; /* If you want to provide sideloaded records of the same type that the primary data you can do that by prefixing the key with `_`. Example ``` { users: [ { id: 1, title: 'Tom', manager: 3 }, { id: 2, title: 'Yehuda', manager: 3 } ], _users: [ { id: 3, title: 'Tomster' } ] } ``` This forces `_users` to be added to `included` instead of `data`. */ if (prop.charAt(0) === '_') { forcedSecondary = true; modelName = prop.substr(1); } var typeName = this.modelNameFromPayloadKey(modelName); if (!store.modelFactoryFor(typeName)) { continue; } var isPrimary = !forcedSecondary && this.isPrimaryType(store, typeName, primaryModelClass); var value = payload[prop]; if (value === null) { continue; } /* Support primary data as an object instead of an array. Example ``` { user: { id: 1, title: 'Tom', manager: 3 } } ``` */ if (isPrimary && _ember.default.typeOf(value) !== 'array') { var _normalizePolymorphicRecord2 = this._normalizePolymorphicRecord(store, value, prop, primaryModelClass, this); var _data = _normalizePolymorphicRecord2.data; var _included = _normalizePolymorphicRecord2.included; documentHash.data = _data; if (_included) { var _documentHash$included2; (_documentHash$included2 = documentHash.included).push.apply(_documentHash$included2, _toConsumableArray(_included)); } continue; } var _normalizeArray = this._normalizeArray(store, typeName, value, prop); var data = _normalizeArray.data; var included = _normalizeArray.included; if (included) { var _documentHash$included3; (_documentHash$included3 = documentHash.included).push.apply(_documentHash$included3, _toConsumableArray(included)); } if (isSingle) { data.forEach(function (resource) { /* Figures out if this is the primary record or not. It's either: 1. The record with the same ID as the original request 2. If it's a newly created record without an ID, the first record in the array */ var isUpdatedRecord = isPrimary && (0, _emberDataPrivateSystemCoerceId.default)(resource.id) === id; var isFirstCreatedRecord = isPrimary && !id && !documentHash.data; if (isFirstCreatedRecord || isUpdatedRecord) { documentHash.data = resource; } else { documentHash.included.push(resource); } }); } else { if (isPrimary) { documentHash.data = data; } else { if (data) { var _documentHash$included4; (_documentHash$included4 = documentHash.included).push.apply(_documentHash$included4, _toConsumableArray(data)); } } } } return documentHash; }, isPrimaryType: function (store, typeName, primaryTypeClass) { var typeClass = store.modelFor(typeName); return typeClass.modelName === primaryTypeClass.modelName; }, /** This method allows you to push a payload containing top-level collections of records organized per type. ```js { "posts": [{ "id": "1", "title": "Rails is omakase", "author", "1", "comments": [ "1" ] }], "comments": [{ "id": "1", "body": "FIRST" }], "users": [{ "id": "1", "name": "@d2h" }] } ``` It will first normalize the payload, so you can use this to push in data streaming in from your server structured the same way that fetches and saves are structured. @method pushPayload @param {DS.Store} store @param {Object} payload */ pushPayload: function (store, payload) { var documentHash = { data: [], included: [] }; for (var prop in payload) { var modelName = this.modelNameFromPayloadKey(prop); if (!store.modelFactoryFor(modelName)) { continue; } var type = store.modelFor(modelName); var typeSerializer = store.serializerFor(type.modelName); _ember.default.makeArray(payload[prop]).forEach(function (hash) { var _typeSerializer$normalize = typeSerializer.normalize(type, hash, prop); var data = _typeSerializer$normalize.data; var included = _typeSerializer$normalize.included; documentHash.data.push(data); if (included) { var _documentHash$included5; (_documentHash$included5 = documentHash.included).push.apply(_documentHash$included5, _toConsumableArray(included)); } }); } if (false) { return store.push(documentHash); } else { store.push(documentHash); } }, /** This method is used to convert each JSON root key in the payload into a modelName that it can use to look up the appropriate model for that part of the payload. For example, your server may send a model name that does not correspond with the name of the model in your app. Let's take a look at an example model, and an example payload: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ }); ``` ```javascript { "blog/post": { "id": "1 } } ``` Ember Data is going to normalize the payload's root key for the modelName. As a result, it will try to look up the "blog/post" model. Since we don't have a model called "blog/post" (or a file called app/models/blog/post.js in ember-cli), Ember Data will throw an error because it cannot find the "blog/post" model. Since we want to remove this namespace, we can define a serializer for the application that will remove "blog/" from the payload key whenver it's encountered by Ember Data: ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ modelNameFromPayloadKey: function(payloadKey) { if (payloadKey === 'blog/post') { return this._super(payloadKey.replace('blog/', '')); } else { return this._super(payloadKey); } } }); ``` After refreshing, Ember Data will appropriately look up the "post" model. By default the modelName for a model is its name in dasherized form. This means that a payload key like "blogPost" would be normalized to "blog-post" when Ember Data looks up the model. Usually, Ember Data can use the correct inflection to do this for you. Most of the time, you won't need to override `modelNameFromPayloadKey` for this purpose. @method modelNameFromPayloadKey @param {String} key @return {String} the model's modelName */ modelNameFromPayloadKey: function (key) { return (0, _emberInflector.singularize)((0, _emberDataPrivateSystemNormalizeModelName.default)(key)); }, // SERIALIZE /** Called when a record is saved in order to convert the record into JSON. By default, it creates a JSON object with a key for each attribute and belongsTo relationship. For example, consider this model: ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.belongsTo('user') }); ``` The default serialization would create a JSON object like: ```js { "title": "Rails is unagi", "body": "Rails? Omakase? O_O", "author": 12 } ``` By default, attributes are passed through as-is, unless you specified an attribute type (`DS.attr('date')`). If you specify a transform, the JavaScript value will be serialized when inserted into the JSON hash. By default, belongs-to relationships are converted into IDs when inserted into the JSON hash. ## IDs `serialize` takes an options hash with a single option: `includeId`. If this option is `true`, `serialize` will, by default include the ID in the JSON object it builds. The adapter passes in `includeId: true` when serializing a record for `createRecord`, but not for `updateRecord`. ## Customization Your server may expect a different JSON format than the built-in serialization format. In that case, you can implement `serialize` yourself and return a JSON hash of your choosing. ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ serialize: function(snapshot, options) { var json = { POST_TTL: snapshot.attr('title'), POST_BDY: snapshot.attr('body'), POST_CMS: snapshot.hasMany('comments', { ids: true }) } if (options.includeId) { json.POST_ID_ = snapshot.id; } return json; } }); ``` ## Customizing an App-Wide Serializer If you want to define a serializer for your entire application, you'll probably want to use `eachAttribute` and `eachRelationship` on the record. ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ serialize: function(snapshot, options) { var json = {}; snapshot.eachAttribute(function(name) { json[serverAttributeName(name)] = snapshot.attr(name); }) snapshot.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true }); } }); if (options.includeId) { json.ID_ = snapshot.id; } return json; } }); function serverAttributeName(attribute) { return attribute.underscore().toUpperCase(); } function serverHasManyName(name) { return serverAttributeName(name.singularize()) + "_IDS"; } ``` This serializer will generate JSON that looks like this: ```js { "TITLE": "Rails is omakase", "BODY": "Yep. Omakase.", "COMMENT_IDS": [ 1, 2, 3 ] } ``` ## Tweaking the Default JSON If you just want to do some small tweaks on the default JSON, you can call super first and make the tweaks on the returned JSON. ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ serialize: function(snapshot, options) { var json = this._super(snapshot, options); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param {DS.Snapshot} snapshot @param {Object} options @return {Object} json */ serialize: function (snapshot, options) { return this._super.apply(this, arguments); }, /** You can use this method to customize the root keys serialized into the JSON. The hash property should be modified by reference (possibly using something like _.extend) By default the REST Serializer sends the modelName of a model, which is a camelized version of the name. For example, your server may expect underscored root objects. ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ serializeIntoHash: function(data, type, record, options) { var root = Ember.String.decamelize(type.modelName); data[root] = this.serialize(record, options); } }); ``` @method serializeIntoHash @param {Object} hash @param {DS.Model} typeClass @param {DS.Snapshot} snapshot @param {Object} options */ serializeIntoHash: function (hash, typeClass, snapshot, options) { var normalizedRootKey = this.payloadKeyFromModelName(typeClass.modelName); hash[normalizedRootKey] = this.serialize(snapshot, options); }, /** You can use `payloadKeyFromModelName` to override the root key for an outgoing request. By default, the RESTSerializer returns a camelized version of the model's name. For a model called TacoParty, its `modelName` would be the string `taco-party`. The RESTSerializer will send it to the server with `tacoParty` as the root key in the JSON payload: ```js { "tacoParty": { "id": "1", "location": "Matthew Beale's House" } } ``` For example, your server may expect dasherized root objects: ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ payloadKeyFromModelName: function(modelName) { return Ember.String.dasherize(modelName); } }); ``` Given a `TacoParty` model, calling `save` on it would produce an outgoing request like: ```js { "taco-party": { "id": "1", "location": "Matthew Beale's House" } } ``` @method payloadKeyFromModelName @param {String} modelName @return {String} */ payloadKeyFromModelName: function (modelName) { return camelize(modelName); }, /** You can use this method to customize how polymorphic objects are serialized. By default the REST Serializer creates the key by appending `Type` to the attribute and value from the model's camelcased model name. @method serializePolymorphicType @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializePolymorphicType: function (snapshot, json, relationship) { var key = relationship.key; var belongsTo = snapshot.belongsTo(key); var typeKey = this.keyForPolymorphicType(key, relationship.type, 'serialize'); // old way of getting the key for the polymorphic type key = this.keyForAttribute ? this.keyForAttribute(key, "serialize") : key; key = key + "Type"; // The old way of serializing the type of a polymorphic record used // `keyForAttribute`, which is not correct. The next code checks if the old // way is used and if it differs from the new way of using // `keyForPolymorphicType`. If this is the case, a deprecation warning is // logged and the old way is restored (so nothing breaks). if (key !== typeKey && this.keyForPolymorphicType === RESTSerializer.prototype.keyForPolymorphicType) { typeKey = key; } if (_ember.default.isNone(belongsTo)) { json[typeKey] = null; } else { if (false) { json[typeKey] = this.payloadTypeFromModelName(belongsTo.modelName); } else { json[typeKey] = camelize(belongsTo.modelName); } } }, /** You can use this method to customize how a polymorphic relationship should be extracted. @method extractPolymorphicRelationship @param {Object} relationshipType @param {Object} relationshipHash @param {Object} relationshipOptions @return {Object} */ extractPolymorphicRelationship: function (relationshipType, relationshipHash, relationshipOptions) { var key = relationshipOptions.key; var resourceHash = relationshipOptions.resourceHash; var relationshipMeta = relationshipOptions.relationshipMeta; // A polymorphic belongsTo relationship can be present in the payload // either in the form where the `id` and the `type` are given: // // { // message: { id: 1, type: 'post' } // } // // or by the `id` and a `<relationship>Type` attribute: // // { // message: 1, // messageType: 'post' // } // // The next code checks if the latter case is present and returns the // corresponding JSON-API representation. The former case is handled within // the base class JSONSerializer. var isPolymorphic = relationshipMeta.options.polymorphic; var typeProperty = this.keyForPolymorphicType(key, relationshipType, 'deserialize'); if (isPolymorphic && resourceHash[typeProperty] !== undefined && typeof relationshipHash !== 'object') { if (false) { var payloadType = resourceHash[typeProperty]; var type = this.modelNameFromPayloadType(payloadType); var deprecatedTypeLookup = this.modelNameFromPayloadKey(payloadType); if (payloadType !== deprecatedTypeLookup && !this._hasCustomModelNameFromPayloadType() && this._hasCustomModelNameFromPayloadKey()) { type = deprecatedTypeLookup; } return { id: relationshipHash, type: type }; } else { var type = this.modelNameFromPayloadKey(resourceHash[typeProperty]); return { id: relationshipHash, type: type }; } } return this._super.apply(this, arguments); } }); if (false) { RESTSerializer.reopen({ /** `modelNameFromPayloadType` can be used to change the mapping for a DS model name, taken from the value in the payload. Say your API namespaces the type of a model and returns the following payload for the `post` model, which has a polymorphic `user` relationship: ```javascript // GET /api/posts/1 { "post": { "id": 1, "user": 1, "userType: "api::v1::administrator" } } ``` By overwriting `modelNameFromPayloadType` you can specify that the `administrator` model should be used: ```app/serializers/application.js import DS from "ember-data"; export default DS.RESTSerializer.extend({ modelNameFromPayloadType(payloadType) { return payloadType.replace('api::v1::', ''); } }); ``` By default the modelName for a model is its name in dasherized form. Usually, Ember Data can use the correct inflection to do this for you. Most of the time, you won't need to override `modelNameFromPayloadType` for this purpose. Also take a look at [payloadTypeFromModelName](#method_payloadTypeFromModelName) to customize how the type of a record should be serialized. @method modelNameFromPayloadType @public @param {String} payloadType type from payload @return {String} modelName */ modelNameFromPayloadType: function (payloadType) { return (0, _emberInflector.singularize)((0, _emberDataPrivateSystemNormalizeModelName.default)(payloadType)); }, /** `payloadTypeFromModelName` can be used to change the mapping for the type in the payload, taken from the model name. Say your API namespaces the type of a model and expects the following payload when you update the `post` model, which has a polymorphic `user` relationship: ```javascript // POST /api/posts/1 { "post": { "id": 1, "user": 1, "userType": "api::v1::administrator" } } ``` By overwriting `payloadTypeFromModelName` you can specify that the namespaces model name for the `administrator` should be used: ```app/serializers/application.js import DS from "ember-data"; export default DS.RESTSerializer.extend({ payloadTypeFromModelName(modelName) { return "api::v1::" + modelName; } }); ``` By default the payload type is the camelized model name. Usually, Ember Data can use the correct inflection to do this for you. Most of the time, you won't need to override `payloadTypeFromModelName` for this purpose. Also take a look at [modelNameFromPayloadType](#method_modelNameFromPayloadType) to customize how the model name from should be mapped from the payload. @method payloadTypeFromModelName @public @param {String} modelname modelName from the record @return {String} payloadType */ payloadTypeFromModelName: function (modelName) { return camelize(modelName); }, _hasCustomModelNameFromPayloadKey: function () { return this.modelNameFromPayloadKey !== RESTSerializer.prototype.modelNameFromPayloadKey; }, _hasCustomModelNameFromPayloadType: function () { return this.modelNameFromPayloadType !== RESTSerializer.prototype.modelNameFromPayloadType; }, _hasCustomPayloadTypeFromModelName: function () { return this.payloadTypeFromModelName !== RESTSerializer.prototype.payloadTypeFromModelName; }, _hasCustomPayloadKeyFromModelName: function () { return this.payloadKeyFromModelName !== RESTSerializer.prototype.payloadKeyFromModelName; } }); } exports.default = RESTSerializer; }); /** @module ember-data */ define('ember-data/setup-container', ['exports', 'ember-data/-private/initializers/store', 'ember-data/-private/initializers/transforms', 'ember-data/-private/initializers/store-injections', 'ember-data/-private/initializers/data-adapter'], function (exports, _emberDataPrivateInitializersStore, _emberDataPrivateInitializersTransforms, _emberDataPrivateInitializersStoreInjections, _emberDataPrivateInitializersDataAdapter) { exports.default = setupContainer; function setupContainer(application) { (0, _emberDataPrivateInitializersDataAdapter.default)(application); (0, _emberDataPrivateInitializersTransforms.default)(application); (0, _emberDataPrivateInitializersStoreInjections.default)(application); (0, _emberDataPrivateInitializersStore.default)(application); } }); define("ember-data/store", ["exports", "ember-data/-private/system/store"], function (exports, _emberDataPrivateSystemStore) { exports.default = _emberDataPrivateSystemStore.default; }); define('ember-data/transform', ['exports', 'ember'], function (exports, _ember) { /** The `DS.Transform` class is used to serialize and deserialize model attributes when they are saved or loaded from an adapter. Subclassing `DS.Transform` is useful for creating custom attributes. All subclasses of `DS.Transform` must implement a `serialize` and a `deserialize` method. Example ```app/transforms/temperature.js import DS from 'ember-data'; // Converts centigrade in the JSON to fahrenheit in the app export default DS.Transform.extend({ deserialize: function(serialized, options) { return (serialized * 1.8) + 32; }, serialize: function(deserialized, options) { return (deserialized - 32) / 1.8; } }); ``` The options passed into the `DS.attr` function when the attribute is declared on the model is also available in the transform. ```app/models/post.js export default DS.Model.extend({ title: DS.attr('string'), markdown: DS.attr('markdown', { markdown: { gfm: false, sanitize: true } }) }); ``` ```app/transforms/markdown.js export default DS.Transform.extend({ serialize: function (deserialized, options) { return deserialized.raw; }, deserialize: function (serialized, options) { var markdownOptions = options.markdown || {}; return marked(serialized, markdownOptions); } }); ``` Usage ```app/models/requirement.js import DS from 'ember-data'; export default DS.Model.extend({ name: DS.attr('string'), temperature: DS.attr('temperature') }); ``` @class Transform @namespace DS */ exports.default = _ember.default.Object.extend({ /** When given a deserialized value from a record attribute this method must return the serialized value. Example ```javascript serialize: function(deserialized, options) { return Ember.isEmpty(deserialized) ? null : Number(deserialized); } ``` @method serialize @param deserialized The deserialized value @param options hash of options passed to `DS.attr` @return The serialized value */ serialize: null, /** When given a serialize value from a JSON object this method must return the deserialized value for the record attribute. Example ```javascript deserialize: function(serialized, options) { return empty(serialized) ? null : Number(serialized); } ``` @method deserialize @param serialized The serialized value @param options hash of options passed to `DS.attr` @return The deserialized value */ deserialize: null }); }); define("ember-data/version", ["exports"], function (exports) { exports.default = "2.11.0"; }); define("ember-inflector", ["exports", "ember", "ember-inflector/lib/system", "ember-inflector/lib/ext/string"], function (exports, _ember, _emberInflectorLibSystem, _emberInflectorLibExtString) { _emberInflectorLibSystem.Inflector.defaultRules = _emberInflectorLibSystem.defaultRules; _ember.default.Inflector = _emberInflectorLibSystem.Inflector; _ember.default.String.pluralize = _emberInflectorLibSystem.pluralize; _ember.default.String.singularize = _emberInflectorLibSystem.singularize; exports.default = _emberInflectorLibSystem.Inflector; exports.pluralize = _emberInflectorLibSystem.pluralize; exports.singularize = _emberInflectorLibSystem.singularize; exports.defaultRules = _emberInflectorLibSystem.defaultRules; if (typeof define !== 'undefined' && define.amd) { define('ember-inflector', ['exports'], function (__exports__) { __exports__['default'] = _emberInflectorLibSystem.Inflector; __exports__.pluralize = _emberInflectorLibSystem.pluralize; __exports__.singularize = _emberInflectorLibSystem.singularize; return __exports__; }); } else if (typeof module !== 'undefined' && module['exports']) { module['exports'] = _emberInflectorLibSystem.Inflector; _emberInflectorLibSystem.Inflector.singularize = _emberInflectorLibSystem.singularize; _emberInflectorLibSystem.Inflector.pluralize = _emberInflectorLibSystem.pluralize; } }); /* global define, module */ define('ember-inflector/lib/ext/string', ['exports', 'ember', 'ember-inflector/lib/system/string'], function (exports, _ember, _emberInflectorLibSystemString) { if (_ember.default.EXTEND_PROTOTYPES === true || _ember.default.EXTEND_PROTOTYPES.String) { /** See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}} @method pluralize @for String */ String.prototype.pluralize = function () { return (0, _emberInflectorLibSystemString.pluralize)(this); }; /** See {{#crossLink "Ember.String/singularize"}}{{/crossLink}} @method singularize @for String */ String.prototype.singularize = function () { return (0, _emberInflectorLibSystemString.singularize)(this); }; } }); define('ember-inflector/lib/helpers/pluralize', ['exports', 'ember-inflector', 'ember-inflector/lib/utils/make-helper'], function (exports, _emberInflector, _emberInflectorLibUtilsMakeHelper) { /** * * If you have Ember Inflector (such as if Ember Data is present), * pluralize a word. For example, turn "ox" into "oxen". * * Example: * * {{pluralize count myProperty}} * {{pluralize 1 "oxen"}} * {{pluralize myProperty}} * {{pluralize "ox"}} * * @for Ember.HTMLBars.helpers * @method pluralize * @param {Number|Property} [count] count of objects * @param {String|Property} word word to pluralize */ exports.default = (0, _emberInflectorLibUtilsMakeHelper.default)(function (params) { var count = undefined, word = undefined; if (params.length === 1) { word = params[0]; return (0, _emberInflector.pluralize)(word); } else { count = params[0]; word = params[1]; if (parseFloat(count) !== 1) { word = (0, _emberInflector.pluralize)(word); } return count + " " + word; } }); }); define('ember-inflector/lib/helpers/singularize', ['exports', 'ember-inflector', 'ember-inflector/lib/utils/make-helper'], function (exports, _emberInflector, _emberInflectorLibUtilsMakeHelper) { /** * * If you have Ember Inflector (such as if Ember Data is present), * singularize a word. For example, turn "oxen" into "ox". * * Example: * * {{singularize myProperty}} * {{singularize "oxen"}} * * @for Ember.HTMLBars.helpers * @method singularize * @param {String|Property} word word to singularize */ exports.default = (0, _emberInflectorLibUtilsMakeHelper.default)(function (params) { return (0, _emberInflector.singularize)(params[0]); }); }); define("ember-inflector/lib/system", ["exports", "ember-inflector/lib/system/inflector", "ember-inflector/lib/system/string", "ember-inflector/lib/system/inflections"], function (exports, _emberInflectorLibSystemInflector, _emberInflectorLibSystemString, _emberInflectorLibSystemInflections) { _emberInflectorLibSystemInflector.default.inflector = new _emberInflectorLibSystemInflector.default(_emberInflectorLibSystemInflections.default); exports.Inflector = _emberInflectorLibSystemInflector.default; exports.singularize = _emberInflectorLibSystemString.singularize; exports.pluralize = _emberInflectorLibSystemString.pluralize; exports.defaultRules = _emberInflectorLibSystemInflections.default; }); define('ember-inflector/lib/system/inflections', ['exports'], function (exports) { exports.default = { plurals: [[/$/, 's'], [/s$/i, 's'], [/^(ax|test)is$/i, '$1es'], [/(octop|vir)us$/i, '$1i'], [/(octop|vir)i$/i, '$1i'], [/(alias|status|bonus)$/i, '$1es'], [/(bu)s$/i, '$1ses'], [/(buffal|tomat)o$/i, '$1oes'], [/([ti])um$/i, '$1a'], [/([ti])a$/i, '$1a'], [/sis$/i, 'ses'], [/(?:([^f])fe|([lr])f)$/i, '$1$2ves'], [/(hive)$/i, '$1s'], [/([^aeiouy]|qu)y$/i, '$1ies'], [/(x|ch|ss|sh)$/i, '$1es'], [/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'], [/^(m|l)ouse$/i, '$1ice'], [/^(m|l)ice$/i, '$1ice'], [/^(ox)$/i, '$1en'], [/^(oxen)$/i, '$1'], [/(quiz)$/i, '$1zes']], singular: [[/s$/i, ''], [/(ss)$/i, '$1'], [/(n)ews$/i, '$1ews'], [/([ti])a$/i, '$1um'], [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'], [/(^analy)(sis|ses)$/i, '$1sis'], [/([^f])ves$/i, '$1fe'], [/(hive)s$/i, '$1'], [/(tive)s$/i, '$1'], [/([lr])ves$/i, '$1f'], [/([^aeiouy]|qu)ies$/i, '$1y'], [/(s)eries$/i, '$1eries'], [/(m)ovies$/i, '$1ovie'], [/(x|ch|ss|sh)es$/i, '$1'], [/^(m|l)ice$/i, '$1ouse'], [/(bus)(es)?$/i, '$1'], [/(o)es$/i, '$1'], [/(shoe)s$/i, '$1'], [/(cris|test)(is|es)$/i, '$1is'], [/^(a)x[ie]s$/i, '$1xis'], [/(octop|vir)(us|i)$/i, '$1us'], [/(alias|status|bonus)(es)?$/i, '$1'], [/^(ox)en/i, '$1'], [/(vert|ind)ices$/i, '$1ex'], [/(matr)ices$/i, '$1ix'], [/(quiz)zes$/i, '$1'], [/(database)s$/i, '$1']], irregularPairs: [['person', 'people'], ['man', 'men'], ['child', 'children'], ['sex', 'sexes'], ['move', 'moves'], ['cow', 'kine'], ['zombie', 'zombies']], uncountable: ['equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans', 'police'] }; }); define('ember-inflector/lib/system/inflector', ['exports', 'ember'], function (exports, _ember) { var capitalize = _ember.default.String.capitalize; var BLANK_REGEX = /^\s*$/; var LAST_WORD_DASHED_REGEX = /([\w/-]+[_/\s-])([a-z\d]+$)/; var LAST_WORD_CAMELIZED_REGEX = /([\w/\s-]+)([A-Z][a-z\d]*$)/; var CAMELIZED_REGEX = /[A-Z][a-z\d]*$/; function loadUncountable(rules, uncountable) { for (var i = 0, length = uncountable.length; i < length; i++) { rules.uncountable[uncountable[i].toLowerCase()] = true; } } function loadIrregular(rules, irregularPairs) { var pair; for (var i = 0, length = irregularPairs.length; i < length; i++) { pair = irregularPairs[i]; //pluralizing rules.irregular[pair[0].toLowerCase()] = pair[1]; rules.irregular[pair[1].toLowerCase()] = pair[1]; //singularizing rules.irregularInverse[pair[1].toLowerCase()] = pair[0]; rules.irregularInverse[pair[0].toLowerCase()] = pair[0]; } } /** Inflector.Ember provides a mechanism for supplying inflection rules for your application. Ember includes a default set of inflection rules, and provides an API for providing additional rules. Examples: Creating an inflector with no rules. ```js var inflector = new Ember.Inflector(); ``` Creating an inflector with the default ember ruleset. ```js var inflector = new Ember.Inflector(Ember.Inflector.defaultRules); inflector.pluralize('cow'); //=> 'kine' inflector.singularize('kine'); //=> 'cow' ``` Creating an inflector and adding rules later. ```javascript var inflector = Ember.Inflector.inflector; inflector.pluralize('advice'); // => 'advices' inflector.uncountable('advice'); inflector.pluralize('advice'); // => 'advice' inflector.pluralize('formula'); // => 'formulas' inflector.irregular('formula', 'formulae'); inflector.pluralize('formula'); // => 'formulae' // you would not need to add these as they are the default rules inflector.plural(/$/, 's'); inflector.singular(/s$/i, ''); ``` Creating an inflector with a nondefault ruleset. ```javascript var rules = { plurals: [ /$/, 's' ], singular: [ /\s$/, '' ], irregularPairs: [ [ 'cow', 'kine' ] ], uncountable: [ 'fish' ] }; var inflector = new Ember.Inflector(rules); ``` @class Inflector @namespace Ember */ function Inflector(ruleSet) { ruleSet = ruleSet || {}; ruleSet.uncountable = ruleSet.uncountable || makeDictionary(); ruleSet.irregularPairs = ruleSet.irregularPairs || makeDictionary(); var rules = this.rules = { plurals: ruleSet.plurals || [], singular: ruleSet.singular || [], irregular: makeDictionary(), irregularInverse: makeDictionary(), uncountable: makeDictionary() }; loadUncountable(rules, ruleSet.uncountable); loadIrregular(rules, ruleSet.irregularPairs); this.enableCache(); } if (!Object.create && !Object.create(null).hasOwnProperty) { throw new Error("This browser does not support Object.create(null), please polyfil with es5-sham: http://git.io/yBU2rg"); } function makeDictionary() { var cache = Object.create(null); cache['_dict'] = null; delete cache['_dict']; return cache; } Inflector.prototype = { /** @public As inflections can be costly, and commonly the same subset of words are repeatedly inflected an optional cache is provided. @method enableCache */ enableCache: function () { this.purgeCache(); this.singularize = function (word) { this._cacheUsed = true; return this._sCache[word] || (this._sCache[word] = this._singularize(word)); }; this.pluralize = function (word) { this._cacheUsed = true; return this._pCache[word] || (this._pCache[word] = this._pluralize(word)); }; }, /** @public @method purgedCache */ purgeCache: function () { this._cacheUsed = false; this._sCache = makeDictionary(); this._pCache = makeDictionary(); }, /** @public disable caching @method disableCache; */ disableCache: function () { this._sCache = null; this._pCache = null; this.singularize = function (word) { return this._singularize(word); }; this.pluralize = function (word) { return this._pluralize(word); }; }, /** @method plural @param {RegExp} regex @param {String} string */ plural: function (regex, string) { if (this._cacheUsed) { this.purgeCache(); } this.rules.plurals.push([regex, string.toLowerCase()]); }, /** @method singular @param {RegExp} regex @param {String} string */ singular: function (regex, string) { if (this._cacheUsed) { this.purgeCache(); } this.rules.singular.push([regex, string.toLowerCase()]); }, /** @method uncountable @param {String} regex */ uncountable: function (string) { if (this._cacheUsed) { this.purgeCache(); } loadUncountable(this.rules, [string.toLowerCase()]); }, /** @method irregular @param {String} singular @param {String} plural */ irregular: function (singular, plural) { if (this._cacheUsed) { this.purgeCache(); } loadIrregular(this.rules, [[singular, plural]]); }, /** @method pluralize @param {String} word */ pluralize: function (word) { return this._pluralize(word); }, _pluralize: function (word) { return this.inflect(word, this.rules.plurals, this.rules.irregular); }, /** @method singularize @param {String} word */ singularize: function (word) { return this._singularize(word); }, _singularize: function (word) { return this.inflect(word, this.rules.singular, this.rules.irregularInverse); }, /** @protected @method inflect @param {String} word @param {Object} typeRules @param {Object} irregular */ inflect: function (word, typeRules, irregular) { var inflection, substitution, result, lowercase, wordSplit, firstPhrase, lastWord, isBlank, isCamelized, rule, isUncountable; isBlank = !word || BLANK_REGEX.test(word); isCamelized = CAMELIZED_REGEX.test(word); firstPhrase = ""; if (isBlank) { return word; } lowercase = word.toLowerCase(); wordSplit = LAST_WORD_DASHED_REGEX.exec(word) || LAST_WORD_CAMELIZED_REGEX.exec(word); if (wordSplit) { firstPhrase = wordSplit[1]; lastWord = wordSplit[2].toLowerCase(); } isUncountable = this.rules.uncountable[lowercase] || this.rules.uncountable[lastWord]; if (isUncountable) { return word; } for (rule in irregular) { if (lowercase.match(rule + "$")) { substitution = irregular[rule]; if (isCamelized && irregular[lastWord]) { substitution = capitalize(substitution); rule = capitalize(rule); } return word.replace(new RegExp(rule, 'i'), substitution); } } for (var i = typeRules.length, min = 0; i > min; i--) { inflection = typeRules[i - 1]; rule = inflection[0]; if (rule.test(word)) { break; } } inflection = inflection || []; rule = inflection[0]; substitution = inflection[1]; result = word.replace(rule, substitution); return result; } }; exports.default = Inflector; }); define('ember-inflector/lib/system/string', ['exports', 'ember-inflector/lib/system/inflector'], function (exports, _emberInflectorLibSystemInflector) { function pluralize(word) { return _emberInflectorLibSystemInflector.default.inflector.pluralize(word); } function singularize(word) { return _emberInflectorLibSystemInflector.default.inflector.singularize(word); } exports.pluralize = pluralize; exports.singularize = singularize; }); define('ember-inflector/lib/utils/make-helper', ['exports', 'ember'], function (exports, _ember) { exports.default = makeHelper; function makeHelper(helperFunction) { if (_ember.default.Helper) { return _ember.default.Helper.helper(helperFunction); } if (_ember.default.HTMLBars) { return _ember.default.HTMLBars.makeBoundHelper(helperFunction); } return _ember.default.Handlebars.makeBoundHelper(helperFunction); } }); define('ember-load-initializers', ['exports', 'ember'], function (exports, _ember) { exports.default = function (app, prefix) { var regex = new RegExp('^' + prefix + '\/((?:instance-)?initializers)\/'); var getKeys = Object.keys || _ember.default.keys; getKeys(requirejs._eak_seen).map(function (moduleName) { return { moduleName: moduleName, matches: regex.exec(moduleName) }; }).filter(function (dep) { return dep.matches && dep.matches.length === 2; }).forEach(function (dep) { var moduleName = dep.moduleName; var module = require(moduleName, null, null, true); if (!module) { throw new Error(moduleName + ' must export an initializer.'); } var initializerType = _ember.default.String.camelize(dep.matches[1].substring(0, dep.matches[1].length - 1)); var initializer = module['default']; if (!initializer.name) { var initializerName = moduleName.match(/[^\/]+\/?$/)[0]; initializer.name = initializerName; } if (app[initializerType]) { app[initializerType](initializer); } }); }; }); define('ember', [], function() { return { default: Ember }; }); require("ember-data"); require("ember-load-initializers")["default"](Ember.Application, "ember-data"); ;(function() { var global = require('ember-data/-private/global').default; var DS = require('ember-data').default; Object.defineProperty(global, 'DS', { get: function() { return DS; } }); })(); })(); ;(function() { function processEmberDataShims() { var shims = { 'ember-data': { default: DS }, 'ember-data/model': { default: DS.Model }, 'ember-data/mixins/embedded-records': { default: DS.EmbeddedRecordsMixin }, 'ember-data/serializers/rest': { default: DS.RESTSerializer }, 'ember-data/serializers/active-model': { default: DS.ActiveModelSerializer }, 'ember-data/serializers/json': { default: DS.JSONSerializer }, 'ember-data/serializers/json-api': { default: DS.JSONAPISerializer }, 'ember-data/serializer': { default: DS.Serializer }, 'ember-data/adapters/json-api': { default: DS.JSONAPIAdapter }, 'ember-data/adapters/rest': { default: DS.RESTAdapter }, 'ember-data/adapter': { default: DS.Adapter }, 'ember-data/adapters/active-model': { default: DS.ActiveModelAdapter }, 'ember-data/store': { default: DS.Store }, 'ember-data/transform': { default: DS.Transform }, 'ember-data/attr': { default: DS.attr }, 'ember-data/relationships': { hasMany: DS.hasMany, belongsTo: DS.belongsTo } }; for (var moduleName in shims) { generateModule(moduleName, shims[moduleName]); } } function generateModule(name, values) { define(name, [], function() { 'use strict'; return values; }); } if (typeof define !== 'undefined' && define && define.petal) { processEmberDataShims(); } })();