path
stringlengths 5
300
| repo_name
stringlengths 6
76
| content
stringlengths 26
1.05M
|
---|---|---|
src/components/Home.js | aalselius/Test | import React, { Component } from 'react';
import Image from './Image.js';
import ImageHeader from './ImageHeader.js';
import InfoText from './InfoText.js';
import Header from './Header.js';
class Home extends Component {
constructor() {
super();
this.state = {
imageUrl: '',
url:'',
inputType: '',
imageNumber: 0,
json:'',
images:[],
text: 'cat',
loaded: false,
}
}
componentDidMount() {
this.url = "http://api.giphy.com/v1/gifs/trending?api_key=dc6zaTOxFJmzC";
console.log(this.url);
fetch(this.url)
.then((data) => {
return data.json();
})
.then((json) => {
console.log(json);
this.setState({json:json});
this.setState({imageUrl:this.state.json.data[0].images.downsized.url});
this.setState({loaded: true});
})
;
}
changeLink = (arrow) => {
if (arrow === "left") {
this.setState({imageNumber: this.state.imageNumber -1}); //previous state, if 0 => 25
if (this.state.imageNumber <= 0) {
this.setState({imageNumber: 24}); //previous state, if 0 => 25
}
} else if (arrow === "right") {
this.setState({imageNumber: this.state.imageNumber +1}); // previous state, if 25 => 0
if (this.state.imageNumber >= 24) {
this.setState({imageNumber: 0}); //previous state, if 0 => 25
}
}
console.log(this.state.imageNumber);
let xx=this.state.json;
this.setState ({imageUrl:xx.data[this.state.imageNumber].images.downsized.url});
}
updateText = (event) => {
this.setState({text: event.target.value})
}
handleSubmit = (event) => {
if(event.keyCode === 13) {
this.setState({text: event.target.value})
console.log(this.state.text);
// set new url
this.updateUrl(this.state.text);
event.target.value='';
}
}
render() {
return (
<div className="pageContainer">
<Header headerText="Home" headerClass="sideHeader"/>
<ImageHeader text="Popular Giphy"/>
{this.state.loaded ? (
<div>
<div className="imageContainer">
<i className="fa fa-angle-left" onClick={()=>this.changeLink("left")}></i>
<Image url={this.state.imageUrl}/>
<i className="fa fa-angle-right" onClick={()=>this.changeLink("right")}></i>
</div>
<InfoText infoText="I don't take responsibility for giphys shown on this site. There is no filter on the giphys."/>
</div>
) : (
<div className="imageContainer"><i className="fa fa-spinner" aria-hidden="true"></i></div>
)}
</div>
);
}
}
export default Home; |
src/routes/contact/index.js | fvalencia/react-vimeo | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Layout from '../../components/Layout';
import Contact from './Contact';
const title = 'Contact Us';
export default {
path: '/contact',
action() {
return {
title,
component: <Layout><Contact title={title} /></Layout>,
};
},
};
|
packages/react-ui-components/src/_lib/storyUtils.js | grebaldi/PackageFactory.Guevara | import React from 'react';
import PropTypes from 'prop-types';
/**
* The StoryWrapper is a simple component which can be used to wrap stories
* of the react-storybook lib.
*/
export const StoryWrapper = ({children, ...rest}) => (
<div
style={{background: '#000', padding: '1rem', position: 'relative'}}
{...rest}
>
{children}
</div>
);
StoryWrapper.propTypes = {
children: PropTypes.node.isRequired
};
|
Frontend/WebContent/api/lib/jquery-1.8.0.min.js | TeamNeko/CatBox | /*! jQuery [email protected] jquery.com | jquery.org/license */
(function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d<e;d++)p.event.add(b,c,h[c][d])}g.data&&(g.data=p.extend({},g.data))}function bE(a,b){var c;if(b.nodeType!==1)return;b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?(b.parentNode&&(b.outerHTML=a.outerHTML),p.support.html5Clone&&a.innerHTML&&!p.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):c==="input"&&bv.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text),b.removeAttribute(p.expando)}function bF(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bG(a){bv.test(a.type)&&(a.defaultChecked=a.checked)}function bX(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=bV.length;while(e--){b=bV[e]+c;if(b in a)return b}return d}function bY(a,b){return a=b||a,p.css(a,"display")==="none"||!p.contains(a.ownerDocument,a)}function bZ(a,b){var c,d,e=[],f=0,g=a.length;for(;f<g;f++){c=a[f];if(!c.style)continue;e[f]=p._data(c,"olddisplay"),b?(!e[f]&&c.style.display==="none"&&(c.style.display=""),c.style.display===""&&bY(c)&&(e[f]=p._data(c,"olddisplay",cb(c.nodeName)))):(d=bH(c,"display"),!e[f]&&d!=="none"&&p._data(c,"olddisplay",d))}for(f=0;f<g;f++){c=a[f];if(!c.style)continue;if(!b||c.style.display==="none"||c.style.display==="")c.style.display=b?e[f]||"":"none"}return a}function b$(a,b,c){var d=bO.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function b_(a,b,c,d){var e=c===(d?"border":"content")?4:b==="width"?1:0,f=0;for(;e<4;e+=2)c==="margin"&&(f+=p.css(a,c+bU[e],!0)),d?(c==="content"&&(f-=parseFloat(bH(a,"padding"+bU[e]))||0),c!=="margin"&&(f-=parseFloat(bH(a,"border"+bU[e]+"Width"))||0)):(f+=parseFloat(bH(a,"padding"+bU[e]))||0,c!=="padding"&&(f+=parseFloat(bH(a,"border"+bU[e]+"Width"))||0));return f}function ca(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=!0,f=p.support.boxSizing&&p.css(a,"boxSizing")==="border-box";if(d<=0){d=bH(a,b);if(d<0||d==null)d=a.style[b];if(bP.test(d))return d;e=f&&(p.support.boxSizingReliable||d===a.style[b]),d=parseFloat(d)||0}return d+b_(a,b,c||(f?"border":"content"),e)+"px"}function cb(a){if(bR[a])return bR[a];var b=p("<"+a+">").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write("<!doctype html><html><body>"),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bR[a]=c,c}function ch(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||cd.test(a)?d(a,e):ch(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ch(a+"["+e+"]",b[e],c,d);else d(a,b)}function cy(a){return function(b,c){typeof b!="string"&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(s),h=0,i=g.length;if(p.isFunction(c))for(;h<i;h++)d=g[h],f=/^\+/.test(d),f&&(d=d.substr(1)||"*"),e=a[d]=a[d]||[],e[f?"unshift":"push"](c)}}function cz(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h,i=a[f],j=0,k=i?i.length:0,l=a===cu;for(;j<k&&(l||!h);j++)h=i[j](c,d,e),typeof h=="string"&&(!l||g[h]?h=b:(c.dataTypes.unshift(h),h=cz(a,c,d,e,h,g)));return(l||!h)&&!g["*"]&&(h=cz(a,c,d,e,"*",g)),h}function cA(a,c){var d,e,f=p.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((f[d]?a:e||(e={}))[d]=c[d]);e&&p.extend(!0,a,e)}function cB(a,c,d){var e,f,g,h,i=a.contents,j=a.dataTypes,k=a.responseFields;for(f in k)f in d&&(c[k[f]]=d[f]);while(j[0]==="*")j.shift(),e===b&&(e=a.mimeType||c.getResponseHeader("content-type"));if(e)for(f in i)if(i[f]&&i[f].test(e)){j.unshift(f);break}if(j[0]in d)g=j[0];else{for(f in d){if(!j[0]||a.converters[f+" "+j[0]]){g=f;break}h||(h=f)}g=g||h}if(g)return g!==j[0]&&j.unshift(g),d[g]}function cC(a,b){var c,d,e,f,g=a.dataTypes.slice(),h=g[0],i={},j=0;a.dataFilter&&(b=a.dataFilter(b,a.dataType));if(g[1])for(c in a.converters)i[c.toLowerCase()]=a.converters[c];for(;e=g[++j];)if(e!=="*"){if(h!=="*"&&h!==e){c=i[h+" "+e]||i["* "+e];if(!c)for(d in i){f=d.split(" ");if(f[1]===e){c=i[h+" "+f[0]]||i["* "+f[0]];if(c){c===!0?c=i[d]:i[d]!==!0&&(e=f[0],g.splice(j--,0,e));break}}}if(c!==!0)if(c&&a["throws"])b=c(b);else try{b=c(b)}catch(k){return{state:"parsererror",error:c?k:"No conversion from "+h+" to "+e}}}h=e}return{state:"success",data:b}}function cK(){try{return new a.XMLHttpRequest}catch(b){}}function cL(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function cT(){return setTimeout(function(){cM=b},0),cM=p.now()}function cU(a,b){p.each(b,function(b,c){var d=(cS[b]||[]).concat(cS["*"]),e=0,f=d.length;for(;e<f;e++)if(d[e].call(a,b,c))return})}function cV(a,b,c){var d,e=0,f=0,g=cR.length,h=p.Deferred().always(function(){delete i.elem}),i=function(){var b=cM||cT(),c=Math.max(0,j.startTime+j.duration-b),d=1-(c/j.duration||0),e=0,f=j.tweens.length;for(;e<f;e++)j.tweens[e].run(d);return h.notifyWith(a,[j,d,c]),d<1&&f?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:p.extend({},b),opts:p.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:cM||cT(),duration:c.duration,tweens:[],createTween:function(b,c,d){var e=p.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(e),e},stop:function(b){var c=0,d=b?j.tweens.length:0;for(;c<d;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;cW(k,j.opts.specialEasing);for(;e<g;e++){d=cR[e].call(j,a,k,j.opts);if(d)return d}return cU(j,k),p.isFunction(j.opts.start)&&j.opts.start.call(a,j),p.fx.timer(p.extend(i,{anim:j,queue:j.opts.queue,elem:a})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}function cW(a,b){var c,d,e,f,g;for(c in a){d=p.camelCase(c),e=b[d],f=a[c],p.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=p.cssHooks[d];if(g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}}function cX(a,b,c){var d,e,f,g,h,i,j,k,l=this,m=a.style,n={},o=[],q=a.nodeType&&bY(a);c.queue||(j=p._queueHooks(a,"fx"),j.unqueued==null&&(j.unqueued=0,k=j.empty.fire,j.empty.fire=function(){j.unqueued||k()}),j.unqueued++,l.always(function(){l.always(function(){j.unqueued--,p.queue(a,"fx").length||j.empty.fire()})})),a.nodeType===1&&("height"in b||"width"in b)&&(c.overflow=[m.overflow,m.overflowX,m.overflowY],p.css(a,"display")==="inline"&&p.css(a,"float")==="none"&&(!p.support.inlineBlockNeedsLayout||cb(a.nodeName)==="inline"?m.display="inline-block":m.zoom=1)),c.overflow&&(m.overflow="hidden",p.support.shrinkWrapBlocks||l.done(function(){m.overflow=c.overflow[0],m.overflowX=c.overflow[1],m.overflowY=c.overflow[2]}));for(d in b){f=b[d];if(cO.exec(f)){delete b[d];if(f===(q?"hide":"show"))continue;o.push(d)}}g=o.length;if(g){h=p._data(a,"fxshow")||p._data(a,"fxshow",{}),q?p(a).show():l.done(function(){p(a).hide()}),l.done(function(){var b;p.removeData(a,"fxshow",!0);for(b in n)p.style(a,b,n[b])});for(d=0;d<g;d++)e=o[d],i=l.createTween(e,q?h[e]:0),n[e]=h[e]||p.style(a,e),e in h||(h[e]=i.start,q&&(i.end=i.start,i.start=e==="width"||e==="height"?1:0))}}function cY(a,b,c,d,e){return new cY.prototype.init(a,b,c,d,e)}function cZ(a,b){var c,d={height:a},e=0;for(;e<4;e+=2-b)c=bU[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function c_(a){return p.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}var c,d,e=a.document,f=a.location,g=a.navigator,h=a.jQuery,i=a.$,j=Array.prototype.push,k=Array.prototype.slice,l=Array.prototype.indexOf,m=Object.prototype.toString,n=Object.prototype.hasOwnProperty,o=String.prototype.trim,p=function(a,b){return new p.fn.init(a,b,c)},q=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,r=/\S/,s=/\s+/,t=r.test(" ")?/^[\s\xA0]+|[\s\xA0]+$/g:/^\s+|\s+$/g,u=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,y=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,z=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,A=/^-ms-/,B=/-([\da-z])/gi,C=function(a,b){return(b+"").toUpperCase()},D=function(){e.addEventListener?(e.removeEventListener("DOMContentLoaded",D,!1),p.ready()):e.readyState==="complete"&&(e.detachEvent("onreadystatechange",D),p.ready())},E={};p.fn=p.prototype={constructor:p,init:function(a,c,d){var f,g,h,i;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(typeof a=="string"){a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?f=[null,a,null]:f=u.exec(a);if(f&&(f[1]||!c)){if(f[1])return c=c instanceof p?c[0]:c,i=c&&c.nodeType?c.ownerDocument||c:e,a=p.parseHTML(f[1],i,!0),v.test(f[1])&&p.isPlainObject(c)&&this.attr.call(a,c,!0),p.merge(this,a);g=e.getElementById(f[2]);if(g&&g.parentNode){if(g.id!==f[2])return d.find(a);this.length=1,this[0]=g}return this.context=e,this.selector=a,this}return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a)}return p.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),p.makeArray(a,this))},selector:"",jquery:"1.8.0",length:0,size:function(){return this.length},toArray:function(){return k.call(this)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=p.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return p.each(this,a,b)},ready:function(a){return p.ready.promise().done(a),this},eq:function(a){return a=+a,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(k.apply(this,arguments),"slice",k.call(arguments).join(","))},map:function(a){return this.pushStack(p.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:j,sort:[].sort,splice:[].splice},p.fn.init.prototype=p.fn,p.extend=p.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;typeof h=="boolean"&&(k=h,h=arguments[1]||{},i=2),typeof h!="object"&&!p.isFunction(h)&&(h={}),j===i&&(h=this,--i);for(;i<j;i++)if((a=arguments[i])!=null)for(c in a){d=h[c],e=a[c];if(h===e)continue;k&&e&&(p.isPlainObject(e)||(f=p.isArray(e)))?(f?(f=!1,g=d&&p.isArray(d)?d:[]):g=d&&p.isPlainObject(d)?d:{},h[c]=p.extend(k,g,e)):e!==b&&(h[c]=e)}return h},p.extend({noConflict:function(b){return a.$===p&&(a.$=i),b&&a.jQuery===p&&(a.jQuery=h),p},isReady:!1,readyWait:1,holdReady:function(a){a?p.readyWait++:p.ready(!0)},ready:function(a){if(a===!0?--p.readyWait:p.isReady)return;if(!e.body)return setTimeout(p.ready,1);p.isReady=!0;if(a!==!0&&--p.readyWait>0)return;d.resolveWith(e,[p]),p.fn.trigger&&p(e).trigger("ready").off("ready")},isFunction:function(a){return p.type(a)==="function"},isArray:Array.isArray||function(a){return p.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):E[m.call(a)]||"object"},isPlainObject:function(a){if(!a||p.type(a)!=="object"||a.nodeType||p.isWindow(a))return!1;try{if(a.constructor&&!n.call(a,"constructor")&&!n.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||n.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return!a||typeof a!="string"?null:(typeof b=="boolean"&&(c=b,b=0),b=b||e,(d=v.exec(a))?[b.createElement(d[1])]:(d=p.buildFragment([a],b,c?null:[]),p.merge([],(d.cacheable?p.clone(d.fragment):d.fragment).childNodes)))},parseJSON:function(b){if(!b||typeof b!="string")return null;b=p.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(w.test(b.replace(y,"@").replace(z,"]").replace(x,"")))return(new Function("return "+b))();p.error("Invalid JSON: "+b)},parseXML:function(c){var d,e;if(!c||typeof c!="string")return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&p.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&r.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(A,"ms-").replace(B,C)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d){if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;f<g;)if(c.apply(a[f++],d)===!1)break}else if(h){for(e in a)if(c.call(a[e],e,a[e])===!1)break}else for(;f<g;)if(c.call(a[f],f,a[f++])===!1)break;return a},trim:o?function(a){return a==null?"":o.call(a)}:function(a){return a==null?"":a.toString().replace(t,"")},makeArray:function(a,b){var c,d=b||[];return a!=null&&(c=p.type(a),a.length==null||c==="string"||c==="function"||c==="regexp"||p.isWindow(a)?j.call(d,a):p.merge(d,a)),d},inArray:function(a,b,c){var d;if(b){if(l)return l.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=c.length,e=a.length,f=0;if(typeof d=="number")for(;f<d;f++)a[e++]=c[f];else while(c[f]!==b)a[e++]=c[f++];return a.length=e,a},grep:function(a,b,c){var d,e=[],f=0,g=a.length;c=!!c;for(;f<g;f++)d=!!b(a[f],f),c!==d&&e.push(a[f]);return e},map:function(a,c,d){var e,f,g=[],h=0,i=a.length,j=a instanceof p||i!==b&&typeof i=="number"&&(i>0&&a[0]&&a[i-1]||i===0||p.isArray(a));if(j)for(;h<i;h++)e=c(a[h],h,d),e!=null&&(g[g.length]=e);else for(f in a)e=c(a[f],f,d),e!=null&&(g[g.length]=e);return g.concat.apply([],g)},guid:1,proxy:function(a,c){var d,e,f;return typeof c=="string"&&(d=a[c],c=a,a=d),p.isFunction(a)?(e=k.call(arguments,2),f=function(){return a.apply(c,e.concat(k.call(arguments)))},f.guid=a.guid=a.guid||f.guid||p.guid++,f):b},access:function(a,c,d,e,f,g,h){var i,j=d==null,k=0,l=a.length;if(d&&typeof d=="object"){for(k in d)p.access(a,c,k,d[k],1,g,e);f=1}else if(e!==b){i=h===b&&p.isFunction(e),j&&(i?(i=c,c=function(a,b,c){return i.call(p(a),c)}):(c.call(a,e),c=null));if(c)for(;k<l;k++)c(a[k],d,i?e.call(a[k],k,c(a[k],d)):e,h);f=1}return f?a:j?c.call(a):l?c(a[0],d):g},now:function(){return(new Date).getTime()}}),p.ready.promise=function(b){if(!d){d=p.Deferred();if(e.readyState==="complete"||e.readyState!=="loading"&&e.addEventListener)setTimeout(p.ready,1);else if(e.addEventListener)e.addEventListener("DOMContentLoaded",D,!1),a.addEventListener("load",p.ready,!1);else{e.attachEvent("onreadystatechange",D),a.attachEvent("onload",p.ready);var c=!1;try{c=a.frameElement==null&&e.documentElement}catch(f){}c&&c.doScroll&&function g(){if(!p.isReady){try{c.doScroll("left")}catch(a){return setTimeout(g,50)}p.ready()}}()}}return d.promise(b)},p.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){E["[object "+b+"]"]=b.toLowerCase()}),c=p(e);var F={};p.Callbacks=function(a){a=typeof a=="string"?F[a]||G(a):p.extend({},a);var c,d,e,f,g,h,i=[],j=!a.once&&[],k=function(b){c=a.memory&&b,d=!0,h=f||0,f=0,g=i.length,e=!0;for(;i&&h<g;h++)if(i[h].apply(b[0],b[1])===!1&&a.stopOnFalse){c=!1;break}e=!1,i&&(j?j.length&&k(j.shift()):c?i=[]:l.disable())},l={add:function(){if(i){var b=i.length;(function d(b){p.each(b,function(b,c){p.isFunction(c)&&(!a.unique||!l.has(c))?i.push(c):c&&c.length&&d(c)})})(arguments),e?g=i.length:c&&(f=b,k(c))}return this},remove:function(){return i&&p.each(arguments,function(a,b){var c;while((c=p.inArray(b,i,c))>-1)i.splice(c,1),e&&(c<=g&&g--,c<=h&&h--)}),this},has:function(a){return p.inArray(a,i)>-1},empty:function(){return i=[],this},disable:function(){return i=j=c=b,this},disabled:function(){return!i},lock:function(){return j=b,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],i&&(!d||j)&&(e?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},p.extend({Deferred:function(a){var b=[["resolve","done",p.Callbacks("once memory"),"resolved"],["reject","fail",p.Callbacks("once memory"),"rejected"],["notify","progress",p.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return p.Deferred(function(c){p.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]](p.isFunction(g)?function(){var a=g.apply(this,arguments);a&&p.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return typeof a=="object"?p.extend(a,d):d}},e={};return d.pipe=d.then,p.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[a^1][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=k.call(arguments),d=c.length,e=d!==1||a&&p.isFunction(a.promise)?d:0,f=e===1?a:p.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?k.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}},h,i,j;if(d>1){h=new Array(d),i=new Array(d),j=new Array(d);for(;b<d;b++)c[b]&&p.isFunction(c[b].promise)?c[b].promise().done(g(b,j,c)).fail(f.reject).progress(g(b,i,h)):--e}return e||f.resolveWith(j,c),f.promise()}}),p.support=function(){var b,c,d,f,g,h,i,j,k,l,m,n=e.createElement("div");n.setAttribute("className","t"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",c=n.getElementsByTagName("*"),d=n.getElementsByTagName("a")[0],d.style.cssText="top:1px;float:left;opacity:.5";if(!c||!c.length||!d)return{};f=e.createElement("select"),g=f.appendChild(e.createElement("option")),h=n.getElementsByTagName("input")[0],b={leadingWhitespace:n.firstChild.nodeType===3,tbody:!n.getElementsByTagName("tbody").length,htmlSerialize:!!n.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:d.getAttribute("href")==="/a",opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:h.value==="on",optSelected:g.selected,getSetAttribute:n.className!=="t",enctype:!!e.createElement("form").enctype,html5Clone:e.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:e.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},h.checked=!0,b.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,b.optDisabled=!g.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}!n.addEventListener&&n.attachEvent&&n.fireEvent&&(n.attachEvent("onclick",m=function(){b.noCloneEvent=!1}),n.cloneNode(!0).fireEvent("onclick"),n.detachEvent("onclick",m)),h=e.createElement("input"),h.value="t",h.setAttribute("type","radio"),b.radioValue=h.value==="t",h.setAttribute("checked","checked"),h.setAttribute("name","t"),n.appendChild(h),i=e.createDocumentFragment(),i.appendChild(n.lastChild),b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=h.checked,i.removeChild(h),i.appendChild(n);if(n.attachEvent)for(k in{submit:!0,change:!0,focusin:!0})j="on"+k,l=j in n,l||(n.setAttribute(j,"return;"),l=typeof n[j]=="function"),b[k+"Bubbles"]=l;return p(function(){var c,d,f,g,h="padding:0;margin:0;border:0;display:block;overflow:hidden;",i=e.getElementsByTagName("body")[0];if(!i)return;c=e.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",i.insertBefore(c,i.firstChild),d=e.createElement("div"),c.appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",f=d.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&f[0].offsetHeight===0,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",b.boxSizing=d.offsetWidth===4,b.doesNotIncludeMarginInBodyOffset=i.offsetTop!==1,a.getComputedStyle&&(b.pixelPosition=(a.getComputedStyle(d,null)||{}).top!=="1%",b.boxSizingReliable=(a.getComputedStyle(d,null)||{width:"4px"}).width==="4px",g=e.createElement("div"),g.style.cssText=d.style.cssText=h,g.style.marginRight=g.style.width="0",d.style.width="1px",d.appendChild(g),b.reliableMarginRight=!parseFloat((a.getComputedStyle(g,null)||{}).marginRight)),typeof d.style.zoom!="undefined"&&(d.innerHTML="",d.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=d.offsetWidth===3,d.style.display="block",d.style.overflow="visible",d.innerHTML="<div></div>",d.firstChild.style.width="5px",b.shrinkWrapBlocks=d.offsetWidth!==3,c.style.zoom=1),i.removeChild(c),c=d=f=g=null}),i.removeChild(n),c=d=f=g=h=i=n=null,b}();var H=/^(?:\{.*\}|\[.*\])$/,I=/([A-Z])/g;p.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(p.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?p.cache[a[p.expando]]:a[p.expando],!!a&&!K(a)},data:function(a,c,d,e){if(!p.acceptData(a))return;var f,g,h=p.expando,i=typeof c=="string",j=a.nodeType,k=j?p.cache:a,l=j?a[h]:a[h]&&h;if((!l||!k[l]||!e&&!k[l].data)&&i&&d===b)return;l||(j?a[h]=l=p.deletedIds.pop()||++p.uuid:l=h),k[l]||(k[l]={},j||(k[l].toJSON=p.noop));if(typeof c=="object"||typeof c=="function")e?k[l]=p.extend(k[l],c):k[l].data=p.extend(k[l].data,c);return f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[p.camelCase(c)]=d),i?(g=f[c],g==null&&(g=f[p.camelCase(c)])):g=f,g},removeData:function(a,b,c){if(!p.acceptData(a))return;var d,e,f,g=a.nodeType,h=g?p.cache:a,i=g?a[p.expando]:p.expando;if(!h[i])return;if(b){d=c?h[i]:h[i].data;if(d){p.isArray(b)||(b in d?b=[b]:(b=p.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,f=b.length;e<f;e++)delete d[b[e]];if(!(c?K:p.isEmptyObject)(d))return}}if(!c){delete h[i].data;if(!K(h[i]))return}g?p.cleanData([a],!0):p.support.deleteExpando||h!=h.window?delete h[i]:h[i]=null},_data:function(a,b,c){return p.data(a,b,c,!0)},acceptData:function(a){var b=a.nodeName&&p.noData[a.nodeName.toLowerCase()];return!b||b!==!0&&a.getAttribute("classid")===b}}),p.fn.extend({data:function(a,c){var d,e,f,g,h,i=this[0],j=0,k=null;if(a===b){if(this.length){k=p.data(i);if(i.nodeType===1&&!p._data(i,"parsedAttrs")){f=i.attributes;for(h=f.length;j<h;j++)g=f[j].name,g.indexOf("data-")===0&&(g=p.camelCase(g.substring(5)),J(i,g,k[g]));p._data(i,"parsedAttrs",!0)}}return k}return typeof a=="object"?this.each(function(){p.data(this,a)}):(d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!",p.access(this,function(c){if(c===b)return k=this.triggerHandler("getData"+e,[d[0]]),k===b&&i&&(k=p.data(i,a),k=J(i,a,k)),k===b&&d[1]?this.data(d[0]):k;d[1]=c,this.each(function(){var b=p(this);b.triggerHandler("setData"+e,d),p.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1))},removeData:function(a){return this.each(function(){p.removeData(this,a)})}}),p.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=p._data(a,b),c&&(!d||p.isArray(c)?d=p._data(a,b,p.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=p.queue(a,b),d=c.shift(),e=p._queueHooks(a,b),f=function(){p.dequeue(a,b)};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),delete e.stop,d.call(a,f,e)),!c.length&&e&&e.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return p._data(a,c)||p._data(a,c,{empty:p.Callbacks("once memory").add(function(){p.removeData(a,b+"queue",!0),p.removeData(a,c,!0)})})}}),p.fn.extend({queue:function(a,c){var d=2;return typeof a!="string"&&(c=a,a="fx",d--),arguments.length<d?p.queue(this[0],a):c===b?this:this.each(function(){var b=p.queue(this,a,c);p._queueHooks(this,a),a==="fx"&&b[0]!=="inprogress"&&p.dequeue(this,a)})},dequeue:function(a){return this.each(function(){p.dequeue(this,a)})},delay:function(a,b){return a=p.fx?p.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){var d,e=1,f=p.Deferred(),g=this,h=this.length,i=function(){--e||f.resolveWith(g,[g])};typeof a!="string"&&(c=a,a=b),a=a||"fx";while(h--)(d=p._data(g[h],a+"queueHooks"))&&d.empty&&(e++,d.empty.add(i));return i(),f.promise(c)}});var L,M,N,O=/[\t\r\n]/g,P=/\r/g,Q=/^(?:button|input)$/i,R=/^(?:button|input|object|select|textarea)$/i,S=/^a(?:rea|)$/i,T=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,U=p.support.getSetAttribute;p.fn.extend({attr:function(a,b){return p.access(this,p.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){p.removeAttr(this,a)})},prop:function(a,b){return p.access(this,p.prop,a,b,arguments.length>1)},removeProp:function(a){return a=p.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if(p.isFunction(a))return this.each(function(b){p(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(s);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{f=" "+e.className+" ";for(g=0,h=b.length;g<h;g++)~f.indexOf(" "+b[g]+" ")||(f+=b[g]+" ");e.className=p.trim(f)}}}return this},removeClass:function(a){var c,d,e,f,g,h,i;if(p.isFunction(a))return this.each(function(b){p(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(s);for(h=0,i=this.length;h<i;h++){e=this[h];if(e.nodeType===1&&e.className){d=(" "+e.className+" ").replace(O," ");for(f=0,g=c.length;f<g;f++)while(d.indexOf(" "+c[f]+" ")>-1)d=d.replace(" "+c[f]+" "," ");e.className=a?p.trim(d):""}}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";return p.isFunction(a)?this.each(function(c){p(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if(c==="string"){var e,f=0,g=p(this),h=b,i=a.split(s);while(e=i[f++])h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&p._data(this,"__className__",this.className),this.className=this.className||a===!1?"":p._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(O," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,f=this[0];if(!arguments.length){if(f)return c=p.valHooks[f.type]||p.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,typeof d=="string"?d.replace(P,""):d==null?"":d);return}return e=p.isFunction(a),this.each(function(d){var f,g=p(this);if(this.nodeType!==1)return;e?f=a.call(this,d,g.val()):f=a,f==null?f="":typeof f=="number"?f+="":p.isArray(f)&&(f=p.map(f,function(a){return a==null?"":a+""})),c=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,f,"value")===b)this.value=f})}}),p.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,f=a.selectedIndex,g=[],h=a.options,i=a.type==="select-one";if(f<0)return null;c=i?f:0,d=i?f+1:h.length;for(;c<d;c++){e=h[c];if(e.selected&&(p.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!p.nodeName(e.parentNode,"optgroup"))){b=p(e).val();if(i)return b;g.push(b)}}return i&&!g.length&&h.length?p(h[f]).val():g},set:function(a,b){var c=p.makeArray(b);return p(a).find("option").each(function(){this.selected=p.inArray(p(this).val(),c)>=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return;if(e&&p.isFunction(p.fn[c]))return p(a)[c](d);if(typeof a.getAttribute=="undefined")return p.prop(a,c,d);h=i!==1||!p.isXMLDoc(a),h&&(c=c.toLowerCase(),g=p.attrHooks[c]||(T.test(c)?M:L));if(d!==b){if(d===null){p.removeAttr(a,c);return}return g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,""+d),d)}return g&&"get"in g&&h&&(f=g.get(a,c))!==null?f:(f=a.getAttribute(c),f===null?b:f)},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&a.nodeType===1){d=b.split(s);for(;g<d.length;g++)e=d[g],e&&(c=p.propFix[e]||e,f=T.test(e),f||p.attr(a,e,""),a.removeAttribute(U?e:c),f&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(Q.test(a.nodeName)&&a.parentNode)p.error("type property can't be changed");else if(!p.support.radioValue&&b==="radio"&&p.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}},value:{get:function(a,b){return L&&p.nodeName(a,"button")?L.get(a,b):b in a?a.value:null},set:function(a,b,c){if(L&&p.nodeName(a,"button"))return L.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,f,g,h=a.nodeType;if(!a||h===3||h===8||h===2)return;return g=h!==1||!p.isXMLDoc(a),g&&(c=p.propFix[c]||c,f=p.propHooks[c]),d!==b?f&&"set"in f&&(e=f.set(a,d,c))!==b?e:a[c]=d:f&&"get"in f&&(e=f.get(a,c))!==null?e:a[c]},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):R.test(a.nodeName)||S.test(a.nodeName)&&a.href?0:b}}}}),M={get:function(a,c){var d,e=p.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;return b===!1?p.removeAttr(a,c):(d=p.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase())),c}},U||(N={name:!0,id:!0,coords:!0},L=p.valHooks.button={get:function(a,c){var d;return d=a.getAttributeNode(c),d&&(N[c]?d.value!=="":d.specified)?d.value:b},set:function(a,b,c){var d=a.getAttributeNode(c);return d||(d=e.createAttribute(c),a.setAttributeNode(d)),d.value=b+""}},p.each(["width","height"],function(a,b){p.attrHooks[b]=p.extend(p.attrHooks[b],{set:function(a,c){if(c==="")return a.setAttribute(b,"auto"),c}})}),p.attrHooks.contenteditable={get:L.get,set:function(a,b,c){b===""&&(b="false"),L.set(a,b,c)}}),p.support.hrefNormalized||p.each(["href","src","width","height"],function(a,c){p.attrHooks[c]=p.extend(p.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),p.support.style||(p.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),p.support.optSelected||(p.propHooks.selected=p.extend(p.propHooks.selected,{get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}})),p.support.enctype||(p.propFix.enctype="encoding"),p.support.checkOn||p.each(["radio","checkbox"],function(){p.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),p.each(["radio","checkbox"],function(){p.valHooks[this]=p.extend(p.valHooks[this],{set:function(a,b){if(p.isArray(b))return a.checked=p.inArray(p(a).val(),b)>=0}})});var V=/^(?:textarea|input|select)$/i,W=/^([^\.]*|)(?:\.(.+)|)$/,X=/(?:^|\s)hover(\.\S+|)\b/,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=function(a){return p.event.special.hover?a:a.replace(X,"mouseenter$1 mouseleave$1")};p.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,q,r;if(a.nodeType===3||a.nodeType===8||!c||!d||!(g=p._data(a)))return;d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=p.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return typeof p!="undefined"&&(!a||p.event.triggered!==a.type)?p.event.dispatch.apply(h.elem,arguments):b},h.elem=a),c=p.trim(_(c)).split(" ");for(j=0;j<c.length;j++){k=W.exec(c[j])||[],l=k[1],m=(k[2]||"").split(".").sort(),r=p.event.special[l]||{},l=(f?r.delegateType:r.bindType)||l,r=p.event.special[l]||{},n=p.extend({type:l,origType:k[1],data:e,handler:d,guid:d.guid,selector:f,namespace:m.join(".")},o),q=i[l];if(!q){q=i[l]=[],q.delegateCount=0;if(!r.setup||r.setup.call(a,e,m,h)===!1)a.addEventListener?a.addEventListener(l,h,!1):a.attachEvent&&a.attachEvent("on"+l,h)}r.add&&(r.add.call(a,n),n.handler.guid||(n.handler.guid=d.guid)),f?q.splice(q.delegateCount++,0,n):q.push(n),p.event.global[l]=!0}a=null},global:{},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,q,r=p.hasData(a)&&p._data(a);if(!r||!(m=r.events))return;b=p.trim(_(b||"")).split(" ");for(f=0;f<b.length;f++){g=W.exec(b[f])||[],h=i=g[1],j=g[2];if(!h){for(h in m)p.event.remove(a,h+b[f],c,d,!0);continue}n=p.event.special[h]||{},h=(d?n.delegateType:n.bindType)||h,o=m[h]||[],k=o.length,j=j?new RegExp("(^|\\.)"+j.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(l=0;l<o.length;l++)q=o[l],(e||i===q.origType)&&(!c||c.guid===q.guid)&&(!j||j.test(q.namespace))&&(!d||d===q.selector||d==="**"&&q.selector)&&(o.splice(l--,1),q.selector&&o.delegateCount--,n.remove&&n.remove.call(a,q));o.length===0&&k!==o.length&&((!n.teardown||n.teardown.call(a,j,r.handle)===!1)&&p.removeEvent(a,h,r.handle),delete m[h])}p.isEmptyObject(m)&&(delete r.handle,p.removeData(a,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,f,g){if(!f||f.nodeType!==3&&f.nodeType!==8){var h,i,j,k,l,m,n,o,q,r,s=c.type||c,t=[];if($.test(s+p.event.triggered))return;s.indexOf("!")>=0&&(s=s.slice(0,-1),i=!0),s.indexOf(".")>=0&&(t=s.split("."),s=t.shift(),t.sort());if((!f||p.event.customEvent[s])&&!p.event.global[s])return;c=typeof c=="object"?c[p.expando]?c:new p.Event(s,c):new p.Event(s),c.type=s,c.isTrigger=!0,c.exclusive=i,c.namespace=t.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,m=s.indexOf(":")<0?"on"+s:"";if(!f){h=p.cache;for(j in h)h[j].events&&h[j].events[s]&&p.event.trigger(c,d,h[j].handle.elem,!0);return}c.result=b,c.target||(c.target=f),d=d!=null?p.makeArray(d):[],d.unshift(c),n=p.event.special[s]||{};if(n.trigger&&n.trigger.apply(f,d)===!1)return;q=[[f,n.bindType||s]];if(!g&&!n.noBubble&&!p.isWindow(f)){r=n.delegateType||s,k=$.test(r+s)?f:f.parentNode;for(l=f;k;k=k.parentNode)q.push([k,r]),l=k;l===(f.ownerDocument||e)&&q.push([l.defaultView||l.parentWindow||a,r])}for(j=0;j<q.length&&!c.isPropagationStopped();j++)k=q[j][0],c.type=q[j][1],o=(p._data(k,"events")||{})[c.type]&&p._data(k,"handle"),o&&o.apply(k,d),o=m&&k[m],o&&p.acceptData(k)&&o.apply(k,d)===!1&&c.preventDefault();return c.type=s,!g&&!c.isDefaultPrevented()&&(!n._default||n._default.apply(f.ownerDocument,d)===!1)&&(s!=="click"||!p.nodeName(f,"a"))&&p.acceptData(f)&&m&&f[s]&&(s!=="focus"&&s!=="blur"||c.target.offsetWidth!==0)&&!p.isWindow(f)&&(l=f[m],l&&(f[m]=null),p.event.triggered=s,f[s](),p.event.triggered=b,l&&(f[m]=l)),c.result}return},dispatch:function(c){c=p.event.fix(c||a.event);var d,e,f,g,h,i,j,k,l,m,n,o=(p._data(this,"events")||{})[c.type]||[],q=o.delegateCount,r=[].slice.call(arguments),s=!c.exclusive&&!c.namespace,t=p.event.special[c.type]||{},u=[];r[0]=c,c.delegateTarget=this;if(t.preDispatch&&t.preDispatch.call(this,c)===!1)return;if(q&&(!c.button||c.type!=="click")){g=p(this),g.context=this;for(f=c.target;f!=this;f=f.parentNode||this)if(f.disabled!==!0||c.type!=="click"){i={},k=[],g[0]=f;for(d=0;d<q;d++)l=o[d],m=l.selector,i[m]===b&&(i[m]=g.is(m)),i[m]&&k.push(l);k.length&&u.push({elem:f,matches:k})}}o.length>q&&u.push({elem:this,matches:o.slice(q)});for(d=0;d<u.length&&!c.isPropagationStopped();d++){j=u[d],c.currentTarget=j.elem;for(e=0;e<j.matches.length&&!c.isImmediatePropagationStopped();e++){l=j.matches[e];if(s||!c.namespace&&!l.namespace||c.namespace_re&&c.namespace_re.test(l.namespace))c.data=l.data,c.handleObj=l,h=((p.event.special[l.origType]||{}).handle||l.handler).apply(j.elem,r),h!==b&&(c.result=h,h===!1&&(c.preventDefault(),c.stopPropagation()))}}return t.postDispatch&&t.postDispatch.call(this,c),c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,c){var d,f,g,h=c.button,i=c.fromElement;return a.pageX==null&&c.clientX!=null&&(d=a.target.ownerDocument||e,f=d.documentElement,g=d.body,a.pageX=c.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=c.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?c.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0),a}},fix:function(a){if(a[p.expando])return a;var b,c,d=a,f=p.event.fixHooks[a.type]||{},g=f.props?this.props.concat(f.props):this.props;a=p.Event(d);for(b=g.length;b;)c=g[--b],a[c]=d[c];return a.target||(a.target=d.srcElement||e),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,f.filter?f.filter(a,d):a},special:{ready:{setup:p.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){p.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=p.extend(new p.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?p.event.trigger(e,null,b):p.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},p.event.handle=p.event.dispatch,p.removeEvent=e.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]=="undefined"&&(a[d]=null),a.detachEvent(d,c))},p.Event=function(a,b){if(this instanceof p.Event)a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?bb:ba):this.type=a,b&&p.extend(this,b),this.timeStamp=a&&a.timeStamp||p.now(),this[p.expando]=!0;else return new p.Event(a,b)},p.Event.prototype={preventDefault:function(){this.isDefaultPrevented=bb;var a=this.originalEvent;if(!a)return;a.preventDefault?a.preventDefault():a.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=bb;var a=this.originalEvent;if(!a)return;a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()},isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba},p.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){p.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj,g=f.selector;if(!e||e!==d&&!p.contains(d,e))a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b;return c}}}),p.support.submitBubbles||(p.event.special.submit={setup:function(){if(p.nodeName(this,"form"))return!1;p.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=p.nodeName(c,"input")||p.nodeName(c,"button")?c.form:b;d&&!p._data(d,"_submit_attached")&&(p.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),p._data(d,"_submit_attached",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&p.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(p.nodeName(this,"form"))return!1;p.event.remove(this,"._submit")}}),p.support.changeBubbles||(p.event.special.change={setup:function(){if(V.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")p.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),p.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),p.event.simulate("change",this,a,!0)});return!1}p.event.add(this,"beforeactivate._change",function(a){var b=a.target;V.test(b.nodeName)&&!p._data(b,"_change_attached")&&(p.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&p.event.simulate("change",this.parentNode,a,!0)}),p._data(b,"_change_attached",!0))})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){return p.event.remove(this,"._change"),V.test(this.nodeName)}}),p.support.focusinBubbles||p.each({focus:"focusin",blur:"focusout"},function(a,b){var c=0,d=function(a){p.event.simulate(b,a.target,p.event.fix(a),!0)};p.event.special[b]={setup:function(){c++===0&&e.addEventListener(a,d,!0)},teardown:function(){--c===0&&e.removeEventListener(a,d,!0)}}}),p.fn.extend({on:function(a,c,d,e,f){var g,h;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(h in a)this.on(h,c,d,a[h],f);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=ba;else if(!e)return this;return f===1&&(g=e,e=function(a){return p().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=p.guid++)),this.each(function(){p.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){var e,f;if(a&&a.preventDefault&&a.handleObj)return e=a.handleObj,p(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler),this;if(typeof a=="object"){for(f in a)this.off(f,c,a[f]);return this}if(c===!1||typeof c=="function")d=c,c=b;return d===!1&&(d=ba),this.each(function(){p.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){return p(this.context).on(a,this.selector,b,c),this},die:function(a,b){return p(this.context).off(a,this.selector||"**",b),this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a||"**",c)},trigger:function(a,b){return this.each(function(){p.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return p.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||p.guid++,d=0,e=function(c){var e=(p._data(this,"lastToggle"+a.guid)||0)%d;return p._data(this,"lastToggle"+a.guid,e+1),c.preventDefault(),b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),p.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){p.fn[b]=function(a,c){return c==null&&(c=a,a=null),arguments.length>0?this.on(b,null,a,c):this.trigger(b)},Y.test(b)&&(p.event.fixHooks[b]=p.event.keyHooks),Z.test(b)&&(p.event.fixHooks[b]=p.event.mouseHooks)}),function(a,b){function bd(a,b,c,d){var e=0,f=b.length;for(;e<f;e++)Z(a,b[e],c,d)}function be(a,b,c,d,e,f){var g,h=$.setFilters[b.toLowerCase()];return h||Z.error(b),(a||!(g=e))&&bd(a||"*",d,g=[],e),g.length>0?h(g,c,f):[]}function bf(a,c,d,e,f){var g,h,i,j,k,l,m,n,p=0,q=f.length,s=L.POS,t=new RegExp("^"+s.source+"(?!"+r+")","i"),u=function(){var a=1,c=arguments.length-2;for(;a<c;a++)arguments[a]===b&&(g[a]=b)};for(;p<q;p++){s.exec(""),a=f[p],j=[],i=0,k=e;while(g=s.exec(a)){n=s.lastIndex=g.index+g[0].length;if(n>i){m=a.slice(i,g.index),i=n,l=[c],B.test(m)&&(k&&(l=k),k=e);if(h=H.test(m))m=m.slice(0,-5).replace(B,"$&*");g.length>1&&g[0].replace(t,u),k=be(m,g[1],g[2],l,k,h)}}k?(j=j.concat(k),(m=a.slice(i))&&m!==")"?B.test(m)?bd(m,j,d,e):Z(m,c,d,e?e.concat(k):k):o.apply(d,j)):Z(a,c,d,e)}return q===1?d:Z.uniqueSort(d)}function bg(a,b,c){var d,e,f,g=[],i=0,j=D.exec(a),k=!j.pop()&&!j.pop(),l=k&&a.match(C)||[""],m=$.preFilter,n=$.filter,o=!c&&b!==h;for(;(e=l[i])!=null&&k;i++){g.push(d=[]),o&&(e=" "+e);while(e){k=!1;if(j=B.exec(e))e=e.slice(j[0].length),k=d.push({part:j.pop().replace(A," "),captures:j});for(f in n)(j=L[f].exec(e))&&(!m[f]||(j=m[f](j,b,c)))&&(e=e.slice(j.shift().length),k=d.push({part:f,captures:j}));if(!k)break}}return k||Z.error(a),g}function bh(a,b,e){var f=b.dir,g=m++;return a||(a=function(a){return a===e}),b.first?function(b,c){while(b=b[f])if(b.nodeType===1)return a(b,c)&&b}:function(b,e){var h,i=g+"."+d,j=i+"."+c;while(b=b[f])if(b.nodeType===1){if((h=b[q])===j)return b.sizset;if(typeof h=="string"&&h.indexOf(i)===0){if(b.sizset)return b}else{b[q]=j;if(a(b,e))return b.sizset=!0,b;b.sizset=!1}}}}function bi(a,b){return a?function(c,d){var e=b(c,d);return e&&a(e===!0?c:e,d)}:b}function bj(a,b,c){var d,e,f=0;for(;d=a[f];f++)$.relative[d.part]?e=bh(e,$.relative[d.part],b):(d.captures.push(b,c),e=bi(e,$.filter[d.part].apply(null,d.captures)));return e}function bk(a){return function(b,c){var d,e=0;for(;d=a[e];e++)if(d(b,c))return!0;return!1}}var c,d,e,f,g,h=a.document,i=h.documentElement,j="undefined",k=!1,l=!0,m=0,n=[].slice,o=[].push,q=("sizcache"+Math.random()).replace(".",""),r="[\\x20\\t\\r\\n\\f]",s="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",t=s.replace("w","w#"),u="([*^$|!~]?=)",v="\\["+r+"*("+s+")"+r+"*(?:"+u+r+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+t+")|)|)"+r+"*\\]",w=":("+s+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|((?:[^,]|\\\\,|(?:,(?=[^\\[]*\\]))|(?:,(?=[^\\(]*\\))))*))\\)|)",x=":(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\)|)(?=[^-]|$)",y=r+"*([\\x20\\t\\r\\n\\f>+~])"+r+"*",z="(?=[^\\x20\\t\\r\\n\\f])(?:\\\\.|"+v+"|"+w.replace(2,7)+"|[^\\\\(),])+",A=new RegExp("^"+r+"+|((?:^|[^\\\\])(?:\\\\.)*)"+r+"+$","g"),B=new RegExp("^"+y),C=new RegExp(z+"?(?="+r+"*,|$)","g"),D=new RegExp("^(?:(?!,)(?:(?:^|,)"+r+"*"+z+")*?|"+r+"*(.*?))(\\)|$)"),E=new RegExp(z.slice(19,-6)+"\\x20\\t\\r\\n\\f>+~])+|"+y,"g"),F=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,G=/[\x20\t\r\n\f]*[+~]/,H=/:not\($/,I=/h\d/i,J=/input|select|textarea|button/i,K=/\\(?!\\)/g,L={ID:new RegExp("^#("+s+")"),CLASS:new RegExp("^\\.("+s+")"),NAME:new RegExp("^\\[name=['\"]?("+s+")['\"]?\\]"),TAG:new RegExp("^("+s.replace("[-","[-\\*")+")"),ATTR:new RegExp("^"+v),PSEUDO:new RegExp("^"+w),CHILD:new RegExp("^:(only|nth|last|first)-child(?:\\("+r+"*(even|odd|(([+-]|)(\\d*)n|)"+r+"*(?:([+-]|)"+r+"*(\\d+)|))"+r+"*\\)|)","i"),POS:new RegExp(x,"ig"),needsContext:new RegExp("^"+r+"*[>+~]|"+x,"i")},M={},N=[],O={},P=[],Q=function(a){return a.sizzleFilter=!0,a},R=function(a){return function(b){return b.nodeName.toLowerCase()==="input"&&b.type===a}},S=function(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}},T=function(a){var b=!1,c=h.createElement("div");try{b=a(c)}catch(d){}return c=null,b},U=T(function(a){a.innerHTML="<select></select>";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),V=T(function(a){a.id=q+0,a.innerHTML="<a name='"+q+"'></a><div name='"+q+"'></div>",i.insertBefore(a,i.firstChild);var b=h.getElementsByName&&h.getElementsByName(q).length===2+h.getElementsByName(q+0).length;return g=!h.getElementById(q),i.removeChild(a),b}),W=T(function(a){return a.appendChild(h.createComment("")),a.getElementsByTagName("*").length===0}),X=T(function(a){return a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!==j&&a.firstChild.getAttribute("href")==="#"}),Y=T(function(a){return a.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!a.getElementsByClassName||a.getElementsByClassName("e").length===0?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length!==1)}),Z=function(a,b,c,d){c=c||[],b=b||h;var e,f,g,i,j=b.nodeType;if(j!==1&&j!==9)return[];if(!a||typeof a!="string")return c;g=ba(b);if(!g&&!d)if(e=F.exec(a))if(i=e[1]){if(j===9){f=b.getElementById(i);if(!f||!f.parentNode)return c;if(f.id===i)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(i))&&bb(b,f)&&f.id===i)return c.push(f),c}else{if(e[2])return o.apply(c,n.call(b.getElementsByTagName(a),0)),c;if((i=e[3])&&Y&&b.getElementsByClassName)return o.apply(c,n.call(b.getElementsByClassName(i),0)),c}return bm(a,b,c,d,g)},$=Z.selectors={cacheLength:50,match:L,order:["ID","TAG"],attrHandle:{},createPseudo:Q,find:{ID:g?function(a,b,c){if(typeof b.getElementById!==j&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==j&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==j&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:W?function(a,b){if(typeof b.getElementsByTagName!==j)return b.getElementsByTagName(a)}:function(a,b){var c=b.getElementsByTagName(a);if(a==="*"){var d,e=[],f=0;for(;d=c[f];f++)d.nodeType===1&&e.push(d);return e}return c}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(K,""),a[3]=(a[4]||a[5]||"").replace(K,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||Z.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*(a[2]==="even"||a[2]==="odd")),a[4]=+(a[6]+a[7]||a[2]==="odd")):a[2]&&Z.error(a[0]),a},PSEUDO:function(a){var b,c=a[4];return L.CHILD.test(a[0])?null:(c&&(b=D.exec(c))&&b.pop()&&(a[0]=a[0].slice(0,b[0].length-c.length-1),c=b[0].slice(0,-1)),a.splice(2,3,c||a[3]),a)}},filter:{ID:g?function(a){return a=a.replace(K,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(K,""),function(b){var c=typeof b.getAttributeNode!==j&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(K,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=M[a];return b||(b=M[a]=new RegExp("(^|"+r+")"+a+"("+r+"|$)"),N.push(a),N.length>$.cacheLength&&delete M[N.shift()]),function(a){return b.test(a.className||typeof a.getAttribute!==j&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return b?function(d){var e=Z.attr(d,a),f=e+"";if(e==null)return b==="!=";switch(b){case"=":return f===c;case"!=":return f!==c;case"^=":return c&&f.indexOf(c)===0;case"*=":return c&&f.indexOf(c)>-1;case"$=":return c&&f.substr(f.length-c.length)===c;case"~=":return(" "+f+" ").indexOf(c)>-1;case"|=":return f===c||f.substr(0,c.length+1)===c+"-"}}:function(b){return Z.attr(b,a)!=null}},CHILD:function(a,b,c,d){if(a==="nth"){var e=m++;return function(a){var b,f,g=0,h=a;if(c===1&&d===0)return!0;b=a.parentNode;if(b&&(b[q]!==e||!a.sizset)){for(h=b.firstChild;h;h=h.nextSibling)if(h.nodeType===1){h.sizset=++g;if(h===a)break}b[q]=e}return f=a.sizset-d,c===0?f===0:f%c===0&&f/c>=0}}return function(b){var c=b;switch(a){case"only":case"first":while(c=c.previousSibling)if(c.nodeType===1)return!1;if(a==="first")return!0;c=b;case"last":while(c=c.nextSibling)if(c.nodeType===1)return!1;return!0}}},PSEUDO:function(a,b,c,d){var e=$.pseudos[a]||$.pseudos[a.toLowerCase()];return e||Z.error("unsupported pseudo: "+a),e.sizzleFilter?e(b,c,d):e}},pseudos:{not:Q(function(a,b,c){var d=bl(a.replace(A,"$1"),b,c);return function(a){return!d(a)}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&!!a.checked||b==="option"&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!$.pseudos.empty(a)},empty:function(a){var b;a=a.firstChild;while(a){if(a.nodeName>"@"||(b=a.nodeType)===3||b===4)return!1;a=a.nextSibling}return!0},contains:Q(function(a){return function(b){return(b.textContent||b.innerText||bc(b)).indexOf(a)>-1}}),has:Q(function(a){return function(b){return Z(a,b).length>0}}),header:function(a){return I.test(a.nodeName)},text:function(a){var b,c;return a.nodeName.toLowerCase()==="input"&&(b=a.type)==="text"&&((c=a.getAttribute("type"))==null||c.toLowerCase()===b)},radio:R("radio"),checkbox:R("checkbox"),file:R("file"),password:R("password"),image:R("image"),submit:S("submit"),reset:S("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return J.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&(!!a.type||!!a.href)},active:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b,c){return c?a.slice(1):[a[0]]},last:function(a,b,c){var d=a.pop();return c?a:[d]},even:function(a,b,c){var d=[],e=c?1:0,f=a.length;for(;e<f;e=e+2)d.push(a[e]);return d},odd:function(a,b,c){var d=[],e=c?0:1,f=a.length;for(;e<f;e=e+2)d.push(a[e]);return d},lt:function(a,b,c){return c?a.slice(+b):a.slice(0,+b)},gt:function(a,b,c){return c?a.slice(0,+b+1):a.slice(+b+1)},eq:function(a,b,c){var d=a.splice(+b,1);return c?a:d}}};$.setFilters.nth=$.setFilters.eq,$.filters=$.pseudos,X||($.attrHandle={href:function(a){return a.getAttribute("href",2)},type:function(a){return a.getAttribute("type")}}),V&&($.order.push("NAME"),$.find.NAME=function(a,b){if(typeof b.getElementsByName!==j)return b.getElementsByName(a)}),Y&&($.order.splice(1,0,"CLASS"),$.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!==j&&!c)return b.getElementsByClassName(a)});try{n.call(i.childNodes,0)[0].nodeType}catch(_){n=function(a){var b,c=[];for(;b=this[a];a++)c.push(b);return c}}var ba=Z.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?b.nodeName!=="HTML":!1},bb=Z.contains=i.compareDocumentPosition?function(a,b){return!!(a.compareDocumentPosition(b)&16)}:i.contains?function(a,b){var c=a.nodeType===9?a.documentElement:a,d=b.parentNode;return a===d||!!(d&&d.nodeType===1&&c.contains&&c.contains(d))}:function(a,b){while(b=b.parentNode)if(b===a)return!0;return!1},bc=Z.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(e===1||e===9||e===11){if(typeof a.textContent=="string")return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=bc(a)}else if(e===3||e===4)return a.nodeValue}else for(;b=a[d];d++)c+=bc(b);return c};Z.attr=function(a,b){var c,d=ba(a);return d||(b=b.toLowerCase()),$.attrHandle[b]?$.attrHandle[b](a):U||d?a.getAttribute(b):(c=a.getAttributeNode(b),c?typeof a[b]=="boolean"?a[b]?b:null:c.specified?c.value:null:null)},Z.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},[0,0].sort(function(){return l=0}),i.compareDocumentPosition?e=function(a,b){return a===b?(k=!0,0):(!a.compareDocumentPosition||!b.compareDocumentPosition?a.compareDocumentPosition:a.compareDocumentPosition(b)&4)?-1:1}:(e=function(a,b){if(a===b)return k=!0,0;if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],g=[],h=a.parentNode,i=b.parentNode,j=h;if(h===i)return f(a,b);if(!h)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)g.unshift(j),j=j.parentNode;c=e.length,d=g.length;for(var l=0;l<c&&l<d;l++)if(e[l]!==g[l])return f(e[l],g[l]);return l===c?f(a,g[l],-1):f(e[l],b,1)},f=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}),Z.uniqueSort=function(a){var b,c=1;if(e){k=l,a.sort(e);if(k)for(;b=a[c];c++)b===a[c-1]&&a.splice(c--,1)}return a};var bl=Z.compile=function(a,b,c){var d,e,f,g=O[a];if(g&&g.context===b)return g;e=bg(a,b,c);for(f=0;d=e[f];f++)e[f]=bj(d,b,c);return g=O[a]=bk(e),g.context=b,g.runs=g.dirruns=0,P.push(a),P.length>$.cacheLength&&delete O[P.shift()],g};Z.matches=function(a,b){return Z(a,null,null,b)},Z.matchesSelector=function(a,b){return Z(b,null,null,[a]).length>0};var bm=function(a,b,e,f,g){a=a.replace(A,"$1");var h,i,j,k,l,m,p,q,r,s=a.match(C),t=a.match(E),u=b.nodeType;if(L.POS.test(a))return bf(a,b,e,f,s);if(f)h=n.call(f,0);else if(s&&s.length===1){if(t.length>1&&u===9&&!g&&(s=L.ID.exec(t[0]))){b=$.find.ID(s[1],b,g)[0];if(!b)return e;a=a.slice(t.shift().length)}q=(s=G.exec(t[0]))&&!s.index&&b.parentNode||b,r=t.pop(),m=r.split(":not")[0];for(j=0,k=$.order.length;j<k;j++){p=$.order[j];if(s=L[p].exec(m)){h=$.find[p]((s[1]||"").replace(K,""),q,g);if(h==null)continue;m===r&&(a=a.slice(0,a.length-r.length)+m.replace(L[p],""),a||o.apply(e,n.call(h,0)));break}}}if(a){i=bl(a,b,g),d=i.dirruns++,h==null&&(h=$.find.TAG("*",G.test(a)&&b.parentNode||b));for(j=0;l=h[j];j++)c=i.runs++,i(l,b)&&e.push(l)}return e};h.querySelectorAll&&function(){var a,b=bm,c=/'|\\/g,d=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,e=[],f=[":active"],g=i.matchesSelector||i.mozMatchesSelector||i.webkitMatchesSelector||i.oMatchesSelector||i.msMatchesSelector;T(function(a){a.innerHTML="<select><option selected></option></select>",a.querySelectorAll("[selected]").length||e.push("\\["+r+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),T(function(a){a.innerHTML="<p test=''></p>",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+r+"*(?:\"\"|'')"),a.innerHTML="<input type='hidden'>",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=e.length&&new RegExp(e.join("|")),bm=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a)))if(d.nodeType===9)try{return o.apply(f,n.call(d.querySelectorAll(a),0)),f}catch(i){}else if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){var j=d.getAttribute("id"),k=j||q,l=G.test(a)&&d.parentNode||d;j?k=k.replace(c,"\\$&"):d.setAttribute("id",k);try{return o.apply(f,n.call(l.querySelectorAll(a.replace(C,"[id='"+k+"'] $&")),0)),f}catch(i){}finally{j||d.removeAttribute("id")}}return b(a,d,f,g,h)},g&&(T(function(b){a=g.call(b,"div");try{g.call(b,"[test!='']:sizzle"),f.push($.match.PSEUDO)}catch(c){}}),f=new RegExp(f.join("|")),Z.matchesSelector=function(b,c){c=c.replace(d,"='$1']");if(!ba(b)&&!f.test(c)&&(!e||!e.test(c)))try{var h=g.call(b,c);if(h||a||b.document&&b.document.nodeType!==11)return h}catch(i){}return Z(c,null,null,[b]).length>0})}(),Z.attr=p.attr,p.find=Z,p.expr=Z.selectors,p.expr[":"]=p.expr.pseudos,p.unique=Z.uniqueSort,p.text=Z.getText,p.isXMLDoc=Z.isXML,p.contains=Z.contains}(a);var bc=/Until$/,bd=/^(?:parents|prev(?:Until|All))/,be=/^.[^:#\[\.,]*$/,bf=p.expr.match.needsContext,bg={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if(typeof a!="string")return p(a).filter(function(){for(b=0,c=h.length;b<c;b++)if(p.contains(h[b],this))return!0});g=this.pushStack("","find",a);for(b=0,c=this.length;b<c;b++){d=g.length,p.find(a,this[b],g);if(b>0)for(e=d;e<g.length;e++)for(f=0;f<d;f++)if(g[f]===g[e]){g.splice(e--,1);break}}return g},has:function(a){var b,c=p(a,this),d=c.length;return this.filter(function(){for(b=0;b<d;b++)if(p.contains(this,c[b]))return!0})},not:function(a){return this.pushStack(bj(this,a,!1),"not",a)},filter:function(a){return this.pushStack(bj(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?bf.test(a)?p(a,this.context).index(this[0])>=0:p.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c,d=0,e=this.length,f=[],g=bf.test(a)||typeof a!="string"?p(a,b||this.context):0;for(;d<e;d++){c=this[d];while(c&&c.ownerDocument&&c!==b&&c.nodeType!==11){if(g?g.index(c)>-1:p.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}}return f=f.length>1?p.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?typeof a=="string"?p.inArray(this[0],p(a)):p.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c=typeof a=="string"?p(a,b):p.makeArray(a&&a.nodeType?[a]:a),d=p.merge(this.get(),c);return this.pushStack(bh(c[0])||bh(d[0])?d:p.unique(d))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}}),p.fn.andSelf=p.fn.addBack,p.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return p.dir(a,"parentNode")},parentsUntil:function(a,b,c){return p.dir(a,"parentNode",c)},next:function(a){return bi(a,"nextSibling")},prev:function(a){return bi(a,"previousSibling")},nextAll:function(a){return p.dir(a,"nextSibling")},prevAll:function(a){return p.dir(a,"previousSibling")},nextUntil:function(a,b,c){return p.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return p.dir(a,"previousSibling",c)},siblings:function(a){return p.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return p.sibling(a.firstChild)},contents:function(a){return p.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:p.merge([],a.childNodes)}},function(a,b){p.fn[a]=function(c,d){var e=p.map(this,b,c);return bc.test(a)||(d=c),d&&typeof d=="string"&&(e=p.filter(d,e)),e=this.length>1&&!bg[a]?p.unique(e):e,this.length>1&&bd.test(a)&&(e=e.reverse()),this.pushStack(e,a,k.call(arguments).join(","))}}),p.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),b.length===1?p.find.matchesSelector(b[0],a)?[b[0]]:[]:p.find.matches(a,b)},dir:function(a,c,d){var e=[],f=a[c];while(f&&f.nodeType!==9&&(d===b||f.nodeType!==1||!p(f).is(d)))f.nodeType===1&&e.push(f),f=f[c];return e},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var bl="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",bm=/ jQuery\d+="(?:null|\d+)"/g,bn=/^\s+/,bo=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bp=/<([\w:]+)/,bq=/<tbody/i,br=/<|&#?\w+;/,bs=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,bu=new RegExp("<(?:"+bl+")[\\s/>]","i"),bv=/^(?:checkbox|radio)$/,bw=/checked\s*(?:[^=]|=\s*.checked.)/i,bx=/\/(java|ecma)script/i,by=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,bz={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,"",""]},bA=bk(e),bB=bA.appendChild(e.createElement("div"));bz.optgroup=bz.option,bz.tbody=bz.tfoot=bz.colgroup=bz.caption=bz.thead,bz.th=bz.td,p.support.htmlSerialize||(bz._default=[1,"X<div>","</div>"]),p.fn.extend({text:function(a){return p.access(this,function(a){return a===b?p.text(this):this.empty().append((this[0]&&this[0].ownerDocument||e).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(p.isFunction(a))return this.each(function(b){p(this).wrapAll(a.call(this,b))});if(this[0]){var b=p(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){return p.isFunction(a)?this.each(function(b){p(this).wrapInner(a.call(this,b))}):this.each(function(){var b=p(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=p.isFunction(a);return this.each(function(c){p(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){p.nodeName(this,"body")||p(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(a,this),"before",this.selector)}},after:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(this,a),"after",this.selector)}},remove:function(a,b){var c,d=0;for(;(c=this[d])!=null;d++)if(!a||p.filter(a,[c]).length)!b&&c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),p.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c);return this},empty:function(){var a,b=0;for(;(a=this[b])!=null;b++){a.nodeType===1&&p.cleanData(a.getElementsByTagName("*"));while(a.firstChild)a.removeChild(a.firstChild)}return this},clone:function(a,b){return a=a==null?!1:a,b=b==null?a:b,this.map(function(){return p.clone(this,a,b)})},html:function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(a))&&!bz[(bp.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(bo,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(f){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){return bh(this[0])?this.length?this.pushStack(p(p.isFunction(a)?a():a),"replaceWith",a):this:p.isFunction(a)?this.each(function(b){var c=p(this),d=c.html();c.replaceWith(a.call(this,b,d))}):(typeof a!="string"&&(a=p(a).detach()),this.each(function(){var b=this.nextSibling,c=this.parentNode;p(this).remove(),b?p(b).before(a):p(c).append(a)}))},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){a=[].concat.apply([],a);var e,f,g,h,i=0,j=a[0],k=[],l=this.length;if(!p.support.checkClone&&l>1&&typeof j=="string"&&bw.test(j))return this.each(function(){p(this).domManip(a,c,d)});if(p.isFunction(j))return this.each(function(e){var f=p(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){e=p.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,g.childNodes.length===1&&(g=f);if(f){c=c&&p.nodeName(f,"tr");for(h=e.cacheable||l-1;i<l;i++)d.call(c&&p.nodeName(this[i],"table")?bC(this[i],"tbody"):this[i],i===h?g:p.clone(g,!0,!0))}g=f=null,k.length&&p.each(k,function(a,b){b.src?p.ajax?p.ajax({url:b.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):p.error("no ajax"):p.globalEval((b.text||b.textContent||b.innerHTML||"").replace(by,"")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),p.buildFragment=function(a,c,d){var f,g,h,i=a[0];return c=c||e,c=(c[0]||c).ownerDocument||c[0]||c,typeof c.createDocumentFragment=="undefined"&&(c=e),a.length===1&&typeof i=="string"&&i.length<512&&c===e&&i.charAt(0)==="<"&&!bt.test(i)&&(p.support.checkClone||!bw.test(i))&&(p.support.html5Clone||!bu.test(i))&&(g=!0,f=p.fragments[i],h=f!==b),f||(f=c.createDocumentFragment(),p.clean(a,c,f,d),g&&(p.fragments[i]=h&&f)),{fragment:f,cacheable:g}},p.fragments={},p.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){p.fn[a]=function(c){var d,e=0,f=[],g=p(c),h=g.length,i=this.length===1&&this[0].parentNode;if((i==null||i&&i.nodeType===11&&i.childNodes.length===1)&&h===1)return g[b](this[0]),this;for(;e<h;e++)d=(e>0?this.clone(!0):this).get(),p(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),p.extend({clone:function(a,b,c){var d,e,f,g;p.support.html5Clone||p.isXMLDoc(a)||!bu.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bB.innerHTML=a.outerHTML,bB.removeChild(g=bB.firstChild));if((!p.support.noCloneEvent||!p.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!p.isXMLDoc(a)){bE(a,g),d=bF(a),e=bF(g);for(f=0;d[f];++f)e[f]&&bE(d[f],e[f])}if(b){bD(a,g);if(c){d=bF(a),e=bF(g);for(f=0;d[f];++f)bD(d[f],e[f])}}return d=e=null,g},clean:function(a,b,c,d){var f,g,h,i,j,k,l,m,n,o,q,r,s=0,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(g=b===e&&bA;(h=a[s])!=null;s++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{g=g||bk(b),l=l||g.appendChild(b.createElement("div")),h=h.replace(bo,"<$1></$2>"),i=(bp.exec(h)||["",""])[1].toLowerCase(),j=bz[i]||bz._default,k=j[0],l.innerHTML=j[1]+h+j[2];while(k--)l=l.lastChild;if(!p.support.tbody){m=bq.test(h),n=i==="table"&&!m?l.firstChild&&l.firstChild.childNodes:j[1]==="<table>"&&!m?l.childNodes:[];for(f=n.length-1;f>=0;--f)p.nodeName(n[f],"tbody")&&!n[f].childNodes.length&&n[f].parentNode.removeChild(n[f])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l=g.lastChild}h.nodeType?t.push(h):t=p.merge(t,h)}l&&(g.removeChild(l),h=l=g=null);if(!p.support.appendChecked)for(s=0;(h=t[s])!=null;s++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(s=0;(h=t[s])!=null;s++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[s+1,0].concat(r)),s+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^margin/,bO=new RegExp("^("+q+")(.*)$","i"),bP=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bQ=new RegExp("^([-+])=("+q+")","i"),bR={},bS={position:"absolute",visibility:"hidden",display:"block"},bT={letterSpacing:0,fontWeight:400,lineHeight:1},bU=["Top","Right","Bottom","Left"],bV=["Webkit","O","Moz","ms"],bW=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return bZ(this,!0)},hide:function(){return bZ(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bW.apply(this,arguments):this.each(function(){(c?a:bY(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bX(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bQ.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bX(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bT&&(f=bT[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(a,b){var c,d,e,f,g=getComputedStyle(a,null),h=a.style;return g&&(c=g[b],c===""&&!p.contains(a.ownerDocument.documentElement,a)&&(c=p.style(a,b)),bP.test(c)&&bN.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=c,c=g.width,h.width=d,h.minWidth=e,h.maxWidth=f)),c}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bP.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0||bH(a,"display")!=="none"?ca(a,b,d):p.swap(a,bS,function(){return ca(a,b,d)})},set:function(a,c,d){return b$(a,c,d?b_(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bP.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bU[d]+b]=e[d]||e[d-2]||e[0];return f}},bN.test(a)||(p.cssHooks[a+b].set=b$)});var cc=/%20/g,cd=/\[\]$/,ce=/\r?\n/g,cf=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,cg=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||cg.test(this.nodeName)||cf.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(ce,"\r\n")}}):{name:b.name,value:c.replace(ce,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ch(d,a[d],c,f);return e.join("&").replace(cc,"+")};var ci,cj,ck=/#.*$/,cl=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cm=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,cn=/^(?:GET|HEAD)$/,co=/^\/\//,cp=/\?/,cq=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,cr=/([?&])_=[^&]*/,cs=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,ct=p.fn.load,cu={},cv={},cw=["*/"]+["*"];try{ci=f.href}catch(cx){ci=e.createElement("a"),ci.href="",ci=ci.href}cj=cs.exec(ci.toLowerCase())||[],p.fn.load=function(a,c,d){if(typeof a!="string"&&ct)return ct.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),p.isFunction(c)?(d=c,c=b):typeof c=="object"&&(f="POST"),p.ajax({url:a,type:f,dataType:"html",data:c,complete:function(a,b){d&&h.each(d,g||[a.responseText,b,a])}}).done(function(a){g=arguments,h.html(e?p("<div>").append(a.replace(cq,"")).find(e):a)}),this},p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){p.fn[b]=function(a){return this.on(b,a)}}),p.each(["get","post"],function(a,c){p[c]=function(a,d,e,f){return p.isFunction(d)&&(f=f||e,e=d,d=b),p.ajax({type:c,url:a,data:d,success:e,dataType:f})}}),p.extend({getScript:function(a,c){return p.get(a,b,c,"script")},getJSON:function(a,b,c){return p.get(a,b,c,"json")},ajaxSetup:function(a,b){return b?cA(a,p.ajaxSettings):(b=a,a=p.ajaxSettings),cA(a,b),a},ajaxSettings:{url:ci,isLocal:cm.test(cj[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":cw},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":p.parseJSON,"text xml":p.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:cy(cu),ajaxTransport:cy(cv),ajax:function(a,c){function y(a,c,f,i){var k,s,t,u,w,y=c;if(v===2)return;v=2,h&&clearTimeout(h),g=b,e=i||"",x.readyState=a>0?4:0,f&&(u=cB(l,x,f));if(a>=200&&a<300||a===304)l.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(p.lastModified[d]=w),w=x.getResponseHeader("Etag"),w&&(p.etag[d]=w)),a===304?(y="notmodified",k=!0):(k=cC(l,u),y=k.state,s=k.data,t=k.error,k=!t);else{t=y;if(!y||a)y="error",a<0&&(a=0)}x.status=a,x.statusText=""+(c||y),k?o.resolveWith(m,[s,y,x]):o.rejectWith(m,[x,y,t]),x.statusCode(r),r=b,j&&n.trigger("ajax"+(k?"Success":"Error"),[x,l,k?s:t]),q.fireWith(m,[x,y]),j&&(n.trigger("ajaxComplete",[x,l]),--p.active||p.event.trigger("ajaxStop"))}typeof a=="object"&&(c=a,a=b),c=c||{};var d,e,f,g,h,i,j,k,l=p.ajaxSetup({},c),m=l.context||l,n=m!==l&&(m.nodeType||m instanceof p)?p(m):p.event,o=p.Deferred(),q=p.Callbacks("once memory"),r=l.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,setRequestHeader:function(a,b){if(!v){var c=a.toLowerCase();a=u[c]=u[c]||a,t[a]=b}return this},getAllResponseHeaders:function(){return v===2?e:null},getResponseHeader:function(a){var c;if(v===2){if(!f){f={};while(c=cl.exec(e))f[c[1].toLowerCase()]=c[2]}c=f[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){return v||(l.mimeType=a),this},abort:function(a){return a=a||w,g&&g.abort(a),y(0,a),this}};o.promise(x),x.success=x.done,x.error=x.fail,x.complete=q.add,x.statusCode=function(a){if(a){var b;if(v<2)for(b in a)r[b]=[r[b],a[b]];else b=a[x.status],x.always(b)}return this},l.url=((a||l.url)+"").replace(ck,"").replace(co,cj[1]+"//"),l.dataTypes=p.trim(l.dataType||"*").toLowerCase().split(s),l.crossDomain==null&&(i=cs.exec(l.url.toLowerCase()),l.crossDomain=!(!i||i[1]==cj[1]&&i[2]==cj[2]&&(i[3]||(i[1]==="http:"?80:443))==(cj[3]||(cj[1]==="http:"?80:443)))),l.data&&l.processData&&typeof l.data!="string"&&(l.data=p.param(l.data,l.traditional)),cz(cu,l,c,x);if(v===2)return x;j=l.global,l.type=l.type.toUpperCase(),l.hasContent=!cn.test(l.type),j&&p.active++===0&&p.event.trigger("ajaxStart");if(!l.hasContent){l.data&&(l.url+=(cp.test(l.url)?"&":"?")+l.data,delete l.data),d=l.url;if(l.cache===!1){var z=p.now(),A=l.url.replace(cr,"$1_="+z);l.url=A+(A===l.url?(cp.test(l.url)?"&":"?")+"_="+z:"")}}(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",l.contentType),l.ifModified&&(d=d||l.url,p.lastModified[d]&&x.setRequestHeader("If-Modified-Since",p.lastModified[d]),p.etag[d]&&x.setRequestHeader("If-None-Match",p.etag[d])),x.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+(l.dataTypes[0]!=="*"?", "+cw+"; q=0.01":""):l.accepts["*"]);for(k in l.headers)x.setRequestHeader(k,l.headers[k]);if(!l.beforeSend||l.beforeSend.call(m,x,l)!==!1&&v!==2){w="abort";for(k in{success:1,error:1,complete:1})x[k](l[k]);g=cz(cv,l,c,x);if(!g)y(-1,"No Transport");else{x.readyState=1,j&&n.trigger("ajaxSend",[x,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){x.abort("timeout")},l.timeout));try{v=1,g.send(t,y)}catch(B){if(v<2)y(-1,B);else throw B}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var cD=[],cE=/\?/,cF=/(=)\?(?=&|$)|\?\?/,cG=p.now();p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cD.pop()||p.expando+"_"+cG++;return this[a]=!0,a}}),p.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.data,j=c.url,k=c.jsonp!==!1,l=k&&cF.test(j),m=k&&!l&&typeof i=="string"&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&cF.test(i);if(c.dataTypes[0]==="jsonp"||l||m)return f=c.jsonpCallback=p.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,g=a[f],l?c.url=j.replace(cF,"$1"+f):m?c.data=i.replace(cF,"$1"+f):k&&(c.url+=(cE.test(j)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||p.error(f+" was not called"),h[0]},c.dataTypes[0]="json",a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,cD.push(f)),h&&p.isFunction(g)&&g(h[0]),h=g=b}),"script"}),p.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){return p.globalEval(a),a}}}),p.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),p.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=e.head||e.getElementsByTagName("head")[0]||e.documentElement;return{send:function(f,g){c=e.createElement("script"),c.async="async",a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,e){if(e||!c.readyState||/loaded|complete/.test(c.readyState))c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=b,e||g(200,"success")},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(0,1)}}}});var cH,cI=a.ActiveXObject?function(){for(var a in cH)cH[a](0,1)}:!1,cJ=0;p.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&cK()||cL()}:cK,function(a){p.extend(p.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(p.ajaxSettings.xhr()),p.support.ajax&&p.ajaxTransport(function(c){if(!c.crossDomain||p.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async);if(c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l,m;try{if(d&&(e||i.readyState===4)){d=b,g&&(i.onreadystatechange=p.noop,cI&&delete cH[g]);if(e)i.readyState!==4&&i.abort();else{h=i.status,k=i.getAllResponseHeaders(),l={},m=i.responseXML,m&&m.documentElement&&(l.xml=m);try{l.text=i.responseText}catch(a){}try{j=i.statusText}catch(n){j=""}!h&&c.isLocal&&!c.crossDomain?h=l.text?200:404:h===1223&&(h=204)}}}catch(o){e||f(-1,o)}l&&f(h,j,l,k)},c.async?i.readyState===4?setTimeout(d,0):(g=++cJ,cI&&(cH||(cH={},p(a).unload(cI)),cH[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var cM,cN,cO=/^(?:toggle|show|hide)$/,cP=new RegExp("^(?:([-+])=|)("+q+")([a-z%]*)$","i"),cQ=/queueHooks$/,cR=[cX],cS={"*":[function(a,b){var c,d,e,f=this.createTween(a,b),g=cP.exec(b),h=f.cur(),i=+h||0,j=1;if(g){c=+g[2],d=g[3]||(p.cssNumber[a]?"":"px");if(d!=="px"&&i){i=p.css(f.elem,a,!0)||c||1;do e=j=j||".5",i=i/j,p.style(f.elem,a,i+d),j=f.cur()/h;while(j!==1&&j!==e)}f.unit=d,f.start=i,f.end=g[1]?i+(g[1]+1)*c:c}return f}]};p.Animation=p.extend(cV,{tweener:function(a,b){p.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");var c,d=0,e=a.length;for(;d<e;d++)c=a[d],cS[c]=cS[c]||[],cS[c].unshift(b)},prefilter:function(a,b){b?cR.unshift(a):cR.push(a)}}),p.Tween=cY,cY.prototype={constructor:cY,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(p.cssNumber[c]?"":"px")},cur:function(){var a=cY.propHooks[this.prop];return a&&a.get?a.get(this):cY.propHooks._default.get(this)},run:function(a){var b,c=cY.propHooks[this.prop];return this.pos=b=p.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration),this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):cY.propHooks._default.set(this),this}},cY.prototype.init.prototype=cY.prototype,cY.propHooks={_default:{get:function(a){var b;return a.elem[a.prop]==null||!!a.elem.style&&a.elem.style[a.prop]!=null?(b=p.css(a.elem,a.prop,!1,""),!b||b==="auto"?0:b):a.elem[a.prop]},set:function(a){p.fx.step[a.prop]?p.fx.step[a.prop](a):a.elem.style&&(a.elem.style[p.cssProps[a.prop]]!=null||p.cssHooks[a.prop])?p.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},cY.propHooks.scrollTop=cY.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},p.each(["toggle","show","hide"],function(a,b){var c=p.fn[b];p.fn[b]=function(d,e,f){return d==null||typeof d=="boolean"||!a&&p.isFunction(d)&&p.isFunction(e)?c.apply(this,arguments):this.animate(cZ(b,!0),d,e,f)}}),p.fn.extend({fadeTo:function(a,b,c,d){return this.filter(bY).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=p.isEmptyObject(a),f=p.speed(b,c,d),g=function(){var b=cV(this,p.extend({},a),f);e&&b.stop(!0)};return e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,c,d){var e=function(a){var b=a.stop;delete a.stop,b(d)};return typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,c=a!=null&&a+"queueHooks",f=p.timers,g=p._data(this);if(c)g[c]&&g[c].stop&&e(g[c]);else for(c in g)g[c]&&g[c].stop&&cQ.test(c)&&e(g[c]);for(c=f.length;c--;)f[c].elem===this&&(a==null||f[c].queue===a)&&(f[c].anim.stop(d),b=!1,f.splice(c,1));(b||!d)&&p.dequeue(this,a)})}}),p.each({slideDown:cZ("show"),slideUp:cZ("hide"),slideToggle:cZ("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){p.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),p.speed=function(a,b,c){var d=a&&typeof a=="object"?p.extend({},a):{complete:c||!c&&b||p.isFunction(a)&&a,duration:a,easing:c&&b||b&&!p.isFunction(b)&&b};d.duration=p.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in p.fx.speeds?p.fx.speeds[d.duration]:p.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";return d.old=d.complete,d.complete=function(){p.isFunction(d.old)&&d.old.call(this),d.queue&&p.dequeue(this,d.queue)},d},p.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},p.timers=[],p.fx=cY.prototype.init,p.fx.tick=function(){var a,b=p.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||p.fx.stop()},p.fx.timer=function(a){a()&&p.timers.push(a)&&!cN&&(cN=setInterval(p.fx.tick,p.fx.interval))},p.fx.interval=13,p.fx.stop=function(){clearInterval(cN),cN=null},p.fx.speeds={slow:600,fast:200,_default:400},p.fx.step={},p.expr&&p.expr.filters&&(p.expr.filters.animated=function(a){return p.grep(p.timers,function(b){return a===b.elem}).length});var c$=/^(?:body|html)$/i;p.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){p.offset.setOffset(this,a,b)});var c,d,e,f,g,h,i,j,k,l,m=this[0],n=m&&m.ownerDocument;if(!n)return;return(e=n.body)===m?p.offset.bodyOffset(m):(d=n.documentElement,p.contains(d,m)?(c=m.getBoundingClientRect(),f=c_(n),g=d.clientTop||e.clientTop||0,h=d.clientLeft||e.clientLeft||0,i=f.pageYOffset||d.scrollTop,j=f.pageXOffset||d.scrollLeft,k=c.top+i-g,l=c.left+j-h,{top:k,left:l}):{top:0,left:0})},p.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;return p.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(p.css(a,"marginTop"))||0,c+=parseFloat(p.css(a,"marginLeft"))||0),{top:b,left:c}},setOffset:function(a,b,c){var d=p.css(a,"position");d==="static"&&(a.style.position="relative");var e=p(a),f=e.offset(),g=p.css(a,"top"),h=p.css(a,"left"),i=(d==="absolute"||d==="fixed")&&p.inArray("auto",[g,h])>-1,j={},k={},l,m;i?(k=e.position(),l=k.top,m=k.left):(l=parseFloat(g)||0,m=parseFloat(h)||0),p.isFunction(b)&&(b=b.call(a,c,f)),b.top!=null&&(j.top=b.top-f.top+l),b.left!=null&&(j.left=b.left-f.left+m),"using"in b?b.using.call(a,j):e.css(j)}},p.fn.extend({position:function(){if(!this[0])return;var a=this[0],b=this.offsetParent(),c=this.offset(),d=c$.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat(p.css(a,"marginTop"))||0,c.left-=parseFloat(p.css(a,"marginLeft"))||0,d.top+=parseFloat(p.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(p.css(b[0],"borderLeftWidth"))||0,{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||e.body;while(a&&!c$.test(a.nodeName)&&p.css(a,"position")==="static")a=a.offsetParent;return a||e.body})}}),p.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);p.fn[a]=function(e){return p.access(this,function(a,e,f){var g=c_(a);if(f===b)return g?c in g?g[c]:g.document.documentElement[e]:a[e];g?g.scrollTo(d?p(g).scrollLeft():f,d?f:p(g).scrollTop()):a[e]=f},a,e,arguments.length,null)}}),p.each({Height:"height",Width:"width"},function(a,c){p.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){p.fn[e]=function(e,f){var g=arguments.length&&(d||typeof e!="boolean"),h=d||(e===!0||f===!0?"margin":"border");return p.access(this,function(c,d,e){var f;return p.isWindow(c)?c.document.documentElement["client"+a]:c.nodeType===9?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?p.css(c,d,e,h):p.style(c,d,e,h)},c,g?e:b,g)}})}),a.jQuery=a.$=p,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return p})})(window); |
js/pages/Main.js | connectordb/connectordb-frontend | /*
Main is the index page shown after initially logging in to ConnectorDB
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { go } from "../actions";
import MainToolbar from "../components/MainToolbar";
import FontIcon from "material-ui/FontIcon";
import IconButton from "material-ui/IconButton";
import Welcome from "../components/Welcome";
import DataInput from "../components/DataInput";
import { objectFilter } from "../util";
class Main extends Component {
static propTypes = {
user: PropTypes.shape({ name: PropTypes.string.isRequired }).isRequired,
device: PropTypes.shape({ name: PropTypes.string.isRequired }).isRequired,
streamarray: PropTypes.object.isRequired,
state: PropTypes.object.isRequired,
indexState: PropTypes.object.isRequired,
onStreamClick: PropTypes.func.isRequired
};
render() {
let state = this.props.state;
let user = this.props.user;
let device = this.props.device;
let streams = this.props.streamarray;
let indexState = this.props.indexState;
return (
<div
style={{
textAlign: "left"
}}
>
<MainToolbar user={user} device={device} state={state} />
{" "}
{streams == null || Object.keys(streams).length == 0
? <Welcome />
: <div
style={{
marginLeft: "-15px",
marginRight: "-15px"
}}
>
{Object.keys(
objectFilter(indexState.search.text, streams)
).map(skey => {
let s = streams[skey];
let path = user.name + "/" + device.name + "/" + s.name;
return (
<DataInput
key={s.name}
size={6}
thisUser={user}
thisDevice={device}
title={
s.nickname == ""
? s.name.capitalizeFirstLetter()
: s.nickname
}
subtitle={path}
user={user}
device={device}
stream={s}
icons={[
<IconButton
key="showstream"
onTouchTap={() => this.props.onStreamClick(path)}
tooltip="view stream"
>
<FontIcon
className="material-icons"
color="rgba(0,0,0,0.8)"
>
list
</FontIcon>
</IconButton>
]}
/>
);
})}
</div>}
</div>
);
}
}
export default connect(
state => ({ indexState: state.pages.index }),
(dispatch, props) => ({
onStreamClick: s => dispatch(go(s))
})
)(Main);
|
ajax/libs/react-popper/0.9.1-alpha.1/react-popper.umd.js | extend1994/cdnjs | (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('prop-types'), require('popper.js')) :
typeof define === 'function' && define.amd ? define(['exports', 'react', 'prop-types', 'popper.js'], factory) :
(factory((global['react-popper'] = {}),global.react,global.PropTypes,global.PopperJS));
}(this, (function (exports,react,PropTypes,PopperJS) { 'use strict';
PropTypes = PropTypes && PropTypes.hasOwnProperty('default') ? PropTypes['default'] : PropTypes;
PopperJS = PopperJS && PopperJS.hasOwnProperty('default') ? PopperJS['default'] : PopperJS;
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var objectWithoutProperties = function (obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
var Manager = function (_Component) {
inherits(Manager, _Component);
function Manager() {
var _ref;
var _temp, _this, _ret;
classCallCheck(this, Manager);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = Manager.__proto__ || Object.getPrototypeOf(Manager)).call.apply(_ref, [this].concat(args))), _this), _this._setTargetNode = function (node) {
_this._targetNode = node;
}, _this._getTargetNode = function () {
return _this._targetNode;
}, _temp), possibleConstructorReturn(_this, _ret);
}
createClass(Manager, [{
key: 'getChildContext',
value: function getChildContext() {
return {
popperManager: {
setTargetNode: this._setTargetNode,
getTargetNode: this._getTargetNode
}
};
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
tag = _props.tag,
children = _props.children,
restProps = objectWithoutProperties(_props, ['tag', 'children']);
if (tag !== false) {
return react.createElement(tag, restProps, children);
} else {
return children;
}
}
}]);
return Manager;
}(react.Component);
Manager.childContextTypes = {
popperManager: PropTypes.object.isRequired
};
Manager.defaultProps = {
tag: 'div'
};
Manager.propTypes = process.env.NODE_ENV !== "production" ? {
tag: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
children: PropTypes.oneOfType([PropTypes.node, PropTypes.func])
} : {};
var Target = function Target(props, context) {
var _props$component = props.component,
component = _props$component === undefined ? 'div' : _props$component,
innerRef = props.innerRef,
children = props.children,
restProps = objectWithoutProperties(props, ['component', 'innerRef', 'children']);
var popperManager = context.popperManager;
var targetRef = function targetRef(node) {
popperManager.setTargetNode(node);
if (typeof innerRef === 'function') {
innerRef(node);
}
};
if (typeof children === 'function') {
var targetProps = { ref: targetRef };
return children({ targetProps: targetProps, restProps: restProps });
}
var componentProps = _extends({}, restProps);
if (typeof component === 'string') {
componentProps.ref = targetRef;
} else {
componentProps.innerRef = targetRef;
}
return react.createElement(component, componentProps, children);
};
Target.contextTypes = {
popperManager: PropTypes.object.isRequired
};
Target.propTypes = {
component: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
innerRef: PropTypes.func,
children: PropTypes.oneOfType([PropTypes.node, PropTypes.func])
};
var Popper = function (_Component) {
inherits(Popper, _Component);
function Popper() {
var _ref;
var _temp, _this, _ret;
classCallCheck(this, Popper);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = Popper.__proto__ || Object.getPrototypeOf(Popper)).call.apply(_ref, [this].concat(args))), _this), _this.state = {}, _this._setArrowNode = function (node) {
_this._arrowNode = node;
}, _this._getTargetNode = function () {
if (_this.props.target) {
return _this.props.target;
} else if (!_this.context.popperManager || !_this.context.popperManager.getTargetNode()) {
throw new Error('Target missing. Popper must be given a target from the Popper Manager, or as a prop.');
}
return _this.context.popperManager.getTargetNode();
}, _this._getOffsets = function (data) {
return Object.keys(data.offsets).map(function (key) {
return data.offsets[key];
});
}, _this._isDataDirty = function (data) {
if (_this.state.data) {
return JSON.stringify(_this._getOffsets(_this.state.data)) !== JSON.stringify(_this._getOffsets(data));
} else {
return true;
}
}, _this._updateStateModifier = {
enabled: true,
order: 900,
fn: function fn(data) {
if (_this._isDataDirty(data)) {
_this.setState({ data: data });
}
return data;
}
}, _this._getPopperStyle = function () {
var data = _this.state.data;
if (!_this._popper || !data) {
return {
position: 'absolute',
pointerEvents: 'none',
opacity: 0
};
}
return _extends({
position: data.offsets.popper.position
}, data.styles);
}, _this._getPopperPlacement = function () {
return _this.state.data ? _this.state.data.placement : undefined;
}, _this._getPopperHide = function () {
return !!_this.state.data && _this.state.data.hide ? '' : undefined;
}, _this._getArrowStyle = function () {
if (!_this.state.data || !_this.state.data.offsets.arrow) {
return {};
} else {
var _this$state$data$offs = _this.state.data.offsets.arrow,
top = _this$state$data$offs.top,
left = _this$state$data$offs.left;
return { top: top, left: left };
}
}, _this._handlePopperRef = function (node) {
_this._popperNode = node;
if (node) {
_this._createPopper();
} else {
_this._destroyPopper();
}
if (_this.props.innerRef) {
_this.props.innerRef(node);
}
}, _this._scheduleUpdate = function () {
_this._popper && _this._popper.scheduleUpdate();
}, _temp), possibleConstructorReturn(_this, _ret);
}
createClass(Popper, [{
key: 'getChildContext',
value: function getChildContext() {
return {
popper: {
setArrowNode: this._setArrowNode,
getArrowStyle: this._getArrowStyle
}
};
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate(lastProps) {
if (lastProps.placement !== this.props.placement || lastProps.eventsEnabled !== this.props.eventsEnabled || lastProps.target !== this.props.target) {
this._destroyPopper();
this._createPopper();
}
if (lastProps.children !== this.props.children) {
this._scheduleUpdate();
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this._destroyPopper();
}
}, {
key: '_createPopper',
value: function _createPopper() {
var _this2 = this;
var _props = this.props,
placement = _props.placement,
eventsEnabled = _props.eventsEnabled;
var modifiers = _extends({}, this.props.modifiers, {
applyStyle: { enabled: false },
updateState: this._updateStateModifier
});
if (this._arrowNode) {
modifiers.arrow = {
element: this._arrowNode
};
}
this._popper = new PopperJS(this._getTargetNode(), this._popperNode, {
placement: placement,
eventsEnabled: eventsEnabled,
modifiers: modifiers
});
// TODO: look into setTimeout scheduleUpdate call, without it, the popper will not position properly on creation
setTimeout(function () {
return _this2._scheduleUpdate();
});
}
}, {
key: '_destroyPopper',
value: function _destroyPopper() {
if (this._popper) {
this._popper.destroy();
}
}
}, {
key: 'render',
value: function render() {
var _props2 = this.props,
component = _props2.component,
innerRef = _props2.innerRef,
placement = _props2.placement,
eventsEnabled = _props2.eventsEnabled,
modifiers = _props2.modifiers,
children = _props2.children,
restProps = objectWithoutProperties(_props2, ['component', 'innerRef', 'placement', 'eventsEnabled', 'modifiers', 'children']);
var popperStyle = this._getPopperStyle();
var popperPlacement = this._getPopperPlacement();
var popperHide = this._getPopperHide();
if (typeof children === 'function') {
var popperProps = {
ref: this._handlePopperRef,
style: popperStyle,
'data-placement': popperPlacement,
'data-x-out-of-boundaries': popperHide
};
return children({
popperProps: popperProps,
restProps: restProps,
scheduleUpdate: this._scheduleUpdate
});
}
var componentProps = _extends({}, restProps, {
style: _extends({}, restProps.style, popperStyle),
'data-placement': popperPlacement,
'data-x-out-of-boundaries': popperHide
});
if (typeof component === 'string') {
componentProps.ref = this._handlePopperRef;
} else {
componentProps.innerRef = this._handlePopperRef;
}
return react.createElement(component, componentProps, children);
}
}]);
return Popper;
}(react.Component);
Popper.contextTypes = {
popperManager: PropTypes.object
};
Popper.childContextTypes = {
popper: PropTypes.object.isRequired
};
Popper.defaultProps = {
component: 'div',
placement: 'bottom',
eventsEnabled: true,
modifiers: {}
};
Popper.propTypes = process.env.NODE_ENV !== "production" ? {
component: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
innerRef: PropTypes.func,
placement: PropTypes.oneOf(PopperJS.placements),
eventsEnabled: PropTypes.bool,
modifiers: PropTypes.object,
children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
target: PropTypes.oneOfType([PropTypes.instanceOf(Element), PropTypes.shape({
getBoundingClientRect: PropTypes.func.isRequired,
clientWidth: PropTypes.number.isRequired,
clientHeight: PropTypes.number.isRequired
})])
} : {};
var Arrow = function Arrow(props, context) {
var _props$component = props.component,
component = _props$component === undefined ? 'span' : _props$component,
innerRef = props.innerRef,
children = props.children,
restProps = objectWithoutProperties(props, ['component', 'innerRef', 'children']);
var popper = context.popper;
var arrowRef = function arrowRef(node) {
popper.setArrowNode(node);
if (typeof innerRef === 'function') {
innerRef(node);
}
};
var arrowStyle = popper.getArrowStyle();
if (typeof children === 'function') {
var arrowProps = {
ref: arrowRef,
style: arrowStyle
};
return children({ arrowProps: arrowProps, restProps: restProps });
}
var componentProps = _extends({}, restProps, {
style: _extends({}, arrowStyle, restProps.style)
});
if (typeof component === 'string') {
componentProps.ref = arrowRef;
} else {
componentProps.innerRef = arrowRef;
}
return react.createElement(component, componentProps, children);
};
Arrow.contextTypes = {
popper: PropTypes.object.isRequired
};
Arrow.propTypes = {
component: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
innerRef: PropTypes.func,
children: PropTypes.oneOfType([PropTypes.node, PropTypes.func])
};
exports.Manager = Manager;
exports.Target = Target;
exports.Popper = Popper;
exports.Arrow = Arrow;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=react-popper.umd.js.map
|
ajax/libs/yui/3.1.1/event-custom/event-custom-base-debug.js | Nadeermalangadan/cdnjs | YUI.add('event-custom-base', function(Y) {
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
*/
Y.Env.evt = {
handles: {},
plugins: {}
};
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
* @submodule event-custom-base
*/
(function() {
/**
* Allows for the insertion of methods that are executed before or after
* a specified method
* @class Do
* @static
*/
var BEFORE = 0,
AFTER = 1;
Y.Do = {
/**
* Cache of objects touched by the utility
* @property objs
* @static
*/
objs: {},
/**
* Execute the supplied method before the specified function
* @method before
* @param fn {Function} the function to execute
* @param obj the object hosting the method to displace
* @param sFn {string} the name of the method to displace
* @param c The execution context for fn
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* when the event fires.
* @return {string} handle for the subscription
* @static
*/
before: function(fn, obj, sFn, c) {
// Y.log('Do before: ' + sFn, 'info', 'event');
var f = fn, a;
if (c) {
a = [fn, c].concat(Y.Array(arguments, 4, true));
f = Y.rbind.apply(Y, a);
}
return this._inject(BEFORE, f, obj, sFn);
},
/**
* Execute the supplied method after the specified function
* @method after
* @param fn {Function} the function to execute
* @param obj the object hosting the method to displace
* @param sFn {string} the name of the method to displace
* @param c The execution context for fn
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* @return {string} handle for the subscription
* @static
*/
after: function(fn, obj, sFn, c) {
var f = fn, a;
if (c) {
a = [fn, c].concat(Y.Array(arguments, 4, true));
f = Y.rbind.apply(Y, a);
}
return this._inject(AFTER, f, obj, sFn);
},
/**
* Execute the supplied method after the specified function
* @method _inject
* @param when {string} before or after
* @param fn {Function} the function to execute
* @param obj the object hosting the method to displace
* @param sFn {string} the name of the method to displace
* @param c The execution context for fn
* @return {string} handle for the subscription
* @private
* @static
*/
_inject: function(when, fn, obj, sFn) {
// object id
var id = Y.stamp(obj), o, sid;
if (! this.objs[id]) {
// create a map entry for the obj if it doesn't exist
this.objs[id] = {};
}
o = this.objs[id];
if (! o[sFn]) {
// create a map entry for the method if it doesn't exist
o[sFn] = new Y.Do.Method(obj, sFn);
// re-route the method to our wrapper
obj[sFn] =
function() {
return o[sFn].exec.apply(o[sFn], arguments);
};
}
// subscriber id
sid = id + Y.stamp(fn) + sFn;
// register the callback
o[sFn].register(sid, fn, when);
return new Y.EventHandle(o[sFn], sid);
},
/**
* Detach a before or after subscription
* @method detach
* @param handle {string} the subscription handle
*/
detach: function(handle) {
if (handle.detach) {
handle.detach();
}
},
_unload: function(e, me) {
}
};
//////////////////////////////////////////////////////////////////////////
/**
* Wrapper for a displaced method with aop enabled
* @class Do.Method
* @constructor
* @param obj The object to operate on
* @param sFn The name of the method to displace
*/
Y.Do.Method = function(obj, sFn) {
this.obj = obj;
this.methodName = sFn;
this.method = obj[sFn];
this.before = {};
this.after = {};
};
/**
* Register a aop subscriber
* @method register
* @param sid {string} the subscriber id
* @param fn {Function} the function to execute
* @param when {string} when to execute the function
*/
Y.Do.Method.prototype.register = function (sid, fn, when) {
if (when) {
this.after[sid] = fn;
} else {
this.before[sid] = fn;
}
};
/**
* Unregister a aop subscriber
* @method delete
* @param sid {string} the subscriber id
* @param fn {Function} the function to execute
* @param when {string} when to execute the function
*/
Y.Do.Method.prototype._delete = function (sid) {
// Y.log('Y.Do._delete: ' + sid, 'info', 'Event');
delete this.before[sid];
delete this.after[sid];
};
/**
* Execute the wrapped method
* @method exec
*/
Y.Do.Method.prototype.exec = function () {
var args = Y.Array(arguments, 0, true),
i, ret, newRet,
bf = this.before,
af = this.after,
prevented = false;
// execute before
for (i in bf) {
if (bf.hasOwnProperty(i)) {
ret = bf[i].apply(this.obj, args);
if (ret) {
switch (ret.constructor) {
case Y.Do.Halt:
return ret.retVal;
case Y.Do.AlterArgs:
args = ret.newArgs;
break;
case Y.Do.Prevent:
prevented = true;
break;
default:
}
}
}
}
// execute method
if (!prevented) {
ret = this.method.apply(this.obj, args);
}
// execute after methods.
for (i in af) {
if (af.hasOwnProperty(i)) {
newRet = af[i].apply(this.obj, args);
// Stop processing if a Halt object is returned
if (newRet && newRet.constructor == Y.Do.Halt) {
return newRet.retVal;
// Check for a new return value
} else if (newRet && newRet.constructor == Y.Do.AlterReturn) {
ret = newRet.newRetVal;
}
}
}
return ret;
};
//////////////////////////////////////////////////////////////////////////
/**
* Return an AlterArgs object when you want to change the arguments that
* were passed into the function. An example would be a service that scrubs
* out illegal characters prior to executing the core business logic.
* @class Do.AlterArgs
*/
Y.Do.AlterArgs = function(msg, newArgs) {
this.msg = msg;
this.newArgs = newArgs;
};
/**
* Return an AlterReturn object when you want to change the result returned
* from the core method to the caller
* @class Do.AlterReturn
*/
Y.Do.AlterReturn = function(msg, newRetVal) {
this.msg = msg;
this.newRetVal = newRetVal;
};
/**
* Return a Halt object when you want to terminate the execution
* of all subsequent subscribers as well as the wrapped method
* if it has not exectued yet.
* @class Do.Halt
*/
Y.Do.Halt = function(msg, retVal) {
this.msg = msg;
this.retVal = retVal;
};
/**
* Return a Prevent object when you want to prevent the wrapped function
* from executing, but want the remaining listeners to execute
* @class Do.Prevent
*/
Y.Do.Prevent = function(msg) {
this.msg = msg;
};
/**
* Return an Error object when you want to terminate the execution
* of all subsequent method calls.
* @class Do.Error
* @deprecated use Y.Do.Halt or Y.Do.Prevent
*/
Y.Do.Error = Y.Do.Halt;
//////////////////////////////////////////////////////////////////////////
// Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do);
})();
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
* @submodule event-custom-base
*/
/**
* Return value from all subscribe operations
* @class EventHandle
* @constructor
* @param evt {CustomEvent} the custom event
* @param sub {Subscriber} the subscriber
*/
// var onsubscribeType = "_event:onsub",
var AFTER = 'after',
CONFIGS = [
'broadcast',
'monitored',
'bubbles',
'context',
'contextFn',
'currentTarget',
'defaultFn',
'defaultTargetOnly',
'details',
'emitFacade',
'fireOnce',
'async',
'host',
'preventable',
'preventedFn',
'queuable',
'silent',
'stoppedFn',
'target',
'type'
],
YUI3_SIGNATURE = 9,
YUI_LOG = 'yui:log';
Y.EventHandle = function(evt, sub) {
/**
* The custom event
* @type CustomEvent
*/
this.evt = evt;
/**
* The subscriber object
* @type Subscriber
*/
this.sub = sub;
};
Y.EventHandle.prototype = {
/**
* Detaches this subscriber
* @method detach
*/
detach: function() {
var evt = this.evt, detached = 0, i;
if (evt) {
// Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event');
if (Y.Lang.isArray(evt)) {
for (i=0; i<evt.length; i++) {
detached += evt[i].detach();
}
} else {
evt._delete(this.sub);
detached = 1;
}
}
return detached;
},
/**
* Monitor the event state for the subscribed event. The first parameter
* is what should be monitored, the rest are the normal parameters when
* subscribing to an event.
* @method monitor
* @param what {string} what to monitor ('attach', 'detach', 'publish')
* @return {EventHandle} return value from the monitor event subscription
*/
monitor: function(what) {
return this.evt.monitor.apply(this.evt, arguments);
}
};
/**
* The CustomEvent class lets you define events for your application
* that can be subscribed to by one or more independent component.
*
* @param {String} type The type of event, which is passed to the callback
* when the event fires
* @param o configuration object
* @class CustomEvent
* @constructor
*/
Y.CustomEvent = function(type, o) {
// if (arguments.length > 2) {
// this.log('CustomEvent context and silent are now in the config', 'warn', 'Event');
// }
o = o || {};
this.id = Y.stamp(this);
/**
* The type of event, returned to subscribers when the event fires
* @property type
* @type string
*/
this.type = type;
/**
* The context the the event will fire from by default. Defaults to the YUI
* instance.
* @property context
* @type object
*/
this.context = Y;
/**
* Monitor when an event is attached or detached.
*
* @property monitored
* @type boolean
*/
// this.monitored = false;
this.logSystem = (type == YUI_LOG);
/**
* If 0, this event does not broadcast. If 1, the YUI instance is notified
* every time this event fires. If 2, the YUI instance and the YUI global
* (if event is enabled on the global) are notified every time this event
* fires.
* @property broadcast
* @type int
*/
// this.broadcast = 0;
/**
* By default all custom events are logged in the debug build, set silent
* to true to disable debug outpu for this event.
* @property silent
* @type boolean
*/
this.silent = this.logSystem;
/**
* Specifies whether this event should be queued when the host is actively
* processing an event. This will effect exectution order of the callbacks
* for the various events.
* @property queuable
* @type boolean
* @default false
*/
// this.queuable = false;
/**
* The subscribers to this event
* @property subscribers
* @type Subscriber{}
*/
this.subscribers = {};
/**
* 'After' subscribers
* @property afters
* @type Subscriber{}
*/
this.afters = {};
/**
* This event has fired if true
*
* @property fired
* @type boolean
* @default false;
*/
// this.fired = false;
/**
* An array containing the arguments the custom event
* was last fired with.
* @property firedWith
* @type Array
*/
// this.firedWith;
/**
* This event should only fire one time if true, and if
* it has fired, any new subscribers should be notified
* immediately.
*
* @property fireOnce
* @type boolean
* @default false;
*/
// this.fireOnce = false;
/**
* fireOnce listeners will fire syncronously unless async
* is set to true
* @property async
* @type boolean
* @default false
*/
//this.async = false;
/**
* Flag for stopPropagation that is modified during fire()
* 1 means to stop propagation to bubble targets. 2 means
* to also stop additional subscribers on this target.
* @property stopped
* @type int
*/
// this.stopped = 0;
/**
* Flag for preventDefault that is modified during fire().
* if it is not 0, the default behavior for this event
* @property prevented
* @type int
*/
// this.prevented = 0;
/**
* Specifies the host for this custom event. This is used
* to enable event bubbling
* @property host
* @type EventTarget
*/
// this.host = null;
/**
* The default function to execute after event listeners
* have fire, but only if the default action was not
* prevented.
* @property defaultFn
* @type Function
*/
// this.defaultFn = null;
/**
* The function to execute if a subscriber calls
* stopPropagation or stopImmediatePropagation
* @property stoppedFn
* @type Function
*/
// this.stoppedFn = null;
/**
* The function to execute if a subscriber calls
* preventDefault
* @property preventedFn
* @type Function
*/
// this.preventedFn = null;
/**
* Specifies whether or not this event's default function
* can be cancelled by a subscriber by executing preventDefault()
* on the event facade
* @property preventable
* @type boolean
* @default true
*/
this.preventable = true;
/**
* Specifies whether or not a subscriber can stop the event propagation
* via stopPropagation(), stopImmediatePropagation(), or halt()
*
* Events can only bubble if emitFacade is true.
*
* @property bubbles
* @type boolean
* @default true
*/
this.bubbles = true;
/**
* Supports multiple options for listener signatures in order to
* port YUI 2 apps.
* @property signature
* @type int
* @default 9
*/
this.signature = YUI3_SIGNATURE;
this.subCount = 0;
this.afterCount = 0;
// this.hasSubscribers = false;
// this.hasAfters = false;
/**
* If set to true, the custom event will deliver an EventFacade object
* that is similar to a DOM event object.
* @property emitFacade
* @type boolean
* @default false
*/
// this.emitFacade = false;
this.applyConfig(o, true);
// this.log("Creating " + this.type);
};
Y.CustomEvent.prototype = {
hasSubs: function(when) {
var s = this.subCount, a = this.afterCount, sib = this.sibling;
if (sib) {
s += sib.subCount;
a += sib.afterCount;
}
if (when) {
return (when == 'after') ? a : s;
}
return (s + a);
},
/**
* Monitor the event state for the subscribed event. The first parameter
* is what should be monitored, the rest are the normal parameters when
* subscribing to an event.
* @method monitor
* @param what {string} what to monitor ('detach', 'attach', 'publish')
* @return {EventHandle} return value from the monitor event subscription
*/
monitor: function(what) {
this.monitored = true;
var type = this.id + '|' + this.type + '_' + what,
args = Y.Array(arguments, 0, true);
args[0] = type;
return this.host.on.apply(this.host, args);
},
/**
* Get all of the subscribers to this event and any sibling event
* @return {Array} first item is the on subscribers, second the after
*/
getSubs: function() {
var s = Y.merge(this.subscribers), a = Y.merge(this.afters), sib = this.sibling;
if (sib) {
Y.mix(s, sib.subscribers);
Y.mix(a, sib.afters);
}
return [s, a];
},
/**
* Apply configuration properties. Only applies the CONFIG whitelist
* @method applyConfig
* @param o hash of properties to apply
* @param force {boolean} if true, properties that exist on the event
* will be overwritten.
*/
applyConfig: function(o, force) {
if (o) {
Y.mix(this, o, force, CONFIGS);
}
},
_on: function(fn, context, args, when) {
if (!fn) {
this.log("Invalid callback for CE: " + this.type);
}
var s = new Y.Subscriber(fn, context, args, when);
if (this.fireOnce && this.fired) {
if (this.async) {
setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0);
} else {
this._notify(s, this.firedWith);
}
}
if (when == AFTER) {
this.afters[s.id] = s;
this.afterCount++;
} else {
this.subscribers[s.id] = s;
this.subCount++;
}
return new Y.EventHandle(this, s);
},
/**
* Listen for this event
* @method subscribe
* @param {Function} fn The function to execute
* @return {EventHandle} Unsubscribe handle
* @deprecated use on
*/
subscribe: function(fn, context) {
Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated');
var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null;
return this._on(fn, context, a, true);
},
/**
* Listen for this event
* @method on
* @param {Function} fn The function to execute
* @param context {object} optional execution context.
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* when the event fires.
* @return {EventHandle} An object with a detach method to detch the handler(s)
*/
on: function(fn, context) {
var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null;
this.host._monitor('attach', this.type, {
args: arguments
});
return this._on(fn, context, a, true);
},
/**
* Listen for this event after the normal subscribers have been notified and
* the default behavior has been applied. If a normal subscriber prevents the
* default behavior, it also prevents after listeners from firing.
* @method after
* @param {Function} fn The function to execute
* @param context {object} optional execution context.
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* when the event fires.
* @return {EventHandle} handle Unsubscribe handle
*/
after: function(fn, context) {
var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null;
return this._on(fn, context, a, AFTER);
},
/**
* Detach listeners.
* @method detach
* @param {Function} fn The subscribed function to remove, if not supplied
* all will be removed
* @param {Object} context The context object passed to subscribe.
* @return {int} returns the number of subscribers unsubscribed
*/
detach: function(fn, context) {
// unsubscribe handle
if (fn && fn.detach) {
return fn.detach();
}
var found = 0, subs = this.subscribers, i, s;
for (i in subs) {
if (subs.hasOwnProperty(i)) {
s = subs[i];
if (s && (!fn || fn === s.fn)) {
this._delete(s);
found++;
}
}
}
return found;
},
/**
* Detach listeners.
* @method unsubscribe
* @param {Function} fn The subscribed function to remove, if not supplied
* all will be removed
* @param {Object} context The context object passed to subscribe.
* @return {int|undefined} returns the number of subscribers unsubscribed
* @deprecated use detach
*/
unsubscribe: function() {
return this.detach.apply(this, arguments);
},
/**
* Notify a single subscriber
* @method _notify
* @param s {Subscriber} the subscriber
* @param args {Array} the arguments array to apply to the listener
* @private
*/
_notify: function(s, args, ef) {
this.log(this.type + "->" + "sub: " + s.id);
var ret;
ret = s.notify(args, this);
if (false === ret || this.stopped > 1) {
this.log(this.type + " cancelled by subscriber");
return false;
}
return true;
},
/**
* Logger abstraction to centralize the application of the silent flag
* @method log
* @param msg {string} message to log
* @param cat {string} log category
*/
log: function(msg, cat) {
if (!this.silent) {
Y.log(this.id + ': ' + msg, cat || "info", "event");
}
},
/**
* Notifies the subscribers. The callback functions will be executed
* from the context specified when the event was created, and with the
* following parameters:
* <ul>
* <li>The type of event</li>
* <li>All of the arguments fire() was executed with as an array</li>
* <li>The custom object (if any) that was passed into the subscribe()
* method</li>
* </ul>
* @method fire
* @param {Object*} arguments an arbitrary set of parameters to pass to
* the handler.
* @return {boolean} false if one of the subscribers returned false,
* true otherwise
*
*/
fire: function() {
if (this.fireOnce && this.fired) {
this.log('fireOnce event: ' + this.type + ' already fired');
return true;
} else {
var args = Y.Array(arguments, 0, true);
// this doesn't happen if the event isn't published
// this.host._monitor('fire', this.type, args);
this.fired = true;
this.firedWith = args;
if (this.emitFacade) {
return this.fireComplex(args);
} else {
return this.fireSimple(args);
}
}
},
fireSimple: function(args) {
this.stopped = 0;
this.prevented = 0;
if (this.hasSubs()) {
// this._procSubs(Y.merge(this.subscribers, this.afters), args);
var subs = this.getSubs();
this._procSubs(subs[0], args);
this._procSubs(subs[1], args);
}
this._broadcast(args);
return this.stopped ? false : true;
},
// Requires the event-custom-complex module for full funcitonality.
fireComplex: function(args) {
Y.log('Missing event-custom-complex needed to emit a facade for: ' + this.type);
args[0] = args[0] || {};
return this.fireSimple(args);
},
_procSubs: function(subs, args, ef) {
var s, i;
for (i in subs) {
if (subs.hasOwnProperty(i)) {
s = subs[i];
if (s && s.fn) {
if (false === this._notify(s, args, ef)) {
this.stopped = 2;
}
if (this.stopped == 2) {
return false;
}
}
}
}
return true;
},
_broadcast: function(args) {
if (!this.stopped && this.broadcast) {
var a = Y.Array(args);
a.unshift(this.type);
if (this.host !== Y) {
Y.fire.apply(Y, a);
}
if (this.broadcast == 2) {
Y.Global.fire.apply(Y.Global, a);
}
}
},
/**
* Removes all listeners
* @method unsubscribeAll
* @return {int} The number of listeners unsubscribed
* @deprecated use detachAll
*/
unsubscribeAll: function() {
return this.detachAll.apply(this, arguments);
},
/**
* Removes all listeners
* @method detachAll
* @return {int} The number of listeners unsubscribed
*/
detachAll: function() {
return this.detach();
},
/**
* @method _delete
* @param subscriber object
* @private
*/
_delete: function(s) {
if (s) {
delete s.fn;
delete s.context;
delete this.subscribers[s.id];
delete this.afters[s.id];
}
this.host._monitor('detach', this.type, {
ce: this,
sub: s
});
}
};
/////////////////////////////////////////////////////////////////////
/**
* Stores the subscriber information to be used when the event fires.
* @param {Function} fn The wrapped function to execute
* @param {Object} context The value of the keyword 'this' in the listener
* @param {Array} args* 0..n additional arguments to supply the listener
*
* @class Subscriber
* @constructor
*/
Y.Subscriber = function(fn, context, args) {
/**
* The callback that will be execute when the event fires
* This is wrapped by Y.rbind if obj was supplied.
* @property fn
* @type Function
*/
this.fn = fn;
/**
* Optional 'this' keyword for the listener
* @property context
* @type Object
*/
this.context = context;
/**
* Unique subscriber id
* @property id
* @type String
*/
this.id = Y.stamp(this);
/**
* Additional arguments to propagate to the subscriber
* @property args
* @type Array
*/
this.args = args;
/**
* Custom events for a given fire transaction.
* @property events
* @type {EventTarget}
*/
// this.events = null;
/**
* This listener only reacts to the event once
* @property once
*/
// this.once = false;
};
Y.Subscriber.prototype = {
_notify: function(c, args, ce) {
var a = this.args, ret;
switch (ce.signature) {
case 0:
ret = this.fn.call(c, ce.type, args, c);
break;
case 1:
ret = this.fn.call(c, args[0] || null, c);
break;
default:
if (a || args) {
args = args || [];
a = (a) ? args.concat(a) : args;
ret = this.fn.apply(c, a);
} else {
ret = this.fn.call(c);
}
}
if (this.once) {
ce._delete(this);
}
return ret;
},
/**
* Executes the subscriber.
* @method notify
* @param args {Array} Arguments array for the subscriber
* @param ce {CustomEvent} The custom event that sent the notification
*/
notify: function(args, ce) {
var c = this.context,
ret = true;
if (!c) {
c = (ce.contextFn) ? ce.contextFn() : ce.context;
}
// only catch errors if we will not re-throw them.
if (Y.config.throwFail) {
ret = this._notify(c, args, ce);
} else {
try {
ret = this._notify(c, args, ce);
} catch(e) {
Y.error(this + ' failed: ' + e.message, e);
}
}
return ret;
},
/**
* Returns true if the fn and obj match this objects properties.
* Used by the unsubscribe method to match the right subscriber.
*
* @method contains
* @param {Function} fn the function to execute
* @param {Object} context optional 'this' keyword for the listener
* @return {boolean} true if the supplied arguments match this
* subscriber's signature.
*/
contains: function(fn, context) {
if (context) {
return ((this.fn == fn) && this.context == context);
} else {
return (this.fn == fn);
}
}
};
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
* @submodule event-custom-base
*/
(function() {
/**
* EventTarget provides the implementation for any object to
* publish, subscribe and fire to custom events, and also
* alows other EventTargets to target the object with events
* sourced from the other object.
* EventTarget is designed to be used with Y.augment to wrap
* EventCustom in an interface that allows events to be listened to
* and fired by name. This makes it possible for implementing code to
* subscribe to an event that either has not been created yet, or will
* not be created at all.
* @class EventTarget
* @param opts a configuration object
* @config emitFacade {boolean} if true, all events will emit event
* facade payloads by default (default false)
* @config prefix {string} the prefix to apply to non-prefixed event names
* @config chain {boolean} if true, on/after/detach return the host to allow
* chaining, otherwise they return an EventHandle (default false)
*/
var L = Y.Lang,
PREFIX_DELIMITER = ':',
CATEGORY_DELIMITER = '|',
AFTER_PREFIX = '~AFTER~',
_wildType = Y.cached(function(type) {
return type.replace(/(.*)(:)(.*)/, "*$2$3");
}),
/**
* If the instance has a prefix attribute and the
* event type is not prefixed, the instance prefix is
* applied to the supplied type.
* @method _getType
* @private
*/
_getType = Y.cached(function(type, pre) {
if (!pre || !L.isString(type) || type.indexOf(PREFIX_DELIMITER) > -1) {
return type;
}
return pre + PREFIX_DELIMITER + type;
}),
/**
* Returns an array with the detach key (if provided),
* and the prefixed event name from _getType
* Y.on('detachcategory| menu:click', fn)
* @method _parseType
* @private
*/
_parseType = Y.cached(function(type, pre) {
var t = type, detachcategory, after, i;
if (!L.isString(t)) {
return t;
}
i = t.indexOf(AFTER_PREFIX);
if (i > -1) {
after = true;
t = t.substr(AFTER_PREFIX.length);
// Y.log(t);
}
i = t.indexOf(CATEGORY_DELIMITER);
if (i > -1) {
detachcategory = t.substr(0, (i));
t = t.substr(i+1);
if (t == '*') {
t = null;
}
}
// detach category, full type with instance prefix, is this an after listener, short type
return [detachcategory, (pre) ? _getType(t, pre) : t, after, t];
}),
ET = function(opts) {
// Y.log('EventTarget constructor executed: ' + this._yuid);
var o = (L.isObject(opts)) ? opts : {};
this._yuievt = this._yuievt || {
id: Y.guid(),
events: {},
targets: {},
config: o,
chain: ('chain' in o) ? o.chain : Y.config.chain,
bubbling: false,
defaults: {
context: o.context || this,
host: this,
emitFacade: o.emitFacade,
fireOnce: o.fireOnce,
queuable: o.queuable,
monitored: o.monitored,
broadcast: o.broadcast,
defaultTargetOnly: o.defaulTargetOnly,
bubbles: ('bubbles' in o) ? o.bubbles : true
}
};
};
ET.prototype = {
/**
* Listen to a custom event hosted by this object one time.
* This is the equivalent to <code>on</code> except the
* listener is immediatelly detached when it is executed.
* @method once
* @param type {string} The type of the event
* @param fn {Function} The callback
* @param context {object} optional execution context.
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* @return the event target or a detach handle per 'chain' config
*/
once: function() {
var handle = this.on.apply(this, arguments);
handle.sub.once = true;
return handle;
},
/**
* Subscribe to a custom event hosted by this object
* @method on
* @param type {string} The type of the event
* @param fn {Function} The callback
* @param context {object} optional execution context.
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* @return the event target or a detach handle per 'chain' config
*/
on: function(type, fn, context) {
var parts = _parseType(type, this._yuievt.config.prefix), f, c, args, ret, ce,
detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype,
Node = Y.Node, n, domevent, isArr;
// full name, args, detachcategory, after
this._monitor('attach', parts[1], {
args: arguments,
category: parts[0],
after: parts[2]
});
if (L.isObject(type)) {
if (L.isFunction(type)) {
return Y.Do.before.apply(Y.Do, arguments);
}
f = fn;
c = context;
args = Y.Array(arguments, 0, true);
ret = {};
if (L.isArray(type)) {
isArr = true;
} else {
after = type._after;
delete type._after;
}
Y.each(type, function(v, k) {
if (L.isObject(v)) {
f = v.fn || ((L.isFunction(v)) ? v : f);
c = v.context || c;
}
args[0] = (isArr) ? v : ((after) ? AFTER_PREFIX + k : k);
args[1] = f;
args[2] = c;
ret[k] = this.on.apply(this, args);
}, this);
return (this._yuievt.chain) ? this : new Y.EventHandle(ret);
}
detachcategory = parts[0];
after = parts[2];
shorttype = parts[3];
// extra redirection so we catch adaptor events too. take a look at this.
if (Node && (this instanceof Node) && (shorttype in Node.DOM_EVENTS)) {
args = Y.Array(arguments, 0, true);
args.splice(2, 0, Node.getDOMNode(this));
// Y.log("Node detected, redirecting with these args: " + args);
return Y.on.apply(Y, args);
}
type = parts[1];
if (this instanceof YUI) {
adapt = Y.Env.evt.plugins[type];
args = Y.Array(arguments, 0, true);
args[0] = shorttype;
if (Node) {
n = args[2];
if (n instanceof Y.NodeList) {
n = Y.NodeList.getDOMNodes(n);
} else if (n instanceof Node) {
n = Node.getDOMNode(n);
}
domevent = (shorttype in Node.DOM_EVENTS);
// Captures both DOM events and event plugins.
if (domevent) {
args[2] = n;
}
}
// check for the existance of an event adaptor
if (adapt) {
Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event');
handle = adapt.on.apply(Y, args);
} else if ((!type) || domevent) {
handle = Y.Event._attach(args);
}
}
if (!handle) {
ce = this._yuievt.events[type] || this.publish(type);
handle = ce._on(fn, context, (arguments.length > 3) ? Y.Array(arguments, 3, true) : null, (after) ? 'after' : true);
}
if (detachcategory) {
store[detachcategory] = store[detachcategory] || {};
store[detachcategory][type] = store[detachcategory][type] || [];
store[detachcategory][type].push(handle);
}
return (this._yuievt.chain) ? this : handle;
},
/**
* subscribe to an event
* @method subscribe
* @deprecated use on
*/
subscribe: function() {
Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated');
return this.on.apply(this, arguments);
},
/**
* Detach one or more listeners the from the specified event
* @method detach
* @param type {string|Object} Either the handle to the subscriber or the
* type of event. If the type
* is not specified, it will attempt to remove
* the listener from all hosted events.
* @param fn {Function} The subscribed function to unsubscribe, if not
* supplied, all subscribers will be removed.
* @param context {Object} The custom object passed to subscribe. This is
* optional, but if supplied will be used to
* disambiguate multiple listeners that are the same
* (e.g., you subscribe many object using a function
* that lives on the prototype)
* @return {EventTarget} the host
*/
detach: function(type, fn, context) {
var evts = this._yuievt.events, i,
Node = Y.Node, isNode = Node && (this instanceof Node);
// detachAll disabled on the Y instance.
if (!type && (this !== Y)) {
for (i in evts) {
if (evts.hasOwnProperty(i)) {
evts[i].detach(fn, context);
}
}
if (isNode) {
Y.Event.purgeElement(Node.getDOMNode(this));
}
return this;
}
var parts = _parseType(type, this._yuievt.config.prefix),
detachcategory = L.isArray(parts) ? parts[0] : null,
shorttype = (parts) ? parts[3] : null,
handle, adapt, store = Y.Env.evt.handles, cat, args,
ce,
keyDetacher = function(lcat, ltype) {
var handles = lcat[ltype];
if (handles) {
while (handles.length) {
handle = handles.pop();
handle.detach();
}
}
};
if (detachcategory) {
cat = store[detachcategory];
type = parts[1];
if (cat) {
if (type) {
keyDetacher(cat, type);
} else {
for (i in cat) {
if (cat.hasOwnProperty(i)) {
keyDetacher(cat, i);
}
}
}
return this;
}
// If this is an event handle, use it to detach
} else if (L.isObject(type) && type.detach) {
type.detach();
return this;
// extra redirection so we catch adaptor events too. take a look at this.
} else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) {
args = Y.Array(arguments, 0, true);
args[2] = Node.getDOMNode(this);
Y.detach.apply(Y, args);
return this;
}
adapt = Y.Env.evt.plugins[shorttype];
// The YUI instance handles DOM events and adaptors
if (this instanceof YUI) {
args = Y.Array(arguments, 0, true);
// use the adaptor specific detach code if
if (adapt && adapt.detach) {
adapt.detach.apply(Y, args);
return this;
// DOM event fork
} else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) {
args[0] = type;
Y.Event.detach.apply(Y.Event, args);
return this;
}
}
// ce = evts[type];
ce = evts[parts[1]];
if (ce) {
ce.detach(fn, context);
}
return this;
},
/**
* detach a listener
* @method unsubscribe
* @deprecated use detach
*/
unsubscribe: function() {
Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated');
return this.detach.apply(this, arguments);
},
/**
* Removes all listeners from the specified event. If the event type
* is not specified, all listeners from all hosted custom events will
* be removed.
* @method detachAll
* @param type {string} The type, or name of the event
*/
detachAll: function(type) {
return this.detach(type);
},
/**
* Removes all listeners from the specified event. If the event type
* is not specified, all listeners from all hosted custom events will
* be removed.
* @method unsubscribeAll
* @param type {string} The type, or name of the event
* @deprecated use detachAll
*/
unsubscribeAll: function() {
Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated');
return this.detachAll.apply(this, arguments);
},
/**
* Creates a new custom event of the specified type. If a custom event
* by that name already exists, it will not be re-created. In either
* case the custom event is returned.
*
* @method publish
*
* @param type {string} the type, or name of the event
* @param opts {object} optional config params. Valid properties are:
*
* <ul>
* <li>
* 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false)
* </li>
* <li>
* 'bubbles': whether or not this event bubbles (true)
* Events can only bubble if emitFacade is true.
* </li>
* <li>
* 'context': the default execution context for the listeners (this)
* </li>
* <li>
* 'defaultFn': the default function to execute when this event fires if preventDefault was not called
* </li>
* <li>
* 'emitFacade': whether or not this event emits a facade (false)
* </li>
* <li>
* 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click'
* </li>
* <li>
* 'fireOnce': if an event is configured to fire once, new subscribers after
* the fire will be notified immediately.
* </li>
* <li>
* 'preventable': whether or not preventDefault() has an effect (true)
* </li>
* <li>
* 'preventedFn': a function that is executed when preventDefault is called
* </li>
* <li>
* 'queuable': whether or not this event can be queued during bubbling (false)
* </li>
* <li>
* 'silent': if silent is true, debug messages are not provided for this event.
* </li>
* <li>
* 'stoppedFn': a function that is executed when stopPropagation is called
* </li>
*
* <li>
* 'monitored': specifies whether or not this event should send notifications about
* when the event has been attached, detached, or published.
* </li>
* <li>
* 'type': the event type (valid option if not provided as the first parameter to publish)
* </li>
* </ul>
*
* @return {CustomEvent} the custom event
*
*/
publish: function(type, opts) {
var events, ce, ret, pre = this._yuievt.config.prefix;
type = (pre) ? _getType(type, pre) : type;
this._monitor('publish', type, {
args: arguments
});
if (L.isObject(type)) {
ret = {};
Y.each(type, function(v, k) {
ret[k] = this.publish(k, v || opts);
}, this);
return ret;
}
events = this._yuievt.events;
ce = events[type];
if (ce) {
// ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event');
if (opts) {
ce.applyConfig(opts, true);
}
} else {
// apply defaults
ce = new Y.CustomEvent(type, (opts) ? Y.mix(opts, this._yuievt.defaults) : this._yuievt.defaults);
events[type] = ce;
}
// make sure we turn the broadcast flag off if this
// event was published as a result of bubbling
// if (opts instanceof Y.CustomEvent) {
// events[type].broadcast = false;
// }
return events[type];
},
/**
* This is the entry point for the event monitoring system.
* You can monitor 'attach', 'detach', 'fire', and 'publish'.
* When configured, these events generate an event. click ->
* click_attach, click_detach, click_publish -- these can
* be subscribed to like other events to monitor the event
* system. Inividual published events can have monitoring
* turned on or off (publish can't be turned off before it
* it published) by setting the events 'monitor' config.
*
* @private
*/
_monitor: function(what, type, o) {
var monitorevt, ce = this.getEvent(type);
if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) {
monitorevt = type + '_' + what;
// Y.log('monitoring: ' + monitorevt);
o.monitored = what;
this.fire.call(this, monitorevt, o);
}
},
/**
* Fire a custom event by name. The callback functions will be executed
* from the context specified when the event was created, and with the
* following parameters.
*
* If the custom event object hasn't been created, then the event hasn't
* been published and it has no subscribers. For performance sake, we
* immediate exit in this case. This means the event won't bubble, so
* if the intention is that a bubble target be notified, the event must
* be published on this object first.
*
* The first argument is the event type, and any additional arguments are
* passed to the listeners as parameters. If the first of these is an
* object literal, and the event is configured to emit an event facade,
* that object is mixed into the event facade and the facade is provided
* in place of the original object.
*
* @method fire
* @param type {String|Object} The type of the event, or an object that contains
* a 'type' property.
* @param arguments {Object*} an arbitrary set of parameters to pass to
* the handler. If the first of these is an object literal and the event is
* configured to emit an event facade, the event facade will replace that
* parameter after the properties the object literal contains are copied to
* the event facade.
* @return {EventTarget} the event host
*
*/
fire: function(type) {
var typeIncluded = L.isString(type),
t = (typeIncluded) ? type : (type && type.type),
ce, ret, pre = this._yuievt.config.prefix, ce2,
args = (typeIncluded) ? Y.Array(arguments, 1, true) : arguments;
t = (pre) ? _getType(t, pre) : t;
this._monitor('fire', t, {
args: args
});
ce = this.getEvent(t, true);
ce2 = this.getSibling(t, ce);
if (ce2 && !ce) {
ce = this.publish(t);
}
// this event has not been published or subscribed to
if (!ce) {
if (this._yuievt.hasTargets) {
return this.bubble({ type: t }, args, this);
}
// otherwise there is nothing to be done
ret = true;
} else {
ce.sibling = ce2;
ret = ce.fire.apply(ce, args);
}
return (this._yuievt.chain) ? this : ret;
},
getSibling: function(type, ce) {
var ce2;
// delegate to *:type events if there are subscribers
if (type.indexOf(PREFIX_DELIMITER) > -1) {
type = _wildType(type);
// console.log(type);
ce2 = this.getEvent(type, true);
if (ce2) {
// console.log("GOT ONE: " + type);
ce2.applyConfig(ce);
ce2.bubbles = false;
ce2.broadcast = 0;
// ret = ce2.fire.apply(ce2, a);
}
}
return ce2;
},
/**
* Returns the custom event of the provided type has been created, a
* falsy value otherwise
* @method getEvent
* @param type {string} the type, or name of the event
* @param prefixed {string} if true, the type is prefixed already
* @return {CustomEvent} the custom event or null
*/
getEvent: function(type, prefixed) {
var pre, e;
if (!prefixed) {
pre = this._yuievt.config.prefix;
type = (pre) ? _getType(type, pre) : type;
}
e = this._yuievt.events;
return e[type] || null;
},
/**
* Subscribe to a custom event hosted by this object. The
* supplied callback will execute after any listeners add
* via the subscribe method, and after the default function,
* if configured for the event, has executed.
* @method after
* @param type {string} The type of the event
* @param fn {Function} The callback
* @param context {object} optional execution context.
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* @return the event target or a detach handle per 'chain' config
*/
after: function(type, fn) {
var a = Y.Array(arguments, 0, true);
switch (L.type(type)) {
case 'function':
return Y.Do.after.apply(Y.Do, arguments);
case 'object':
a[0]._after = true;
break;
default:
a[0] = AFTER_PREFIX + type;
}
return this.on.apply(this, a);
},
/**
* Executes the callback before a DOM event, custom event
* or method. If the first argument is a function, it
* is assumed the target is a method. For DOM and custom
* events, this is an alias for Y.on.
*
* For DOM and custom events:
* type, callback, context, 0-n arguments
*
* For methods:
* callback, object (method host), methodName, context, 0-n arguments
*
* @method before
* @return detach handle
*/
before: function() {
return this.on.apply(this, arguments);
}
};
Y.EventTarget = ET;
// make Y an event target
Y.mix(Y, ET.prototype, false, false, {
bubbles: false
});
ET.call(Y);
YUI.Env.globalEvents = YUI.Env.globalEvents || new ET();
/**
* Hosts YUI page level events. This is where events bubble to
* when the broadcast config is set to 2. This property is
* only available if the custom event module is loaded.
* @property Global
* @type EventTarget
* @for YUI
*/
Y.Global = YUI.Env.globalEvents;
// @TODO implement a global namespace function on Y.Global?
})();
/**
* <code>YUI</code>'s <code>on</code> method is a unified interface for subscribing to
* most events exposed by YUI. This includes custom events, DOM events, and
* function events. <code>detach</code> is also provided to remove listeners
* serviced by this function.
*
* The signature that <code>on</code> accepts varies depending on the type
* of event being consumed. Refer to the specific methods that will
* service a specific request for additional information about subscribing
* to that type of event.
*
* <ul>
* <li>Custom events. These events are defined by various
* modules in the library. This type of event is delegated to
* <code>EventTarget</code>'s <code>on</code> method.
* <ul>
* <li>The type of the event</li>
* <li>The callback to execute</li>
* <li>An optional context object</li>
* <li>0..n additional arguments to supply the callback.</li>
* </ul>
* Example:
* <code>Y.on('domready', function() { // start work });</code>
* </li>
* <li>DOM events. These are moments reported by the browser related
* to browser functionality and user interaction.
* This type of event is delegated to <code>Event</code>'s
* <code>attach</code> method.
* <ul>
* <li>The type of the event</li>
* <li>The callback to execute</li>
* <li>The specification for the Node(s) to attach the listener
* to. This can be a selector, collections, or Node/Element
* refereces.</li>
* <li>An optional context object</li>
* <li>0..n additional arguments to supply the callback.</li>
* </ul>
* Example:
* <code>Y.on('click', function(e) { // something was clicked }, '#someelement');</code>
* </li>
* <li>Function events. These events can be used to react before or after a
* function is executed. This type of event is delegated to <code>Event.Do</code>'s
* <code>before</code> method.
* <ul>
* <li>The callback to execute</li>
* <li>The object that has the function that will be listened for.</li>
* <li>The name of the function to listen for.</li>
* <li>An optional context object</li>
* <li>0..n additional arguments to supply the callback.</li>
* </ul>
* Example <code>Y.on(function(arg1, arg2, etc) { // obj.methodname was executed }, obj 'methodname');</code>
* </li>
* </ul>
*
* <code>on</code> corresponds to the moment before any default behavior of
* the event. <code>after</code> works the same way, but these listeners
* execute after the event's default behavior. <code>before</code> is an
* alias for <code>on</code>.
*
* @method on
* @param type** event type (this parameter does not apply for function events)
* @param fn the callback
* @param target** a descriptor for the target (applies to custom events only).
* For function events, this is the object that contains the function to
* execute.
* @param extra** 0..n Extra information a particular event may need. These
* will be documented with the event. In the case of function events, this
* is the name of the function to execute on the host. In the case of
* delegate listeners, this is the event delegation specification.
* @param context optionally change the value of 'this' in the callback
* @param args* 0..n additional arguments to pass to the callback.
* @return the event target or a detach handle per 'chain' config
* @for YUI
*/
/**
* Listen for an event one time. Equivalent to <code>on</code>, except that
* the listener is immediately detached when executed.
* @see on
* @method once
* @param type** event type (this parameter does not apply for function events)
* @param fn the callback
* @param target** a descriptor for the target (applies to custom events only).
* For function events, this is the object that contains the function to
* execute.
* @param extra** 0..n Extra information a particular event may need. These
* will be documented with the event. In the case of function events, this
* is the name of the function to execute on the host. In the case of
* delegate listeners, this is the event delegation specification.
* @param context optionally change the value of 'this' in the callback
* @param args* 0..n additional arguments to pass to the callback.
* @return the event target or a detach handle per 'chain' config
* @for YUI
*/
/**
* after() is a unified interface for subscribing to
* most events exposed by YUI. This includes custom events,
* DOM events, and AOP events. This works the same way as
* the on() function, only it operates after any default
* behavior for the event has executed. @see <code>on</code> for more
* information.
* @method after
* @param type event type (this parameter does not apply for function events)
* @param fn the callback
* @param target a descriptor for the target (applies to custom events only).
* For function events, this is the object that contains the function to
* execute.
* @param extra 0..n Extra information a particular event may need. These
* will be documented with the event. In the case of function events, this
* is the name of the function to execute on the host. In the case of
* delegate listeners, this is the event delegation specification.
* @param context optionally change the value of 'this' in the callback
* @param args* 0..n additional arguments to pass to the callback.
* @return the event target or a detach handle per 'chain' config
* @for YUI
*/
}, '@VERSION@' ,{requires:['oop']});
|
features/apimgt/org.wso2.carbon.apimgt.store.feature/src/main/resources/store/source/src/app/components/Base/index.js | thusithak/carbon-apimgt | /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import Header from './Header/Header'
import Footer from './Footer/Footer'
import Grid from 'material-ui/Grid';
class Layout extends React.Component {
constructor(props){
super(props);
}
render(props){
return (
<div>
<Header />
<Grid container spacing={0} >
<Grid item xs={12} >
{this.props.children}
</Grid>
</Grid>
<Footer />
</div>
);
}
}
export default Layout; |
src/mui/detail/Edit.spec.js | epwqice/admin-on-rest-old-man | import React from 'react';
import assert from 'assert';
import { shallow } from 'enzyme';
import { Edit } from './Edit';
import TextInput from '../input/TextInput';
import SimpleForm from '../form/SimpleForm';
describe('<Edit />', () => {
const defaultProps = {
data: {},
crudGetOne: () => {},
crudUpdate: () => {},
hasDelete: false,
id: 'foo',
isLoading: false,
location: { pathname: '' },
params: {},
resource: '',
translate: x => x,
};
it('should display correctly when called with a child', () => {
const Foo = () => <div/>;
const wrapper = shallow(<Edit {...defaultProps}><Foo/></Edit>);
const inner = wrapper.find('Foo');
assert.equal(inner.length, 1);
});
it('should display children inputs of SimpleForm', () => {
const wrapper = shallow(<Edit {...defaultProps}>
<SimpleForm>
<TextInput source="foo" />
<TextInput source="bar" />
</SimpleForm>
</Edit>);
const inputs = wrapper.find('TextInput');
assert.deepEqual(inputs.map(i => i.prop('source')), ['foo', 'bar']);
});
});
|
src/app/pages/blog/Post.js | ROZ32/react-example | import React, { Component } from 'react';
import postImage from '../../images/post-sample-image.jpg';
class Post extends Component {
constructor(props) {
super(props);
}
render() {
return (
<article>
<div className="container">
<div className="row">
<div className="col-lg-8 col-md-10 mx-auto">
<p>Never in all their history have men been able truly to conceive of the world as one: a single sphere, a globe, having the qualities of a globe, a round earth in which all the directions eventually meet, in which there is no center because every point, or none, is center — an equal earth which all men occupy as equals. The airmans earth, if free men make it, will be truly round: a globe in practice, not in theory.</p>
<p>Science cuts two ways, of course, its products can be used for both good and evil. But there is no turning back from science. The early warnings about technological dangers also come from science.</p>
<p>What was most significant about the lunar voyage was not that man set foot on the Moon but that they set eye on the earth.</p>
<p>A Chinese tale tells of some men sent to harm a young girl who, upon seeing her beauty, become her protectors rather than her violators. That is how I felt seeing the Earth for the first time. I could not help but love and cherish her.</p>
<p>For those who have seen the Earth from space, and for the hundreds and perhaps thousands more who will, the experience most certainly changes your perspective. The things that we share in our world are far more valuable than those which divide us.</p>
<h2 className="section-heading">The Final Frontier</h2>
<p>There can be no thought of finishing for ‘aiming for the stars.’ Both figuratively and literally, it is a task to occupy the generations. And no matter how much progress one makes, there is always the thrill of just beginning.</p>
<blockquote className="blockquote">The dreams of yesterday are the hopes of today and the reality of tomorrow. Science has not yet mastered prophecy. We predict too much for the next year and yet far too little for the next ten.</blockquote>
<p>Spaceflights cannot be stopped. This is not the work of any one man or even a group of men. It is a historical process which mankind is carrying out in accordance with the natural laws of human development.</p>
<h2 className="section-heading">Reaching for the Stars</h2>
<p>As we got further and further away, it [the Earth] diminished in size. Finally it shrank to the size of a marble, the most beautiful you can imagine. That beautiful, warm, living object looked so fragile, so delicate, that if you touched it with a finger it would crumble and fall apart. Seeing this has to change a man.</p>
<a href="#">
<img className="img-fluid" src={postImage} alt=""/>
</a>
<span className="caption text-muted">To go places and do things that have never been done before – that’s what living is all about.</span>
<p>Space, the final frontier. These are the voyages of the Starship Enterprise. Its five-year mission: to explore strange new worlds, to seek out new life and new civilizations, to boldly go where no man has gone before.</p>
<p>As I stand out here in the wonders of the unknown at Hadley, I sort of realize there’s a fundamental truth to our nature, Man must explore, and this is exploration at its greatest.</p>
<p>Placeholder text by
<a href="http://spaceipsum.com/">Space Ipsum</a>. Photographs by
<a href="https://www.flickr.com/photos/nasacommons/">NASA on The Commons</a>.
</p>
</div>
</div>
</div>
</article>
);
}
}
export default Post;
|
ajax/libs/graphiql/0.3.1/graphiql.js | x112358/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.GraphiQL = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE-examples file in the root directory of this source tree.
*/
'use strict';
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _codemirror = require('codemirror');
var _codemirror2 = _interopRequireDefault(_codemirror);
var _jsonLint = require('./jsonLint');
_codemirror2['default'].registerHelper('lint', 'json', function (text) {
var err = _jsonLint.jsonLint(text);
if (err) {
return [{
message: err.message,
severity: 'error',
from: getLocation(text, err.start),
to: getLocation(text, err.end)
}];
}
return [];
});
function getLocation(source, position) {
var line = 0;
var column = position;
var lineRegexp = /\r\n|[\n\r]/g;
var match;
while ((match = lineRegexp.exec(source)) && match.index < position) {
line += 1;
column = position - (match.index + match[0].length);
}
return _codemirror2['default'].Pos(line, column);
}
},{"./jsonLint":2,"codemirror":25}],2:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE-examples file in the root directory of this source tree.
*/
/**
* This JSON parser simply walks the input, but does not generate an AST
* or Value. Instead it returns either an syntax error object, or null.
*
* The returned syntax error object:
*
* - message: string
* - start: int - the start inclusive offset of the syntax error
* - end: int - the end exclusive offset of the syntax error
*
*/
'use strict';
exports.__esModule = true;
exports.jsonLint = jsonLint;
function jsonLint(str, looseMode) {
string = str;
strLen = str.length;
end = -1;
try {
ch();
lex();
if (looseMode) {
readVal();
} else {
readObj();
}
expect('EOF');
} catch (err) {
return err;
}
}
var string;
var strLen;
var start;
var end;
var code;
var kind;
function readObj() {
expect('{');
if (!skip('}')) {
do {
expect('String');
expect(':');
readVal();
} while (skip(','));
expect('}');
}
}
function readArr() {
expect('[');
if (!skip(']')) {
do {
readVal();
} while (skip(','));
expect(']');
}
}
function readVal() {
switch (kind) {
case '[':
return readArr();
case '{':
return readObj();
case 'String':
return lex();
default:
return expect('Value');
}
}
function syntaxError(message) {
return { message: message, start: start, end: end };
}
function expect(str) {
if (kind === str) {
return lex();
}
throw syntaxError('Expected ' + str + ' but got ' + string.slice(start, end) + '.');
}
function skip(k) {
if (kind === k) {
lex();
return true;
}
}
function ch() {
if (end < strLen) {
end++;
code = end === strLen ? 0 : string.charCodeAt(end);
}
}
function lex() {
while (code === 9 || code === 10 || code === 13 || code === 32) {
ch();
}
if (code === 0) {
kind = 'EOF';
return;
}
start = end;
switch (code) {
// "
case 34:
kind = 'String';
return readString();
// -
case 45:
// 0-9
case 48:case 49:case 50:case 51:case 52:
case 53:case 54:case 55:case 56:case 57:
kind = 'Value';
return readNumber();
// f
case 102:
if (string.slice(start, start + 5) !== 'false') {
break;
}
end += 4;ch();
kind = 'Value';
return;
// n
case 110:
if (string.slice(start, start + 4) !== 'null') {
break;
}
end += 3;ch();
kind = 'Value';
return;
// t
case 116:
if (string.slice(start, start + 4) !== 'true') {
break;
}
end += 3;ch();
kind = 'Value';
return;
}
kind = string[start];
ch();
}
function readString() {
ch();
while (code !== 34) {
ch();
if (code === 92) {
// \
ch();
switch (code) {
case 34: // '
case 47: // /
case 92: // \
case 98: // b
case 102: // f
case 110: // n
case 114: // r
case 116:
// t
ch();
break;
case 117:
// u
ch();
readHex();
readHex();
readHex();
readHex();
break;
default:
throw syntaxError('Bad character escape sequence.');
}
} else if (end === strLen) {
throw syntaxError('Unterminated string.');
}
}
if (code === 34) {
ch();
return;
}
throw syntaxError('Unterminated string.');
}
function readHex() {
if (code >= 48 && code <= 57 || // 0-9
code >= 65 && code <= 70 || // A-F
code >= 97 && code <= 102 // a-f
) {
return ch();
}
throw syntaxError('Expected hexadecimal digit.');
}
function readNumber() {
if (code === 45) {
// -
ch();
}
if (code === 48) {
// 0
ch();
} else {
readDigits();
}
if (code === 46) {
// .
ch();
readDigits();
}
if (code === 69 || code === 101) {
// E e
ch();
if (code === 43 || code === 45) {
// + -
ch();
}
readDigits();
}
}
function readDigits() {
if (code < 48 || code > 57) {
// 0 - 9
throw syntaxError('Expected decimal digit.');
}
do {
ch();
} while (code >= 48 && code <= 57); // 0 - 9
}
},{}],3:[function(require,module,exports){
(function (global){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE-examples file in the root directory of this source tree.
*/
'use strict';
exports.__esModule = 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; }; })();
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 _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 _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _marked = require('marked');
var _marked2 = _interopRequireDefault(_marked);
var _graphqlType = require('graphql/type');
/**
* DocExplorer
*
* Shows documentations for GraphQL definitions from the schema.
*
* Props:
*
* - schema: A required GraphQLSchema instance that provides GraphQL document
* definitions.
*
* Children:
*
* - Any provided children will be positioned in the right-hand-side of the
* top bar. Typically this will be a "close" button for temporary explorer.
*
*/
var DocExplorer = (function (_React$Component) {
_inherits(DocExplorer, _React$Component);
// Public API
DocExplorer.prototype.showDoc = function showDoc(typeOrField) {
var navStack = this.state.navStack;
var isCurrentlyShown = navStack.length > 0 && navStack[navStack.length - 1] === typeOrField;
if (!isCurrentlyShown) {
navStack = navStack.concat([typeOrField]);
}
this.setState({ navStack: navStack });
};
_createClass(DocExplorer, null, [{
key: 'propTypes',
value: {
schema: _react.PropTypes.instanceOf(_graphqlType.GraphQLSchema)
},
enumerable: true
}]);
function DocExplorer() {
var _this = this;
_classCallCheck(this, DocExplorer);
_React$Component.call(this);
this._onToggleBtnClick = function () {
_this.setState({ expanded: !_this.state.expanded });
};
this._onNavBackClick = function () {
_this.setState({ navStack: _this.state.navStack.slice(0, -1) });
};
this._onClickTypeOrField = function (typeOrField) {
_this.showDoc(typeOrField);
};
this.state = { navStack: [] };
}
// Render the top level Schema
DocExplorer.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) {
return this.props.schema !== nextProps.schema || this.state.navStack !== nextState.navStack;
};
DocExplorer.prototype.render = function render() {
var schema = this.props.schema;
var navStack = this.state.navStack;
var typeOrField;
if (navStack.length > 0) {
typeOrField = navStack[navStack.length - 1];
}
var title;
var content;
if (typeOrField) {
title = typeOrField.name;
content = _graphqlType.isType(typeOrField) ? _react2['default'].createElement(TypeDoc, {
key: typeOrField.name,
type: typeOrField,
onClickType: this._onClickTypeOrField,
onClickField: this._onClickTypeOrField
}) : _react2['default'].createElement(FieldDoc, {
key: typeOrField.name,
field: typeOrField,
onClickType: this._onClickTypeOrField
});
} else if (schema) {
title = 'Documentation Explorer';
content = _react2['default'].createElement(SchemaDoc, {
schema: schema,
onClickType: this._onClickTypeOrField
});
}
var prevName;
if (navStack.length === 1) {
prevName = 'Schema';
} else if (navStack.length > 1) {
prevName = navStack[navStack.length - 2].name;
}
return _react2['default'].createElement(
'div',
{ className: 'doc-explorer' },
_react2['default'].createElement(
'div',
{ className: 'doc-explorer-title-bar' },
prevName && _react2['default'].createElement(
'div',
{ className: 'doc-explorer-back', onClick: this._onNavBackClick },
prevName
),
_react2['default'].createElement(
'div',
{ className: 'doc-explorer-title' },
title
),
_react2['default'].createElement(
'div',
{ className: 'doc-explorer-rhs' },
this.props.children
)
),
_react2['default'].createElement(
'div',
{ className: 'doc-explorer-contents' },
content
)
);
};
return DocExplorer;
})(_react2['default'].Component);
exports.DocExplorer = DocExplorer;
var SchemaDoc = (function (_React$Component2) {
_inherits(SchemaDoc, _React$Component2);
function SchemaDoc() {
_classCallCheck(this, SchemaDoc);
_React$Component2.apply(this, arguments);
}
// Documentation for a Type
SchemaDoc.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
return this.props.schema !== nextProps.schema;
};
SchemaDoc.prototype.render = function render() {
var schema = this.props.schema;
var queryType = schema.getQueryType();
var mutationType = schema.getMutationType();
return _react2['default'].createElement(
'div',
null,
_react2['default'].createElement(Description, {
className: 'doc-type-description',
markdown: 'A GraphQL schema provides a root type for each kind of operation.'
}),
_react2['default'].createElement(
'div',
{ className: 'doc-category' },
_react2['default'].createElement(
'div',
{ className: 'doc-category-title' },
'root types'
),
_react2['default'].createElement(
'div',
{ className: 'doc-category-item' },
_react2['default'].createElement(
'span',
{ className: 'keyword' },
'query'
),
': ',
_react2['default'].createElement(TypeLink, { type: queryType, onClick: this.props.onClickType })
),
mutationType && _react2['default'].createElement(
'div',
{ className: 'doc-category-item' },
_react2['default'].createElement(
'span',
{ className: 'keyword' },
'mutation'
),
': ',
_react2['default'].createElement(TypeLink, { type: mutationType, onClick: this.props.onClickType })
)
)
);
};
return SchemaDoc;
})(_react2['default'].Component);
var TypeDoc = (function (_React$Component3) {
_inherits(TypeDoc, _React$Component3);
function TypeDoc() {
_classCallCheck(this, TypeDoc);
_React$Component3.apply(this, arguments);
}
// Documentation for a field
TypeDoc.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
return this.props.type !== nextProps.type;
};
TypeDoc.prototype.render = function render() {
var type = this.props.type;
var onClickType = this.props.onClickType || function () {};
var onClickField = this.props.onClickField || function () {};
var typesTitle;
var types;
if (type instanceof _graphqlType.GraphQLUnionType) {
typesTitle = 'possible types';
types = type.getPossibleTypes();
} else if (type instanceof _graphqlType.GraphQLInterfaceType) {
typesTitle = 'implementations';
types = type.getPossibleTypes();
} else if (type instanceof _graphqlType.GraphQLObjectType) {
typesTitle = 'implements';
types = type.getInterfaces();
}
var typesDef;
if (types && types.length > 0) {
typesDef = _react2['default'].createElement(
'div',
{ className: 'doc-category' },
_react2['default'].createElement(
'div',
{ className: 'doc-category-title' },
typesTitle
),
types.map(function (subtype) {
return _react2['default'].createElement(
'div',
{ key: subtype.name, className: 'doc-category-item' },
_react2['default'].createElement(TypeLink, { type: subtype, onClick: onClickType })
);
})
);
}
// InputObject and Object
var fieldsDef;
if (type.getFields) {
var fieldMap = type.getFields();
var fields = Object.keys(fieldMap).map(function (name) {
return fieldMap[name];
});
fieldsDef = _react2['default'].createElement(
'div',
{ className: 'doc-category' },
_react2['default'].createElement(
'div',
{ className: 'doc-category-title' },
'fields'
),
fields.map(function (field) {
// Field arguments
var argsDef;
if (field.args && field.args.length > 0) {
argsDef = field.args.map(function (arg) {
return _react2['default'].createElement(
'span',
{ className: 'arg', key: arg.name },
_react2['default'].createElement(
'span',
{ className: 'arg-name' },
arg.name
),
': ',
_react2['default'].createElement(TypeLink, { type: arg.type, onClick: onClickType })
);
});
}
return _react2['default'].createElement(
'div',
{ key: field.name, className: 'doc-category-item' },
_react2['default'].createElement(
'a',
{
className: 'field-name',
onClick: function (event) {
return onClickField(field, type, event);
} },
field.name
),
argsDef && ['(', _react2['default'].createElement(
'span',
null,
argsDef
), ')'],
': ',
_react2['default'].createElement(TypeLink, { type: field.type, onClick: onClickType })
);
})
);
}
var valuesDef;
if (type instanceof _graphqlType.GraphQLEnumType) {
valuesDef = _react2['default'].createElement(
'div',
{ className: 'doc-category' },
_react2['default'].createElement(
'div',
{ className: 'doc-category-title' },
'values'
),
type.getValues().map(function (value) {
return _react2['default'].createElement(
'div',
{ key: value.name, className: 'doc-category-item' },
_react2['default'].createElement(
'div',
{ className: 'enum-value' },
value.name
),
_react2['default'].createElement(Description, {
className: 'doc-value-description',
markdown: type.description
})
);
})
);
}
return _react2['default'].createElement(
'div',
null,
_react2['default'].createElement(Description, {
className: 'doc-type-description',
markdown: type.description || 'No Description'
}),
type instanceof _graphqlType.GraphQLObjectType && typesDef,
fieldsDef,
valuesDef,
!(type instanceof _graphqlType.GraphQLObjectType) && typesDef
);
};
return TypeDoc;
})(_react2['default'].Component);
var FieldDoc = (function (_React$Component4) {
_inherits(FieldDoc, _React$Component4);
function FieldDoc() {
_classCallCheck(this, FieldDoc);
_React$Component4.apply(this, arguments);
}
// Renders a type link
FieldDoc.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
return this.props.field !== nextProps.field;
};
FieldDoc.prototype.render = function render() {
var _this2 = this;
var field = this.props.field;
var argsDef;
if (field.args && field.args.length > 0) {
argsDef = _react2['default'].createElement(
'div',
{ className: 'doc-category' },
_react2['default'].createElement(
'div',
{ className: 'doc-category-title' },
'arguments'
),
field.args.map(function (arg) {
return _react2['default'].createElement(
'div',
{ key: arg.name, className: 'doc-category-item' },
_react2['default'].createElement(
'div',
null,
_react2['default'].createElement(
'span',
{ className: 'arg-name' },
arg.name
),
': ',
_react2['default'].createElement(TypeLink, { type: arg.type, onClick: _this2.props.onClickType })
),
_react2['default'].createElement(Description, {
className: 'doc-value-description',
markdown: arg.description
})
);
})
);
}
return _react2['default'].createElement(
'div',
null,
_react2['default'].createElement(Description, {
className: 'doc-type-description',
markdown: field.description || 'No Description'
}),
_react2['default'].createElement(
'div',
{ className: 'doc-category' },
_react2['default'].createElement(
'div',
{ className: 'doc-category-title' },
'type'
),
_react2['default'].createElement(TypeLink, { type: field.type, onClick: this.props.onClickType })
),
argsDef
);
};
return FieldDoc;
})(_react2['default'].Component);
var TypeLink = (function (_React$Component5) {
_inherits(TypeLink, _React$Component5);
function TypeLink() {
_classCallCheck(this, TypeLink);
_React$Component5.apply(this, arguments);
}
TypeLink.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
return this.props.type !== nextProps.type;
};
TypeLink.prototype.render = function render() {
return renderType(this.props.type, this.props.onClick);
};
return TypeLink;
})(_react2['default'].Component);
function renderType(type, onClick) {
if (type instanceof _graphqlType.GraphQLNonNull) {
return _react2['default'].createElement(
'span',
null,
renderType(type.ofType, onClick),
'!'
);
}
if (type instanceof _graphqlType.GraphQLList) {
return _react2['default'].createElement(
'span',
null,
'[',
renderType(type.ofType, onClick),
']'
);
}
return _react2['default'].createElement(
'a',
{ className: 'type-name', onClick: function (event) {
return onClick(type, event);
} },
type.name
);
}
// Renders a description
var Description = (function (_React$Component6) {
_inherits(Description, _React$Component6);
function Description() {
_classCallCheck(this, Description);
_React$Component6.apply(this, arguments);
}
Description.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
return this.props.markdown !== nextProps.markdown;
};
Description.prototype.render = function render() {
var markdown = this.props.markdown;
if (!markdown) {
return _react2['default'].createElement('div', null);
}
var html = _marked2['default'](markdown);
return _react2['default'].createElement('div', {
className: this.props.className,
dangerouslySetInnerHTML: { __html: html }
});
};
return Description;
})(_react2['default'].Component);
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"graphql/type":136,"marked":178}],4:[function(require,module,exports){
(function (global){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE-examples file in the root directory of this source tree.
*/
"use strict";
exports.__esModule = 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; }; })();
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 _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 _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
/**
* ExecuteButton
*
* What a nice round shiny button. Cmd/Ctrl-Enter is the shortcut.
*/
var ExecuteButton = (function (_React$Component) {
_inherits(ExecuteButton, _React$Component);
function ExecuteButton() {
_classCallCheck(this, ExecuteButton);
_React$Component.apply(this, arguments);
}
ExecuteButton.prototype.render = function render() {
return _react2["default"].createElement(
"button",
{
className: "execute-button",
onClick: this.props.onClick,
title: "Execute Query (Ctrl-Enter)" },
_react2["default"].createElement(
"svg",
{ width: "34", height: "34" },
_react2["default"].createElement("path", { d: "M 11 9 L 24 16 L 11 23 z" })
)
);
};
ExecuteButton.prototype.componentDidMount = function componentDidMount() {
var _this = this;
this.keyHandler = function (event) {
if ((event.metaKey || event.ctrlKey) && event.keyCode === 13) {
event.preventDefault();
if (_this.props.onClick) {
_this.props.onClick();
}
}
};
document.addEventListener('keydown', this.keyHandler, true);
};
ExecuteButton.prototype.componentWillUnmount = function componentWillUnmount() {
document.removeEventListener('keydown', this.keyHandler, true);
};
_createClass(ExecuteButton, null, [{
key: "propTypes",
value: {
onClick: _react.PropTypes.func
},
enumerable: true
}]);
return ExecuteButton;
})(_react2["default"].Component);
exports.ExecuteButton = ExecuteButton;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],5:[function(require,module,exports){
(function (global){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE-examples file in the root directory of this source tree.
*/
'use strict';
exports.__esModule = 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; }; })();
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 _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 _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _ExecuteButton = require('./ExecuteButton');
var _QueryEditor = require('./QueryEditor');
var _VariableEditor = require('./VariableEditor');
var _ResultViewer = require('./ResultViewer');
var _DocExplorer = require('./DocExplorer');
var _graphqlType = require('graphql/type');
var _graphqlUtilities = require('graphql/utilities');
var _graphqlJsutilsFind = require('graphql/jsutils/find');
var _graphqlJsutilsFind2 = _interopRequireDefault(_graphqlJsutilsFind);
var _utilityFillLeafs = require('../utility/fillLeafs');
var _utilityElementPosition = require('../utility/elementPosition');
/**
* GraphiQL
*
* This React component is responsible for rendering the GraphiQL editor.
*
* Props:
*
* - fetcher: a function which accepts GraphQL-HTTP parameters and returns
* a Promise which resolves to the GraphQL parsed JSON response.
*
* - schema: an optional GraphQLSchema instance. If one is not provided,
* GraphiQL will fetch one using introspection.
*
* - query: an optional GraphQL string to use as the initial displayed query,
* if not provided, the stored query or defaultQuery will be used.
*
* - response: an optional JSON string to use as the initial displayed
* response. If not provided, no response will be initialy shown. You might
* provide this if illustrating the result of the initial query.
*
* - storage: an instance of [Storage][] GraphiQL will use to persist state.
* Only `getItem` and `setItem` are called. Default: window.localStorage
*
* - defaultQuery: an optional GraphQL string to use instead of a
* blank screen when a query was not found in the local cache.
*
* - variables: an optional GraphQL string to use as the initial displayed
* query variables, if not provided, the stored variables will be used.
*
* - onEditQuery: an optional function which will be called when the Query
* editor changes. The argument to the function will be the query string.
*
* - onEditVariables: an optional function which will be called when the Query
* varible editor changes. The argument to the function will be the
* variables string.
*
* - getDefaultFieldNames: an optional function used to provide default fields
* to non-leaf fields which invalidly lack a selection set.
* Accepts a GraphQLType instance and returns an array of field names.
* If not provided, a default behavior will be used.
*
* Children:
*
* - <GraphiQL.Logo> Replace the GraphiQL logo with your own.
*
* - <GraphiQL.Toolbar> Add a custom toolbar above GraphiQL.
*
* - <GraphiQL.Footer> Add a custom footer below GraphiQL Results.
*
*
* [Storage]: https://developer.mozilla.org/en-US/docs/Web/API/Storage
*/
var GraphiQL = (function (_React$Component) {
_inherits(GraphiQL, _React$Component);
/**
* Inspect the query, automatically filling in selection sets for non-leaf
* fields which do not yet have them.
*
* @public
*/
GraphiQL.prototype.autoCompleteLeafs = function autoCompleteLeafs() {
var _fillLeafs = _utilityFillLeafs.fillLeafs(this.state.schema, this.state.query, this.props.getDefaultFieldNames);
var insertions = _fillLeafs.insertions;
var result = _fillLeafs.result;
if (insertions.length > 0) {
var editor = this.refs.queryEditor.getCodeMirror();
editor.operation(function () {
var cursor = editor.getCursor();
var cursorIndex = editor.indexFromPos(cursor);
editor.setValue(result);
var added = 0;
var markers = insertions.map(function (_ref) {
var index = _ref.index;
var string = _ref.string;
return editor.markText(editor.posFromIndex(index + added), editor.posFromIndex(index + (added += string.length)), {
className: 'autoInsertedLeaf',
clearOnEnter: true,
title: 'Automatically added leaf fields'
});
});
setTimeout(function () {
return markers.forEach(function (marker) {
return marker.clear();
});
}, 7000);
var newCursorIndex = cursorIndex;
insertions.forEach(function (_ref2) {
var index = _ref2.index;
var string = _ref2.string;
if (index < cursorIndex) {
newCursorIndex += string.length;
}
});
var newCursor = editor.posFromIndex(newCursorIndex);
editor.setCursor(newCursor);
});
}
};
// Lifecycle
_createClass(GraphiQL, null, [{
key: 'propTypes',
value: {
fetcher: _react.PropTypes.func.isRequired,
schema: _react.PropTypes.instanceOf(_graphqlType.GraphQLSchema),
query: _react.PropTypes.string,
response: _react.PropTypes.string,
storage: _react.PropTypes.shape({
getItem: _react.PropTypes.func,
setItem: _react.PropTypes.func
}),
defaultQuery: _react.PropTypes.string,
variables: _react.PropTypes.string,
onEditQuery: _react.PropTypes.func,
onEditVariables: _react.PropTypes.func,
getDefaultFieldNames: _react.PropTypes.func
},
enumerable: true
}]);
function GraphiQL(props) {
var _this = this;
_classCallCheck(this, GraphiQL);
_React$Component.call(this);
// Ensure props are correct
this._runEditorQuery = function () {
_this._editorQueryID++;
var queryID = _this._editorQueryID;
_this.autoCompleteLeafs();
_this._fetchQuery(_this.state.query, _this.state.variables, function (result) {
if (queryID === _this._editorQueryID) {
_this.setState({ response: JSON.stringify(result, null, 2) });
}
});
};
this._onEditQuery = function (value) {
_this._storageSet('query', value);
_this.setState({ query: value });
if (_this.props.onEditQuery) {
return _this.props.onEditQuery(value);
}
};
this._onEditVariables = function (value) {
_this._storageSet('variables', value);
_this.setState({ variables: value });
if (_this.props.onEditVariables) {
_this.props.onEditVariables(value);
}
};
this._onHintInformationRender = function (elem) {
elem.addEventListener('click', _this._onClickHintInformation);
var onRemoveFn;
elem.addEventListener('DOMNodeRemoved', onRemoveFn = function () {
elem.removeEventListener('DOMNodeRemoved', onRemoveFn);
elem.removeEventListener('click', _this._onClickHintInformation);
});
};
this._onClickHintInformation = function (event) {
if (event.target.className === 'typeName') {
var typeName = event.target.innerHTML;
var schema = _this.state.schema;
if (schema) {
var type = schema.getType(typeName);
if (type) {
_this.setState({ docsOpen: true }, function () {
_this.refs.docExplorer.showDoc(type);
});
}
}
}
};
this._onToggleDocs = function () {
_this.setState({ docsOpen: !_this.state.docsOpen });
};
this._onResizeStart = function (downEvent) {
if (!_this._didClickDragBar(downEvent)) {
return;
}
downEvent.preventDefault();
var offset = downEvent.clientX - _utilityElementPosition.getLeft(downEvent.target);
var onMouseMove = function onMouseMove(moveEvent) {
if (moveEvent.buttons === 0) {
return onMouseUp();
}
var editorBar = _react2['default'].findDOMNode(_this.refs.editorBar);
var leftSize = moveEvent.clientX - _utilityElementPosition.getLeft(editorBar) - offset;
var rightSize = editorBar.clientWidth - leftSize;
_this.setState({ editorFlex: leftSize / rightSize });
};
var onMouseUp = (function (_onMouseUp) {
function onMouseUp() {
return _onMouseUp.apply(this, arguments);
}
onMouseUp.toString = function () {
return _onMouseUp.toString();
};
return onMouseUp;
})(function () {
_this._storageSet('editorFlex', _this.state.editorFlex);
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
onMouseMove = null;
onMouseUp = null;
});
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
};
this._onDocsResizeStart = function (downEvent) {
downEvent.preventDefault();
var hadWidth = _this.state.docsWidth;
var offset = downEvent.clientX - _utilityElementPosition.getLeft(downEvent.target);
var onMouseMove = function onMouseMove(moveEvent) {
if (moveEvent.buttons === 0) {
return onMouseUp();
}
var app = _react2['default'].findDOMNode(_this);
var cursorPos = moveEvent.clientX - _utilityElementPosition.getLeft(app) - offset;
var docsSize = app.clientWidth - cursorPos;
if (docsSize < 100) {
_this.setState({ docsOpen: false });
} else {
_this.setState({
docsOpen: true,
docsWidth: Math.min(docsSize, 650)
});
}
};
var onMouseUp = (function (_onMouseUp2) {
function onMouseUp() {
return _onMouseUp2.apply(this, arguments);
}
onMouseUp.toString = function () {
return _onMouseUp2.toString();
};
return onMouseUp;
})(function () {
if (_this.state.docsOpen) {
_this._storageSet('docExplorerWidth', _this.state.docsWidth);
} else {
_this.setState({ docsWidth: hadWidth });
}
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
onMouseMove = null;
onMouseUp = null;
});
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
};
this._onVariableResizeStart = function (downEvent) {
downEvent.preventDefault();
var didMove = false;
var wasOpen = _this.state.variableEditorOpen;
var hadHeight = _this.state.variableEditorHeight;
var offset = downEvent.clientY - _utilityElementPosition.getTop(downEvent.target);
var onMouseMove = function onMouseMove(moveEvent) {
if (moveEvent.buttons === 0) {
return onMouseUp();
}
didMove = true;
var editorBar = _react2['default'].findDOMNode(_this.refs.editorBar);
var topSize = moveEvent.clientY - _utilityElementPosition.getTop(editorBar) - offset;
var bottomSize = editorBar.clientHeight - topSize;
if (bottomSize < 60) {
_this.setState({
variableEditorOpen: false,
variableEditorHeight: hadHeight
});
} else {
_this.setState({
variableEditorOpen: true,
variableEditorHeight: bottomSize
});
}
};
var onMouseUp = (function (_onMouseUp3) {
function onMouseUp() {
return _onMouseUp3.apply(this, arguments);
}
onMouseUp.toString = function () {
return _onMouseUp3.toString();
};
return onMouseUp;
})(function () {
if (didMove) {
_this._storageSet('variableEditorHeight', _this.state.variableEditorHeight);
} else {
_this.setState({ variableEditorOpen: !wasOpen });
}
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
onMouseMove = null;
onMouseUp = null;
});
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
};
if (typeof props.fetcher !== 'function') {
throw new TypeError('GraphiQL requires a fetcher function.');
}
// Cache the storage instance
this._storage = props.storage || window.localStorage;
// Determine the initial query to display.
var query = props.query || this._storageGet('query') || props.defaultQuery || defaultQuery;
// Determine the initial variables to display.
var variables = props.variables || this._storageGet('variables');
// Initialize state
this.state = {
schema: props.schema,
query: query,
variables: variables,
response: props.response,
editorFlex: this._storageGet('editorFlex') || 1,
variableEditorOpen: Boolean(variables),
variableEditorHeight: this._storageGet('variableEditorHeight') || 200,
docsOpen: false,
docsWidth: this._storageGet('docExplorerWidth') || 350
};
// Ensure only the last executed editor query is rendered.
this._editorQueryID = 0;
}
// Configure the UI by providing this Component as a child of GraphiQL.
GraphiQL.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var nextQuery = this.state.query;
var nextVariables = this.state.variables;
var nextResult = this.state.result;
if (nextProps.query && nextProps.query !== nextQuery) {
nextQuery = nextProps.query;
}
if (nextProps.variables && nextProps.variables !== nextVariables) {
nextVariables = nextProps.variables;
}
if (nextProps.result && nextProps.result !== nextResult) {
nextResult = nextProps.result;
}
this.setState({
query: nextQuery,
variables: nextVariables,
result: nextResult
});
};
GraphiQL.prototype.componentDidMount = function componentDidMount() {
var _this2 = this;
if (!this.state.schema) {
this._fetchQuery(_graphqlUtilities.introspectionQuery, null, function (result) {
if (!result.data) {
_this2.setState({ response: JSON.stringify(result, null, 2) });
} else {
_this2.setState({ schema: _graphqlUtilities.buildClientSchema(result.data) });
}
});
}
};
GraphiQL.prototype.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
// When UI-altering state changes, simulate a window resize event so all
// CodeMirror instances become properly rendered.
if (this.state.variableEditorOpen !== prevState.variableEditorOpen || this.state.variableEditorHeight !== prevState.variableEditorHeight) {
window.dispatchEvent(new Event('resize'));
}
};
GraphiQL.prototype.render = function render() {
var children = [];
_react2['default'].Children.forEach(this.props.children, function (child) {
children.push(child);
});
var logo = _graphqlJsutilsFind2['default'](children, function (child) {
return child.type === GraphiQL.Logo;
}) || _react2['default'].createElement(GraphiQL.Logo, null);
var toolbar = _graphqlJsutilsFind2['default'](children, function (child) {
return child.type === GraphiQL.Toolbar;
});
var footer = _graphqlJsutilsFind2['default'](children, function (child) {
return child.type === GraphiQL.Footer;
});
var queryWrapStyle = {
WebkitFlex: this.state.editorFlex,
flex: this.state.editorFlex
};
var docWrapStyle = {
display: this.state.docsOpen ? 'block' : 'none',
width: this.state.docsWidth
};
var variableOpen = this.state.variableEditorOpen;
var variableStyle = {
height: variableOpen ? this.state.variableEditorHeight : null
};
return _react2['default'].createElement(
'div',
{ id: 'graphiql-container' },
_react2['default'].createElement(
'div',
{ className: 'editorWrap' },
_react2['default'].createElement(
'div',
{ className: 'topBarWrap' },
_react2['default'].createElement(
'div',
{ className: 'topBar' },
logo,
_react2['default'].createElement(_ExecuteButton.ExecuteButton, { onClick: this._runEditorQuery }),
toolbar
),
!this.state.docsOpen && _react2['default'].createElement(
'button',
{ className: 'docExplorerShow', onClick: this._onToggleDocs },
'Docs'
)
),
_react2['default'].createElement(
'div',
{
ref: 'editorBar',
className: 'editorBar',
onMouseDown: this._onResizeStart
},
_react2['default'].createElement(
'div',
{ className: 'queryWrap', style: queryWrapStyle },
_react2['default'].createElement(_QueryEditor.QueryEditor, {
ref: 'queryEditor',
schema: this.state.schema,
value: this.state.query,
onEdit: this._onEditQuery,
onHintInformationRender: this._onHintInformationRender
}),
_react2['default'].createElement(
'div',
{ className: 'variable-editor', style: variableStyle },
_react2['default'].createElement(
'div',
{
className: 'variable-editor-title',
style: { cursor: variableOpen ? 'row-resize' : 'n-resize' },
onMouseDown: this._onVariableResizeStart
},
'Query Variables'
),
_react2['default'].createElement(_VariableEditor.VariableEditor, {
value: this.state.variables,
onEdit: this._onEditVariables
})
)
),
_react2['default'].createElement(
'div',
{ className: 'resultWrap' },
_react2['default'].createElement(_ResultViewer.ResultViewer, { ref: 'result', value: this.state.response }),
footer
)
)
),
_react2['default'].createElement(
'div',
{ className: 'docExplorerWrap', style: docWrapStyle },
_react2['default'].createElement('div', {
className: 'docExplorerResizer',
onMouseDown: this._onDocsResizeStart
}),
_react2['default'].createElement(
_DocExplorer.DocExplorer,
{ ref: 'docExplorer', schema: this.state.schema },
_react2['default'].createElement(
'div',
{ className: 'docExplorerHide', onClick: this._onToggleDocs },
'✕'
)
)
)
);
};
// Private methods
GraphiQL.prototype._storageGet = function _storageGet(name) {
return this._storage.getItem('graphiql:' + name);
};
GraphiQL.prototype._storageSet = function _storageSet(name, value) {
this._storage.setItem('graphiql:' + name, value);
};
GraphiQL.prototype._fetchQuery = function _fetchQuery(query, variables, cb) {
var _this3 = this;
this.props.fetcher({ query: query, variables: variables }).then(cb)['catch'](function (error) {
_this3.setState({ response: error && error.stack || error });
});
};
GraphiQL.prototype._didClickDragBar = function _didClickDragBar(event) {
// Only for primary unmodified clicks
if (event.button !== 0 || event.ctrlKey) {
return false;
}
var target = event.target;
// We use codemirror's gutter as the drag bar.
if (target.className.indexOf('CodeMirror-gutter') !== 0) {
return false;
}
// Specifically the result window's drag bar.
var resultWindow = _react2['default'].findDOMNode(this.refs.result);
while (target) {
if (target === resultWindow) {
return true;
}
target = target.parentNode;
}
return false;
};
return GraphiQL;
})(_react2['default'].Component);
exports.GraphiQL = GraphiQL;
GraphiQL.Logo = (function (_React$Component2) {
_inherits(GraphiQLLogo, _React$Component2);
function GraphiQLLogo() {
_classCallCheck(this, GraphiQLLogo);
_React$Component2.apply(this, arguments);
}
GraphiQLLogo.prototype.render = function render() {
return _react2['default'].createElement(
'div',
{ className: 'title' },
this.props.children || _react2['default'].createElement(
'span',
null,
'Graph',
_react2['default'].createElement(
'em',
null,
'i'
),
'QL'
)
);
};
return GraphiQLLogo;
})(_react2['default'].Component);
// Configure the UI by providing this Component as a child of GraphiQL.
GraphiQL.Toolbar = (function (_React$Component3) {
_inherits(GraphiQLToolbar, _React$Component3);
function GraphiQLToolbar() {
_classCallCheck(this, GraphiQLToolbar);
_React$Component3.apply(this, arguments);
}
GraphiQLToolbar.prototype.render = function render() {
return _react2['default'].createElement(
'div',
{ className: 'toolbar' },
this.props.children
);
};
return GraphiQLToolbar;
})(_react2['default'].Component);
// Configure the UI by providing this Component as a child of GraphiQL.
GraphiQL.Footer = (function (_React$Component4) {
_inherits(GraphiQLFooter, _React$Component4);
function GraphiQLFooter() {
_classCallCheck(this, GraphiQLFooter);
_React$Component4.apply(this, arguments);
}
GraphiQLFooter.prototype.render = function render() {
return _react2['default'].createElement(
'div',
{ className: 'footer' },
this.props.children
);
};
return GraphiQLFooter;
})(_react2['default'].Component);
var defaultQuery = '# Welcome to GraphiQL\n#\n# GraphiQL is an in-browser IDE for writing, validating, and\n# testing GraphQL queries.\n#\n# Type queries into this side of the screen, and you will\n# see intelligent typeaheads aware of the current GraphQL type schema and\n# live syntax and validation errors highlighted within the text.\n#\n# To bring up the auto-complete at any point, just press Ctrl-Space.\n#\n# Press the run button above, or Cmd-Enter to execute the query, and the result\n# will appear in the pane to the right.\n\n';
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../utility/elementPosition":10,"../utility/fillLeafs":11,"./DocExplorer":3,"./ExecuteButton":4,"./QueryEditor":6,"./ResultViewer":7,"./VariableEditor":8,"graphql/jsutils/find":32,"graphql/type":136,"graphql/utilities":145}],6:[function(require,module,exports){
(function (global){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE-examples file in the root directory of this source tree.
*/
'use strict';
exports.__esModule = 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; }; })();
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 _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 _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _marked = require('marked');
var _marked2 = _interopRequireDefault(_marked);
var _codemirror = require('codemirror');
var _codemirror2 = _interopRequireDefault(_codemirror);
var _graphqlType = require('graphql/type');
require('codemirror/addon/hint/show-hint');
require('codemirror/addon/comment/comment');
require('codemirror/addon/edit/matchbrackets');
require('codemirror/addon/edit/closebrackets');
require('codemirror/addon/fold/foldgutter');
require('codemirror/addon/fold/brace-fold');
require('codemirror/addon/lint/lint');
require('codemirror/keymap/sublime');
require('codemirror-graphql/hint');
require('codemirror-graphql/lint');
require('codemirror-graphql/mode');
/**
* QueryEditor
*
* Maintains an instance of CodeMirror responsible for editing a GraphQL query.
*
* Props:
*
* - schema: A GraphQLSchema instance enabling editor linting and hinting.
* - value: The text of the editor.
* - onEdit: A function called when the editor changes, given the edited text.
*
*/
var QueryEditor = (function (_React$Component) {
_inherits(QueryEditor, _React$Component);
_createClass(QueryEditor, null, [{
key: 'propTypes',
value: {
schema: _react.PropTypes.instanceOf(_graphqlType.GraphQLSchema),
value: _react.PropTypes.string,
onEdit: _react.PropTypes.func
},
enumerable: true
}]);
function QueryEditor(props) {
var _this = this;
_classCallCheck(this, QueryEditor);
_React$Component.call(this);
// Keep a cached version of the value, this cache will be updated when the
// editor is updated, which can later be used to protect the editor from
// unnecessary updates during the update lifecycle.
this._onKeyUp = function (cm, event) {
var code = event.keyCode;
if (code >= 65 && code <= 90 || // letters
!event.shiftKey && code >= 48 && code <= 57 || // numbers
event.shiftKey && code === 189 || // underscore
event.shiftKey && code === 50 || // @
event.shiftKey && code === 57 // (
) {
_this.editor.execCommand('autocomplete');
}
};
this._onEdit = function () {
if (!_this.ignoreChangeEvent) {
_this.cachedValue = _this.editor.getValue();
if (_this.props.onEdit) {
_this.props.onEdit(_this.cachedValue);
}
}
};
this._onHasCompletion = function (cm, data) {
var wrapper;
var information;
// When a hint result is selected, we touch the UI.
_codemirror2['default'].on(data, 'select', function (ctx, el) {
// Only the first time (usually when the hint UI is first displayed)
// do we create the wrapping node.
if (!wrapper) {
// Wrap the existing hint UI, so we have a place to put information.
var hintsUl = el.parentNode;
var container = hintsUl.parentNode;
wrapper = document.createElement('div');
container.appendChild(wrapper);
// CodeMirror vertically inverts the hint UI if there is not enough
// space below the cursor. Since this modified UI appends to the bottom
// of CodeMirror's existing UI, it could cover the cursor. This adjusts
// the positioning of the hint UI to accomodate.
var top = hintsUl.style.top;
var bottom = '';
var cursorTop = cm.cursorCoords().top;
if (parseInt(top, 10) < cursorTop) {
top = '';
bottom = window.innerHeight - cursorTop + 3 + 'px';
}
// Style the wrapper, remove positioning from hints. Note that usage
// of this option will need to specify CSS to remove some styles from
// the existing hint UI.
wrapper.className = 'CodeMirror-hints-wrapper';
wrapper.style.left = hintsUl.style.left;
wrapper.style.top = top;
wrapper.style.bottom = bottom;
hintsUl.style.left = '';
hintsUl.style.top = '';
// This "information" node will contain the additional info about the
// highlighted typeahead option.
information = document.createElement('div');
information.className = 'CodeMirror-hint-information';
if (bottom) {
wrapper.appendChild(information);
wrapper.appendChild(hintsUl);
} else {
wrapper.appendChild(hintsUl);
wrapper.appendChild(information);
}
// When CodeMirror attempts to remove the hint UI, we detect that it was
// removed from our wrapper and in turn remove the wrapper from the
// original container.
var onRemoveFn;
wrapper.addEventListener('DOMNodeRemoved', onRemoveFn = function (event) {
if (event.target === hintsUl) {
wrapper.removeEventListener('DOMNodeRemoved', onRemoveFn);
wrapper.parentNode.removeChild(wrapper);
wrapper = null;
information = null;
onRemoveFn = null;
}
});
}
// Now that the UI has been set up, add info to information.
var description = ctx.description ? _marked2['default'](ctx.description, { smartypants: true }) : 'Self descriptive.';
var type = ctx.type ? '<span class="infoType">' + renderType(ctx.type) + '</span>' : '';
information.innerHTML = '<div class="content">' + (description.slice(0, 3) === '<p>' ? '<p>' + type + description.slice(3) : type + description) + '</div>';
// Additional rendering?
var onHintInformationRender = _this.props.onHintInformationRender;
if (onHintInformationRender) {
onHintInformationRender(information);
}
});
};
this.cachedValue = props.value || '';
}
/**
* Public API for retrieving the CodeMirror instance from this
* React component.
*/
QueryEditor.prototype.getCodeMirror = function getCodeMirror() {
return this.editor;
};
QueryEditor.prototype.componentDidMount = function componentDidMount() {
var _this2 = this;
this.editor = _codemirror2['default'](_react2['default'].findDOMNode(this), {
value: this.props.value || '',
lineNumbers: true,
tabSize: 2,
mode: 'graphql',
theme: 'graphiql',
keyMap: 'sublime',
autoCloseBrackets: true,
matchBrackets: true,
showCursorWhenSelecting: true,
foldGutter: {
minFoldSize: 4
},
lint: {
schema: this.props.schema
},
hintOptions: {
schema: this.props.schema,
closeOnUnfocus: false,
completeSingle: false
},
gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
extraKeys: {
'Cmd-Space': function CmdSpace() {
return _this2.editor.showHint({ completeSingle: true });
},
'Ctrl-Space': function CtrlSpace() {
return _this2.editor.showHint({ completeSingle: true });
},
// Editor improvements
'Ctrl-Left': 'goSubwordLeft',
'Ctrl-Right': 'goSubwordRight',
'Alt-Left': 'goGroupLeft',
'Alt-Right': 'goGroupRight'
}
});
this.editor.on('change', this._onEdit);
this.editor.on('keyup', this._onKeyUp);
this.editor.on('hasCompletion', this._onHasCompletion);
};
QueryEditor.prototype.componentWillUnmount = function componentWillUnmount() {
this.editor.off('change', this._onEdit);
this.editor.off('keyup', this._onKeyUp);
this.editor.off('hasCompletion', this._onHasCompletion);
this.editor = null;
};
QueryEditor.prototype.componentDidUpdate = function componentDidUpdate(prevProps) {
// Ensure the changes caused by this update are not interpretted as
// user-input changes which could otherwise result in an infinite
// event loop.
this.ignoreChangeEvent = true;
if (this.props.schema !== prevProps.schema) {
this.editor.options.lint.schema = this.props.schema;
this.editor.options.hintOptions.schema = this.props.schema;
_codemirror2['default'].signal(this.editor, 'change', this.editor);
}
if (this.props.value !== prevProps.value && this.props.value !== this.cachedValue) {
this.cachedValue = this.props.value;
this.editor.setValue(this.props.value);
}
this.ignoreChangeEvent = false;
};
QueryEditor.prototype.render = function render() {
return _react2['default'].createElement('div', { className: 'query-editor' });
};
return QueryEditor;
})(_react2['default'].Component);
exports.QueryEditor = QueryEditor;
function renderType(type) {
if (type instanceof _graphqlType.GraphQLNonNull) {
return renderType(type.ofType) + '!';
}
if (type instanceof _graphqlType.GraphQLList) {
return '[' + renderType(type.ofType) + ']';
}
return '<a class="typeName">' + type.name + '</a>';
}
/**
* Render a custom UI for CodeMirror's hint which includes additional info
* about the type and description for the selected context.
*/
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"codemirror":25,"codemirror-graphql/hint":12,"codemirror-graphql/lint":13,"codemirror-graphql/mode":14,"codemirror/addon/comment/comment":15,"codemirror/addon/edit/closebrackets":16,"codemirror/addon/edit/matchbrackets":17,"codemirror/addon/fold/brace-fold":18,"codemirror/addon/fold/foldgutter":20,"codemirror/addon/hint/show-hint":21,"codemirror/addon/lint/lint":22,"codemirror/keymap/sublime":24,"graphql/type":136,"marked":178}],7:[function(require,module,exports){
(function (global){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE-examples file in the root directory of this source tree.
*/
'use strict';
exports.__esModule = 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; }; })();
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 _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 _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _codemirror = require('codemirror');
var _codemirror2 = _interopRequireDefault(_codemirror);
require('codemirror/addon/fold/foldgutter');
require('codemirror/addon/fold/brace-fold');
require('codemirror/keymap/sublime');
require('codemirror/mode/javascript/javascript');
/**
* ResultViewer
*
* Maintains an instance of CodeMirror for viewing a GraphQL response.
*
* Props:
*
* - value: The text of the editor.
*
*/
var ResultViewer = (function (_React$Component) {
_inherits(ResultViewer, _React$Component);
function ResultViewer() {
_classCallCheck(this, ResultViewer);
_React$Component.apply(this, arguments);
}
ResultViewer.prototype.componentDidMount = function componentDidMount() {
this.viewer = _codemirror2['default'](_react2['default'].findDOMNode(this), {
value: this.props.value || '',
readOnly: true,
theme: 'graphiql',
mode: {
name: 'javascript',
json: true
},
keyMap: 'sublime',
foldGutter: {
minFoldSize: 4
},
gutters: ['CodeMirror-foldgutter'],
extraKeys: {
// Editor improvements
'Ctrl-Left': 'goSubwordLeft',
'Ctrl-Right': 'goSubwordRight',
'Alt-Left': 'goGroupLeft',
'Alt-Right': 'goGroupRight'
}
});
};
ResultViewer.prototype.componentWillUnmount = function componentWillUnmount() {
this.viewer = null;
};
ResultViewer.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
return this.props.value !== nextProps.value;
};
ResultViewer.prototype.componentDidUpdate = function componentDidUpdate() {
this.viewer.setValue(this.props.value || '');
};
ResultViewer.prototype.render = function render() {
return _react2['default'].createElement('div', { className: 'result-window' });
};
_createClass(ResultViewer, null, [{
key: 'propTypes',
value: {
value: _react.PropTypes.string
},
enumerable: true
}]);
return ResultViewer;
})(_react2['default'].Component);
exports.ResultViewer = ResultViewer;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"codemirror":25,"codemirror/addon/fold/brace-fold":18,"codemirror/addon/fold/foldgutter":20,"codemirror/keymap/sublime":24,"codemirror/mode/javascript/javascript":26}],8:[function(require,module,exports){
(function (global){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE-examples file in the root directory of this source tree.
*/
'use strict';
exports.__esModule = 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; }; })();
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 _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 _react = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var _react2 = _interopRequireDefault(_react);
var _codemirror = require('codemirror');
var _codemirror2 = _interopRequireDefault(_codemirror);
require('codemirror/addon/fold/brace-fold');
require('codemirror/addon/fold/foldgutter');
require('codemirror/addon/lint/lint');
require('codemirror/keymap/sublime');
require('codemirror/mode/javascript/javascript');
require('../codemirror/lint/json-lint');
/**
* VariableEditor
*
* An instance of CodeMirror for editing variables defined in QueryEditor.
*
* Props:
*
* - value: The text of the editor.
* - onEdit: A function called when the editor changes, given the edited text.
*
*/
var VariableEditor = (function (_React$Component) {
_inherits(VariableEditor, _React$Component);
_createClass(VariableEditor, null, [{
key: 'propTypes',
value: {
value: _react.PropTypes.string,
onEdit: _react.PropTypes.func
},
enumerable: true
}]);
function VariableEditor(props) {
var _this = this;
_classCallCheck(this, VariableEditor);
_React$Component.call(this);
// Keep a cached version of the value, this cache will be updated when the
// editor is updated, which can later be used to protect the editor from
// unnecessary updates during the update lifecycle.
this._onEdit = function () {
if (!_this.ignoreChangeEvent) {
_this.cachedValue = _this.editor.getValue();
if (_this.props.onEdit) {
_this.props.onEdit(_this.cachedValue);
}
}
};
this.cachedValue = props.value || '';
}
VariableEditor.prototype.componentDidMount = function componentDidMount() {
this.editor = _codemirror2['default'](_react2['default'].findDOMNode(this), {
value: this.props.value || '',
lineNumbers: true,
theme: 'graphiql',
mode: {
name: 'javascript',
json: true
},
lint: true,
autoCloseBrackets: true,
matchBrackets: true,
showCursorWhenSelecting: true,
keyMap: 'sublime',
foldGutter: {
minFoldSize: 4
},
gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
extraKeys: {
// Editor improvements
'Ctrl-Left': 'goSubwordLeft',
'Ctrl-Right': 'goSubwordRight',
'Alt-Left': 'goGroupLeft',
'Alt-Right': 'goGroupRight'
}
});
this.editor.on('change', this._onEdit);
};
VariableEditor.prototype.componentWillUnmount = function componentWillUnmount() {
this.editor.off('change', this._onEdit);
this.editor = null;
};
VariableEditor.prototype.componentDidUpdate = function componentDidUpdate(prevProps) {
// Ensure the changes caused by this update are not interpretted as
// user-input changes which could otherwise result in an infinite
// event loop.
this.ignoreChangeEvent = true;
if (this.props.value !== prevProps.value && this.props.value !== this.cachedValue) {
this.cachedValue = this.props.value;
this.editor.setValue(this.props.value);
}
this.ignoreChangeEvent = false;
};
VariableEditor.prototype.render = function render() {
return _react2['default'].createElement('div', { className: 'codemirrorWrap', ref: 'codemirror' });
};
return VariableEditor;
})(_react2['default'].Component);
exports.VariableEditor = VariableEditor;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../codemirror/lint/json-lint":1,"codemirror":25,"codemirror/addon/fold/brace-fold":18,"codemirror/addon/fold/foldgutter":20,"codemirror/addon/lint/lint":22,"codemirror/keymap/sublime":24,"codemirror/mode/javascript/javascript":26}],9:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE-examples file in the root directory of this source tree.
*/
// The primary React component to use.
'use strict';
module.exports = require('./components/GraphiQL').GraphiQL;
},{"./components/GraphiQL":5}],10:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE-examples file in the root directory of this source tree.
*/
/**
* Utility functions to get a pixel distance from left/top of the window.
*/
"use strict";
exports.__esModule = true;
exports.getLeft = getLeft;
exports.getTop = getTop;
function getLeft(initialElem) {
var pt = 0;
var elem = initialElem;
while (elem.offsetParent) {
pt += elem.offsetLeft;
elem = elem.offsetParent;
}
return pt;
}
function getTop(initialElem) {
var pt = 0;
var elem = initialElem;
while (elem.offsetParent) {
pt += elem.offsetTop;
elem = elem.offsetParent;
}
return pt;
}
},{}],11:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE-examples file in the root directory of this source tree.
*/
'use strict';
exports.__esModule = true;
exports.fillLeafs = fillLeafs;
var _graphqlUtilities = require('graphql/utilities');
var _graphqlLanguage = require('graphql/language');
var _graphqlType = require('graphql/type');
/**
* Given a document string which may not be valid due to terminal fields not
* representing leaf values (Spec Section: "Leaf Field Selections"), and a
* function which provides reasonable default field names for a given type,
* this function will attempt to produce a schema which is valid after filling
* in selection sets for the invalid fields.
*
* Note that there is no guarantee that the result will be a valid query, this
* utility represents a "best effort" which may be useful within IDE tools.
*/
function fillLeafs(schema, docString, getDefaultFieldNames) {
var ast;
try {
ast = _graphqlLanguage.parse(docString);
} catch (error) {
return docString;
}
var fieldNameFn = getDefaultFieldNames || defaultGetDefaultFieldNames;
var insertions = [];
var typeInfo = new _graphqlUtilities.TypeInfo(schema);
_graphqlLanguage.visit(ast, {
leave: function leave(node) {
typeInfo.leave(node);
},
enter: function enter(node) {
typeInfo.enter(node);
if (node.kind === 'Field' && !node.selectionSet) {
var fieldType = typeInfo.getType();
var selectionSet = buildSelectionSet(fieldType, fieldNameFn);
if (selectionSet) {
var indent = getIndentation(docString, node.loc.start);
insertions.push({
index: node.loc.end,
string: ' ' + _graphqlLanguage.print(selectionSet).replace(/\n/g, '\n' + indent)
});
}
}
}
});
// Apply the insertions, but also return the insertions metadata.
return {
insertions: insertions,
result: withInsertions(docString, insertions)
};
}
// The default function to use for producing the default fields from a type.
// This function first looks for some common patterns, and falls back to
// including all leaf-type fields.
function defaultGetDefaultFieldNames(type) {
var fields = type.getFields();
// Is there an `id` field?
if (fields['id']) {
return ['id'];
}
// Is there an `edges` field?
if (fields['edges']) {
return ['edges'];
}
// Is there an `node` field?
if (fields['node']) {
return ['node'];
}
// Include all leaf-type fields.
var leafFieldNames = [];
Object.keys(fields).forEach(function (fieldName) {
if (_graphqlType.isLeafType(fields[fieldName].type)) {
leafFieldNames.push(fieldName);
}
});
return leafFieldNames;
}
// Given a GraphQL type, and a function which produces field names, recursively
// generate a SelectionSet which includes default fields.
function buildSelectionSet(type, getDefaultFieldNames) {
// Unknown types and leaf types do not have selection sets.
if (!type || _graphqlType.isLeafType(type)) {
return;
}
// Unwrap any non-null or list types.
var namedType = _graphqlType.getNamedType(type);
// Get an array of field names to use.
var fieldNames = getDefaultFieldNames(namedType);
// If there are no field names to use, return no selection set.
if (!Array.isArray(fieldNames) || fieldNames.length === 0) {
return;
}
// Build a selection set of each field, calling buildSelectionSet recursively.
return {
kind: 'SelectionSet',
selections: fieldNames.map(function (fieldName) {
var fieldDef = namedType.getFields()[fieldName];
var fieldType = fieldDef ? fieldDef.type : null;
return {
kind: 'Field',
name: {
kind: 'Name',
value: fieldName
},
selectionSet: buildSelectionSet(fieldType, getDefaultFieldNames)
};
})
};
}
// Given an initial string, and a list of "insertion" { index, string } objects,
// return a new string with these insertions applied.
function withInsertions(initial, insertions) {
if (insertions.length === 0) {
return initial;
}
var edited = '';
var prevIndex = 0;
insertions.forEach(function (_ref) {
var index = _ref.index;
var string = _ref.string;
edited += initial.slice(prevIndex, index) + string;
prevIndex = index;
});
edited += initial.slice(prevIndex);
return edited;
}
// Given a string and an index, look backwards to find the string of whitespace
// following the next previous line break.
function getIndentation(str, index) {
var indentStart = index;
var indentEnd = index;
while (indentStart) {
var c = str.charCodeAt(indentStart - 1);
// line break
if (c === 10 || c === 13 || c === 0x2028 || c === 0x2029) {
break;
}
indentStart--;
// not white space
if (c !== 9 && c !== 11 && c !== 12 && c !== 32 && c !== 160) {
indentEnd = indentStart;
}
}
return str.substring(indentStart, indentEnd);
}
},{"graphql/language":37,"graphql/type":136,"graphql/utilities":145}],12:[function(require,module,exports){
/**
* Copyright (c) 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';
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _codemirror = require('codemirror');
var _codemirror2 = _interopRequireDefault(_codemirror);
var _graphqlType = require('graphql/type');
var _graphqlTypeIntrospection = require('graphql/type/introspection');
/**
* Registers a "hint" helper for CodeMirror.
*
* Using CodeMirror's "hint" addon: https://codemirror.net/demo/complete.html
* Given an editor, this helper will take the token at the cursor and return a
* list of suggested tokens.
*
* Options:
*
* - schema: GraphQLSchema provides the hinter with positionally relevant info
*
* Additional Events:
*
* - hasCompletion (codemirror, data, token) - signaled when the hinter has a
* new list of completion suggestions.
*
*/
_codemirror2['default'].registerHelper('hint', 'graphql', function (editor, options) {
var schema = options.schema;
if (!schema) {
return;
}
var cur = editor.getCursor();
var token = editor.getTokenAt(cur);
var typeInfo = getTypeInfo(schema, token.state);
var state = token.state;
var kind = state.kind;
var step = state.step;
if (token.type === 'comment') {
return;
}
// Definition kinds
if (kind === 'Document') {
return hintList(editor, options, cur, token, [{ text: 'query' }, { text: 'mutation' }, { text: 'fragment' }, { text: '{' }]);
}
// Field names
if (kind === 'SelectionSet' || kind === 'Field' || kind === 'AliasedField') {
if (typeInfo.parentType) {
var fields;
if (typeInfo.parentType.getFields) {
var fieldObj = typeInfo.parentType.getFields();
fields = Object.keys(fieldObj).map(function (fieldName) {
return fieldObj[fieldName];
});
} else {
fields = [];
}
if (_graphqlType.isAbstractType(typeInfo.parentType)) {
fields.push(_graphqlTypeIntrospection.TypeNameMetaFieldDef);
}
if (typeInfo.parentType === schema.getQueryType()) {
fields.push(_graphqlTypeIntrospection.SchemaMetaFieldDef, _graphqlTypeIntrospection.TypeMetaFieldDef);
}
return hintList(editor, options, cur, token, fields.map(function (field) {
return {
text: field.name,
type: field.type,
description: field.description
};
}));
}
}
// Argument names
if (kind === 'Arguments' || kind === 'Argument' && step === 0) {
var argDefs = typeInfo.argDefs;
if (argDefs) {
return hintList(editor, options, cur, token, argDefs.map(function (argDef) {
return {
text: argDef.name,
type: argDef.type,
description: argDef.description
};
}));
}
}
// Input Object fields
if (kind === 'ObjectValue' || kind === 'ObjectField' && step === 0) {
if (typeInfo.objectFieldDefs) {
var objectFields = Object.keys(typeInfo.objectFieldDefs).map(function (fieldName) {
return typeInfo.objectFieldDefs[fieldName];
});
return hintList(editor, options, cur, token, objectFields.map(function (field) {
return {
text: field.name,
type: field.type,
description: field.description
};
}));
}
}
// Input values: Enum and Boolean
if (kind === 'EnumValue' || kind === 'ListValue' && step === 1 || kind === 'ObjectField' && step === 2 || kind === 'Argument' && step === 2) {
var namedInputType = _graphqlType.getNamedType(typeInfo.inputType);
if (namedInputType instanceof _graphqlType.GraphQLEnumType) {
var valueMap = namedInputType.getValues();
var values = Object.keys(valueMap).map(function (valueName) {
return valueMap[valueName];
});
return hintList(editor, options, cur, token, values.map(function (value) {
return {
text: value.name,
type: namedInputType,
description: value.description
};
}));
} else if (namedInputType === _graphqlType.GraphQLBoolean) {
return hintList(editor, options, cur, token, [{ text: 'true', type: _graphqlType.GraphQLBoolean, description: 'Not false.' }, { text: 'false', type: _graphqlType.GraphQLBoolean, description: 'Not true.' }]);
}
}
// Fragment type conditions
if (kind === 'TypeCondition' && step === 1 || kind === 'NamedType' && state.prevState.kind === 'TypeCondition') {
var possibleTypes;
if (typeInfo.parentType) {
possibleTypes = _graphqlType.isAbstractType(typeInfo.parentType) ? typeInfo.parentType.getPossibleTypes() : [typeInfo.parentType];
} else {
var typeMap = schema.getTypeMap();
possibleTypes = Object.keys(typeMap).map(function (typeName) {
return typeMap[typeName];
}).filter(_graphqlType.isCompositeType);
}
return hintList(editor, options, cur, token, possibleTypes.map(function (type) {
return {
text: type.name,
description: type.description
};
}));
}
// Variable definition types
if (kind === 'VariableDefinition' && step === 2 || kind === 'ListType' && step === 1 || kind === 'NamedType' && (state.prevState.kind === 'VariableDefinition' || state.prevState.kind === 'ListType')) {
var inputTypeMap = schema.getTypeMap();
var inputTypes = Object.keys(inputTypeMap).map(function (typeName) {
return inputTypeMap[typeName];
}).filter(_graphqlType.isInputType);
return hintList(editor, options, cur, token, inputTypes.map(function (type) {
return {
text: type.name,
description: type.description
};
}));
}
// Directive names
if (kind === 'Directive') {
var directives = schema.getDirectives().filter(function (directive) {
return directive.onField && state.prevState.kind === 'Field' || directive.onFragment && (state.prevState.kind === 'FragmentDefinition' || state.prevState.kind === 'InlineFragment' || state.prevState.kind === 'FragmentSpread') || directive.onOperation && (state.prevState.kind === 'Query' || state.prevState.kind === 'Mutation');
});
return hintList(editor, options, cur, token, directives.map(function (directive) {
return {
text: directive.name,
description: directive.description
};
}));
}
});
// Utility for collecting rich type information given any token's state
// from the graphql-mode parser.
function getTypeInfo(schema, tokenState) {
var info = {
type: null,
parentType: null,
inputType: null,
directiveDef: null,
fieldDef: null,
argDef: null,
argDefs: null,
objectFieldDefs: null
};
forEachState(tokenState, function (state) {
switch (state.kind) {
case 'Query':case 'ShortQuery':
info.type = schema.getQueryType();
break;
case 'Mutation':
info.type = schema.getMutationType();
break;
case 'InlineFragment':
case 'FragmentDefinition':
info.type = state.type && schema.getType(state.type);
break;
case 'Field':
info.fieldDef = info.type && state.name ? getFieldDef(schema, info.parentType, state.name) : null;
info.type = info.fieldDef && info.fieldDef.type;
break;
case 'SelectionSet':
info.parentType = _graphqlType.getNamedType(info.type);
break;
case 'Directive':
info.directiveDef = state.name && schema.getDirective(state.name);
break;
case 'Arguments':
info.argDefs = state.prevState.kind === 'Field' ? info.fieldDef && info.fieldDef.args : state.prevState.kind === 'Directive' ? info.directiveDef && info.directiveDef.args : null;
break;
case 'Argument':
info.argDef = null;
if (info.argDefs) {
for (var i = 0; i < info.argDefs.length; i++) {
if (info.argDefs[i].name === state.name) {
info.argDef = info.argDefs[i];
break;
}
}
}
info.inputType = info.argDef && info.argDef.type;
break;
case 'ListValue':
var nullableType = _graphqlType.getNullableType(info.inputType);
info.inputType = nullableType instanceof _graphqlType.GraphQLList ? nullableType.ofType : null;
break;
case 'ObjectValue':
var objectType = _graphqlType.getNamedType(info.inputType);
info.objectFieldDefs = objectType instanceof _graphqlType.GraphQLInputObjectType ? objectType.getFields() : null;
break;
case 'ObjectField':
var objectField = state.name && info.objectFieldDefs ? info.objectFieldDefs[state.name] : null;
info.inputType = objectField && objectField.type;
break;
}
});
return info;
}
// Utility for iterating through a state stack bottom-up.
function forEachState(stack, fn) {
var reverseStateStack = [];
var state = stack;
while (state && state.kind) {
reverseStateStack.push(state);
state = state.prevState;
}
for (var i = reverseStateStack.length - 1; i >= 0; i--) {
fn(reverseStateStack[i]);
}
}
// Gets the field definition given a type and field name
function getFieldDef(schema, type, fieldName) {
if (fieldName === _graphqlTypeIntrospection.SchemaMetaFieldDef.name && schema.getQueryType() === type) {
return _graphqlTypeIntrospection.SchemaMetaFieldDef;
}
if (fieldName === _graphqlTypeIntrospection.TypeMetaFieldDef.name && schema.getQueryType() === type) {
return _graphqlTypeIntrospection.TypeMetaFieldDef;
}
if (fieldName === _graphqlTypeIntrospection.TypeNameMetaFieldDef.name && _graphqlType.isCompositeType(type)) {
return _graphqlTypeIntrospection.TypeNameMetaFieldDef;
}
if (type.getFields) {
return type.getFields()[fieldName];
}
}
// Create the expected hint response given a possible list and a token
function hintList(editor, options, cursor, token, list) {
var hints = filterAndSortList(list, normalizeText(token.string));
if (!hints) {
return;
}
var tokenStart = token.type === null ? token.end : /\w/.test(token.string[0]) ? token.start : token.start + 1;
var results = {
list: hints,
from: _codemirror2['default'].Pos(cursor.line, tokenStart),
to: _codemirror2['default'].Pos(cursor.line, token.end)
};
_codemirror2['default'].signal(editor, 'hasCompletion', editor, results, token);
return results;
}
// Given a list of hint entries and currently typed text, sort and filter to
// provide a concise list.
function filterAndSortList(list, text) {
var sorted = !text ? list : list.map(function (entry) {
return {
proximity: getProximity(normalizeText(entry.text), text),
entry: entry
};
}).filter(function (pair) {
return pair.proximity <= 2;
}).sort(function (a, b) {
return a.proximity - b.proximity || a.entry.text.length - b.entry.text.length;
}).map(function (pair) {
return pair.entry;
});
return sorted.length > 0 ? sorted : list;
}
function normalizeText(text) {
return text.toLowerCase().replace(/\W/g, '');
}
// Determine a numeric proximity for a suggestion based on current text.
function getProximity(suggestion, text) {
// start with lexical distance
var proximity = lexicalDistance(text, suggestion);
if (suggestion.length > text.length) {
// do not penalize long suggestions.
proximity -= suggestion.length - text.length - 1;
// penalize suggestions not starting with this phrase
proximity += suggestion.indexOf(text) === 0 ? 0 : 0.5;
}
return proximity;
}
/**
* Computes the lexical distance between strings A and B.
*
* The "distance" between two strings is given by counting the minimum number
* of edits needed to transform string A into string B. An edit can be an
* insertion, deletion, or substitution of a single character, or a swap of two
* adjacent characters.
*
* This distance can be useful for detecting typos in input or sorting
*
* @param {string} a
* @param {string} b
* @return {int} distance in number of edits
*/
function lexicalDistance(a, b) {
var i;
var j;
var d = [];
var aLength = a.length;
var bLength = b.length;
for (i = 0; i <= aLength; i++) {
d[i] = [i];
}
for (j = 1; j <= bLength; j++) {
d[0][j] = j;
}
for (i = 1; i <= aLength; i++) {
for (j = 1; j <= bLength; j++) {
var cost = a[i - 1] === b[j - 1] ? 0 : 1;
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost);
}
}
}
return d[aLength][bLength];
}
},{"codemirror":25,"graphql/type":136,"graphql/type/introspection":137}],13:[function(require,module,exports){
/**
* Copyright (c) 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';
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _codemirror = require('codemirror');
var _codemirror2 = _interopRequireDefault(_codemirror);
var _graphqlLanguage = require('graphql/language');
var _graphqlValidation = require('graphql/validation');
/**
* Registers a "lint" helper for CodeMirror.
*
* Using CodeMirror's "lint" addon: https://codemirror.net/demo/lint.html
* Given the text within an editor, this helper will take that text and return
* a list of linter issues, derived from GraphQL's parse and validate steps.
*
* Options:
*
* - schema: GraphQLSchema provides the linter with positionally relevant info
*
*/
_codemirror2['default'].registerHelper('lint', 'graphql', function (text, options, editor) {
var schema = options.schema;
try {
var ast = _graphqlLanguage.parse(text);
} catch (error) {
var location = error.locations[0];
var pos = _codemirror2['default'].Pos(location.line - 1, location.column);
var token = editor.getTokenAt(pos);
return [{
message: error.message,
severity: 'error',
type: 'syntax',
from: _codemirror2['default'].Pos(location.line - 1, token.start),
to: _codemirror2['default'].Pos(location.line - 1, token.end)
}];
}
var errors = schema ? _graphqlValidation.validate(schema, ast) : [];
return mapCat(errors, function (error) {
return errorAnnotations(editor, error);
});
});
function errorAnnotations(editor, error) {
return error.nodes.map(function (node) {
var highlightNode = node.kind !== 'Variable' && node.name ? node.name : node.variable ? node.variable : node;
return {
message: error.message,
severity: 'error',
type: 'validation',
from: editor.posFromIndex(highlightNode.loc.start),
to: editor.posFromIndex(highlightNode.loc.end)
};
});
}
// General utility for map-cating (aka flat-mapping).
function mapCat(array, mapper) {
return Array.prototype.concat.apply([], array.map(mapper));
}
},{"codemirror":25,"graphql/language":37,"graphql/validation":152}],14:[function(require,module,exports){
/**
* Copyright (c) 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';
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _codemirror = require('codemirror');
var _codemirror2 = _interopRequireDefault(_codemirror);
/**
* The GraphQL mode is defined as a tokenizer along with a list of rules, each
* of which is either a function or an array.
*
* * Function: Provided a token and the stream, returns an expected next step.
* * Array: A list of steps to take in order.
*
* A step is either another rule, or a terminal description of a token. If it
* is a rule, that rule is pushed onto the stack and the parsing continues from
* that point.
*
* If it is a terminal description, the token is checked against it using a
* `match` function. If the match is successful, the token is colored and the
* rule is stepped forward. If the match is unsuccessful, the remainder of the
* rule is skipped and the previous rule is advanced.
*
* This parsing algorithm allows for incremental online parsing within various
* levels of the syntax tree and results in a structured `state` linked-list
* which contains the relevant information to produce valuable typeaheads.
*/
_codemirror2['default'].defineMode('graphql', function (config) {
return {
config: config,
token: getToken,
indent: indent,
startState: function startState() {
var initialState = { level: 0 };
pushRule(initialState, 'Document');
return initialState;
},
electricInput: /^\s*[})\]]/,
fold: 'brace',
lineComment: '#',
closeBrackets: {
pairs: '()[]{}""',
explode: '()[]{}'
}
};
});
function getToken(stream, state) {
if (state.needsAdvance) {
state.needsAdvance = false;
advanceRule(state);
}
// Remember initial indentation
if (stream.sol()) {
state.indentLevel = Math.floor(stream.indentation() / this.config.tabSize);
}
// Consume spaces and ignored characters
if (stream.eatSpace() || stream.eatWhile(',')) {
return null;
}
// Tokenize line comment
if (stream.match(this.lineComment)) {
stream.skipToEnd();
return 'comment';
}
// Lex a token from the stream
var token = lex(stream);
// If there's no matching token, skip ahead.
if (!token) {
stream.match(/\w+|./);
return 'invalidchar';
}
// Save state before continuing.
saveState(state);
// Handle changes in expected indentation level
if (token.kind === 'Punctuation') {
if (/^[{([]/.test(token.value)) {
// Push on the stack of levels one level deeper than the current level.
state.levels = (state.levels || []).concat(state.indentLevel + 1);
} else if (/^[})\]]/.test(token.value)) {
// Pop from the stack of levels.
// If the top of the stack is lower than the current level, lower the
// current level to match.
var levels = state.levels = (state.levels || []).slice(0, -1);
if (levels.length > 0 && levels[levels.length - 1] < state.indentLevel) {
state.indentLevel = levels[levels.length - 1];
}
}
}
while (state.rule) {
// If this is a forking rule, determine what rule to use based on
// the current token, otherwise expect based on the current step.
var expected = typeof state.rule === 'function' ? state.step === 0 ? state.rule(token, stream) : null : state.rule[state.step];
if (expected) {
// Un-wrap optional/list ParseRules.
if (expected.ofRule) {
expected = expected.ofRule;
}
// A string represents a Rule
if (typeof expected === 'string') {
pushRule(state, expected);
continue;
}
// Otherwise, match a Terminal.
if (expected.match && expected.match(token)) {
if (expected.update) {
expected.update(state, token);
}
// If this token was a punctuator, advance the parse rule, otherwise
// mark the state to be advanced before the next token. This ensures
// that tokens which can be appended to keep the appropriate state.
if (token.kind === 'Punctuation') {
advanceRule(state);
} else {
state.needsAdvance = true;
}
return expected.style;
}
}
unsuccessful(state);
}
// The parser does not know how to interpret this token, do not affect state.
restoreState(state);
return 'invalidchar';
}
function indent(state, textAfter) {
var levels = state.levels;
// If there is no stack of levels, use the current level.
// Otherwise, use the top level, pre-emptively dedenting for close braces.
var level = !levels || levels.length === 0 ? state.indentLevel : levels[levels.length - 1] - (this.electricInput.test(textAfter) ? 1 : 0);
return level * this.config.indentUnit;
}
function assign(to, from) {
var keys = Object.keys(from);
for (var i = 0; i < keys.length; i++) {
to[keys[i]] = from[keys[i]];
}
return to;
}
var stateCache = {};
// Save the current state in the cache.
function saveState(state) {
assign(stateCache, state);
}
// Restore from the state cache.
function restoreState(state) {
assign(state, stateCache);
}
// Push a new rule onto the state.
function pushRule(state, ruleKind) {
state.prevState = assign({}, state);
state.kind = ruleKind;
state.name = null;
state.type = null;
state.rule = ParseRules[ruleKind];
state.step = 0;
}
// Pop the current rule from the state.
function popRule(state) {
state.kind = state.prevState.kind;
state.name = state.prevState.name;
state.type = state.prevState.type;
state.rule = state.prevState.rule;
state.step = state.prevState.step;
state.prevState = state.prevState.prevState;
}
// Advance the step of the current rule.
function advanceRule(state) {
// Advance the step in the rule. If the rule is completed, pop
// the rule and advance the parent rule as well (recursively).
state.step++;
while (state.rule && !(Array.isArray(state.rule) && state.step < state.rule.length)) {
popRule(state);
// Do not advance a List step so it has the opportunity to repeat itself.
if (state.rule && !(Array.isArray(state.rule) && state.rule[state.step].isList)) {
state.step++;
}
}
}
// Unwind the state after an unsuccessful match.
function unsuccessful(state) {
// Fall back to the parent rule until you get to an optional or list rule or
// until the entire stack of rules is empty.
while (state.rule && !(Array.isArray(state.rule) && state.rule[state.step].ofRule)) {
popRule(state);
}
// If there is still a rule, it must be an optional or list rule.
// Consider this rule a success so that we may move past it.
if (state.rule) {
advanceRule(state);
}
}
// Given a stream, returns a { kind, value } pair, or null.
function lex(stream) {
var kinds = Object.keys(LexRules);
for (var i = 0; i < kinds.length; i++) {
var match = stream.match(LexRules[kinds[i]]);
if (match) {
return { kind: kinds[i], value: match[0] };
}
}
}
// An optional rule.
function opt(ofRule) {
return { ofRule: ofRule };
}
// A list of another rule.
function list(ofRule) {
return { ofRule: ofRule, isList: true };
}
// Token of a kind
function t(kind, style) {
return { style: style, match: function match(token) {
return token.kind === kind;
} };
}
// Punctuator
function p(value, style) {
return {
style: style || 'punctuation',
match: function match(token) {
return token.kind === 'Punctuation' && token.value === value;
}
};
}
// A keyword Token
function word(value) {
return {
style: 'keyword',
match: function match(token) {
return token.kind === 'Name' && token.value === value;
}
};
}
// A Name Token which will decorate the state with a `name`
function name(style) {
return {
style: style,
match: function match(token) {
return token.kind === 'Name';
},
update: function update(state, token) {
state.name = token.value;
}
};
}
// A Name Token which will decorate the previous state with a `type`
function type(style) {
return {
style: style,
match: function match(token) {
return token.kind === 'Name';
},
update: function update(state, token) {
state.prevState.type = token.value;
}
};
}
/**
* The lexer rules. These are exactly as described by the spec.
*/
var LexRules = {
// The Name token.
Name: /^[_A-Za-z][_0-9A-Za-z]*/,
// All Punctuation used in GraphQL
Punctuation: /^(?:!|\$|\(|\)|\.\.\.|:|=|@|\[|\]|\{|\})/,
// Combines the IntValue and FloatValue tokens.
Number: /^-?(?:0|(?:[1-9][0-9]*))(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?/,
// Note the closing quote is made optional as an IDE experience improvment.
String: /^"(?:[^"\\]|\\(?:b|f|n|r|t|u[0-9a-fA-F]{4}))*"?/
};
/**
* The parser rules. These are very close to, but not exactly the same as the
* spec. Minor deviations allow for a simpler implementation. The resulting
* parser can parse everything the spec declares possible.
*/
var ParseRules = {
Document: [list('Definition')],
Definition: function Definition(token) {
switch (token.value) {
case 'query':
return 'Query';
case 'mutation':
return 'Mutation';
case 'fragment':
return 'FragmentDefinition';
case '{':
return 'ShortQuery';
}
},
// Note: instead of "Operation", these rules have been separated out.
Query: [word('query'), opt(name('def')), opt('VariableDefinitions'), list('Directive'), 'SelectionSet'],
ShortQuery: ['SelectionSet'],
Mutation: [word('mutation'), opt(name('def')), opt('VariableDefinitions'), list('Directive'), 'SelectionSet'],
VariableDefinitions: [p('('), list('VariableDefinition'), p(')')],
VariableDefinition: ['Variable', p(':'), 'Type', opt('DefaultValue')],
Variable: [p('$', 'variable'), name('variable')],
DefaultValue: [p('='), 'Value'],
SelectionSet: [p('{'), list('Selection'), p('}')],
Selection: function Selection(token, stream) {
return token.value === '...' ? stream.match(/[\s\u00a0,]*on\b/, false) ? 'InlineFragment' : 'FragmentSpread' : stream.match(/[\s\u00a0,]*:/, false) ? 'AliasedField' : 'Field';
},
// Note: this minor deviation of "AliasedField" simplifies the lookahead.
AliasedField: [name('qualifier'), p(':'), 'Field'],
Field: [name('property'), opt('Arguments'), list('Directive'), opt('SelectionSet')],
Arguments: [p('('), list('Argument'), p(')')],
Argument: [name('attribute'), p(':'), 'Value'],
FragmentSpread: [p('...'), name('def'), list('Directive')],
InlineFragment: [p('...'), opt('TypeCondition'), list('Directive'), 'SelectionSet'],
FragmentDefinition: [word('fragment'), name('def'), 'TypeCondition', list('Directive'), 'SelectionSet'],
TypeCondition: [word('on'), type('atom')],
// Variables could be parsed in cases where only Const is expected by spec.
Value: function Value(token) {
switch (token.kind) {
case 'Number':
return 'NumberValue';
case 'String':
return 'StringValue';
case 'Punctuation':
switch (token.value) {
case '[':
return 'ListValue';
case '{':
return 'ObjectValue';
case '$':
return 'Variable';
}
return null;
case 'Name':
switch (token.value) {
case 'true':case 'false':
return 'BooleanValue';
}
return 'EnumValue';
}
},
NumberValue: [t('Number', 'number')],
StringValue: [t('String', 'string')],
BooleanValue: [t('Name', 'builtin')],
EnumValue: [name('string-2')],
ListValue: [p('['), list('Value'), p(']')],
ObjectValue: [p('{'), list('ObjectField'), p('}')],
ObjectField: [name('attribute'), p(':'), 'Value'],
Type: function Type(token) {
return token.value === '[' ? 'ListType' : 'NamedType';
},
// NonNullType has been merged into ListType and NamedType to simplify.
ListType: [p('['), 'NamedType', p(']'), opt(p('!'))],
NamedType: [name('atom'), opt(p('!'))],
Directive: [p('@', 'meta'), name('meta'), opt('Arguments')]
};
},{"codemirror":25}],15:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var noOptions = {};
var nonWS = /[^\s\u00a0]/;
var Pos = CodeMirror.Pos;
function firstNonWS(str) {
var found = str.search(nonWS);
return found == -1 ? 0 : found;
}
CodeMirror.commands.toggleComment = function(cm) {
var minLine = Infinity, ranges = cm.listSelections(), mode = null;
for (var i = ranges.length - 1; i >= 0; i--) {
var from = ranges[i].from(), to = ranges[i].to();
if (from.line >= minLine) continue;
if (to.line >= minLine) to = Pos(minLine, 0);
minLine = from.line;
if (mode == null) {
if (cm.uncomment(from, to)) mode = "un";
else { cm.lineComment(from, to); mode = "line"; }
} else if (mode == "un") {
cm.uncomment(from, to);
} else {
cm.lineComment(from, to);
}
}
};
CodeMirror.defineExtension("lineComment", function(from, to, options) {
if (!options) options = noOptions;
var self = this, mode = self.getModeAt(from);
var commentString = options.lineComment || mode.lineComment;
if (!commentString) {
if (options.blockCommentStart || mode.blockCommentStart) {
options.fullLines = true;
self.blockComment(from, to, options);
}
return;
}
var firstLine = self.getLine(from.line);
if (firstLine == null) return;
var end = Math.min(to.ch != 0 || to.line == from.line ? to.line + 1 : to.line, self.lastLine() + 1);
var pad = options.padding == null ? " " : options.padding;
var blankLines = options.commentBlankLines || from.line == to.line;
self.operation(function() {
if (options.indent) {
var baseString = firstLine.slice(0, firstNonWS(firstLine));
for (var i = from.line; i < end; ++i) {
var line = self.getLine(i), cut = baseString.length;
if (!blankLines && !nonWS.test(line)) continue;
if (line.slice(0, cut) != baseString) cut = firstNonWS(line);
self.replaceRange(baseString + commentString + pad, Pos(i, 0), Pos(i, cut));
}
} else {
for (var i = from.line; i < end; ++i) {
if (blankLines || nonWS.test(self.getLine(i)))
self.replaceRange(commentString + pad, Pos(i, 0));
}
}
});
});
CodeMirror.defineExtension("blockComment", function(from, to, options) {
if (!options) options = noOptions;
var self = this, mode = self.getModeAt(from);
var startString = options.blockCommentStart || mode.blockCommentStart;
var endString = options.blockCommentEnd || mode.blockCommentEnd;
if (!startString || !endString) {
if ((options.lineComment || mode.lineComment) && options.fullLines != false)
self.lineComment(from, to, options);
return;
}
var end = Math.min(to.line, self.lastLine());
if (end != from.line && to.ch == 0 && nonWS.test(self.getLine(end))) --end;
var pad = options.padding == null ? " " : options.padding;
if (from.line > end) return;
self.operation(function() {
if (options.fullLines != false) {
var lastLineHasText = nonWS.test(self.getLine(end));
self.replaceRange(pad + endString, Pos(end));
self.replaceRange(startString + pad, Pos(from.line, 0));
var lead = options.blockCommentLead || mode.blockCommentLead;
if (lead != null) for (var i = from.line + 1; i <= end; ++i)
if (i != end || lastLineHasText)
self.replaceRange(lead + pad, Pos(i, 0));
} else {
self.replaceRange(endString, to);
self.replaceRange(startString, from);
}
});
});
CodeMirror.defineExtension("uncomment", function(from, to, options) {
if (!options) options = noOptions;
var self = this, mode = self.getModeAt(from);
var end = Math.min(to.ch != 0 || to.line == from.line ? to.line : to.line - 1, self.lastLine()), start = Math.min(from.line, end);
// Try finding line comments
var lineString = options.lineComment || mode.lineComment, lines = [];
var pad = options.padding == null ? " " : options.padding, didSomething;
lineComment: {
if (!lineString) break lineComment;
for (var i = start; i <= end; ++i) {
var line = self.getLine(i);
var found = line.indexOf(lineString);
if (found > -1 && !/comment/.test(self.getTokenTypeAt(Pos(i, found + 1)))) found = -1;
if (found == -1 && (i != end || i == start) && nonWS.test(line)) break lineComment;
if (found > -1 && nonWS.test(line.slice(0, found))) break lineComment;
lines.push(line);
}
self.operation(function() {
for (var i = start; i <= end; ++i) {
var line = lines[i - start];
var pos = line.indexOf(lineString), endPos = pos + lineString.length;
if (pos < 0) continue;
if (line.slice(endPos, endPos + pad.length) == pad) endPos += pad.length;
didSomething = true;
self.replaceRange("", Pos(i, pos), Pos(i, endPos));
}
});
if (didSomething) return true;
}
// Try block comments
var startString = options.blockCommentStart || mode.blockCommentStart;
var endString = options.blockCommentEnd || mode.blockCommentEnd;
if (!startString || !endString) return false;
var lead = options.blockCommentLead || mode.blockCommentLead;
var startLine = self.getLine(start), endLine = end == start ? startLine : self.getLine(end);
var open = startLine.indexOf(startString), close = endLine.lastIndexOf(endString);
if (close == -1 && start != end) {
endLine = self.getLine(--end);
close = endLine.lastIndexOf(endString);
}
if (open == -1 || close == -1 ||
!/comment/.test(self.getTokenTypeAt(Pos(start, open + 1))) ||
!/comment/.test(self.getTokenTypeAt(Pos(end, close + 1))))
return false;
// Avoid killing block comments completely outside the selection.
// Positions of the last startString before the start of the selection, and the first endString after it.
var lastStart = startLine.lastIndexOf(startString, from.ch);
var firstEnd = lastStart == -1 ? -1 : startLine.slice(0, from.ch).indexOf(endString, lastStart + startString.length);
if (lastStart != -1 && firstEnd != -1 && firstEnd + endString.length != from.ch) return false;
// Positions of the first endString after the end of the selection, and the last startString before it.
firstEnd = endLine.indexOf(endString, to.ch);
var almostLastStart = endLine.slice(to.ch).lastIndexOf(startString, firstEnd - to.ch);
lastStart = (firstEnd == -1 || almostLastStart == -1) ? -1 : to.ch + almostLastStart;
if (firstEnd != -1 && lastStart != -1 && lastStart != to.ch) return false;
self.operation(function() {
self.replaceRange("", Pos(end, close - (pad && endLine.slice(close - pad.length, close) == pad ? pad.length : 0)),
Pos(end, close + endString.length));
var openEnd = open + startString.length;
if (pad && startLine.slice(openEnd, openEnd + pad.length) == pad) openEnd += pad.length;
self.replaceRange("", Pos(start, open), Pos(start, openEnd));
if (lead) for (var i = start + 1; i <= end; ++i) {
var line = self.getLine(i), found = line.indexOf(lead);
if (found == -1 || nonWS.test(line.slice(0, found))) continue;
var foundEnd = found + lead.length;
if (pad && line.slice(foundEnd, foundEnd + pad.length) == pad) foundEnd += pad.length;
self.replaceRange("", Pos(i, found), Pos(i, foundEnd));
}
});
return true;
});
});
},{"../../lib/codemirror":25}],16:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
var defaults = {
pairs: "()[]{}''\"\"",
triples: "",
explode: "[]{}"
};
var Pos = CodeMirror.Pos;
CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) {
if (old && old != CodeMirror.Init) {
cm.removeKeyMap(keyMap);
cm.state.closeBrackets = null;
}
if (val) {
cm.state.closeBrackets = val;
cm.addKeyMap(keyMap);
}
});
function getOption(conf, name) {
if (name == "pairs" && typeof conf == "string") return conf;
if (typeof conf == "object" && conf[name] != null) return conf[name];
return defaults[name];
}
var bind = defaults.pairs + "`";
var keyMap = {Backspace: handleBackspace, Enter: handleEnter};
for (var i = 0; i < bind.length; i++)
keyMap["'" + bind.charAt(i) + "'"] = handler(bind.charAt(i));
function handler(ch) {
return function(cm) { return handleChar(cm, ch); };
}
function getConfig(cm) {
var deflt = cm.state.closeBrackets;
if (!deflt) return null;
var mode = cm.getModeAt(cm.getCursor());
return mode.closeBrackets || deflt;
}
function handleBackspace(cm) {
var conf = getConfig(cm);
if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;
var pairs = getOption(conf, "pairs");
var ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
if (!ranges[i].empty()) return CodeMirror.Pass;
var around = charsAround(cm, ranges[i].head);
if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass;
}
for (var i = ranges.length - 1; i >= 0; i--) {
var cur = ranges[i].head;
cm.replaceRange("", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1));
}
}
function handleEnter(cm) {
var conf = getConfig(cm);
var explode = conf && getOption(conf, "explode");
if (!explode || cm.getOption("disableInput")) return CodeMirror.Pass;
var ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
if (!ranges[i].empty()) return CodeMirror.Pass;
var around = charsAround(cm, ranges[i].head);
if (!around || explode.indexOf(around) % 2 != 0) return CodeMirror.Pass;
}
cm.operation(function() {
cm.replaceSelection("\n\n", null);
cm.execCommand("goCharLeft");
ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
var line = ranges[i].head.line;
cm.indentLine(line, null, true);
cm.indentLine(line + 1, null, true);
}
});
}
function contractSelection(sel) {
var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0;
return {anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)),
head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1))};
}
function handleChar(cm, ch) {
var conf = getConfig(cm);
if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;
var pairs = getOption(conf, "pairs");
var pos = pairs.indexOf(ch);
if (pos == -1) return CodeMirror.Pass;
var triples = getOption(conf, "triples");
var identical = pairs.charAt(pos + 1) == ch;
var ranges = cm.listSelections();
var opening = pos % 2 == 0;
var type, next;
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i], cur = range.head, curType;
var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1));
if (opening && !range.empty()) {
curType = "surround";
} else if ((identical || !opening) && next == ch) {
if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch)
curType = "skipThree";
else
curType = "skip";
} else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 &&
cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch &&
(cur.ch <= 2 || cm.getRange(Pos(cur.line, cur.ch - 3), Pos(cur.line, cur.ch - 2)) != ch)) {
curType = "addFour";
} else if (identical) {
if (!CodeMirror.isWordChar(next) && enteringString(cm, cur, ch)) curType = "both";
else return CodeMirror.Pass;
} else if (opening && (cm.getLine(cur.line).length == cur.ch ||
isClosingBracket(next, pairs) ||
/\s/.test(next))) {
curType = "both";
} else {
return CodeMirror.Pass;
}
if (!type) type = curType;
else if (type != curType) return CodeMirror.Pass;
}
var left = pos % 2 ? pairs.charAt(pos - 1) : ch;
var right = pos % 2 ? ch : pairs.charAt(pos + 1);
cm.operation(function() {
if (type == "skip") {
cm.execCommand("goCharRight");
} else if (type == "skipThree") {
for (var i = 0; i < 3; i++)
cm.execCommand("goCharRight");
} else if (type == "surround") {
var sels = cm.getSelections();
for (var i = 0; i < sels.length; i++)
sels[i] = left + sels[i] + right;
cm.replaceSelections(sels, "around");
sels = cm.listSelections().slice();
for (var i = 0; i < sels.length; i++)
sels[i] = contractSelection(sels[i]);
cm.setSelections(sels);
} else if (type == "both") {
cm.replaceSelection(left + right, null);
cm.triggerElectric(left + right);
cm.execCommand("goCharLeft");
} else if (type == "addFour") {
cm.replaceSelection(left + left + left + left, "before");
cm.execCommand("goCharRight");
}
});
}
function isClosingBracket(ch, pairs) {
var pos = pairs.lastIndexOf(ch);
return pos > -1 && pos % 2 == 1;
}
function charsAround(cm, pos) {
var str = cm.getRange(Pos(pos.line, pos.ch - 1),
Pos(pos.line, pos.ch + 1));
return str.length == 2 ? str : null;
}
// Project the token type that will exists after the given char is
// typed, and use it to determine whether it would cause the start
// of a string token.
function enteringString(cm, pos, ch) {
var line = cm.getLine(pos.line);
var token = cm.getTokenAt(pos);
if (/\bstring2?\b/.test(token.type)) return false;
var stream = new CodeMirror.StringStream(line.slice(0, pos.ch) + ch + line.slice(pos.ch), 4);
stream.pos = stream.start = token.start;
for (;;) {
var type1 = cm.getMode().token(stream, token.state);
if (stream.pos >= pos.ch + 1) return /\bstring2?\b/.test(type1);
stream.start = stream.pos;
}
}
});
},{"../../lib/codemirror":25}],17:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
var ie_lt8 = /MSIE \d/.test(navigator.userAgent) &&
(document.documentMode == null || document.documentMode < 8);
var Pos = CodeMirror.Pos;
var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<"};
function findMatchingBracket(cm, where, strict, config) {
var line = cm.getLineHandle(where.line), pos = where.ch - 1;
var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)];
if (!match) return null;
var dir = match.charAt(1) == ">" ? 1 : -1;
if (strict && (dir > 0) != (pos == where.ch)) return null;
var style = cm.getTokenTypeAt(Pos(where.line, pos + 1));
var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config);
if (found == null) return null;
return {from: Pos(where.line, pos), to: found && found.pos,
match: found && found.ch == match.charAt(0), forward: dir > 0};
}
// bracketRegex is used to specify which type of bracket to scan
// should be a regexp, e.g. /[[\]]/
//
// Note: If "where" is on an open bracket, then this bracket is ignored.
//
// Returns false when no bracket was found, null when it reached
// maxScanLines and gave up
function scanForBracket(cm, where, dir, style, config) {
var maxScanLen = (config && config.maxScanLineLength) || 10000;
var maxScanLines = (config && config.maxScanLines) || 1000;
var stack = [];
var re = config && config.bracketRegex ? config.bracketRegex : /[(){}[\]]/;
var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1)
: Math.max(cm.firstLine() - 1, where.line - maxScanLines);
for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) {
var line = cm.getLine(lineNo);
if (!line) continue;
var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1;
if (line.length > maxScanLen) continue;
if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0);
for (; pos != end; pos += dir) {
var ch = line.charAt(pos);
if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) {
var match = matching[ch];
if ((match.charAt(1) == ">") == (dir > 0)) stack.push(ch);
else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch};
else stack.pop();
}
}
}
return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null;
}
function matchBrackets(cm, autoclear, config) {
// Disable brace matching in long lines, since it'll cause hugely slow updates
var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000;
var marks = [], ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, false, config);
if (match && cm.getLine(match.from.line).length <= maxHighlightLen) {
var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style}));
if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen)
marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style}));
}
}
if (marks.length) {
// Kludge to work around the IE bug from issue #1193, where text
// input stops going to the textare whever this fires.
if (ie_lt8 && cm.state.focused) cm.focus();
var clear = function() {
cm.operation(function() {
for (var i = 0; i < marks.length; i++) marks[i].clear();
});
};
if (autoclear) setTimeout(clear, 800);
else return clear;
}
}
var currentlyHighlighted = null;
function doMatchBrackets(cm) {
cm.operation(function() {
if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;}
currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets);
});
}
CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
if (old && old != CodeMirror.Init)
cm.off("cursorActivity", doMatchBrackets);
if (val) {
cm.state.matchBrackets = typeof val == "object" ? val : {};
cm.on("cursorActivity", doMatchBrackets);
}
});
CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);});
CodeMirror.defineExtension("findMatchingBracket", function(pos, strict, config){
return findMatchingBracket(this, pos, strict, config);
});
CodeMirror.defineExtension("scanForBracket", function(pos, dir, style, config){
return scanForBracket(this, pos, dir, style, config);
});
});
},{"../../lib/codemirror":25}],18:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.registerHelper("fold", "brace", function(cm, start) {
var line = start.line, lineText = cm.getLine(line);
var startCh, tokenType;
function findOpening(openCh) {
for (var at = start.ch, pass = 0;;) {
var found = at <= 0 ? -1 : lineText.lastIndexOf(openCh, at - 1);
if (found == -1) {
if (pass == 1) break;
pass = 1;
at = lineText.length;
continue;
}
if (pass == 1 && found < start.ch) break;
tokenType = cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1));
if (!/^(comment|string)/.test(tokenType)) return found + 1;
at = found - 1;
}
}
var startToken = "{", endToken = "}", startCh = findOpening("{");
if (startCh == null) {
startToken = "[", endToken = "]";
startCh = findOpening("[");
}
if (startCh == null) return;
var count = 1, lastLine = cm.lastLine(), end, endCh;
outer: for (var i = line; i <= lastLine; ++i) {
var text = cm.getLine(i), pos = i == line ? startCh : 0;
for (;;) {
var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos);
if (nextOpen < 0) nextOpen = text.length;
if (nextClose < 0) nextClose = text.length;
pos = Math.min(nextOpen, nextClose);
if (pos == text.length) break;
if (cm.getTokenTypeAt(CodeMirror.Pos(i, pos + 1)) == tokenType) {
if (pos == nextOpen) ++count;
else if (!--count) { end = i; endCh = pos; break outer; }
}
++pos;
}
}
if (end == null || line == end && endCh == startCh) return;
return {from: CodeMirror.Pos(line, startCh),
to: CodeMirror.Pos(end, endCh)};
});
CodeMirror.registerHelper("fold", "import", function(cm, start) {
function hasImport(line) {
if (line < cm.firstLine() || line > cm.lastLine()) return null;
var start = cm.getTokenAt(CodeMirror.Pos(line, 1));
if (!/\S/.test(start.string)) start = cm.getTokenAt(CodeMirror.Pos(line, start.end + 1));
if (start.type != "keyword" || start.string != "import") return null;
// Now find closing semicolon, return its position
for (var i = line, e = Math.min(cm.lastLine(), line + 10); i <= e; ++i) {
var text = cm.getLine(i), semi = text.indexOf(";");
if (semi != -1) return {startCh: start.end, end: CodeMirror.Pos(i, semi)};
}
}
var start = start.line, has = hasImport(start), prev;
if (!has || hasImport(start - 1) || ((prev = hasImport(start - 2)) && prev.end.line == start - 1))
return null;
for (var end = has.end;;) {
var next = hasImport(end.line + 1);
if (next == null) break;
end = next.end;
}
return {from: cm.clipPos(CodeMirror.Pos(start, has.startCh + 1)), to: end};
});
CodeMirror.registerHelper("fold", "include", function(cm, start) {
function hasInclude(line) {
if (line < cm.firstLine() || line > cm.lastLine()) return null;
var start = cm.getTokenAt(CodeMirror.Pos(line, 1));
if (!/\S/.test(start.string)) start = cm.getTokenAt(CodeMirror.Pos(line, start.end + 1));
if (start.type == "meta" && start.string.slice(0, 8) == "#include") return start.start + 8;
}
var start = start.line, has = hasInclude(start);
if (has == null || hasInclude(start - 1) != null) return null;
for (var end = start;;) {
var next = hasInclude(end + 1);
if (next == null) break;
++end;
}
return {from: CodeMirror.Pos(start, has + 1),
to: cm.clipPos(CodeMirror.Pos(end))};
});
});
},{"../../lib/codemirror":25}],19:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
function doFold(cm, pos, options, force) {
if (options && options.call) {
var finder = options;
options = null;
} else {
var finder = getOption(cm, options, "rangeFinder");
}
if (typeof pos == "number") pos = CodeMirror.Pos(pos, 0);
var minSize = getOption(cm, options, "minFoldSize");
function getRange(allowFolded) {
var range = finder(cm, pos);
if (!range || range.to.line - range.from.line < minSize) return null;
var marks = cm.findMarksAt(range.from);
for (var i = 0; i < marks.length; ++i) {
if (marks[i].__isFold && force !== "fold") {
if (!allowFolded) return null;
range.cleared = true;
marks[i].clear();
}
}
return range;
}
var range = getRange(true);
if (getOption(cm, options, "scanUp")) while (!range && pos.line > cm.firstLine()) {
pos = CodeMirror.Pos(pos.line - 1, 0);
range = getRange(false);
}
if (!range || range.cleared || force === "unfold") return;
var myWidget = makeWidget(cm, options);
CodeMirror.on(myWidget, "mousedown", function(e) {
myRange.clear();
CodeMirror.e_preventDefault(e);
});
var myRange = cm.markText(range.from, range.to, {
replacedWith: myWidget,
clearOnEnter: true,
__isFold: true
});
myRange.on("clear", function(from, to) {
CodeMirror.signal(cm, "unfold", cm, from, to);
});
CodeMirror.signal(cm, "fold", cm, range.from, range.to);
}
function makeWidget(cm, options) {
var widget = getOption(cm, options, "widget");
if (typeof widget == "string") {
var text = document.createTextNode(widget);
widget = document.createElement("span");
widget.appendChild(text);
widget.className = "CodeMirror-foldmarker";
}
return widget;
}
// Clumsy backwards-compatible interface
CodeMirror.newFoldFunction = function(rangeFinder, widget) {
return function(cm, pos) { doFold(cm, pos, {rangeFinder: rangeFinder, widget: widget}); };
};
// New-style interface
CodeMirror.defineExtension("foldCode", function(pos, options, force) {
doFold(this, pos, options, force);
});
CodeMirror.defineExtension("isFolded", function(pos) {
var marks = this.findMarksAt(pos);
for (var i = 0; i < marks.length; ++i)
if (marks[i].__isFold) return true;
});
CodeMirror.commands.toggleFold = function(cm) {
cm.foldCode(cm.getCursor());
};
CodeMirror.commands.fold = function(cm) {
cm.foldCode(cm.getCursor(), null, "fold");
};
CodeMirror.commands.unfold = function(cm) {
cm.foldCode(cm.getCursor(), null, "unfold");
};
CodeMirror.commands.foldAll = function(cm) {
cm.operation(function() {
for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++)
cm.foldCode(CodeMirror.Pos(i, 0), null, "fold");
});
};
CodeMirror.commands.unfoldAll = function(cm) {
cm.operation(function() {
for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++)
cm.foldCode(CodeMirror.Pos(i, 0), null, "unfold");
});
};
CodeMirror.registerHelper("fold", "combine", function() {
var funcs = Array.prototype.slice.call(arguments, 0);
return function(cm, start) {
for (var i = 0; i < funcs.length; ++i) {
var found = funcs[i](cm, start);
if (found) return found;
}
};
});
CodeMirror.registerHelper("fold", "auto", function(cm, start) {
var helpers = cm.getHelpers(start, "fold");
for (var i = 0; i < helpers.length; i++) {
var cur = helpers[i](cm, start);
if (cur) return cur;
}
});
var defaultOptions = {
rangeFinder: CodeMirror.fold.auto,
widget: "\u2194",
minFoldSize: 0,
scanUp: false
};
CodeMirror.defineOption("foldOptions", null);
function getOption(cm, options, name) {
if (options && options[name] !== undefined)
return options[name];
var editorOptions = cm.options.foldOptions;
if (editorOptions && editorOptions[name] !== undefined)
return editorOptions[name];
return defaultOptions[name];
}
CodeMirror.defineExtension("foldOption", function(options, name) {
return getOption(this, options, name);
});
});
},{"../../lib/codemirror":25}],20:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"), require("./foldcode"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "./foldcode"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineOption("foldGutter", false, function(cm, val, old) {
if (old && old != CodeMirror.Init) {
cm.clearGutter(cm.state.foldGutter.options.gutter);
cm.state.foldGutter = null;
cm.off("gutterClick", onGutterClick);
cm.off("change", onChange);
cm.off("viewportChange", onViewportChange);
cm.off("fold", onFold);
cm.off("unfold", onFold);
cm.off("swapDoc", updateInViewport);
}
if (val) {
cm.state.foldGutter = new State(parseOptions(val));
updateInViewport(cm);
cm.on("gutterClick", onGutterClick);
cm.on("change", onChange);
cm.on("viewportChange", onViewportChange);
cm.on("fold", onFold);
cm.on("unfold", onFold);
cm.on("swapDoc", updateInViewport);
}
});
var Pos = CodeMirror.Pos;
function State(options) {
this.options = options;
this.from = this.to = 0;
}
function parseOptions(opts) {
if (opts === true) opts = {};
if (opts.gutter == null) opts.gutter = "CodeMirror-foldgutter";
if (opts.indicatorOpen == null) opts.indicatorOpen = "CodeMirror-foldgutter-open";
if (opts.indicatorFolded == null) opts.indicatorFolded = "CodeMirror-foldgutter-folded";
return opts;
}
function isFolded(cm, line) {
var marks = cm.findMarksAt(Pos(line));
for (var i = 0; i < marks.length; ++i)
if (marks[i].__isFold && marks[i].find().from.line == line) return marks[i];
}
function marker(spec) {
if (typeof spec == "string") {
var elt = document.createElement("div");
elt.className = spec + " CodeMirror-guttermarker-subtle";
return elt;
} else {
return spec.cloneNode(true);
}
}
function updateFoldInfo(cm, from, to) {
var opts = cm.state.foldGutter.options, cur = from;
var minSize = cm.foldOption(opts, "minFoldSize");
var func = cm.foldOption(opts, "rangeFinder");
cm.eachLine(from, to, function(line) {
var mark = null;
if (isFolded(cm, cur)) {
mark = marker(opts.indicatorFolded);
} else {
var pos = Pos(cur, 0);
var range = func && func(cm, pos);
if (range && range.to.line - range.from.line >= minSize)
mark = marker(opts.indicatorOpen);
}
cm.setGutterMarker(line, opts.gutter, mark);
++cur;
});
}
function updateInViewport(cm) {
var vp = cm.getViewport(), state = cm.state.foldGutter;
if (!state) return;
cm.operation(function() {
updateFoldInfo(cm, vp.from, vp.to);
});
state.from = vp.from; state.to = vp.to;
}
function onGutterClick(cm, line, gutter) {
var state = cm.state.foldGutter;
if (!state) return;
var opts = state.options;
if (gutter != opts.gutter) return;
var folded = isFolded(cm, line);
if (folded) folded.clear();
else cm.foldCode(Pos(line, 0), opts.rangeFinder);
}
function onChange(cm) {
var state = cm.state.foldGutter;
if (!state) return;
var opts = state.options;
state.from = state.to = 0;
clearTimeout(state.changeUpdate);
state.changeUpdate = setTimeout(function() { updateInViewport(cm); }, opts.foldOnChangeTimeSpan || 600);
}
function onViewportChange(cm) {
var state = cm.state.foldGutter;
if (!state) return;
var opts = state.options;
clearTimeout(state.changeUpdate);
state.changeUpdate = setTimeout(function() {
var vp = cm.getViewport();
if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {
updateInViewport(cm);
} else {
cm.operation(function() {
if (vp.from < state.from) {
updateFoldInfo(cm, vp.from, state.from);
state.from = vp.from;
}
if (vp.to > state.to) {
updateFoldInfo(cm, state.to, vp.to);
state.to = vp.to;
}
});
}
}, opts.updateViewportTimeSpan || 400);
}
function onFold(cm, from) {
var state = cm.state.foldGutter;
if (!state) return;
var line = from.line;
if (line >= state.from && line < state.to)
updateFoldInfo(cm, line, line + 1);
}
});
},{"../../lib/codemirror":25,"./foldcode":19}],21:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var HINT_ELEMENT_CLASS = "CodeMirror-hint";
var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active";
// This is the old interface, kept around for now to stay
// backwards-compatible.
CodeMirror.showHint = function(cm, getHints, options) {
if (!getHints) return cm.showHint(options);
if (options && options.async) getHints.async = true;
var newOpts = {hint: getHints};
if (options) for (var prop in options) newOpts[prop] = options[prop];
return cm.showHint(newOpts);
};
CodeMirror.defineExtension("showHint", function(options) {
// We want a single cursor position.
if (this.listSelections().length > 1 || this.somethingSelected()) return;
if (this.state.completionActive) this.state.completionActive.close();
var completion = this.state.completionActive = new Completion(this, options);
if (!completion.options.hint) return;
CodeMirror.signal(this, "startCompletion", this);
completion.update(true);
});
function Completion(cm, options) {
this.cm = cm;
this.options = this.buildOptions(options);
this.widget = null;
this.debounce = 0;
this.tick = 0;
this.startPos = this.cm.getCursor();
this.startLen = this.cm.getLine(this.startPos.line).length;
var self = this;
cm.on("cursorActivity", this.activityFunc = function() { self.cursorActivity(); });
}
var requestAnimationFrame = window.requestAnimationFrame || function(fn) {
return setTimeout(fn, 1000/60);
};
var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout;
Completion.prototype = {
close: function() {
if (!this.active()) return;
this.cm.state.completionActive = null;
this.tick = null;
this.cm.off("cursorActivity", this.activityFunc);
if (this.widget && this.data) CodeMirror.signal(this.data, "close");
if (this.widget) this.widget.close();
CodeMirror.signal(this.cm, "endCompletion", this.cm);
},
active: function() {
return this.cm.state.completionActive == this;
},
pick: function(data, i) {
var completion = data.list[i];
if (completion.hint) completion.hint(this.cm, data, completion);
else this.cm.replaceRange(getText(completion), completion.from || data.from,
completion.to || data.to, "complete");
CodeMirror.signal(data, "pick", completion);
this.close();
},
cursorActivity: function() {
if (this.debounce) {
cancelAnimationFrame(this.debounce);
this.debounce = 0;
}
var pos = this.cm.getCursor(), line = this.cm.getLine(pos.line);
if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch ||
pos.ch < this.startPos.ch || this.cm.somethingSelected() ||
(pos.ch && this.options.closeCharacters.test(line.charAt(pos.ch - 1)))) {
this.close();
} else {
var self = this;
this.debounce = requestAnimationFrame(function() {self.update();});
if (this.widget) this.widget.disable();
}
},
update: function(first) {
if (this.tick == null) return;
if (!this.options.hint.async) {
this.finishUpdate(this.options.hint(this.cm, this.options), first);
} else {
var myTick = ++this.tick, self = this;
this.options.hint(this.cm, function(data) {
if (self.tick == myTick) self.finishUpdate(data, first);
}, this.options);
}
},
finishUpdate: function(data, first) {
if (this.data) CodeMirror.signal(this.data, "update");
if (data && this.data && CodeMirror.cmpPos(data.from, this.data.from)) data = null;
this.data = data;
var picked = (this.widget && this.widget.picked) || (first && this.options.completeSingle);
if (this.widget) this.widget.close();
if (data && data.list.length) {
if (picked && data.list.length == 1) {
this.pick(data, 0);
} else {
this.widget = new Widget(this, data);
CodeMirror.signal(data, "shown");
}
}
},
buildOptions: function(options) {
var editor = this.cm.options.hintOptions;
var out = {};
for (var prop in defaultOptions) out[prop] = defaultOptions[prop];
if (editor) for (var prop in editor)
if (editor[prop] !== undefined) out[prop] = editor[prop];
if (options) for (var prop in options)
if (options[prop] !== undefined) out[prop] = options[prop];
return out;
}
};
function getText(completion) {
if (typeof completion == "string") return completion;
else return completion.text;
}
function buildKeyMap(completion, handle) {
var baseMap = {
Up: function() {handle.moveFocus(-1);},
Down: function() {handle.moveFocus(1);},
PageUp: function() {handle.moveFocus(-handle.menuSize() + 1, true);},
PageDown: function() {handle.moveFocus(handle.menuSize() - 1, true);},
Home: function() {handle.setFocus(0);},
End: function() {handle.setFocus(handle.length - 1);},
Enter: handle.pick,
Tab: handle.pick,
Esc: handle.close
};
var custom = completion.options.customKeys;
var ourMap = custom ? {} : baseMap;
function addBinding(key, val) {
var bound;
if (typeof val != "string")
bound = function(cm) { return val(cm, handle); };
// This mechanism is deprecated
else if (baseMap.hasOwnProperty(val))
bound = baseMap[val];
else
bound = val;
ourMap[key] = bound;
}
if (custom)
for (var key in custom) if (custom.hasOwnProperty(key))
addBinding(key, custom[key]);
var extra = completion.options.extraKeys;
if (extra)
for (var key in extra) if (extra.hasOwnProperty(key))
addBinding(key, extra[key]);
return ourMap;
}
function getHintElement(hintsElement, el) {
while (el && el != hintsElement) {
if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el;
el = el.parentNode;
}
}
function Widget(completion, data) {
this.completion = completion;
this.data = data;
this.picked = false;
var widget = this, cm = completion.cm;
var hints = this.hints = document.createElement("ul");
hints.className = "CodeMirror-hints";
this.selectedHint = data.selectedHint || 0;
var completions = data.list;
for (var i = 0; i < completions.length; ++i) {
var elt = hints.appendChild(document.createElement("li")), cur = completions[i];
var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS);
if (cur.className != null) className = cur.className + " " + className;
elt.className = className;
if (cur.render) cur.render(elt, data, cur);
else elt.appendChild(document.createTextNode(cur.displayText || getText(cur)));
elt.hintId = i;
}
var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null);
var left = pos.left, top = pos.bottom, below = true;
hints.style.left = left + "px";
hints.style.top = top + "px";
// If we're at the edge of the screen, then we want the menu to appear on the left of the cursor.
var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth);
var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
(completion.options.container || document.body).appendChild(hints);
var box = hints.getBoundingClientRect(), overlapY = box.bottom - winH;
if (overlapY > 0) {
var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top);
if (curTop - height > 0) { // Fits above cursor
hints.style.top = (top = pos.top - height) + "px";
below = false;
} else if (height > winH) {
hints.style.height = (winH - 5) + "px";
hints.style.top = (top = pos.bottom - box.top) + "px";
var cursor = cm.getCursor();
if (data.from.ch != cursor.ch) {
pos = cm.cursorCoords(cursor);
hints.style.left = (left = pos.left) + "px";
box = hints.getBoundingClientRect();
}
}
}
var overlapX = box.right - winW;
if (overlapX > 0) {
if (box.right - box.left > winW) {
hints.style.width = (winW - 5) + "px";
overlapX -= (box.right - box.left) - winW;
}
hints.style.left = (left = pos.left - overlapX) + "px";
}
cm.addKeyMap(this.keyMap = buildKeyMap(completion, {
moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); },
setFocus: function(n) { widget.changeActive(n); },
menuSize: function() { return widget.screenAmount(); },
length: completions.length,
close: function() { completion.close(); },
pick: function() { widget.pick(); },
data: data
}));
if (completion.options.closeOnUnfocus) {
var closingOnBlur;
cm.on("blur", this.onBlur = function() { closingOnBlur = setTimeout(function() { completion.close(); }, 100); });
cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
}
var startScroll = cm.getScrollInfo();
cm.on("scroll", this.onScroll = function() {
var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
var newTop = top + startScroll.top - curScroll.top;
var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop);
if (!below) point += hints.offsetHeight;
if (point <= editor.top || point >= editor.bottom) return completion.close();
hints.style.top = newTop + "px";
hints.style.left = (left + startScroll.left - curScroll.left) + "px";
});
CodeMirror.on(hints, "dblclick", function(e) {
var t = getHintElement(hints, e.target || e.srcElement);
if (t && t.hintId != null) {widget.changeActive(t.hintId); widget.pick();}
});
CodeMirror.on(hints, "click", function(e) {
var t = getHintElement(hints, e.target || e.srcElement);
if (t && t.hintId != null) {
widget.changeActive(t.hintId);
if (completion.options.completeOnSingleClick) widget.pick();
}
});
CodeMirror.on(hints, "mousedown", function() {
setTimeout(function(){cm.focus();}, 20);
});
CodeMirror.signal(data, "select", completions[0], hints.firstChild);
return true;
}
Widget.prototype = {
close: function() {
if (this.completion.widget != this) return;
this.completion.widget = null;
this.hints.parentNode.removeChild(this.hints);
this.completion.cm.removeKeyMap(this.keyMap);
var cm = this.completion.cm;
if (this.completion.options.closeOnUnfocus) {
cm.off("blur", this.onBlur);
cm.off("focus", this.onFocus);
}
cm.off("scroll", this.onScroll);
},
disable: function() {
this.completion.cm.removeKeyMap(this.keyMap);
var widget = this;
this.keyMap = {Enter: function() { widget.picked = true; }};
this.completion.cm.addKeyMap(this.keyMap);
},
pick: function() {
this.completion.pick(this.data, this.selectedHint);
},
changeActive: function(i, avoidWrap) {
if (i >= this.data.list.length)
i = avoidWrap ? this.data.list.length - 1 : 0;
else if (i < 0)
i = avoidWrap ? 0 : this.data.list.length - 1;
if (this.selectedHint == i) return;
var node = this.hints.childNodes[this.selectedHint];
node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, "");
node = this.hints.childNodes[this.selectedHint = i];
node.className += " " + ACTIVE_HINT_ELEMENT_CLASS;
if (node.offsetTop < this.hints.scrollTop)
this.hints.scrollTop = node.offsetTop - 3;
else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight)
this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3;
CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node);
},
screenAmount: function() {
return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1;
}
};
CodeMirror.registerHelper("hint", "auto", function(cm, options) {
var helpers = cm.getHelpers(cm.getCursor(), "hint"), words;
if (helpers.length) {
for (var i = 0; i < helpers.length; i++) {
var cur = helpers[i](cm, options);
if (cur && cur.list.length) return cur;
}
} else if (words = cm.getHelper(cm.getCursor(), "hintWords")) {
if (words) return CodeMirror.hint.fromList(cm, {words: words});
} else if (CodeMirror.hint.anyword) {
return CodeMirror.hint.anyword(cm, options);
}
});
CodeMirror.registerHelper("hint", "fromList", function(cm, options) {
var cur = cm.getCursor(), token = cm.getTokenAt(cur);
var to = CodeMirror.Pos(cur.line, token.end);
if (token.string && /\w/.test(token.string[token.string.length - 1])) {
var term = token.string, from = CodeMirror.Pos(cur.line, token.start);
} else {
var term = "", from = to;
}
var found = [];
for (var i = 0; i < options.words.length; i++) {
var word = options.words[i];
if (word.slice(0, term.length) == term)
found.push(word);
}
if (found.length) return {list: found, from: from, to: to};
});
CodeMirror.commands.autocomplete = CodeMirror.showHint;
var defaultOptions = {
hint: CodeMirror.hint.auto,
completeSingle: true,
alignWithWord: true,
closeCharacters: /[\s()\[\]{};:>,]/,
closeOnUnfocus: true,
completeOnSingleClick: false,
container: null,
customKeys: null,
extraKeys: null
};
CodeMirror.defineOption("hintOptions", null);
});
},{"../../lib/codemirror":25}],22:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var GUTTER_ID = "CodeMirror-lint-markers";
function showTooltip(e, content) {
var tt = document.createElement("div");
tt.className = "CodeMirror-lint-tooltip";
tt.appendChild(content.cloneNode(true));
document.body.appendChild(tt);
function position(e) {
if (!tt.parentNode) return CodeMirror.off(document, "mousemove", position);
tt.style.top = Math.max(0, e.clientY - tt.offsetHeight - 5) + "px";
tt.style.left = (e.clientX + 5) + "px";
}
CodeMirror.on(document, "mousemove", position);
position(e);
if (tt.style.opacity != null) tt.style.opacity = 1;
return tt;
}
function rm(elt) {
if (elt.parentNode) elt.parentNode.removeChild(elt);
}
function hideTooltip(tt) {
if (!tt.parentNode) return;
if (tt.style.opacity == null) rm(tt);
tt.style.opacity = 0;
setTimeout(function() { rm(tt); }, 600);
}
function showTooltipFor(e, content, node) {
var tooltip = showTooltip(e, content);
function hide() {
CodeMirror.off(node, "mouseout", hide);
if (tooltip) { hideTooltip(tooltip); tooltip = null; }
}
var poll = setInterval(function() {
if (tooltip) for (var n = node;; n = n.parentNode) {
if (n && n.nodeType == 11) n = n.host;
if (n == document.body) return;
if (!n) { hide(); break; }
}
if (!tooltip) return clearInterval(poll);
}, 400);
CodeMirror.on(node, "mouseout", hide);
}
function LintState(cm, options, hasGutter) {
this.marked = [];
this.options = options;
this.timeout = null;
this.hasGutter = hasGutter;
this.onMouseOver = function(e) { onMouseOver(cm, e); };
this.waitingFor = 0
}
function parseOptions(_cm, options) {
if (options instanceof Function) return {getAnnotations: options};
if (!options || options === true) options = {};
return options;
}
function clearMarks(cm) {
var state = cm.state.lint;
if (state.hasGutter) cm.clearGutter(GUTTER_ID);
for (var i = 0; i < state.marked.length; ++i)
state.marked[i].clear();
state.marked.length = 0;
}
function makeMarker(labels, severity, multiple, tooltips) {
var marker = document.createElement("div"), inner = marker;
marker.className = "CodeMirror-lint-marker-" + severity;
if (multiple) {
inner = marker.appendChild(document.createElement("div"));
inner.className = "CodeMirror-lint-marker-multiple";
}
if (tooltips != false) CodeMirror.on(inner, "mouseover", function(e) {
showTooltipFor(e, labels, inner);
});
return marker;
}
function getMaxSeverity(a, b) {
if (a == "error") return a;
else return b;
}
function groupByLine(annotations) {
var lines = [];
for (var i = 0; i < annotations.length; ++i) {
var ann = annotations[i], line = ann.from.line;
(lines[line] || (lines[line] = [])).push(ann);
}
return lines;
}
function annotationTooltip(ann) {
var severity = ann.severity;
if (!severity) severity = "error";
var tip = document.createElement("div");
tip.className = "CodeMirror-lint-message-" + severity;
tip.appendChild(document.createTextNode(ann.message));
return tip;
}
function lintAsync(cm, getAnnotations, passOptions) {
var state = cm.state.lint
var id = ++state.waitingFor
function abort() {
id = -1
cm.off("change", abort)
}
cm.on("change", abort)
getAnnotations(cm.getValue(), function(annotations, arg2) {
cm.off("change", abort)
if (state.waitingFor != id) return
if (arg2 && annotations instanceof CodeMirror) annotations = arg2
updateLinting(cm, annotations)
}, passOptions, cm);
}
function startLinting(cm) {
var state = cm.state.lint, options = state.options;
var passOptions = options.options || options; // Support deprecated passing of `options` property in options
var getAnnotations = options.getAnnotations || cm.getHelper(CodeMirror.Pos(0, 0), "lint");
if (!getAnnotations) return;
if (options.async || getAnnotations.async) {
lintAsync(cm, getAnnotations, passOptions)
} else {
updateLinting(cm, getAnnotations(cm.getValue(), passOptions, cm));
}
}
function updateLinting(cm, annotationsNotSorted) {
clearMarks(cm);
var state = cm.state.lint, options = state.options;
var annotations = groupByLine(annotationsNotSorted);
for (var line = 0; line < annotations.length; ++line) {
var anns = annotations[line];
if (!anns) continue;
var maxSeverity = null;
var tipLabel = state.hasGutter && document.createDocumentFragment();
for (var i = 0; i < anns.length; ++i) {
var ann = anns[i];
var severity = ann.severity;
if (!severity) severity = "error";
maxSeverity = getMaxSeverity(maxSeverity, severity);
if (options.formatAnnotation) ann = options.formatAnnotation(ann);
if (state.hasGutter) tipLabel.appendChild(annotationTooltip(ann));
if (ann.to) state.marked.push(cm.markText(ann.from, ann.to, {
className: "CodeMirror-lint-mark-" + severity,
__annotation: ann
}));
}
if (state.hasGutter)
cm.setGutterMarker(line, GUTTER_ID, makeMarker(tipLabel, maxSeverity, anns.length > 1,
state.options.tooltips));
}
if (options.onUpdateLinting) options.onUpdateLinting(annotationsNotSorted, annotations, cm);
}
function onChange(cm) {
var state = cm.state.lint;
if (!state) return;
clearTimeout(state.timeout);
state.timeout = setTimeout(function(){startLinting(cm);}, state.options.delay || 500);
}
function popupSpanTooltip(ann, e) {
var target = e.target || e.srcElement;
showTooltipFor(e, annotationTooltip(ann), target);
}
function onMouseOver(cm, e) {
var target = e.target || e.srcElement;
if (!/\bCodeMirror-lint-mark-/.test(target.className)) return;
var box = target.getBoundingClientRect(), x = (box.left + box.right) / 2, y = (box.top + box.bottom) / 2;
var spans = cm.findMarksAt(cm.coordsChar({left: x, top: y}, "client"));
for (var i = 0; i < spans.length; ++i) {
var ann = spans[i].__annotation;
if (ann) return popupSpanTooltip(ann, e);
}
}
CodeMirror.defineOption("lint", false, function(cm, val, old) {
if (old && old != CodeMirror.Init) {
clearMarks(cm);
if (cm.state.lint.options.lintOnChange !== false)
cm.off("change", onChange);
CodeMirror.off(cm.getWrapperElement(), "mouseover", cm.state.lint.onMouseOver);
clearTimeout(cm.state.lint.timeout);
delete cm.state.lint;
}
if (val) {
var gutters = cm.getOption("gutters"), hasLintGutter = false;
for (var i = 0; i < gutters.length; ++i) if (gutters[i] == GUTTER_ID) hasLintGutter = true;
var state = cm.state.lint = new LintState(cm, parseOptions(cm, val), hasLintGutter);
if (state.options.lintOnChange !== false)
cm.on("change", onChange);
if (state.options.tooltips != false)
CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver);
startLinting(cm);
}
});
CodeMirror.defineExtension("performLint", function() {
if (this.state.lint) startLinting(this);
});
});
},{"../../lib/codemirror":25}],23:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var Pos = CodeMirror.Pos;
function SearchCursor(doc, query, pos, caseFold) {
this.atOccurrence = false; this.doc = doc;
if (caseFold == null && typeof query == "string") caseFold = false;
pos = pos ? doc.clipPos(pos) : Pos(0, 0);
this.pos = {from: pos, to: pos};
// The matches method is filled in based on the type of query.
// It takes a position and a direction, and returns an object
// describing the next occurrence of the query, or null if no
// more matches were found.
if (typeof query != "string") { // Regexp match
if (!query.global) query = new RegExp(query.source, query.ignoreCase ? "ig" : "g");
this.matches = function(reverse, pos) {
if (reverse) {
query.lastIndex = 0;
var line = doc.getLine(pos.line).slice(0, pos.ch), cutOff = 0, match, start;
for (;;) {
query.lastIndex = cutOff;
var newMatch = query.exec(line);
if (!newMatch) break;
match = newMatch;
start = match.index;
cutOff = match.index + (match[0].length || 1);
if (cutOff == line.length) break;
}
var matchLen = (match && match[0].length) || 0;
if (!matchLen) {
if (start == 0 && line.length == 0) {match = undefined;}
else if (start != doc.getLine(pos.line).length) {
matchLen++;
}
}
} else {
query.lastIndex = pos.ch;
var line = doc.getLine(pos.line), match = query.exec(line);
var matchLen = (match && match[0].length) || 0;
var start = match && match.index;
if (start + matchLen != line.length && !matchLen) matchLen = 1;
}
if (match && matchLen)
return {from: Pos(pos.line, start),
to: Pos(pos.line, start + matchLen),
match: match};
};
} else { // String query
var origQuery = query;
if (caseFold) query = query.toLowerCase();
var fold = caseFold ? function(str){return str.toLowerCase();} : function(str){return str;};
var target = query.split("\n");
// Different methods for single-line and multi-line queries
if (target.length == 1) {
if (!query.length) {
// Empty string would match anything and never progress, so
// we define it to match nothing instead.
this.matches = function() {};
} else {
this.matches = function(reverse, pos) {
if (reverse) {
var orig = doc.getLine(pos.line).slice(0, pos.ch), line = fold(orig);
var match = line.lastIndexOf(query);
if (match > -1) {
match = adjustPos(orig, line, match);
return {from: Pos(pos.line, match), to: Pos(pos.line, match + origQuery.length)};
}
} else {
var orig = doc.getLine(pos.line).slice(pos.ch), line = fold(orig);
var match = line.indexOf(query);
if (match > -1) {
match = adjustPos(orig, line, match) + pos.ch;
return {from: Pos(pos.line, match), to: Pos(pos.line, match + origQuery.length)};
}
}
};
}
} else {
var origTarget = origQuery.split("\n");
this.matches = function(reverse, pos) {
var last = target.length - 1;
if (reverse) {
if (pos.line - (target.length - 1) < doc.firstLine()) return;
if (fold(doc.getLine(pos.line).slice(0, origTarget[last].length)) != target[target.length - 1]) return;
var to = Pos(pos.line, origTarget[last].length);
for (var ln = pos.line - 1, i = last - 1; i >= 1; --i, --ln)
if (target[i] != fold(doc.getLine(ln))) return;
var line = doc.getLine(ln), cut = line.length - origTarget[0].length;
if (fold(line.slice(cut)) != target[0]) return;
return {from: Pos(ln, cut), to: to};
} else {
if (pos.line + (target.length - 1) > doc.lastLine()) return;
var line = doc.getLine(pos.line), cut = line.length - origTarget[0].length;
if (fold(line.slice(cut)) != target[0]) return;
var from = Pos(pos.line, cut);
for (var ln = pos.line + 1, i = 1; i < last; ++i, ++ln)
if (target[i] != fold(doc.getLine(ln))) return;
if (fold(doc.getLine(ln).slice(0, origTarget[last].length)) != target[last]) return;
return {from: from, to: Pos(ln, origTarget[last].length)};
}
};
}
}
}
SearchCursor.prototype = {
findNext: function() {return this.find(false);},
findPrevious: function() {return this.find(true);},
find: function(reverse) {
var self = this, pos = this.doc.clipPos(reverse ? this.pos.from : this.pos.to);
function savePosAndFail(line) {
var pos = Pos(line, 0);
self.pos = {from: pos, to: pos};
self.atOccurrence = false;
return false;
}
for (;;) {
if (this.pos = this.matches(reverse, pos)) {
this.atOccurrence = true;
return this.pos.match || true;
}
if (reverse) {
if (!pos.line) return savePosAndFail(0);
pos = Pos(pos.line-1, this.doc.getLine(pos.line-1).length);
}
else {
var maxLine = this.doc.lineCount();
if (pos.line == maxLine - 1) return savePosAndFail(maxLine);
pos = Pos(pos.line + 1, 0);
}
}
},
from: function() {if (this.atOccurrence) return this.pos.from;},
to: function() {if (this.atOccurrence) return this.pos.to;},
replace: function(newText, origin) {
if (!this.atOccurrence) return;
var lines = CodeMirror.splitLines(newText);
this.doc.replaceRange(lines, this.pos.from, this.pos.to, origin);
this.pos.to = Pos(this.pos.from.line + lines.length - 1,
lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0));
}
};
// Maps a position in a case-folded line back to a position in the original line
// (compensating for codepoints increasing in number during folding)
function adjustPos(orig, folded, pos) {
if (orig.length == folded.length) return pos;
for (var pos1 = Math.min(pos, orig.length);;) {
var len1 = orig.slice(0, pos1).toLowerCase().length;
if (len1 < pos) ++pos1;
else if (len1 > pos) --pos1;
else return pos1;
}
}
CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) {
return new SearchCursor(this.doc, query, pos, caseFold);
});
CodeMirror.defineDocExtension("getSearchCursor", function(query, pos, caseFold) {
return new SearchCursor(this, query, pos, caseFold);
});
CodeMirror.defineExtension("selectMatches", function(query, caseFold) {
var ranges = [];
var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold);
while (cur.findNext()) {
if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) break;
ranges.push({anchor: cur.from(), head: cur.to()});
}
if (ranges.length)
this.setSelections(ranges, 0);
});
});
},{"../../lib/codemirror":25}],24:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
// A rough approximation of Sublime Text's keybindings
// Depends on addon/search/searchcursor.js and optionally addon/dialog/dialogs.js
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../lib/codemirror"), require("../addon/search/searchcursor"), require("../addon/edit/matchbrackets"));
else if (typeof define == "function" && define.amd) // AMD
define(["../lib/codemirror", "../addon/search/searchcursor", "../addon/edit/matchbrackets"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var map = CodeMirror.keyMap.sublime = {fallthrough: "default"};
var cmds = CodeMirror.commands;
var Pos = CodeMirror.Pos;
var mac = CodeMirror.keyMap["default"] == CodeMirror.keyMap.macDefault;
var ctrl = mac ? "Cmd-" : "Ctrl-";
// This is not exactly Sublime's algorithm. I couldn't make heads or tails of that.
function findPosSubword(doc, start, dir) {
if (dir < 0 && start.ch == 0) return doc.clipPos(Pos(start.line - 1));
var line = doc.getLine(start.line);
if (dir > 0 && start.ch >= line.length) return doc.clipPos(Pos(start.line + 1, 0));
var state = "start", type;
for (var pos = start.ch, e = dir < 0 ? 0 : line.length, i = 0; pos != e; pos += dir, i++) {
var next = line.charAt(dir < 0 ? pos - 1 : pos);
var cat = next != "_" && CodeMirror.isWordChar(next) ? "w" : "o";
if (cat == "w" && next.toUpperCase() == next) cat = "W";
if (state == "start") {
if (cat != "o") { state = "in"; type = cat; }
} else if (state == "in") {
if (type != cat) {
if (type == "w" && cat == "W" && dir < 0) pos--;
if (type == "W" && cat == "w" && dir > 0) { type = "w"; continue; }
break;
}
}
}
return Pos(start.line, pos);
}
function moveSubword(cm, dir) {
cm.extendSelectionsBy(function(range) {
if (cm.display.shift || cm.doc.extend || range.empty())
return findPosSubword(cm.doc, range.head, dir);
else
return dir < 0 ? range.from() : range.to();
});
}
cmds[map["Alt-Left"] = "goSubwordLeft"] = function(cm) { moveSubword(cm, -1); };
cmds[map["Alt-Right"] = "goSubwordRight"] = function(cm) { moveSubword(cm, 1); };
var scrollLineCombo = mac ? "Ctrl-Alt-" : "Ctrl-";
cmds[map[scrollLineCombo + "Up"] = "scrollLineUp"] = function(cm) {
var info = cm.getScrollInfo();
if (!cm.somethingSelected()) {
var visibleBottomLine = cm.lineAtHeight(info.top + info.clientHeight, "local");
if (cm.getCursor().line >= visibleBottomLine)
cm.execCommand("goLineUp");
}
cm.scrollTo(null, info.top - cm.defaultTextHeight());
};
cmds[map[scrollLineCombo + "Down"] = "scrollLineDown"] = function(cm) {
var info = cm.getScrollInfo();
if (!cm.somethingSelected()) {
var visibleTopLine = cm.lineAtHeight(info.top, "local")+1;
if (cm.getCursor().line <= visibleTopLine)
cm.execCommand("goLineDown");
}
cm.scrollTo(null, info.top + cm.defaultTextHeight());
};
cmds[map["Shift-" + ctrl + "L"] = "splitSelectionByLine"] = function(cm) {
var ranges = cm.listSelections(), lineRanges = [];
for (var i = 0; i < ranges.length; i++) {
var from = ranges[i].from(), to = ranges[i].to();
for (var line = from.line; line <= to.line; ++line)
if (!(to.line > from.line && line == to.line && to.ch == 0))
lineRanges.push({anchor: line == from.line ? from : Pos(line, 0),
head: line == to.line ? to : Pos(line)});
}
cm.setSelections(lineRanges, 0);
};
map["Shift-Tab"] = "indentLess";
cmds[map["Esc"] = "singleSelectionTop"] = function(cm) {
var range = cm.listSelections()[0];
cm.setSelection(range.anchor, range.head, {scroll: false});
};
cmds[map[ctrl + "L"] = "selectLine"] = function(cm) {
var ranges = cm.listSelections(), extended = [];
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
extended.push({anchor: Pos(range.from().line, 0),
head: Pos(range.to().line + 1, 0)});
}
cm.setSelections(extended);
};
map["Shift-" + ctrl + "K"] = "deleteLine";
function insertLine(cm, above) {
cm.operation(function() {
var len = cm.listSelections().length, newSelection = [], last = -1;
for (var i = 0; i < len; i++) {
var head = cm.listSelections()[i].head;
if (head.line <= last) continue;
var at = Pos(head.line + (above ? 0 : 1), 0);
cm.replaceRange("\n", at, null, "+insertLine");
cm.indentLine(at.line, null, true);
newSelection.push({head: at, anchor: at});
last = head.line + 1;
}
cm.setSelections(newSelection);
});
}
cmds[map[ctrl + "Enter"] = "insertLineAfter"] = function(cm) { insertLine(cm, false); };
cmds[map["Shift-" + ctrl + "Enter"] = "insertLineBefore"] = function(cm) { insertLine(cm, true); };
function wordAt(cm, pos) {
var start = pos.ch, end = start, line = cm.getLine(pos.line);
while (start && CodeMirror.isWordChar(line.charAt(start - 1))) --start;
while (end < line.length && CodeMirror.isWordChar(line.charAt(end))) ++end;
return {from: Pos(pos.line, start), to: Pos(pos.line, end), word: line.slice(start, end)};
}
cmds[map[ctrl + "D"] = "selectNextOccurrence"] = function(cm) {
var from = cm.getCursor("from"), to = cm.getCursor("to");
var fullWord = cm.state.sublimeFindFullWord == cm.doc.sel;
if (CodeMirror.cmpPos(from, to) == 0) {
var word = wordAt(cm, from);
if (!word.word) return;
cm.setSelection(word.from, word.to);
fullWord = true;
} else {
var text = cm.getRange(from, to);
var query = fullWord ? new RegExp("\\b" + text + "\\b") : text;
var cur = cm.getSearchCursor(query, to);
if (cur.findNext()) {
cm.addSelection(cur.from(), cur.to());
} else {
cur = cm.getSearchCursor(query, Pos(cm.firstLine(), 0));
if (cur.findNext())
cm.addSelection(cur.from(), cur.to());
}
}
if (fullWord)
cm.state.sublimeFindFullWord = cm.doc.sel;
};
var mirror = "(){}[]";
function selectBetweenBrackets(cm) {
var pos = cm.getCursor(), opening = cm.scanForBracket(pos, -1);
if (!opening) return;
for (;;) {
var closing = cm.scanForBracket(pos, 1);
if (!closing) return;
if (closing.ch == mirror.charAt(mirror.indexOf(opening.ch) + 1)) {
cm.setSelection(Pos(opening.pos.line, opening.pos.ch + 1), closing.pos, false);
return true;
}
pos = Pos(closing.pos.line, closing.pos.ch + 1);
}
}
cmds[map["Shift-" + ctrl + "Space"] = "selectScope"] = function(cm) {
selectBetweenBrackets(cm) || cm.execCommand("selectAll");
};
cmds[map["Shift-" + ctrl + "M"] = "selectBetweenBrackets"] = function(cm) {
if (!selectBetweenBrackets(cm)) return CodeMirror.Pass;
};
cmds[map[ctrl + "M"] = "goToBracket"] = function(cm) {
cm.extendSelectionsBy(function(range) {
var next = cm.scanForBracket(range.head, 1);
if (next && CodeMirror.cmpPos(next.pos, range.head) != 0) return next.pos;
var prev = cm.scanForBracket(range.head, -1);
return prev && Pos(prev.pos.line, prev.pos.ch + 1) || range.head;
});
};
var swapLineCombo = mac ? "Cmd-Ctrl-" : "Shift-Ctrl-";
cmds[map[swapLineCombo + "Up"] = "swapLineUp"] = function(cm) {
var ranges = cm.listSelections(), linesToMove = [], at = cm.firstLine() - 1, newSels = [];
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i], from = range.from().line - 1, to = range.to().line;
newSels.push({anchor: Pos(range.anchor.line - 1, range.anchor.ch),
head: Pos(range.head.line - 1, range.head.ch)});
if (range.to().ch == 0 && !range.empty()) --to;
if (from > at) linesToMove.push(from, to);
else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to;
at = to;
}
cm.operation(function() {
for (var i = 0; i < linesToMove.length; i += 2) {
var from = linesToMove[i], to = linesToMove[i + 1];
var line = cm.getLine(from);
cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine");
if (to > cm.lastLine())
cm.replaceRange("\n" + line, Pos(cm.lastLine()), null, "+swapLine");
else
cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine");
}
cm.setSelections(newSels);
cm.scrollIntoView();
});
};
cmds[map[swapLineCombo + "Down"] = "swapLineDown"] = function(cm) {
var ranges = cm.listSelections(), linesToMove = [], at = cm.lastLine() + 1;
for (var i = ranges.length - 1; i >= 0; i--) {
var range = ranges[i], from = range.to().line + 1, to = range.from().line;
if (range.to().ch == 0 && !range.empty()) from--;
if (from < at) linesToMove.push(from, to);
else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to;
at = to;
}
cm.operation(function() {
for (var i = linesToMove.length - 2; i >= 0; i -= 2) {
var from = linesToMove[i], to = linesToMove[i + 1];
var line = cm.getLine(from);
if (from == cm.lastLine())
cm.replaceRange("", Pos(from - 1), Pos(from), "+swapLine");
else
cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine");
cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine");
}
cm.scrollIntoView();
});
};
map[ctrl + "/"] = "toggleComment";
cmds[map[ctrl + "J"] = "joinLines"] = function(cm) {
var ranges = cm.listSelections(), joined = [];
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i], from = range.from();
var start = from.line, end = range.to().line;
while (i < ranges.length - 1 && ranges[i + 1].from().line == end)
end = ranges[++i].to().line;
joined.push({start: start, end: end, anchor: !range.empty() && from});
}
cm.operation(function() {
var offset = 0, ranges = [];
for (var i = 0; i < joined.length; i++) {
var obj = joined[i];
var anchor = obj.anchor && Pos(obj.anchor.line - offset, obj.anchor.ch), head;
for (var line = obj.start; line <= obj.end; line++) {
var actual = line - offset;
if (line == obj.end) head = Pos(actual, cm.getLine(actual).length + 1);
if (actual < cm.lastLine()) {
cm.replaceRange(" ", Pos(actual), Pos(actual + 1, /^\s*/.exec(cm.getLine(actual + 1))[0].length));
++offset;
}
}
ranges.push({anchor: anchor || head, head: head});
}
cm.setSelections(ranges, 0);
});
};
cmds[map["Shift-" + ctrl + "D"] = "duplicateLine"] = function(cm) {
cm.operation(function() {
var rangeCount = cm.listSelections().length;
for (var i = 0; i < rangeCount; i++) {
var range = cm.listSelections()[i];
if (range.empty())
cm.replaceRange(cm.getLine(range.head.line) + "\n", Pos(range.head.line, 0));
else
cm.replaceRange(cm.getRange(range.from(), range.to()), range.from());
}
cm.scrollIntoView();
});
};
map[ctrl + "T"] = "transposeChars";
function sortLines(cm, caseSensitive) {
var ranges = cm.listSelections(), toSort = [], selected;
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (range.empty()) continue;
var from = range.from().line, to = range.to().line;
while (i < ranges.length - 1 && ranges[i + 1].from().line == to)
to = range[++i].to().line;
toSort.push(from, to);
}
if (toSort.length) selected = true;
else toSort.push(cm.firstLine(), cm.lastLine());
cm.operation(function() {
var ranges = [];
for (var i = 0; i < toSort.length; i += 2) {
var from = toSort[i], to = toSort[i + 1];
var start = Pos(from, 0), end = Pos(to);
var lines = cm.getRange(start, end, false);
if (caseSensitive)
lines.sort();
else
lines.sort(function(a, b) {
var au = a.toUpperCase(), bu = b.toUpperCase();
if (au != bu) { a = au; b = bu; }
return a < b ? -1 : a == b ? 0 : 1;
});
cm.replaceRange(lines, start, end);
if (selected) ranges.push({anchor: start, head: end});
}
if (selected) cm.setSelections(ranges, 0);
});
}
cmds[map["F9"] = "sortLines"] = function(cm) { sortLines(cm, true); };
cmds[map[ctrl + "F9"] = "sortLinesInsensitive"] = function(cm) { sortLines(cm, false); };
cmds[map["F2"] = "nextBookmark"] = function(cm) {
var marks = cm.state.sublimeBookmarks;
if (marks) while (marks.length) {
var current = marks.shift();
var found = current.find();
if (found) {
marks.push(current);
return cm.setSelection(found.from, found.to);
}
}
};
cmds[map["Shift-F2"] = "prevBookmark"] = function(cm) {
var marks = cm.state.sublimeBookmarks;
if (marks) while (marks.length) {
marks.unshift(marks.pop());
var found = marks[marks.length - 1].find();
if (!found)
marks.pop();
else
return cm.setSelection(found.from, found.to);
}
};
cmds[map[ctrl + "F2"] = "toggleBookmark"] = function(cm) {
var ranges = cm.listSelections();
var marks = cm.state.sublimeBookmarks || (cm.state.sublimeBookmarks = []);
for (var i = 0; i < ranges.length; i++) {
var from = ranges[i].from(), to = ranges[i].to();
var found = cm.findMarks(from, to);
for (var j = 0; j < found.length; j++) {
if (found[j].sublimeBookmark) {
found[j].clear();
for (var k = 0; k < marks.length; k++)
if (marks[k] == found[j])
marks.splice(k--, 1);
break;
}
}
if (j == found.length)
marks.push(cm.markText(from, to, {sublimeBookmark: true, clearWhenEmpty: false}));
}
};
cmds[map["Shift-" + ctrl + "F2"] = "clearBookmarks"] = function(cm) {
var marks = cm.state.sublimeBookmarks;
if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear();
marks.length = 0;
};
cmds[map["Alt-F2"] = "selectBookmarks"] = function(cm) {
var marks = cm.state.sublimeBookmarks, ranges = [];
if (marks) for (var i = 0; i < marks.length; i++) {
var found = marks[i].find();
if (!found)
marks.splice(i--, 0);
else
ranges.push({anchor: found.from, head: found.to});
}
if (ranges.length)
cm.setSelections(ranges, 0);
};
map["Alt-Q"] = "wrapLines";
var cK = ctrl + "K ";
function modifyWordOrSelection(cm, mod) {
cm.operation(function() {
var ranges = cm.listSelections(), indices = [], replacements = [];
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (range.empty()) { indices.push(i); replacements.push(""); }
else replacements.push(mod(cm.getRange(range.from(), range.to())));
}
cm.replaceSelections(replacements, "around", "case");
for (var i = indices.length - 1, at; i >= 0; i--) {
var range = ranges[indices[i]];
if (at && CodeMirror.cmpPos(range.head, at) > 0) continue;
var word = wordAt(cm, range.head);
at = word.from;
cm.replaceRange(mod(word.word), word.from, word.to);
}
});
}
map[cK + ctrl + "Backspace"] = "delLineLeft";
cmds[map["Backspace"] = "smartBackspace"] = function(cm) {
if (cm.somethingSelected()) return CodeMirror.Pass;
var cursor = cm.getCursor();
var toStartOfLine = cm.getRange({line: cursor.line, ch: 0}, cursor);
var column = CodeMirror.countColumn(toStartOfLine, null, cm.getOption("tabSize"));
var indentUnit = cm.getOption("indentUnit");
if (toStartOfLine && !/\S/.test(toStartOfLine) && column % indentUnit == 0) {
var prevIndent = new Pos(cursor.line,
CodeMirror.findColumn(toStartOfLine, column - indentUnit, indentUnit));
// If no smart delete is happening (due to tab sizing) just do a regular delete
if (prevIndent.ch == cursor.ch) return CodeMirror.Pass;
return cm.replaceRange("", prevIndent, cursor, "+delete");
} else {
return CodeMirror.Pass;
}
};
cmds[map[cK + ctrl + "K"] = "delLineRight"] = function(cm) {
cm.operation(function() {
var ranges = cm.listSelections();
for (var i = ranges.length - 1; i >= 0; i--)
cm.replaceRange("", ranges[i].anchor, Pos(ranges[i].to().line), "+delete");
cm.scrollIntoView();
});
};
cmds[map[cK + ctrl + "U"] = "upcaseAtCursor"] = function(cm) {
modifyWordOrSelection(cm, function(str) { return str.toUpperCase(); });
};
cmds[map[cK + ctrl + "L"] = "downcaseAtCursor"] = function(cm) {
modifyWordOrSelection(cm, function(str) { return str.toLowerCase(); });
};
cmds[map[cK + ctrl + "Space"] = "setSublimeMark"] = function(cm) {
if (cm.state.sublimeMark) cm.state.sublimeMark.clear();
cm.state.sublimeMark = cm.setBookmark(cm.getCursor());
};
cmds[map[cK + ctrl + "A"] = "selectToSublimeMark"] = function(cm) {
var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
if (found) cm.setSelection(cm.getCursor(), found);
};
cmds[map[cK + ctrl + "W"] = "deleteToSublimeMark"] = function(cm) {
var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
if (found) {
var from = cm.getCursor(), to = found;
if (CodeMirror.cmpPos(from, to) > 0) { var tmp = to; to = from; from = tmp; }
cm.state.sublimeKilled = cm.getRange(from, to);
cm.replaceRange("", from, to);
}
};
cmds[map[cK + ctrl + "X"] = "swapWithSublimeMark"] = function(cm) {
var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
if (found) {
cm.state.sublimeMark.clear();
cm.state.sublimeMark = cm.setBookmark(cm.getCursor());
cm.setCursor(found);
}
};
cmds[map[cK + ctrl + "Y"] = "sublimeYank"] = function(cm) {
if (cm.state.sublimeKilled != null)
cm.replaceSelection(cm.state.sublimeKilled, null, "paste");
};
map[cK + ctrl + "G"] = "clearBookmarks";
cmds[map[cK + ctrl + "C"] = "showInCenter"] = function(cm) {
var pos = cm.cursorCoords(null, "local");
cm.scrollTo(null, (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2);
};
cmds[map["Shift-Alt-Up"] = "selectLinesUpward"] = function(cm) {
cm.operation(function() {
var ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (range.head.line > cm.firstLine())
cm.addSelection(Pos(range.head.line - 1, range.head.ch));
}
});
};
cmds[map["Shift-Alt-Down"] = "selectLinesDownward"] = function(cm) {
cm.operation(function() {
var ranges = cm.listSelections();
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (range.head.line < cm.lastLine())
cm.addSelection(Pos(range.head.line + 1, range.head.ch));
}
});
};
function getTarget(cm) {
var from = cm.getCursor("from"), to = cm.getCursor("to");
if (CodeMirror.cmpPos(from, to) == 0) {
var word = wordAt(cm, from);
if (!word.word) return;
from = word.from;
to = word.to;
}
return {from: from, to: to, query: cm.getRange(from, to), word: word};
}
function findAndGoTo(cm, forward) {
var target = getTarget(cm);
if (!target) return;
var query = target.query;
var cur = cm.getSearchCursor(query, forward ? target.to : target.from);
if (forward ? cur.findNext() : cur.findPrevious()) {
cm.setSelection(cur.from(), cur.to());
} else {
cur = cm.getSearchCursor(query, forward ? Pos(cm.firstLine(), 0)
: cm.clipPos(Pos(cm.lastLine())));
if (forward ? cur.findNext() : cur.findPrevious())
cm.setSelection(cur.from(), cur.to());
else if (target.word)
cm.setSelection(target.from, target.to);
}
};
cmds[map[ctrl + "F3"] = "findUnder"] = function(cm) { findAndGoTo(cm, true); };
cmds[map["Shift-" + ctrl + "F3"] = "findUnderPrevious"] = function(cm) { findAndGoTo(cm,false); };
cmds[map["Alt-F3"] = "findAllUnder"] = function(cm) {
var target = getTarget(cm);
if (!target) return;
var cur = cm.getSearchCursor(target.query);
var matches = [];
var primaryIndex = -1;
while (cur.findNext()) {
matches.push({anchor: cur.from(), head: cur.to()});
if (cur.from().line <= target.from.line && cur.from().ch <= target.from.ch)
primaryIndex++;
}
cm.setSelections(matches, primaryIndex);
};
map["Shift-" + ctrl + "["] = "fold";
map["Shift-" + ctrl + "]"] = "unfold";
map[cK + ctrl + "0"] = map[cK + ctrl + "j"] = "unfoldAll";
map[ctrl + "I"] = "findIncremental";
map["Shift-" + ctrl + "I"] = "findIncrementalReverse";
map[ctrl + "H"] = "replace";
map["F3"] = "findNext";
map["Shift-F3"] = "findPrev";
CodeMirror.normalizeKeyMap(map);
});
},{"../addon/edit/matchbrackets":17,"../addon/search/searchcursor":23,"../lib/codemirror":25}],25:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
// This is CodeMirror (http://codemirror.net), a code editor
// implemented in JavaScript on top of the browser's DOM.
//
// You can find some technical background for some of the code below
// at http://marijnhaverbeke.nl/blog/#cm-internals .
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
module.exports = mod();
else if (typeof define == "function" && define.amd) // AMD
return define([], mod);
else // Plain browser env
this.CodeMirror = mod();
})(function() {
"use strict";
// BROWSER SNIFFING
// Kludges for bugs and behavior differences that can't be feature
// detected are enabled based on userAgent etc sniffing.
var gecko = /gecko\/\d/i.test(navigator.userAgent);
var ie_upto10 = /MSIE \d/.test(navigator.userAgent);
var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
var ie = ie_upto10 || ie_11up;
var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);
var webkit = /WebKit\//.test(navigator.userAgent);
var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent);
var chrome = /Chrome\//.test(navigator.userAgent);
var presto = /Opera\//.test(navigator.userAgent);
var safari = /Apple Computer/.test(navigator.vendor);
var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent);
var phantom = /PhantomJS/.test(navigator.userAgent);
var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent);
// This is woefully incomplete. Suggestions for alternative methods welcome.
var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent);
var mac = ios || /Mac/.test(navigator.platform);
var windows = /win/i.test(navigator.platform);
var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/);
if (presto_version) presto_version = Number(presto_version[1]);
if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
// Some browsers use the wrong event properties to signal cmd/ctrl on OS X
var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
var captureRightClick = gecko || (ie && ie_version >= 9);
// Optimize some code when these features are not used.
var sawReadOnlySpans = false, sawCollapsedSpans = false;
// EDITOR CONSTRUCTOR
// A CodeMirror instance represents an editor. This is the object
// that user code is usually dealing with.
function CodeMirror(place, options) {
if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
this.options = options = options ? copyObj(options) : {};
// Determine effective options based on given values and defaults.
copyObj(defaults, options, false);
setGuttersForLineNumbers(options);
var doc = options.value;
if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator);
this.doc = doc;
var input = new CodeMirror.inputStyles[options.inputStyle](this);
var display = this.display = new Display(place, doc, input);
display.wrapper.CodeMirror = this;
updateGutters(this);
themeChanged(this);
if (options.lineWrapping)
this.display.wrapper.className += " CodeMirror-wrap";
if (options.autofocus && !mobile) display.input.focus();
initScrollbars(this);
this.state = {
keyMaps: [], // stores maps added by addKeyMap
overlays: [], // highlighting overlays, as added by addOverlay
modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
overwrite: false,
delayingBlurEvent: false,
focused: false,
suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
selectingText: false,
draggingText: false,
highlight: new Delayed(), // stores highlight worker timeout
keySeq: null, // Unfinished key sequence
specialChars: null
};
var cm = this;
// Override magic textarea content restore that IE sometimes does
// on our hidden textarea on reload
if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20);
registerEventHandlers(this);
ensureGlobalHandlers();
startOperation(this);
this.curOp.forceUpdate = true;
attachDoc(this, doc);
if ((options.autofocus && !mobile) || cm.hasFocus())
setTimeout(bind(onFocus, this), 20);
else
onBlur(this);
for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
optionHandlers[opt](this, options[opt], Init);
maybeUpdateLineNumberWidth(this);
if (options.finishInit) options.finishInit(this);
for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
endOperation(this);
// Suppress optimizelegibility in Webkit, since it breaks text
// measuring on line wrapping boundaries.
if (webkit && options.lineWrapping &&
getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
display.lineDiv.style.textRendering = "auto";
}
// DISPLAY CONSTRUCTOR
// The display handles the DOM integration, both for input reading
// and content drawing. It holds references to DOM nodes and
// display-related state.
function Display(place, doc, input) {
var d = this;
this.input = input;
// Covers bottom-right square when both scrollbars are present.
d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
d.scrollbarFiller.setAttribute("cm-not-content", "true");
// Covers bottom of gutter when coverGutterNextToScrollbar is on
// and h scrollbar is present.
d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
d.gutterFiller.setAttribute("cm-not-content", "true");
// Will contain the actual code, positioned to cover the viewport.
d.lineDiv = elt("div", null, "CodeMirror-code");
// Elements are added to these to represent selection and cursors.
d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
d.cursorDiv = elt("div", null, "CodeMirror-cursors");
// A visibility: hidden element used to find the size of things.
d.measure = elt("div", null, "CodeMirror-measure");
// When lines outside of the viewport are measured, they are drawn in this.
d.lineMeasure = elt("div", null, "CodeMirror-measure");
// Wraps everything that needs to exist inside the vertically-padded coordinate system
d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
null, "position: relative; outline: none");
// Moved around its parent to cover visible view.
d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
// Set to the height of the document, allowing scrolling.
d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
d.sizerWidth = null;
// Behavior of elts with overflow: auto and padding is
// inconsistent across browsers. This is used to ensure the
// scrollable area is big enough.
d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
// Will contain the gutters, if any.
d.gutters = elt("div", null, "CodeMirror-gutters");
d.lineGutter = null;
// Actual scrollable element.
d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
d.scroller.setAttribute("tabIndex", "-1");
// The element in which the editor lives.
d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
// Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
if (!webkit && !(gecko && mobile)) d.scroller.draggable = true;
if (place) {
if (place.appendChild) place.appendChild(d.wrapper);
else place(d.wrapper);
}
// Current rendered range (may be bigger than the view window).
d.viewFrom = d.viewTo = doc.first;
d.reportedViewFrom = d.reportedViewTo = doc.first;
// Information about the rendered lines.
d.view = [];
d.renderedView = null;
// Holds info about a single rendered line when it was rendered
// for measurement, while not in view.
d.externalMeasured = null;
// Empty space (in pixels) above the view
d.viewOffset = 0;
d.lastWrapHeight = d.lastWrapWidth = 0;
d.updateLineNumbers = null;
d.nativeBarWidth = d.barHeight = d.barWidth = 0;
d.scrollbarsClipped = false;
// Used to only resize the line number gutter when necessary (when
// the amount of lines crosses a boundary that makes its width change)
d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
// Set to true when a non-horizontal-scrolling line widget is
// added. As an optimization, line widget aligning is skipped when
// this is false.
d.alignWidgets = false;
d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
// Tracks the maximum line length so that the horizontal scrollbar
// can be kept static when scrolling.
d.maxLine = null;
d.maxLineLength = 0;
d.maxLineChanged = false;
// Used for measuring wheel scrolling granularity
d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
// True when shift is held down.
d.shift = false;
// Used to track whether anything happened since the context menu
// was opened.
d.selForContextMenu = null;
d.activeTouch = null;
input.init(d);
}
// STATE UPDATES
// Used to get the editor into a consistent state again when options change.
function loadMode(cm) {
cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
resetModeState(cm);
}
function resetModeState(cm) {
cm.doc.iter(function(line) {
if (line.stateAfter) line.stateAfter = null;
if (line.styles) line.styles = null;
});
cm.doc.frontier = cm.doc.first;
startWorker(cm, 100);
cm.state.modeGen++;
if (cm.curOp) regChange(cm);
}
function wrappingChanged(cm) {
if (cm.options.lineWrapping) {
addClass(cm.display.wrapper, "CodeMirror-wrap");
cm.display.sizer.style.minWidth = "";
cm.display.sizerWidth = null;
} else {
rmClass(cm.display.wrapper, "CodeMirror-wrap");
findMaxLine(cm);
}
estimateLineHeights(cm);
regChange(cm);
clearCaches(cm);
setTimeout(function(){updateScrollbars(cm);}, 100);
}
// Returns a function that estimates the height of a line, to use as
// first approximation until the line becomes visible (and is thus
// properly measurable).
function estimateHeight(cm) {
var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
return function(line) {
if (lineIsHidden(cm.doc, line)) return 0;
var widgetsHeight = 0;
if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
}
if (wrapping)
return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
else
return widgetsHeight + th;
};
}
function estimateLineHeights(cm) {
var doc = cm.doc, est = estimateHeight(cm);
doc.iter(function(line) {
var estHeight = est(line);
if (estHeight != line.height) updateLineHeight(line, estHeight);
});
}
function themeChanged(cm) {
cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
clearCaches(cm);
}
function guttersChanged(cm) {
updateGutters(cm);
regChange(cm);
setTimeout(function(){alignHorizontally(cm);}, 20);
}
// Rebuild the gutter elements, ensure the margin to the left of the
// code matches their width.
function updateGutters(cm) {
var gutters = cm.display.gutters, specs = cm.options.gutters;
removeChildren(gutters);
for (var i = 0; i < specs.length; ++i) {
var gutterClass = specs[i];
var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
if (gutterClass == "CodeMirror-linenumbers") {
cm.display.lineGutter = gElt;
gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
}
}
gutters.style.display = i ? "" : "none";
updateGutterSpace(cm);
}
function updateGutterSpace(cm) {
var width = cm.display.gutters.offsetWidth;
cm.display.sizer.style.marginLeft = width + "px";
}
// Compute the character length of a line, taking into account
// collapsed ranges (see markText) that might hide parts, and join
// other lines onto it.
function lineLength(line) {
if (line.height == 0) return 0;
var len = line.text.length, merged, cur = line;
while (merged = collapsedSpanAtStart(cur)) {
var found = merged.find(0, true);
cur = found.from.line;
len += found.from.ch - found.to.ch;
}
cur = line;
while (merged = collapsedSpanAtEnd(cur)) {
var found = merged.find(0, true);
len -= cur.text.length - found.from.ch;
cur = found.to.line;
len += cur.text.length - found.to.ch;
}
return len;
}
// Find the longest line in the document.
function findMaxLine(cm) {
var d = cm.display, doc = cm.doc;
d.maxLine = getLine(doc, doc.first);
d.maxLineLength = lineLength(d.maxLine);
d.maxLineChanged = true;
doc.iter(function(line) {
var len = lineLength(line);
if (len > d.maxLineLength) {
d.maxLineLength = len;
d.maxLine = line;
}
});
}
// Make sure the gutters options contains the element
// "CodeMirror-linenumbers" when the lineNumbers option is true.
function setGuttersForLineNumbers(options) {
var found = indexOf(options.gutters, "CodeMirror-linenumbers");
if (found == -1 && options.lineNumbers) {
options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
} else if (found > -1 && !options.lineNumbers) {
options.gutters = options.gutters.slice(0);
options.gutters.splice(found, 1);
}
}
// SCROLLBARS
// Prepare DOM reads needed to update the scrollbars. Done in one
// shot to minimize update/measure roundtrips.
function measureForScrollbars(cm) {
var d = cm.display, gutterW = d.gutters.offsetWidth;
var docH = Math.round(cm.doc.height + paddingVert(cm.display));
return {
clientHeight: d.scroller.clientHeight,
viewHeight: d.wrapper.clientHeight,
scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
viewWidth: d.wrapper.clientWidth,
barLeft: cm.options.fixedGutter ? gutterW : 0,
docHeight: docH,
scrollHeight: docH + scrollGap(cm) + d.barHeight,
nativeBarWidth: d.nativeBarWidth,
gutterWidth: gutterW
};
}
function NativeScrollbars(place, scroll, cm) {
this.cm = cm;
var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
place(vert); place(horiz);
on(vert, "scroll", function() {
if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
});
on(horiz, "scroll", function() {
if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
});
this.checkedOverlay = false;
// Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
}
NativeScrollbars.prototype = copyObj({
update: function(measure) {
var needsH = measure.scrollWidth > measure.clientWidth + 1;
var needsV = measure.scrollHeight > measure.clientHeight + 1;
var sWidth = measure.nativeBarWidth;
if (needsV) {
this.vert.style.display = "block";
this.vert.style.bottom = needsH ? sWidth + "px" : "0";
var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
// A bug in IE8 can cause this value to be negative, so guard it.
this.vert.firstChild.style.height =
Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
} else {
this.vert.style.display = "";
this.vert.firstChild.style.height = "0";
}
if (needsH) {
this.horiz.style.display = "block";
this.horiz.style.right = needsV ? sWidth + "px" : "0";
this.horiz.style.left = measure.barLeft + "px";
var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
this.horiz.firstChild.style.width =
(measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
} else {
this.horiz.style.display = "";
this.horiz.firstChild.style.width = "0";
}
if (!this.checkedOverlay && measure.clientHeight > 0) {
if (sWidth == 0) this.overlayHack();
this.checkedOverlay = true;
}
return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
},
setScrollLeft: function(pos) {
if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
},
setScrollTop: function(pos) {
if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
},
overlayHack: function() {
var w = mac && !mac_geMountainLion ? "12px" : "18px";
this.horiz.style.minHeight = this.vert.style.minWidth = w;
var self = this;
var barMouseDown = function(e) {
if (e_target(e) != self.vert && e_target(e) != self.horiz)
operation(self.cm, onMouseDown)(e);
};
on(this.vert, "mousedown", barMouseDown);
on(this.horiz, "mousedown", barMouseDown);
},
clear: function() {
var parent = this.horiz.parentNode;
parent.removeChild(this.horiz);
parent.removeChild(this.vert);
}
}, NativeScrollbars.prototype);
function NullScrollbars() {}
NullScrollbars.prototype = copyObj({
update: function() { return {bottom: 0, right: 0}; },
setScrollLeft: function() {},
setScrollTop: function() {},
clear: function() {}
}, NullScrollbars.prototype);
CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
function initScrollbars(cm) {
if (cm.display.scrollbars) {
cm.display.scrollbars.clear();
if (cm.display.scrollbars.addClass)
rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
}
cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {
cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
// Prevent clicks in the scrollbars from killing focus
on(node, "mousedown", function() {
if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0);
});
node.setAttribute("cm-not-content", "true");
}, function(pos, axis) {
if (axis == "horizontal") setScrollLeft(cm, pos);
else setScrollTop(cm, pos);
}, cm);
if (cm.display.scrollbars.addClass)
addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
}
function updateScrollbars(cm, measure) {
if (!measure) measure = measureForScrollbars(cm);
var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
updateScrollbarsInner(cm, measure);
for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
updateHeightsInViewport(cm);
updateScrollbarsInner(cm, measureForScrollbars(cm));
startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
}
}
// Re-synchronize the fake scrollbars with the actual size of the
// content.
function updateScrollbarsInner(cm, measure) {
var d = cm.display;
var sizes = d.scrollbars.update(measure);
d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
if (sizes.right && sizes.bottom) {
d.scrollbarFiller.style.display = "block";
d.scrollbarFiller.style.height = sizes.bottom + "px";
d.scrollbarFiller.style.width = sizes.right + "px";
} else d.scrollbarFiller.style.display = "";
if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
d.gutterFiller.style.display = "block";
d.gutterFiller.style.height = sizes.bottom + "px";
d.gutterFiller.style.width = measure.gutterWidth + "px";
} else d.gutterFiller.style.display = "";
}
// Compute the lines that are visible in a given viewport (defaults
// the the current scroll position). viewport may contain top,
// height, and ensure (see op.scrollToPos) properties.
function visibleLines(display, doc, viewport) {
var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
top = Math.floor(top - paddingTop(display));
var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
// Ensure is a {from: {line, ch}, to: {line, ch}} object, and
// forces those lines into the viewport (if possible).
if (viewport && viewport.ensure) {
var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
if (ensureFrom < from) {
from = ensureFrom;
to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
} else if (Math.min(ensureTo, doc.lastLine()) >= to) {
from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
to = ensureTo;
}
}
return {from: from, to: Math.max(to, from + 1)};
}
// LINE NUMBERS
// Re-align line numbers and gutter marks to compensate for
// horizontal scrolling.
function alignHorizontally(cm) {
var display = cm.display, view = display.view;
if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
var gutterW = display.gutters.offsetWidth, left = comp + "px";
for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
if (cm.options.fixedGutter && view[i].gutter)
view[i].gutter.style.left = left;
var align = view[i].alignable;
if (align) for (var j = 0; j < align.length; j++)
align[j].style.left = left;
}
if (cm.options.fixedGutter)
display.gutters.style.left = (comp + gutterW) + "px";
}
// Used to ensure that the line number gutter is still the right
// size for the current document size. Returns true when an update
// is needed.
function maybeUpdateLineNumberWidth(cm) {
if (!cm.options.lineNumbers) return false;
var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
if (last.length != display.lineNumChars) {
var test = display.measure.appendChild(elt("div", [elt("div", last)],
"CodeMirror-linenumber CodeMirror-gutter-elt"));
var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
display.lineGutter.style.width = "";
display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
display.lineNumWidth = display.lineNumInnerWidth + padding;
display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
display.lineGutter.style.width = display.lineNumWidth + "px";
updateGutterSpace(cm);
return true;
}
return false;
}
function lineNumberFor(options, i) {
return String(options.lineNumberFormatter(i + options.firstLineNumber));
}
// Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
// but using getBoundingClientRect to get a sub-pixel-accurate
// result.
function compensateForHScroll(display) {
return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
}
// DISPLAY DRAWING
function DisplayUpdate(cm, viewport, force) {
var display = cm.display;
this.viewport = viewport;
// Store some values that we'll need later (but don't want to force a relayout for)
this.visible = visibleLines(display, cm.doc, viewport);
this.editorIsHidden = !display.wrapper.offsetWidth;
this.wrapperHeight = display.wrapper.clientHeight;
this.wrapperWidth = display.wrapper.clientWidth;
this.oldDisplayWidth = displayWidth(cm);
this.force = force;
this.dims = getDimensions(cm);
this.events = [];
}
DisplayUpdate.prototype.signal = function(emitter, type) {
if (hasHandler(emitter, type))
this.events.push(arguments);
};
DisplayUpdate.prototype.finish = function() {
for (var i = 0; i < this.events.length; i++)
signal.apply(null, this.events[i]);
};
function maybeClipScrollbars(cm) {
var display = cm.display;
if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
display.heightForcer.style.height = scrollGap(cm) + "px";
display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
display.scrollbarsClipped = true;
}
}
// Does the actual updating of the line display. Bails out
// (returning false) when there is nothing to be done and forced is
// false.
function updateDisplayIfNeeded(cm, update) {
var display = cm.display, doc = cm.doc;
if (update.editorIsHidden) {
resetView(cm);
return false;
}
// Bail out if the visible area is already rendered and nothing changed.
if (!update.force &&
update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
(display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
display.renderedView == display.view && countDirtyView(cm) == 0)
return false;
if (maybeUpdateLineNumberWidth(cm)) {
resetView(cm);
update.dims = getDimensions(cm);
}
// Compute a suitable new viewport (from & to)
var end = doc.first + doc.size;
var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
if (sawCollapsedSpans) {
from = visualLineNo(cm.doc, from);
to = visualLineEndNo(cm.doc, to);
}
var different = from != display.viewFrom || to != display.viewTo ||
display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
adjustView(cm, from, to);
display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
// Position the mover div to align with the current scroll position
cm.display.mover.style.top = display.viewOffset + "px";
var toUpdate = countDirtyView(cm);
if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
(display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
return false;
// For big changes, we hide the enclosing element during the
// update, since that speeds up the operations on most browsers.
var focused = activeElt();
if (toUpdate > 4) display.lineDiv.style.display = "none";
patchDisplay(cm, display.updateLineNumbers, update.dims);
if (toUpdate > 4) display.lineDiv.style.display = "";
display.renderedView = display.view;
// There might have been a widget with a focused element that got
// hidden or updated, if so re-focus it.
if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
// Prevent selection and cursors from interfering with the scroll
// width and height.
removeChildren(display.cursorDiv);
removeChildren(display.selectionDiv);
display.gutters.style.height = display.sizer.style.minHeight = 0;
if (different) {
display.lastWrapHeight = update.wrapperHeight;
display.lastWrapWidth = update.wrapperWidth;
startWorker(cm, 400);
}
display.updateLineNumbers = null;
return true;
}
function postUpdateDisplay(cm, update) {
var viewport = update.viewport;
for (var first = true;; first = false) {
if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
// Clip forced viewport to actual scrollable area.
if (viewport && viewport.top != null)
viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
// Updated line heights might result in the drawn area not
// actually covering the viewport. Keep looping until it does.
update.visible = visibleLines(cm.display, cm.doc, viewport);
if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
break;
}
if (!updateDisplayIfNeeded(cm, update)) break;
updateHeightsInViewport(cm);
var barMeasure = measureForScrollbars(cm);
updateSelection(cm);
setDocumentHeight(cm, barMeasure);
updateScrollbars(cm, barMeasure);
}
update.signal(cm, "update", cm);
if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
}
}
function updateDisplaySimple(cm, viewport) {
var update = new DisplayUpdate(cm, viewport);
if (updateDisplayIfNeeded(cm, update)) {
updateHeightsInViewport(cm);
postUpdateDisplay(cm, update);
var barMeasure = measureForScrollbars(cm);
updateSelection(cm);
setDocumentHeight(cm, barMeasure);
updateScrollbars(cm, barMeasure);
update.finish();
}
}
function setDocumentHeight(cm, measure) {
cm.display.sizer.style.minHeight = measure.docHeight + "px";
var total = measure.docHeight + cm.display.barHeight;
cm.display.heightForcer.style.top = total + "px";
cm.display.gutters.style.height = Math.max(total + scrollGap(cm), measure.clientHeight) + "px";
}
// Read the actual heights of the rendered lines, and update their
// stored heights to match.
function updateHeightsInViewport(cm) {
var display = cm.display;
var prevBottom = display.lineDiv.offsetTop;
for (var i = 0; i < display.view.length; i++) {
var cur = display.view[i], height;
if (cur.hidden) continue;
if (ie && ie_version < 8) {
var bot = cur.node.offsetTop + cur.node.offsetHeight;
height = bot - prevBottom;
prevBottom = bot;
} else {
var box = cur.node.getBoundingClientRect();
height = box.bottom - box.top;
}
var diff = cur.line.height - height;
if (height < 2) height = textHeight(display);
if (diff > .001 || diff < -.001) {
updateLineHeight(cur.line, height);
updateWidgetHeight(cur.line);
if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
updateWidgetHeight(cur.rest[j]);
}
}
}
// Read and store the height of line widgets associated with the
// given line.
function updateWidgetHeight(line) {
if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
line.widgets[i].height = line.widgets[i].node.offsetHeight;
}
// Do a bulk-read of the DOM positions and sizes needed to draw the
// view, so that we don't interleave reading and writing to the DOM.
function getDimensions(cm) {
var d = cm.display, left = {}, width = {};
var gutterLeft = d.gutters.clientLeft;
for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
width[cm.options.gutters[i]] = n.clientWidth;
}
return {fixedPos: compensateForHScroll(d),
gutterTotalWidth: d.gutters.offsetWidth,
gutterLeft: left,
gutterWidth: width,
wrapperWidth: d.wrapper.clientWidth};
}
// Sync the actual display DOM structure with display.view, removing
// nodes for lines that are no longer in view, and creating the ones
// that are not there yet, and updating the ones that are out of
// date.
function patchDisplay(cm, updateNumbersFrom, dims) {
var display = cm.display, lineNumbers = cm.options.lineNumbers;
var container = display.lineDiv, cur = container.firstChild;
function rm(node) {
var next = node.nextSibling;
// Works around a throw-scroll bug in OS X Webkit
if (webkit && mac && cm.display.currentWheelTarget == node)
node.style.display = "none";
else
node.parentNode.removeChild(node);
return next;
}
var view = display.view, lineN = display.viewFrom;
// Loop over the elements in the view, syncing cur (the DOM nodes
// in display.lineDiv) with the view as we go.
for (var i = 0; i < view.length; i++) {
var lineView = view[i];
if (lineView.hidden) {
} else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
var node = buildLineElement(cm, lineView, lineN, dims);
container.insertBefore(node, cur);
} else { // Already drawn
while (cur != lineView.node) cur = rm(cur);
var updateNumber = lineNumbers && updateNumbersFrom != null &&
updateNumbersFrom <= lineN && lineView.lineNumber;
if (lineView.changes) {
if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
updateLineForChanges(cm, lineView, lineN, dims);
}
if (updateNumber) {
removeChildren(lineView.lineNumber);
lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
}
cur = lineView.node.nextSibling;
}
lineN += lineView.size;
}
while (cur) cur = rm(cur);
}
// When an aspect of a line changes, a string is added to
// lineView.changes. This updates the relevant part of the line's
// DOM structure.
function updateLineForChanges(cm, lineView, lineN, dims) {
for (var j = 0; j < lineView.changes.length; j++) {
var type = lineView.changes[j];
if (type == "text") updateLineText(cm, lineView);
else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
else if (type == "class") updateLineClasses(lineView);
else if (type == "widget") updateLineWidgets(cm, lineView, dims);
}
lineView.changes = null;
}
// Lines with gutter elements, widgets or a background class need to
// be wrapped, and have the extra elements added to the wrapper div
function ensureLineWrapped(lineView) {
if (lineView.node == lineView.text) {
lineView.node = elt("div", null, null, "position: relative");
if (lineView.text.parentNode)
lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
lineView.node.appendChild(lineView.text);
if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
}
return lineView.node;
}
function updateLineBackground(lineView) {
var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
if (cls) cls += " CodeMirror-linebackground";
if (lineView.background) {
if (cls) lineView.background.className = cls;
else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
} else if (cls) {
var wrap = ensureLineWrapped(lineView);
lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
}
}
// Wrapper around buildLineContent which will reuse the structure
// in display.externalMeasured when possible.
function getLineContent(cm, lineView) {
var ext = cm.display.externalMeasured;
if (ext && ext.line == lineView.line) {
cm.display.externalMeasured = null;
lineView.measure = ext.measure;
return ext.built;
}
return buildLineContent(cm, lineView);
}
// Redraw the line's text. Interacts with the background and text
// classes because the mode may output tokens that influence these
// classes.
function updateLineText(cm, lineView) {
var cls = lineView.text.className;
var built = getLineContent(cm, lineView);
if (lineView.text == lineView.node) lineView.node = built.pre;
lineView.text.parentNode.replaceChild(built.pre, lineView.text);
lineView.text = built.pre;
if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
lineView.bgClass = built.bgClass;
lineView.textClass = built.textClass;
updateLineClasses(lineView);
} else if (cls) {
lineView.text.className = cls;
}
}
function updateLineClasses(lineView) {
updateLineBackground(lineView);
if (lineView.line.wrapClass)
ensureLineWrapped(lineView).className = lineView.line.wrapClass;
else if (lineView.node != lineView.text)
lineView.node.className = "";
var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
lineView.text.className = textClass || "";
}
function updateLineGutter(cm, lineView, lineN, dims) {
if (lineView.gutter) {
lineView.node.removeChild(lineView.gutter);
lineView.gutter = null;
}
if (lineView.gutterBackground) {
lineView.node.removeChild(lineView.gutterBackground);
lineView.gutterBackground = null;
}
if (lineView.line.gutterClass) {
var wrap = ensureLineWrapped(lineView);
lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
"left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +
"px; width: " + dims.gutterTotalWidth + "px");
wrap.insertBefore(lineView.gutterBackground, lineView.text);
}
var markers = lineView.line.gutterMarkers;
if (cm.options.lineNumbers || markers) {
var wrap = ensureLineWrapped(lineView);
var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
(cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px");
cm.display.input.setUneditable(gutterWrap);
wrap.insertBefore(gutterWrap, lineView.text);
if (lineView.line.gutterClass)
gutterWrap.className += " " + lineView.line.gutterClass;
if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
lineView.lineNumber = gutterWrap.appendChild(
elt("div", lineNumberFor(cm.options, lineN),
"CodeMirror-linenumber CodeMirror-gutter-elt",
"left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
+ cm.display.lineNumInnerWidth + "px"));
if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
if (found)
gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
}
}
}
function updateLineWidgets(cm, lineView, dims) {
if (lineView.alignable) lineView.alignable = null;
for (var node = lineView.node.firstChild, next; node; node = next) {
var next = node.nextSibling;
if (node.className == "CodeMirror-linewidget")
lineView.node.removeChild(node);
}
insertLineWidgets(cm, lineView, dims);
}
// Build a line's DOM representation from scratch
function buildLineElement(cm, lineView, lineN, dims) {
var built = getLineContent(cm, lineView);
lineView.text = lineView.node = built.pre;
if (built.bgClass) lineView.bgClass = built.bgClass;
if (built.textClass) lineView.textClass = built.textClass;
updateLineClasses(lineView);
updateLineGutter(cm, lineView, lineN, dims);
insertLineWidgets(cm, lineView, dims);
return lineView.node;
}
// A lineView may contain multiple logical lines (when merged by
// collapsed spans). The widgets for all of them need to be drawn.
function insertLineWidgets(cm, lineView, dims) {
insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
}
function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
if (!line.widgets) return;
var wrap = ensureLineWrapped(lineView);
for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");
positionLineWidget(widget, node, lineView, dims);
cm.display.input.setUneditable(node);
if (allowAbove && widget.above)
wrap.insertBefore(node, lineView.gutter || lineView.text);
else
wrap.appendChild(node);
signalLater(widget, "redraw");
}
}
function positionLineWidget(widget, node, lineView, dims) {
if (widget.noHScroll) {
(lineView.alignable || (lineView.alignable = [])).push(node);
var width = dims.wrapperWidth;
node.style.left = dims.fixedPos + "px";
if (!widget.coverGutter) {
width -= dims.gutterTotalWidth;
node.style.paddingLeft = dims.gutterTotalWidth + "px";
}
node.style.width = width + "px";
}
if (widget.coverGutter) {
node.style.zIndex = 5;
node.style.position = "relative";
if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
}
}
// POSITION OBJECT
// A Pos instance represents a position within the text.
var Pos = CodeMirror.Pos = function(line, ch) {
if (!(this instanceof Pos)) return new Pos(line, ch);
this.line = line; this.ch = ch;
};
// Compare two positions, return 0 if they are the same, a negative
// number when a is less, and a positive number otherwise.
var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
function copyPos(x) {return Pos(x.line, x.ch);}
function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
// INPUT HANDLING
function ensureFocus(cm) {
if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
}
function isReadOnly(cm) {
return cm.options.readOnly || cm.doc.cantEdit;
}
// This will be set to an array of strings when copying, so that,
// when pasting, we know what kind of selections the copied text
// was made out of.
var lastCopied = null;
function applyTextInput(cm, inserted, deleted, sel, origin) {
var doc = cm.doc;
cm.display.shift = false;
if (!sel) sel = doc.sel;
var paste = cm.state.pasteIncoming || origin == "paste";
var textLines = doc.splitLines(inserted), multiPaste = null;
// When pasing N lines into N selections, insert one line per selection
if (paste && sel.ranges.length > 1) {
if (lastCopied && lastCopied.join("\n") == inserted) {
if (sel.ranges.length % lastCopied.length == 0) {
multiPaste = [];
for (var i = 0; i < lastCopied.length; i++)
multiPaste.push(doc.splitLines(lastCopied[i]));
}
} else if (textLines.length == sel.ranges.length) {
multiPaste = map(textLines, function(l) { return [l]; });
}
}
// Normal behavior is to insert the new text into every selection
for (var i = sel.ranges.length - 1; i >= 0; i--) {
var range = sel.ranges[i];
var from = range.from(), to = range.to();
if (range.empty()) {
if (deleted && deleted > 0) // Handle deletion
from = Pos(from.line, from.ch - deleted);
else if (cm.state.overwrite && !paste) // Handle overwrite
to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
}
var updateInput = cm.curOp.updateInput;
var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
makeChange(cm.doc, changeEvent);
signalLater(cm, "inputRead", cm, changeEvent);
}
if (inserted && !paste)
triggerElectric(cm, inserted);
ensureCursorVisible(cm);
cm.curOp.updateInput = updateInput;
cm.curOp.typing = true;
cm.state.pasteIncoming = cm.state.cutIncoming = false;
}
function handlePaste(e, cm) {
var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
if (pasted) {
e.preventDefault();
if (!isReadOnly(cm) && !cm.options.disableInput)
runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); });
return true;
}
}
function triggerElectric(cm, inserted) {
// When an 'electric' character is inserted, immediately trigger a reindent
if (!cm.options.electricChars || !cm.options.smartIndent) return;
var sel = cm.doc.sel;
for (var i = sel.ranges.length - 1; i >= 0; i--) {
var range = sel.ranges[i];
if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue;
var mode = cm.getModeAt(range.head);
var indented = false;
if (mode.electricChars) {
for (var j = 0; j < mode.electricChars.length; j++)
if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
indented = indentLine(cm, range.head.line, "smart");
break;
}
} else if (mode.electricInput) {
if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
indented = indentLine(cm, range.head.line, "smart");
}
if (indented) signalLater(cm, "electricInput", cm, range.head.line);
}
}
function copyableRanges(cm) {
var text = [], ranges = [];
for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
var line = cm.doc.sel.ranges[i].head.line;
var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
ranges.push(lineRange);
text.push(cm.getRange(lineRange.anchor, lineRange.head));
}
return {text: text, ranges: ranges};
}
function disableBrowserMagic(field) {
field.setAttribute("autocorrect", "off");
field.setAttribute("autocapitalize", "off");
field.setAttribute("spellcheck", "false");
}
// TEXTAREA INPUT STYLE
function TextareaInput(cm) {
this.cm = cm;
// See input.poll and input.reset
this.prevInput = "";
// Flag that indicates whether we expect input to appear real soon
// now (after some event like 'keypress' or 'input') and are
// polling intensively.
this.pollingFast = false;
// Self-resetting timeout for the poller
this.polling = new Delayed();
// Tracks when input.reset has punted to just putting a short
// string into the textarea instead of the full selection.
this.inaccurateSelection = false;
// Used to work around IE issue with selection being forgotten when focus moves away from textarea
this.hasSelection = false;
this.composing = null;
};
function hiddenTextarea() {
var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
// The textarea is kept positioned near the cursor to prevent the
// fact that it'll be scrolled into view on input from scrolling
// our fake cursor out of view. On webkit, when wrap=off, paste is
// very slow. So make the area wide instead.
if (webkit) te.style.width = "1000px";
else te.setAttribute("wrap", "off");
// If border: 0; -- iOS fails to open keyboard (issue #1287)
if (ios) te.style.border = "1px solid black";
disableBrowserMagic(te);
return div;
}
TextareaInput.prototype = copyObj({
init: function(display) {
var input = this, cm = this.cm;
// Wraps and hides input textarea
var div = this.wrapper = hiddenTextarea();
// The semihidden textarea that is focused when the editor is
// focused, and receives input.
var te = this.textarea = div.firstChild;
display.wrapper.insertBefore(div, display.wrapper.firstChild);
// Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
if (ios) te.style.width = "0px";
on(te, "input", function() {
if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null;
input.poll();
});
on(te, "paste", function(e) {
if (handlePaste(e, cm)) return true;
cm.state.pasteIncoming = true;
input.fastPoll();
});
function prepareCopyCut(e) {
if (cm.somethingSelected()) {
lastCopied = cm.getSelections();
if (input.inaccurateSelection) {
input.prevInput = "";
input.inaccurateSelection = false;
te.value = lastCopied.join("\n");
selectInput(te);
}
} else if (!cm.options.lineWiseCopyCut) {
return;
} else {
var ranges = copyableRanges(cm);
lastCopied = ranges.text;
if (e.type == "cut") {
cm.setSelections(ranges.ranges, null, sel_dontScroll);
} else {
input.prevInput = "";
te.value = ranges.text.join("\n");
selectInput(te);
}
}
if (e.type == "cut") cm.state.cutIncoming = true;
}
on(te, "cut", prepareCopyCut);
on(te, "copy", prepareCopyCut);
on(display.scroller, "paste", function(e) {
if (eventInWidget(display, e)) return;
cm.state.pasteIncoming = true;
input.focus();
});
// Prevent normal selection in the editor (we handle our own)
on(display.lineSpace, "selectstart", function(e) {
if (!eventInWidget(display, e)) e_preventDefault(e);
});
on(te, "compositionstart", function() {
var start = cm.getCursor("from");
if (input.composing) input.composing.range.clear()
input.composing = {
start: start,
range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
};
});
on(te, "compositionend", function() {
if (input.composing) {
input.poll();
input.composing.range.clear();
input.composing = null;
}
});
},
prepareSelection: function() {
// Redraw the selection and/or cursor
var cm = this.cm, display = cm.display, doc = cm.doc;
var result = prepareSelection(cm);
// Move the hidden textarea near the cursor to prevent scrolling artifacts
if (cm.options.moveInputWithCursor) {
var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
headPos.top + lineOff.top - wrapOff.top));
result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
headPos.left + lineOff.left - wrapOff.left));
}
return result;
},
showSelection: function(drawn) {
var cm = this.cm, display = cm.display;
removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
removeChildrenAndAdd(display.selectionDiv, drawn.selection);
if (drawn.teTop != null) {
this.wrapper.style.top = drawn.teTop + "px";
this.wrapper.style.left = drawn.teLeft + "px";
}
},
// Reset the input to correspond to the selection (or to be empty,
// when not typing and nothing is selected)
reset: function(typing) {
if (this.contextMenuPending) return;
var minimal, selected, cm = this.cm, doc = cm.doc;
if (cm.somethingSelected()) {
this.prevInput = "";
var range = doc.sel.primary();
minimal = hasCopyEvent &&
(range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
var content = minimal ? "-" : selected || cm.getSelection();
this.textarea.value = content;
if (cm.state.focused) selectInput(this.textarea);
if (ie && ie_version >= 9) this.hasSelection = content;
} else if (!typing) {
this.prevInput = this.textarea.value = "";
if (ie && ie_version >= 9) this.hasSelection = null;
}
this.inaccurateSelection = minimal;
},
getField: function() { return this.textarea; },
supportsTouch: function() { return false; },
focus: function() {
if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
try { this.textarea.focus(); }
catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
}
},
blur: function() { this.textarea.blur(); },
resetPosition: function() {
this.wrapper.style.top = this.wrapper.style.left = 0;
},
receivedFocus: function() { this.slowPoll(); },
// Poll for input changes, using the normal rate of polling. This
// runs as long as the editor is focused.
slowPoll: function() {
var input = this;
if (input.pollingFast) return;
input.polling.set(this.cm.options.pollInterval, function() {
input.poll();
if (input.cm.state.focused) input.slowPoll();
});
},
// When an event has just come in that is likely to add or change
// something in the input textarea, we poll faster, to ensure that
// the change appears on the screen quickly.
fastPoll: function() {
var missed = false, input = this;
input.pollingFast = true;
function p() {
var changed = input.poll();
if (!changed && !missed) {missed = true; input.polling.set(60, p);}
else {input.pollingFast = false; input.slowPoll();}
}
input.polling.set(20, p);
},
// Read input from the textarea, and update the document to match.
// When something is selected, it is present in the textarea, and
// selected (unless it is huge, in which case a placeholder is
// used). When nothing is selected, the cursor sits after previously
// seen text (can be empty), which is stored in prevInput (we must
// not reset the textarea when typing, because that breaks IME).
poll: function() {
var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
// Since this is called a *lot*, try to bail out as cheaply as
// possible when it is clear that nothing happened. hasSelection
// will be the case when there is a lot of text in the textarea,
// in which case reading its value would be expensive.
if (this.contextMenuPending || !cm.state.focused ||
(hasSelection(input) && !prevInput && !this.composing) ||
isReadOnly(cm) || cm.options.disableInput || cm.state.keySeq)
return false;
var text = input.value;
// If nothing changed, bail.
if (text == prevInput && !cm.somethingSelected()) return false;
// Work around nonsensical selection resetting in IE9/10, and
// inexplicable appearance of private area unicode characters on
// some key combos in Mac (#2689).
if (ie && ie_version >= 9 && this.hasSelection === text ||
mac && /[\uf700-\uf7ff]/.test(text)) {
cm.display.input.reset();
return false;
}
if (cm.doc.sel == cm.display.selForContextMenu) {
var first = text.charCodeAt(0);
if (first == 0x200b && !prevInput) prevInput = "\u200b";
if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); }
}
// Find the part of the input that is actually new
var same = 0, l = Math.min(prevInput.length, text.length);
while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
var self = this;
runInOp(cm, function() {
applyTextInput(cm, text.slice(same), prevInput.length - same,
null, self.composing ? "*compose" : null);
// Don't leave long text in the textarea, since it makes further polling slow
if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = "";
else self.prevInput = text;
if (self.composing) {
self.composing.range.clear();
self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"),
{className: "CodeMirror-composing"});
}
});
return true;
},
ensurePolled: function() {
if (this.pollingFast && this.poll()) this.pollingFast = false;
},
onKeyPress: function() {
if (ie && ie_version >= 9) this.hasSelection = null;
this.fastPoll();
},
onContextMenu: function(e) {
var input = this, cm = input.cm, display = cm.display, te = input.textarea;
var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
if (!pos || presto) return; // Opera is difficult.
// Reset the current text selection only if the click is done outside of the selection
// and 'resetSelectionOnContextMenu' option is true.
var reset = cm.options.resetSelectionOnContextMenu;
if (reset && cm.doc.sel.contains(pos) == -1)
operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
var oldCSS = te.style.cssText;
input.wrapper.style.position = "absolute";
te.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) +
"px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " +
(ie ? "rgba(255, 255, 255, .05)" : "transparent") +
"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
display.input.focus();
if (webkit) window.scrollTo(null, oldScrollY);
display.input.reset();
// Adds "Select all" to context menu in FF
if (!cm.somethingSelected()) te.value = input.prevInput = " ";
input.contextMenuPending = true;
display.selForContextMenu = cm.doc.sel;
clearTimeout(display.detectingSelectAll);
// Select-all will be greyed out if there's nothing to select, so
// this adds a zero-width space so that we can later check whether
// it got selected.
function prepareSelectAllHack() {
if (te.selectionStart != null) {
var selected = cm.somethingSelected();
var extval = "\u200b" + (selected ? te.value : "");
te.value = "\u21da"; // Used to catch context-menu undo
te.value = extval;
input.prevInput = selected ? "" : "\u200b";
te.selectionStart = 1; te.selectionEnd = extval.length;
// Re-set this, in case some other handler touched the
// selection in the meantime.
display.selForContextMenu = cm.doc.sel;
}
}
function rehide() {
input.contextMenuPending = false;
input.wrapper.style.position = "relative";
te.style.cssText = oldCSS;
if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
// Try to detect the user choosing select-all
if (te.selectionStart != null) {
if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
var i = 0, poll = function() {
if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
te.selectionEnd > 0 && input.prevInput == "\u200b")
operation(cm, commands.selectAll)(cm);
else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
else display.input.reset();
};
display.detectingSelectAll = setTimeout(poll, 200);
}
}
if (ie && ie_version >= 9) prepareSelectAllHack();
if (captureRightClick) {
e_stop(e);
var mouseup = function() {
off(window, "mouseup", mouseup);
setTimeout(rehide, 20);
};
on(window, "mouseup", mouseup);
} else {
setTimeout(rehide, 50);
}
},
readOnlyChanged: function(val) {
if (!val) this.reset();
},
setUneditable: nothing,
needsContentAttribute: false
}, TextareaInput.prototype);
// CONTENTEDITABLE INPUT STYLE
function ContentEditableInput(cm) {
this.cm = cm;
this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
this.polling = new Delayed();
this.gracePeriod = false;
}
ContentEditableInput.prototype = copyObj({
init: function(display) {
var input = this, cm = input.cm;
var div = input.div = display.lineDiv;
disableBrowserMagic(div);
on(div, "paste", function(e) { handlePaste(e, cm); })
on(div, "compositionstart", function(e) {
var data = e.data;
input.composing = {sel: cm.doc.sel, data: data, startData: data};
if (!data) return;
var prim = cm.doc.sel.primary();
var line = cm.getLine(prim.head.line);
var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length));
if (found > -1 && found <= prim.head.ch)
input.composing.sel = simpleSelection(Pos(prim.head.line, found),
Pos(prim.head.line, found + data.length));
});
on(div, "compositionupdate", function(e) {
input.composing.data = e.data;
});
on(div, "compositionend", function(e) {
var ours = input.composing;
if (!ours) return;
if (e.data != ours.startData && !/\u200b/.test(e.data))
ours.data = e.data;
// Need a small delay to prevent other code (input event,
// selection polling) from doing damage when fired right after
// compositionend.
setTimeout(function() {
if (!ours.handled)
input.applyComposition(ours);
if (input.composing == ours)
input.composing = null;
}, 50);
});
on(div, "touchstart", function() {
input.forceCompositionEnd();
});
on(div, "input", function() {
if (input.composing) return;
if (isReadOnly(cm) || !input.pollContent())
runInOp(input.cm, function() {regChange(cm);});
});
function onCopyCut(e) {
if (cm.somethingSelected()) {
lastCopied = cm.getSelections();
if (e.type == "cut") cm.replaceSelection("", null, "cut");
} else if (!cm.options.lineWiseCopyCut) {
return;
} else {
var ranges = copyableRanges(cm);
lastCopied = ranges.text;
if (e.type == "cut") {
cm.operation(function() {
cm.setSelections(ranges.ranges, 0, sel_dontScroll);
cm.replaceSelection("", null, "cut");
});
}
}
// iOS exposes the clipboard API, but seems to discard content inserted into it
if (e.clipboardData && !ios) {
e.preventDefault();
e.clipboardData.clearData();
e.clipboardData.setData("text/plain", lastCopied.join("\n"));
} else {
// Old-fashioned briefly-focus-a-textarea hack
var kludge = hiddenTextarea(), te = kludge.firstChild;
cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
te.value = lastCopied.join("\n");
var hadFocus = document.activeElement;
selectInput(te);
setTimeout(function() {
cm.display.lineSpace.removeChild(kludge);
hadFocus.focus();
}, 50);
}
}
on(div, "copy", onCopyCut);
on(div, "cut", onCopyCut);
},
prepareSelection: function() {
var result = prepareSelection(this.cm, false);
result.focus = this.cm.state.focused;
return result;
},
showSelection: function(info) {
if (!info || !this.cm.display.view.length) return;
if (info.focus) this.showPrimarySelection();
this.showMultipleSelections(info);
},
showPrimarySelection: function() {
var sel = window.getSelection(), prim = this.cm.doc.sel.primary();
var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset);
var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset);
if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
return;
var start = posToDOM(this.cm, prim.from());
var end = posToDOM(this.cm, prim.to());
if (!start && !end) return;
var view = this.cm.display.view;
var old = sel.rangeCount && sel.getRangeAt(0);
if (!start) {
start = {node: view[0].measure.map[2], offset: 0};
} else if (!end) { // FIXME dangerously hacky
var measure = view[view.length - 1].measure;
var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
}
try { var rng = range(start.node, start.offset, end.offset, end.node); }
catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
if (rng) {
sel.removeAllRanges();
sel.addRange(rng);
if (old && sel.anchorNode == null) sel.addRange(old);
else if (gecko) this.startGracePeriod();
}
this.rememberSelection();
},
startGracePeriod: function() {
var input = this;
clearTimeout(this.gracePeriod);
this.gracePeriod = setTimeout(function() {
input.gracePeriod = false;
if (input.selectionChanged())
input.cm.operation(function() { input.cm.curOp.selectionChanged = true; });
}, 20);
},
showMultipleSelections: function(info) {
removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
},
rememberSelection: function() {
var sel = window.getSelection();
this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
},
selectionInEditor: function() {
var sel = window.getSelection();
if (!sel.rangeCount) return false;
var node = sel.getRangeAt(0).commonAncestorContainer;
return contains(this.div, node);
},
focus: function() {
if (this.cm.options.readOnly != "nocursor") this.div.focus();
},
blur: function() { this.div.blur(); },
getField: function() { return this.div; },
supportsTouch: function() { return true; },
receivedFocus: function() {
var input = this;
if (this.selectionInEditor())
this.pollSelection();
else
runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; });
function poll() {
if (input.cm.state.focused) {
input.pollSelection();
input.polling.set(input.cm.options.pollInterval, poll);
}
}
this.polling.set(this.cm.options.pollInterval, poll);
},
selectionChanged: function() {
var sel = window.getSelection();
return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
},
pollSelection: function() {
if (!this.composing && !this.gracePeriod && this.selectionChanged()) {
var sel = window.getSelection(), cm = this.cm;
this.rememberSelection();
var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
var head = domToPos(cm, sel.focusNode, sel.focusOffset);
if (anchor && head) runInOp(cm, function() {
setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
});
}
},
pollContent: function() {
var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
var from = sel.from(), to = sel.to();
if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false;
var fromIndex;
if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
var fromLine = lineNo(display.view[0].line);
var fromNode = display.view[0].node;
} else {
var fromLine = lineNo(display.view[fromIndex].line);
var fromNode = display.view[fromIndex - 1].node.nextSibling;
}
var toIndex = findViewIndex(cm, to.line);
if (toIndex == display.view.length - 1) {
var toLine = display.viewTo - 1;
var toNode = display.lineDiv.lastChild;
} else {
var toLine = lineNo(display.view[toIndex + 1].line) - 1;
var toNode = display.view[toIndex + 1].node.previousSibling;
}
var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
while (newText.length > 1 && oldText.length > 1) {
if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
else break;
}
var cutFront = 0, cutEnd = 0;
var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
++cutFront;
var newBot = lst(newText), oldBot = lst(oldText);
var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
oldBot.length - (oldText.length == 1 ? cutFront : 0));
while (cutEnd < maxCutEnd &&
newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
++cutEnd;
newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
newText[0] = newText[0].slice(cutFront);
var chFrom = Pos(fromLine, cutFront);
var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
replaceRange(cm.doc, newText, chFrom, chTo, "+input");
return true;
}
},
ensurePolled: function() {
this.forceCompositionEnd();
},
reset: function() {
this.forceCompositionEnd();
},
forceCompositionEnd: function() {
if (!this.composing || this.composing.handled) return;
this.applyComposition(this.composing);
this.composing.handled = true;
this.div.blur();
this.div.focus();
},
applyComposition: function(composing) {
if (isReadOnly(this.cm))
operation(this.cm, regChange)(this.cm)
else if (composing.data && composing.data != composing.startData)
operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
},
setUneditable: function(node) {
node.contentEditable = "false"
},
onKeyPress: function(e) {
e.preventDefault();
if (!isReadOnly(this.cm))
operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
},
readOnlyChanged: function(val) {
this.div.contentEditable = String(val != "nocursor")
},
onContextMenu: nothing,
resetPosition: nothing,
needsContentAttribute: true
}, ContentEditableInput.prototype);
function posToDOM(cm, pos) {
var view = findViewForLine(cm, pos.line);
if (!view || view.hidden) return null;
var line = getLine(cm.doc, pos.line);
var info = mapFromLineView(view, line, pos.line);
var order = getOrder(line), side = "left";
if (order) {
var partPos = getBidiPartAt(order, pos.ch);
side = partPos % 2 ? "right" : "left";
}
var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
result.offset = result.collapse == "right" ? result.end : result.start;
return result;
}
function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
function domToPos(cm, node, offset) {
var lineNode;
if (node == cm.display.lineDiv) {
lineNode = cm.display.lineDiv.childNodes[offset];
if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
node = null; offset = 0;
} else {
for (lineNode = node;; lineNode = lineNode.parentNode) {
if (!lineNode || lineNode == cm.display.lineDiv) return null;
if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break;
}
}
for (var i = 0; i < cm.display.view.length; i++) {
var lineView = cm.display.view[i];
if (lineView.node == lineNode)
return locateNodeInLineView(lineView, node, offset);
}
}
function locateNodeInLineView(lineView, node, offset) {
var wrapper = lineView.text.firstChild, bad = false;
if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true);
if (node == wrapper) {
bad = true;
node = wrapper.childNodes[offset];
offset = 0;
if (!node) {
var line = lineView.rest ? lst(lineView.rest) : lineView.line;
return badPos(Pos(lineNo(line), line.text.length), bad);
}
}
var textNode = node.nodeType == 3 ? node : null, topNode = node;
if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
textNode = node.firstChild;
if (offset) offset = textNode.nodeValue.length;
}
while (topNode.parentNode != wrapper) topNode = topNode.parentNode;
var measure = lineView.measure, maps = measure.maps;
function find(textNode, topNode, offset) {
for (var i = -1; i < (maps ? maps.length : 0); i++) {
var map = i < 0 ? measure.map : maps[i];
for (var j = 0; j < map.length; j += 3) {
var curNode = map[j + 2];
if (curNode == textNode || curNode == topNode) {
var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
var ch = map[j] + offset;
if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)];
return Pos(line, ch);
}
}
}
}
var found = find(textNode, topNode, offset);
if (found) return badPos(found, bad);
// FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
found = find(after, after.firstChild, 0);
if (found)
return badPos(Pos(found.line, found.ch - dist), bad);
else
dist += after.textContent.length;
}
for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
found = find(before, before.firstChild, -1);
if (found)
return badPos(Pos(found.line, found.ch + dist), bad);
else
dist += after.textContent.length;
}
}
function domTextBetween(cm, from, to, fromLine, toLine) {
var text = "", closing = false, lineSep = cm.doc.lineSeparator();
function recognizeMarker(id) { return function(marker) { return marker.id == id; }; }
function walk(node) {
if (node.nodeType == 1) {
var cmText = node.getAttribute("cm-text");
if (cmText != null) {
if (cmText == "") cmText = node.textContent.replace(/\u200b/g, "");
text += cmText;
return;
}
var markerID = node.getAttribute("cm-marker"), range;
if (markerID) {
var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
if (found.length && (range = found[0].find()))
text += getBetween(cm.doc, range.from, range.to).join(lineSep);
return;
}
if (node.getAttribute("contenteditable") == "false") return;
for (var i = 0; i < node.childNodes.length; i++)
walk(node.childNodes[i]);
if (/^(pre|div|p)$/i.test(node.nodeName))
closing = true;
} else if (node.nodeType == 3) {
var val = node.nodeValue;
if (!val) return;
if (closing) {
text += lineSep;
closing = false;
}
text += val;
}
}
for (;;) {
walk(from);
if (from == to) break;
from = from.nextSibling;
}
return text;
}
CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
// SELECTION / CURSOR
// Selection objects are immutable. A new one is created every time
// the selection changes. A selection is one or more non-overlapping
// (and non-touching) ranges, sorted, and an integer that indicates
// which one is the primary selection (the one that's scrolled into
// view, that getCursor returns, etc).
function Selection(ranges, primIndex) {
this.ranges = ranges;
this.primIndex = primIndex;
}
Selection.prototype = {
primary: function() { return this.ranges[this.primIndex]; },
equals: function(other) {
if (other == this) return true;
if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
for (var i = 0; i < this.ranges.length; i++) {
var here = this.ranges[i], there = other.ranges[i];
if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
}
return true;
},
deepCopy: function() {
for (var out = [], i = 0; i < this.ranges.length; i++)
out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
return new Selection(out, this.primIndex);
},
somethingSelected: function() {
for (var i = 0; i < this.ranges.length; i++)
if (!this.ranges[i].empty()) return true;
return false;
},
contains: function(pos, end) {
if (!end) end = pos;
for (var i = 0; i < this.ranges.length; i++) {
var range = this.ranges[i];
if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
return i;
}
return -1;
}
};
function Range(anchor, head) {
this.anchor = anchor; this.head = head;
}
Range.prototype = {
from: function() { return minPos(this.anchor, this.head); },
to: function() { return maxPos(this.anchor, this.head); },
empty: function() {
return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
}
};
// Take an unsorted, potentially overlapping set of ranges, and
// build a selection out of it. 'Consumes' ranges array (modifying
// it).
function normalizeSelection(ranges, primIndex) {
var prim = ranges[primIndex];
ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
primIndex = indexOf(ranges, prim);
for (var i = 1; i < ranges.length; i++) {
var cur = ranges[i], prev = ranges[i - 1];
if (cmp(prev.to(), cur.from()) >= 0) {
var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
if (i <= primIndex) --primIndex;
ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
}
}
return new Selection(ranges, primIndex);
}
function simpleSelection(anchor, head) {
return new Selection([new Range(anchor, head || anchor)], 0);
}
// Most of the external API clips given positions to make sure they
// actually exist within the document.
function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
function clipPos(doc, pos) {
if (pos.line < doc.first) return Pos(doc.first, 0);
var last = doc.first + doc.size - 1;
if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
return clipToLen(pos, getLine(doc, pos.line).text.length);
}
function clipToLen(pos, linelen) {
var ch = pos.ch;
if (ch == null || ch > linelen) return Pos(pos.line, linelen);
else if (ch < 0) return Pos(pos.line, 0);
else return pos;
}
function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
function clipPosArray(doc, array) {
for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
return out;
}
// SELECTION UPDATES
// The 'scroll' parameter given to many of these indicated whether
// the new cursor position should be scrolled into view after
// modifying the selection.
// If shift is held or the extend flag is set, extends a range to
// include a given position (and optionally a second position).
// Otherwise, simply returns the range between the given positions.
// Used for cursor motion and such.
function extendRange(doc, range, head, other) {
if (doc.cm && doc.cm.display.shift || doc.extend) {
var anchor = range.anchor;
if (other) {
var posBefore = cmp(head, anchor) < 0;
if (posBefore != (cmp(other, anchor) < 0)) {
anchor = head;
head = other;
} else if (posBefore != (cmp(head, other) < 0)) {
head = other;
}
}
return new Range(anchor, head);
} else {
return new Range(other || head, head);
}
}
// Extend the primary selection range, discard the rest.
function extendSelection(doc, head, other, options) {
setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
}
// Extend all selections (pos is an array of selections with length
// equal the number of selections)
function extendSelections(doc, heads, options) {
for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
var newSel = normalizeSelection(out, doc.sel.primIndex);
setSelection(doc, newSel, options);
}
// Updates a single range in the selection.
function replaceOneSelection(doc, i, range, options) {
var ranges = doc.sel.ranges.slice(0);
ranges[i] = range;
setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
}
// Reset the selection to a single range.
function setSimpleSelection(doc, anchor, head, options) {
setSelection(doc, simpleSelection(anchor, head), options);
}
// Give beforeSelectionChange handlers a change to influence a
// selection update.
function filterSelectionChange(doc, sel) {
var obj = {
ranges: sel.ranges,
update: function(ranges) {
this.ranges = [];
for (var i = 0; i < ranges.length; i++)
this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
clipPos(doc, ranges[i].head));
}
};
signal(doc, "beforeSelectionChange", doc, obj);
if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
else return sel;
}
function setSelectionReplaceHistory(doc, sel, options) {
var done = doc.history.done, last = lst(done);
if (last && last.ranges) {
done[done.length - 1] = sel;
setSelectionNoUndo(doc, sel, options);
} else {
setSelection(doc, sel, options);
}
}
// Set a new selection.
function setSelection(doc, sel, options) {
setSelectionNoUndo(doc, sel, options);
addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
}
function setSelectionNoUndo(doc, sel, options) {
if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
sel = filterSelectionChange(doc, sel);
var bias = options && options.bias ||
(cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
if (!(options && options.scroll === false) && doc.cm)
ensureCursorVisible(doc.cm);
}
function setSelectionInner(doc, sel) {
if (sel.equals(doc.sel)) return;
doc.sel = sel;
if (doc.cm) {
doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
signalCursorActivity(doc.cm);
}
signalLater(doc, "cursorActivity", doc);
}
// Verify that the selection does not partially select any atomic
// marked ranges.
function reCheckSelection(doc) {
setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
}
// Return a selection that does not partially select any atomic
// ranges.
function skipAtomicInSelection(doc, sel, bias, mayClear) {
var out;
for (var i = 0; i < sel.ranges.length; i++) {
var range = sel.ranges[i];
var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear);
var newHead = skipAtomic(doc, range.head, bias, mayClear);
if (out || newAnchor != range.anchor || newHead != range.head) {
if (!out) out = sel.ranges.slice(0, i);
out[i] = new Range(newAnchor, newHead);
}
}
return out ? normalizeSelection(out, sel.primIndex) : sel;
}
// Ensure a given position is not inside an atomic range.
function skipAtomic(doc, pos, bias, mayClear) {
var flipped = false, curPos = pos;
var dir = bias || 1;
doc.cantEdit = false;
search: for (;;) {
var line = getLine(doc, curPos.line);
if (line.markedSpans) {
for (var i = 0; i < line.markedSpans.length; ++i) {
var sp = line.markedSpans[i], m = sp.marker;
if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
(sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
if (mayClear) {
signal(m, "beforeCursorEnter");
if (m.explicitlyCleared) {
if (!line.markedSpans) break;
else {--i; continue;}
}
}
if (!m.atomic) continue;
var newPos = m.find(dir < 0 ? -1 : 1);
if (cmp(newPos, curPos) == 0) {
newPos.ch += dir;
if (newPos.ch < 0) {
if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
else newPos = null;
} else if (newPos.ch > line.text.length) {
if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
else newPos = null;
}
if (!newPos) {
if (flipped) {
// Driven in a corner -- no valid cursor position found at all
// -- try again *with* clearing, if we didn't already
if (!mayClear) return skipAtomic(doc, pos, bias, true);
// Otherwise, turn off editing until further notice, and return the start of the doc
doc.cantEdit = true;
return Pos(doc.first, 0);
}
flipped = true; newPos = pos; dir = -dir;
}
}
curPos = newPos;
continue search;
}
}
}
return curPos;
}
}
// SELECTION DRAWING
function updateSelection(cm) {
cm.display.input.showSelection(cm.display.input.prepareSelection());
}
function prepareSelection(cm, primary) {
var doc = cm.doc, result = {};
var curFragment = result.cursors = document.createDocumentFragment();
var selFragment = result.selection = document.createDocumentFragment();
for (var i = 0; i < doc.sel.ranges.length; i++) {
if (primary === false && i == doc.sel.primIndex) continue;
var range = doc.sel.ranges[i];
var collapsed = range.empty();
if (collapsed || cm.options.showCursorWhenSelecting)
drawSelectionCursor(cm, range.head, curFragment);
if (!collapsed)
drawSelectionRange(cm, range, selFragment);
}
return result;
}
// Draws a cursor for the given range
function drawSelectionCursor(cm, head, output) {
var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
cursor.style.left = pos.left + "px";
cursor.style.top = pos.top + "px";
cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
if (pos.other) {
// Secondary cursor, shown when on a 'jump' in bi-directional text
var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
otherCursor.style.display = "";
otherCursor.style.left = pos.other.left + "px";
otherCursor.style.top = pos.other.top + "px";
otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
}
}
// Draws the given range as a highlighted selection
function drawSelectionRange(cm, range, output) {
var display = cm.display, doc = cm.doc;
var fragment = document.createDocumentFragment();
var padding = paddingH(cm.display), leftSide = padding.left;
var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
function add(left, top, width, bottom) {
if (top < 0) top = 0;
top = Math.round(top);
bottom = Math.round(bottom);
fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
"px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
"px; height: " + (bottom - top) + "px"));
}
function drawForLine(line, fromArg, toArg) {
var lineObj = getLine(doc, line);
var lineLen = lineObj.text.length;
var start, end;
function coords(ch, bias) {
return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
}
iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
var leftPos = coords(from, "left"), rightPos, left, right;
if (from == to) {
rightPos = leftPos;
left = right = leftPos.left;
} else {
rightPos = coords(to - 1, "right");
if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
left = leftPos.left;
right = rightPos.right;
}
if (fromArg == null && from == 0) left = leftSide;
if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
add(left, leftPos.top, null, leftPos.bottom);
left = leftSide;
if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
}
if (toArg == null && to == lineLen) right = rightSide;
if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
start = leftPos;
if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
end = rightPos;
if (left < leftSide + 1) left = leftSide;
add(left, rightPos.top, right - left, rightPos.bottom);
});
return {start: start, end: end};
}
var sFrom = range.from(), sTo = range.to();
if (sFrom.line == sTo.line) {
drawForLine(sFrom.line, sFrom.ch, sTo.ch);
} else {
var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
var singleVLine = visualLine(fromLine) == visualLine(toLine);
var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
if (singleVLine) {
if (leftEnd.top < rightStart.top - 2) {
add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
} else {
add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
}
}
if (leftEnd.bottom < rightStart.top)
add(leftSide, leftEnd.bottom, null, rightStart.top);
}
output.appendChild(fragment);
}
// Cursor-blinking
function restartBlink(cm) {
if (!cm.state.focused) return;
var display = cm.display;
clearInterval(display.blinker);
var on = true;
display.cursorDiv.style.visibility = "";
if (cm.options.cursorBlinkRate > 0)
display.blinker = setInterval(function() {
display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
}, cm.options.cursorBlinkRate);
else if (cm.options.cursorBlinkRate < 0)
display.cursorDiv.style.visibility = "hidden";
}
// HIGHLIGHT WORKER
function startWorker(cm, time) {
if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
cm.state.highlight.set(time, bind(highlightWorker, cm));
}
function highlightWorker(cm) {
var doc = cm.doc;
if (doc.frontier < doc.first) doc.frontier = doc.first;
if (doc.frontier >= cm.display.viewTo) return;
var end = +new Date + cm.options.workTime;
var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
var changedLines = [];
doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
if (doc.frontier >= cm.display.viewFrom) { // Visible
var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength;
var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true);
line.styles = highlighted.styles;
var oldCls = line.styleClasses, newCls = highlighted.classes;
if (newCls) line.styleClasses = newCls;
else if (oldCls) line.styleClasses = null;
var ischange = !oldStyles || oldStyles.length != line.styles.length ||
oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
if (ischange) changedLines.push(doc.frontier);
line.stateAfter = tooLong ? state : copyState(doc.mode, state);
} else {
if (line.text.length <= cm.options.maxHighlightLength)
processLine(cm, line.text, state);
line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
}
++doc.frontier;
if (+new Date > end) {
startWorker(cm, cm.options.workDelay);
return true;
}
});
if (changedLines.length) runInOp(cm, function() {
for (var i = 0; i < changedLines.length; i++)
regLineChange(cm, changedLines[i], "text");
});
}
// Finds the line to start with when starting a parse. Tries to
// find a line with a stateAfter, so that it can start with a
// valid state. If that fails, it returns the line with the
// smallest indentation, which tends to need the least context to
// parse correctly.
function findStartLine(cm, n, precise) {
var minindent, minline, doc = cm.doc;
var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
for (var search = n; search > lim; --search) {
if (search <= doc.first) return doc.first;
var line = getLine(doc, search - 1);
if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
var indented = countColumn(line.text, null, cm.options.tabSize);
if (minline == null || minindent > indented) {
minline = search - 1;
minindent = indented;
}
}
return minline;
}
function getStateBefore(cm, n, precise) {
var doc = cm.doc, display = cm.display;
if (!doc.mode.startState) return true;
var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
if (!state) state = startState(doc.mode);
else state = copyState(doc.mode, state);
doc.iter(pos, n, function(line) {
processLine(cm, line.text, state);
var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
line.stateAfter = save ? copyState(doc.mode, state) : null;
++pos;
});
if (precise) doc.frontier = pos;
return state;
}
// POSITION MEASUREMENT
function paddingTop(display) {return display.lineSpace.offsetTop;}
function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
function paddingH(display) {
if (display.cachedPaddingH) return display.cachedPaddingH;
var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
return data;
}
function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
function displayWidth(cm) {
return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
}
function displayHeight(cm) {
return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
}
// Ensure the lineView.wrapping.heights array is populated. This is
// an array of bottom offsets for the lines that make up a drawn
// line. When lineWrapping is on, there might be more than one
// height.
function ensureLineHeights(cm, lineView, rect) {
var wrapping = cm.options.lineWrapping;
var curWidth = wrapping && displayWidth(cm);
if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
var heights = lineView.measure.heights = [];
if (wrapping) {
lineView.measure.width = curWidth;
var rects = lineView.text.firstChild.getClientRects();
for (var i = 0; i < rects.length - 1; i++) {
var cur = rects[i], next = rects[i + 1];
if (Math.abs(cur.bottom - next.bottom) > 2)
heights.push((cur.bottom + next.top) / 2 - rect.top);
}
}
heights.push(rect.bottom - rect.top);
}
}
// Find a line map (mapping character offsets to text nodes) and a
// measurement cache for the given line number. (A line view might
// contain multiple lines when collapsed ranges are present.)
function mapFromLineView(lineView, line, lineN) {
if (lineView.line == line)
return {map: lineView.measure.map, cache: lineView.measure.cache};
for (var i = 0; i < lineView.rest.length; i++)
if (lineView.rest[i] == line)
return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
for (var i = 0; i < lineView.rest.length; i++)
if (lineNo(lineView.rest[i]) > lineN)
return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
}
// Render a line into the hidden node display.externalMeasured. Used
// when measurement is needed for a line that's not in the viewport.
function updateExternalMeasurement(cm, line) {
line = visualLine(line);
var lineN = lineNo(line);
var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
view.lineN = lineN;
var built = view.built = buildLineContent(cm, view);
view.text = built.pre;
removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
return view;
}
// Get a {top, bottom, left, right} box (in line-local coordinates)
// for a given character.
function measureChar(cm, line, ch, bias) {
return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
}
// Find a line view that corresponds to the given line number.
function findViewForLine(cm, lineN) {
if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
return cm.display.view[findViewIndex(cm, lineN)];
var ext = cm.display.externalMeasured;
if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
return ext;
}
// Measurement can be split in two steps, the set-up work that
// applies to the whole line, and the measurement of the actual
// character. Functions like coordsChar, that need to do a lot of
// measurements in a row, can thus ensure that the set-up work is
// only done once.
function prepareMeasureForLine(cm, line) {
var lineN = lineNo(line);
var view = findViewForLine(cm, lineN);
if (view && !view.text) {
view = null;
} else if (view && view.changes) {
updateLineForChanges(cm, view, lineN, getDimensions(cm));
cm.curOp.forceUpdate = true;
}
if (!view)
view = updateExternalMeasurement(cm, line);
var info = mapFromLineView(view, line, lineN);
return {
line: line, view: view, rect: null,
map: info.map, cache: info.cache, before: info.before,
hasHeights: false
};
}
// Given a prepared measurement object, measures the position of an
// actual character (or fetches it from the cache).
function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
if (prepared.before) ch = -1;
var key = ch + (bias || ""), found;
if (prepared.cache.hasOwnProperty(key)) {
found = prepared.cache[key];
} else {
if (!prepared.rect)
prepared.rect = prepared.view.text.getBoundingClientRect();
if (!prepared.hasHeights) {
ensureLineHeights(cm, prepared.view, prepared.rect);
prepared.hasHeights = true;
}
found = measureCharInner(cm, prepared, ch, bias);
if (!found.bogus) prepared.cache[key] = found;
}
return {left: found.left, right: found.right,
top: varHeight ? found.rtop : found.top,
bottom: varHeight ? found.rbottom : found.bottom};
}
var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
function nodeAndOffsetInLineMap(map, ch, bias) {
var node, start, end, collapse;
// First, search the line map for the text node corresponding to,
// or closest to, the target character.
for (var i = 0; i < map.length; i += 3) {
var mStart = map[i], mEnd = map[i + 1];
if (ch < mStart) {
start = 0; end = 1;
collapse = "left";
} else if (ch < mEnd) {
start = ch - mStart;
end = start + 1;
} else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
end = mEnd - mStart;
start = end - 1;
if (ch >= mEnd) collapse = "right";
}
if (start != null) {
node = map[i + 2];
if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
collapse = bias;
if (bias == "left" && start == 0)
while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
node = map[(i -= 3) + 2];
collapse = "left";
}
if (bias == "right" && start == mEnd - mStart)
while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
node = map[(i += 3) + 2];
collapse = "right";
}
break;
}
}
return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd};
}
function measureCharInner(cm, prepared, ch, bias) {
var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
var rect;
if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end;
if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) {
rect = node.parentNode.getBoundingClientRect();
} else if (ie && cm.options.lineWrapping) {
var rects = range(node, start, end).getClientRects();
if (rects.length)
rect = rects[bias == "right" ? rects.length - 1 : 0];
else
rect = nullRect;
} else {
rect = range(node, start, end).getBoundingClientRect() || nullRect;
}
if (rect.left || rect.right || start == 0) break;
end = start;
start = start - 1;
collapse = "right";
}
if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
} else { // If it is a widget, simply get the box for the whole widget.
if (start > 0) collapse = bias = "right";
var rects;
if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
rect = rects[bias == "right" ? rects.length - 1 : 0];
else
rect = node.getBoundingClientRect();
}
if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
var rSpan = node.parentNode.getClientRects()[0];
if (rSpan)
rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
else
rect = nullRect;
}
var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
var mid = (rtop + rbot) / 2;
var heights = prepared.view.measure.heights;
for (var i = 0; i < heights.length - 1; i++)
if (mid < heights[i]) break;
var top = i ? heights[i - 1] : 0, bot = heights[i];
var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
top: top, bottom: bot};
if (!rect.left && !rect.right) result.bogus = true;
if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
return result;
}
// Work around problem with bounding client rects on ranges being
// returned incorrectly when zoomed on IE10 and below.
function maybeUpdateRectForZooming(measure, rect) {
if (!window.screen || screen.logicalXDPI == null ||
screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
return rect;
var scaleX = screen.logicalXDPI / screen.deviceXDPI;
var scaleY = screen.logicalYDPI / screen.deviceYDPI;
return {left: rect.left * scaleX, right: rect.right * scaleX,
top: rect.top * scaleY, bottom: rect.bottom * scaleY};
}
function clearLineMeasurementCacheFor(lineView) {
if (lineView.measure) {
lineView.measure.cache = {};
lineView.measure.heights = null;
if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
lineView.measure.caches[i] = {};
}
}
function clearLineMeasurementCache(cm) {
cm.display.externalMeasure = null;
removeChildren(cm.display.lineMeasure);
for (var i = 0; i < cm.display.view.length; i++)
clearLineMeasurementCacheFor(cm.display.view[i]);
}
function clearCaches(cm) {
clearLineMeasurementCache(cm);
cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
cm.display.lineNumChars = null;
}
function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
// Converts a {top, bottom, left, right} box from line-local
// coordinates into another coordinate system. Context may be one of
// "line", "div" (display.lineDiv), "local"/null (editor), "window",
// or "page".
function intoCoordSystem(cm, lineObj, rect, context) {
if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
var size = widgetHeight(lineObj.widgets[i]);
rect.top += size; rect.bottom += size;
}
if (context == "line") return rect;
if (!context) context = "local";
var yOff = heightAtLine(lineObj);
if (context == "local") yOff += paddingTop(cm.display);
else yOff -= cm.display.viewOffset;
if (context == "page" || context == "window") {
var lOff = cm.display.lineSpace.getBoundingClientRect();
yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
rect.left += xOff; rect.right += xOff;
}
rect.top += yOff; rect.bottom += yOff;
return rect;
}
// Coverts a box from "div" coords to another coordinate system.
// Context may be "window", "page", "div", or "local"/null.
function fromCoordSystem(cm, coords, context) {
if (context == "div") return coords;
var left = coords.left, top = coords.top;
// First move into "page" coordinate system
if (context == "page") {
left -= pageScrollX();
top -= pageScrollY();
} else if (context == "local" || !context) {
var localBox = cm.display.sizer.getBoundingClientRect();
left += localBox.left;
top += localBox.top;
}
var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
}
function charCoords(cm, pos, context, lineObj, bias) {
if (!lineObj) lineObj = getLine(cm.doc, pos.line);
return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
}
// Returns a box for a given cursor position, which may have an
// 'other' property containing the position of the secondary cursor
// on a bidi boundary.
function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
lineObj = lineObj || getLine(cm.doc, pos.line);
if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
function get(ch, right) {
var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
if (right) m.left = m.right; else m.right = m.left;
return intoCoordSystem(cm, lineObj, m, context);
}
function getBidi(ch, partPos) {
var part = order[partPos], right = part.level % 2;
if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
part = order[--partPos];
ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
right = true;
} else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
part = order[++partPos];
ch = bidiLeft(part) - part.level % 2;
right = false;
}
if (right && ch == part.to && ch > part.from) return get(ch - 1);
return get(ch, right);
}
var order = getOrder(lineObj), ch = pos.ch;
if (!order) return get(ch);
var partPos = getBidiPartAt(order, ch);
var val = getBidi(ch, partPos);
if (bidiOther != null) val.other = getBidi(ch, bidiOther);
return val;
}
// Used to cheaply estimate the coordinates for a position. Used for
// intermediate scroll updates.
function estimateCoords(cm, pos) {
var left = 0, pos = clipPos(cm.doc, pos);
if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
var lineObj = getLine(cm.doc, pos.line);
var top = heightAtLine(lineObj) + paddingTop(cm.display);
return {left: left, right: left, top: top, bottom: top + lineObj.height};
}
// Positions returned by coordsChar contain some extra information.
// xRel is the relative x position of the input coordinates compared
// to the found position (so xRel > 0 means the coordinates are to
// the right of the character position, for example). When outside
// is true, that means the coordinates lie outside the line's
// vertical range.
function PosWithInfo(line, ch, outside, xRel) {
var pos = Pos(line, ch);
pos.xRel = xRel;
if (outside) pos.outside = true;
return pos;
}
// Compute the character position closest to the given coordinates.
// Input must be lineSpace-local ("div" coordinate system).
function coordsChar(cm, x, y) {
var doc = cm.doc;
y += cm.display.viewOffset;
if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
if (lineN > last)
return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
if (x < 0) x = 0;
var lineObj = getLine(doc, lineN);
for (;;) {
var found = coordsCharInner(cm, lineObj, lineN, x, y);
var merged = collapsedSpanAtEnd(lineObj);
var mergedPos = merged && merged.find(0, true);
if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
lineN = lineNo(lineObj = mergedPos.to.line);
else
return found;
}
}
function coordsCharInner(cm, lineObj, lineNo, x, y) {
var innerOff = y - heightAtLine(lineObj);
var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
var preparedMeasure = prepareMeasureForLine(cm, lineObj);
function getX(ch) {
var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
wrongLine = true;
if (innerOff > sp.bottom) return sp.left - adjust;
else if (innerOff < sp.top) return sp.left + adjust;
else wrongLine = false;
return sp.left;
}
var bidi = getOrder(lineObj), dist = lineObj.text.length;
var from = lineLeft(lineObj), to = lineRight(lineObj);
var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
// Do a binary search between these bounds.
for (;;) {
if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
var ch = x < fromX || x - fromX <= toX - x ? from : to;
var xDiff = x - (ch == from ? fromX : toX);
while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
return pos;
}
var step = Math.ceil(dist / 2), middle = from + step;
if (bidi) {
middle = from;
for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
}
var middleX = getX(middle);
if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
}
}
var measureText;
// Compute the default text height.
function textHeight(display) {
if (display.cachedTextHeight != null) return display.cachedTextHeight;
if (measureText == null) {
measureText = elt("pre");
// Measure a bunch of lines, for browsers that compute
// fractional heights.
for (var i = 0; i < 49; ++i) {
measureText.appendChild(document.createTextNode("x"));
measureText.appendChild(elt("br"));
}
measureText.appendChild(document.createTextNode("x"));
}
removeChildrenAndAdd(display.measure, measureText);
var height = measureText.offsetHeight / 50;
if (height > 3) display.cachedTextHeight = height;
removeChildren(display.measure);
return height || 1;
}
// Compute the default character width.
function charWidth(display) {
if (display.cachedCharWidth != null) return display.cachedCharWidth;
var anchor = elt("span", "xxxxxxxxxx");
var pre = elt("pre", [anchor]);
removeChildrenAndAdd(display.measure, pre);
var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
if (width > 2) display.cachedCharWidth = width;
return width || 10;
}
// OPERATIONS
// Operations are used to wrap a series of changes to the editor
// state in such a way that each change won't have to update the
// cursor and display (which would be awkward, slow, and
// error-prone). Instead, display updates are batched and then all
// combined and executed at once.
var operationGroup = null;
var nextOpId = 0;
// Start a new operation.
function startOperation(cm) {
cm.curOp = {
cm: cm,
viewChanged: false, // Flag that indicates that lines might need to be redrawn
startHeight: cm.doc.height, // Used to detect need to update scrollbar
forceUpdate: false, // Used to force a redraw
updateInput: null, // Whether to reset the input textarea
typing: false, // Whether this reset should be careful to leave existing text (for compositing)
changeObjs: null, // Accumulated changes, for firing change events
cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
selectionChanged: false, // Whether the selection needs to be redrawn
updateMaxLine: false, // Set when the widest line needs to be determined anew
scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
scrollToPos: null, // Used to scroll to a specific position
focus: false,
id: ++nextOpId // Unique ID
};
if (operationGroup) {
operationGroup.ops.push(cm.curOp);
} else {
cm.curOp.ownsGroup = operationGroup = {
ops: [cm.curOp],
delayedCallbacks: []
};
}
}
function fireCallbacksForOps(group) {
// Calls delayed callbacks and cursorActivity handlers until no
// new ones appear
var callbacks = group.delayedCallbacks, i = 0;
do {
for (; i < callbacks.length; i++)
callbacks[i].call(null);
for (var j = 0; j < group.ops.length; j++) {
var op = group.ops[j];
if (op.cursorActivityHandlers)
while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm);
}
} while (i < callbacks.length);
}
// Finish an operation, updating the display and signalling delayed events
function endOperation(cm) {
var op = cm.curOp, group = op.ownsGroup;
if (!group) return;
try { fireCallbacksForOps(group); }
finally {
operationGroup = null;
for (var i = 0; i < group.ops.length; i++)
group.ops[i].cm.curOp = null;
endOperations(group);
}
}
// The DOM updates done when an operation finishes are batched so
// that the minimum number of relayouts are required.
function endOperations(group) {
var ops = group.ops;
for (var i = 0; i < ops.length; i++) // Read DOM
endOperation_R1(ops[i]);
for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
endOperation_W1(ops[i]);
for (var i = 0; i < ops.length; i++) // Read DOM
endOperation_R2(ops[i]);
for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
endOperation_W2(ops[i]);
for (var i = 0; i < ops.length; i++) // Read DOM
endOperation_finish(ops[i]);
}
function endOperation_R1(op) {
var cm = op.cm, display = cm.display;
maybeClipScrollbars(cm);
if (op.updateMaxLine) findMaxLine(cm);
op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
op.scrollToPos.to.line >= display.viewTo) ||
display.maxLineChanged && cm.options.lineWrapping;
op.update = op.mustUpdate &&
new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
}
function endOperation_W1(op) {
op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
}
function endOperation_R2(op) {
var cm = op.cm, display = cm.display;
if (op.updatedDisplay) updateHeightsInViewport(cm);
op.barMeasure = measureForScrollbars(cm);
// If the max line changed since it was last measured, measure it,
// and ensure the document's width matches it.
// updateDisplay_W2 will use these properties to do the actual resizing
if (display.maxLineChanged && !cm.options.lineWrapping) {
op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
cm.display.sizerWidth = op.adjustWidthTo;
op.barMeasure.scrollWidth =
Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
}
if (op.updatedDisplay || op.selectionChanged)
op.preparedSelection = display.input.prepareSelection();
}
function endOperation_W2(op) {
var cm = op.cm;
if (op.adjustWidthTo != null) {
cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
if (op.maxScrollLeft < cm.doc.scrollLeft)
setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
cm.display.maxLineChanged = false;
}
if (op.preparedSelection)
cm.display.input.showSelection(op.preparedSelection);
if (op.updatedDisplay)
setDocumentHeight(cm, op.barMeasure);
if (op.updatedDisplay || op.startHeight != cm.doc.height)
updateScrollbars(cm, op.barMeasure);
if (op.selectionChanged) restartBlink(cm);
if (cm.state.focused && op.updateInput)
cm.display.input.reset(op.typing);
if (op.focus && op.focus == activeElt()) ensureFocus(op.cm);
}
function endOperation_finish(op) {
var cm = op.cm, display = cm.display, doc = cm.doc;
if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
// Abort mouse wheel delta measurement, when scrolling explicitly
if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
display.wheelStartX = display.wheelStartY = null;
// Propagate the scroll position to the actual DOM scroller
if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
display.scrollbars.setScrollTop(doc.scrollTop);
display.scroller.scrollTop = doc.scrollTop;
}
if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), op.scrollLeft));
display.scrollbars.setScrollLeft(doc.scrollLeft);
display.scroller.scrollLeft = doc.scrollLeft;
alignHorizontally(cm);
}
// If we need to scroll a specific position into view, do so.
if (op.scrollToPos) {
var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
}
// Fire events for markers that are hidden/unidden by editing or
// undoing
var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
if (hidden) for (var i = 0; i < hidden.length; ++i)
if (!hidden[i].lines.length) signal(hidden[i], "hide");
if (unhidden) for (var i = 0; i < unhidden.length; ++i)
if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
if (display.wrapper.offsetHeight)
doc.scrollTop = cm.display.scroller.scrollTop;
// Fire change events, and delayed event handlers
if (op.changeObjs)
signal(cm, "changes", cm, op.changeObjs);
if (op.update)
op.update.finish();
}
// Run the given function in an operation
function runInOp(cm, f) {
if (cm.curOp) return f();
startOperation(cm);
try { return f(); }
finally { endOperation(cm); }
}
// Wraps a function in an operation. Returns the wrapped function.
function operation(cm, f) {
return function() {
if (cm.curOp) return f.apply(cm, arguments);
startOperation(cm);
try { return f.apply(cm, arguments); }
finally { endOperation(cm); }
};
}
// Used to add methods to editor and doc instances, wrapping them in
// operations.
function methodOp(f) {
return function() {
if (this.curOp) return f.apply(this, arguments);
startOperation(this);
try { return f.apply(this, arguments); }
finally { endOperation(this); }
};
}
function docMethodOp(f) {
return function() {
var cm = this.cm;
if (!cm || cm.curOp) return f.apply(this, arguments);
startOperation(cm);
try { return f.apply(this, arguments); }
finally { endOperation(cm); }
};
}
// VIEW TRACKING
// These objects are used to represent the visible (currently drawn)
// part of the document. A LineView may correspond to multiple
// logical lines, if those are connected by collapsed ranges.
function LineView(doc, line, lineN) {
// The starting line
this.line = line;
// Continuing lines, if any
this.rest = visualLineContinued(line);
// Number of logical lines in this visual line
this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
this.node = this.text = null;
this.hidden = lineIsHidden(doc, line);
}
// Create a range of LineView objects for the given lines.
function buildViewArray(cm, from, to) {
var array = [], nextPos;
for (var pos = from; pos < to; pos = nextPos) {
var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
nextPos = pos + view.size;
array.push(view);
}
return array;
}
// Updates the display.view data structure for a given change to the
// document. From and to are in pre-change coordinates. Lendiff is
// the amount of lines added or subtracted by the change. This is
// used for changes that span multiple lines, or change the way
// lines are divided into visual lines. regLineChange (below)
// registers single-line changes.
function regChange(cm, from, to, lendiff) {
if (from == null) from = cm.doc.first;
if (to == null) to = cm.doc.first + cm.doc.size;
if (!lendiff) lendiff = 0;
var display = cm.display;
if (lendiff && to < display.viewTo &&
(display.updateLineNumbers == null || display.updateLineNumbers > from))
display.updateLineNumbers = from;
cm.curOp.viewChanged = true;
if (from >= display.viewTo) { // Change after
if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
resetView(cm);
} else if (to <= display.viewFrom) { // Change before
if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
resetView(cm);
} else {
display.viewFrom += lendiff;
display.viewTo += lendiff;
}
} else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
resetView(cm);
} else if (from <= display.viewFrom) { // Top overlap
var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
if (cut) {
display.view = display.view.slice(cut.index);
display.viewFrom = cut.lineN;
display.viewTo += lendiff;
} else {
resetView(cm);
}
} else if (to >= display.viewTo) { // Bottom overlap
var cut = viewCuttingPoint(cm, from, from, -1);
if (cut) {
display.view = display.view.slice(0, cut.index);
display.viewTo = cut.lineN;
} else {
resetView(cm);
}
} else { // Gap in the middle
var cutTop = viewCuttingPoint(cm, from, from, -1);
var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
if (cutTop && cutBot) {
display.view = display.view.slice(0, cutTop.index)
.concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
.concat(display.view.slice(cutBot.index));
display.viewTo += lendiff;
} else {
resetView(cm);
}
}
var ext = display.externalMeasured;
if (ext) {
if (to < ext.lineN)
ext.lineN += lendiff;
else if (from < ext.lineN + ext.size)
display.externalMeasured = null;
}
}
// Register a change to a single line. Type must be one of "text",
// "gutter", "class", "widget"
function regLineChange(cm, line, type) {
cm.curOp.viewChanged = true;
var display = cm.display, ext = cm.display.externalMeasured;
if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
display.externalMeasured = null;
if (line < display.viewFrom || line >= display.viewTo) return;
var lineView = display.view[findViewIndex(cm, line)];
if (lineView.node == null) return;
var arr = lineView.changes || (lineView.changes = []);
if (indexOf(arr, type) == -1) arr.push(type);
}
// Clear the view.
function resetView(cm) {
cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
cm.display.view = [];
cm.display.viewOffset = 0;
}
// Find the view element corresponding to a given line. Return null
// when the line isn't visible.
function findViewIndex(cm, n) {
if (n >= cm.display.viewTo) return null;
n -= cm.display.viewFrom;
if (n < 0) return null;
var view = cm.display.view;
for (var i = 0; i < view.length; i++) {
n -= view[i].size;
if (n < 0) return i;
}
}
function viewCuttingPoint(cm, oldN, newN, dir) {
var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
return {index: index, lineN: newN};
for (var i = 0, n = cm.display.viewFrom; i < index; i++)
n += view[i].size;
if (n != oldN) {
if (dir > 0) {
if (index == view.length - 1) return null;
diff = (n + view[index].size) - oldN;
index++;
} else {
diff = n - oldN;
}
oldN += diff; newN += diff;
}
while (visualLineNo(cm.doc, newN) != newN) {
if (index == (dir < 0 ? 0 : view.length - 1)) return null;
newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
index += dir;
}
return {index: index, lineN: newN};
}
// Force the view to cover a given range, adding empty view element
// or clipping off existing ones as needed.
function adjustView(cm, from, to) {
var display = cm.display, view = display.view;
if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
display.view = buildViewArray(cm, from, to);
display.viewFrom = from;
} else {
if (display.viewFrom > from)
display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
else if (display.viewFrom < from)
display.view = display.view.slice(findViewIndex(cm, from));
display.viewFrom = from;
if (display.viewTo < to)
display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
else if (display.viewTo > to)
display.view = display.view.slice(0, findViewIndex(cm, to));
}
display.viewTo = to;
}
// Count the number of lines in the view whose DOM representation is
// out of date (or nonexistent).
function countDirtyView(cm) {
var view = cm.display.view, dirty = 0;
for (var i = 0; i < view.length; i++) {
var lineView = view[i];
if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
}
return dirty;
}
// EVENT HANDLERS
// Attach the necessary event handlers when initializing the editor
function registerEventHandlers(cm) {
var d = cm.display;
on(d.scroller, "mousedown", operation(cm, onMouseDown));
// Older IE's will not fire a second mousedown for a double click
if (ie && ie_version < 11)
on(d.scroller, "dblclick", operation(cm, function(e) {
if (signalDOMEvent(cm, e)) return;
var pos = posFromMouse(cm, e);
if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
e_preventDefault(e);
var word = cm.findWordAt(pos);
extendSelection(cm.doc, word.anchor, word.head);
}));
else
on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
// Some browsers fire contextmenu *after* opening the menu, at
// which point we can't mess with it anymore. Context menu is
// handled in onMouseDown for these browsers.
if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
// Used to suppress mouse event handling when a touch happens
var touchFinished, prevTouch = {end: 0};
function finishTouch() {
if (d.activeTouch) {
touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000);
prevTouch = d.activeTouch;
prevTouch.end = +new Date;
}
};
function isMouseLikeTouchEvent(e) {
if (e.touches.length != 1) return false;
var touch = e.touches[0];
return touch.radiusX <= 1 && touch.radiusY <= 1;
}
function farAway(touch, other) {
if (other.left == null) return true;
var dx = other.left - touch.left, dy = other.top - touch.top;
return dx * dx + dy * dy > 20 * 20;
}
on(d.scroller, "touchstart", function(e) {
if (!isMouseLikeTouchEvent(e)) {
clearTimeout(touchFinished);
var now = +new Date;
d.activeTouch = {start: now, moved: false,
prev: now - prevTouch.end <= 300 ? prevTouch : null};
if (e.touches.length == 1) {
d.activeTouch.left = e.touches[0].pageX;
d.activeTouch.top = e.touches[0].pageY;
}
}
});
on(d.scroller, "touchmove", function() {
if (d.activeTouch) d.activeTouch.moved = true;
});
on(d.scroller, "touchend", function(e) {
var touch = d.activeTouch;
if (touch && !eventInWidget(d, e) && touch.left != null &&
!touch.moved && new Date - touch.start < 300) {
var pos = cm.coordsChar(d.activeTouch, "page"), range;
if (!touch.prev || farAway(touch, touch.prev)) // Single tap
range = new Range(pos, pos);
else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
range = cm.findWordAt(pos);
else // Triple tap
range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
cm.setSelection(range.anchor, range.head);
cm.focus();
e_preventDefault(e);
}
finishTouch();
});
on(d.scroller, "touchcancel", finishTouch);
// Sync scrolling between fake scrollbars and real scrollable
// area, ensure viewport is updated when scrolling.
on(d.scroller, "scroll", function() {
if (d.scroller.clientHeight) {
setScrollTop(cm, d.scroller.scrollTop);
setScrollLeft(cm, d.scroller.scrollLeft, true);
signal(cm, "scroll", cm);
}
});
// Listen to wheel events in order to try and update the viewport on time.
on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
// Prevent wrapper from ever scrolling
on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
d.dragFunctions = {
enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);},
over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
start: function(e){onDragStart(cm, e);},
drop: operation(cm, onDrop),
leave: function() {clearDragCursor(cm);}
};
var inp = d.input.getField();
on(inp, "keyup", function(e) { onKeyUp.call(cm, e); });
on(inp, "keydown", operation(cm, onKeyDown));
on(inp, "keypress", operation(cm, onKeyPress));
on(inp, "focus", bind(onFocus, cm));
on(inp, "blur", bind(onBlur, cm));
}
function dragDropChanged(cm, value, old) {
var wasOn = old && old != CodeMirror.Init;
if (!value != !wasOn) {
var funcs = cm.display.dragFunctions;
var toggle = value ? on : off;
toggle(cm.display.scroller, "dragstart", funcs.start);
toggle(cm.display.scroller, "dragenter", funcs.enter);
toggle(cm.display.scroller, "dragover", funcs.over);
toggle(cm.display.scroller, "dragleave", funcs.leave);
toggle(cm.display.scroller, "drop", funcs.drop);
}
}
// Called when the window resizes
function onResize(cm) {
var d = cm.display;
if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
return;
// Might be a text scaling operation, clear size caches.
d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
d.scrollbarsClipped = false;
cm.setSize();
}
// MOUSE EVENTS
// Return true when the given mouse event happened in a widget
function eventInWidget(display, e) {
for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
(n.parentNode == display.sizer && n != display.mover))
return true;
}
}
// Given a mouse event, find the corresponding position. If liberal
// is false, it checks whether a gutter or scrollbar was clicked,
// and returns null if it was. forRect is used by rectangular
// selections, and tries to estimate a character position even for
// coordinates beyond the right of the text.
function posFromMouse(cm, e, liberal, forRect) {
var display = cm.display;
if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null;
var x, y, space = display.lineSpace.getBoundingClientRect();
// Fails unpredictably on IE[67] when mouse is dragged around quickly.
try { x = e.clientX - space.left; y = e.clientY - space.top; }
catch (e) { return null; }
var coords = coordsChar(cm, x, y), line;
if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
}
return coords;
}
// A mouse down can be a single click, double click, triple click,
// start of selection drag, start of text drag, new cursor
// (ctrl-click), rectangle drag (alt-drag), or xwin
// middle-click-paste. Or it might be a click on something we should
// not interfere with, such as a scrollbar or widget.
function onMouseDown(e) {
var cm = this, display = cm.display;
if (display.activeTouch && display.input.supportsTouch() || signalDOMEvent(cm, e)) return;
display.shift = e.shiftKey;
if (eventInWidget(display, e)) {
if (!webkit) {
// Briefly turn off draggability, to allow widgets to do
// normal dragging things.
display.scroller.draggable = false;
setTimeout(function(){display.scroller.draggable = true;}, 100);
}
return;
}
if (clickInGutter(cm, e)) return;
var start = posFromMouse(cm, e);
window.focus();
switch (e_button(e)) {
case 1:
// #3261: make sure, that we're not starting a second selection
if (cm.state.selectingText)
cm.state.selectingText(e);
else if (start)
leftButtonDown(cm, e, start);
else if (e_target(e) == display.scroller)
e_preventDefault(e);
break;
case 2:
if (webkit) cm.state.lastMiddleDown = +new Date;
if (start) extendSelection(cm.doc, start);
setTimeout(function() {display.input.focus();}, 20);
e_preventDefault(e);
break;
case 3:
if (captureRightClick) onContextMenu(cm, e);
else delayBlurEvent(cm);
break;
}
}
var lastClick, lastDoubleClick;
function leftButtonDown(cm, e, start) {
if (ie) setTimeout(bind(ensureFocus, cm), 0);
else cm.curOp.focus = activeElt();
var now = +new Date, type;
if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
type = "triple";
} else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
type = "double";
lastDoubleClick = {time: now, pos: start};
} else {
type = "single";
lastClick = {time: now, pos: start};
}
var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) &&
type == "single" && (contained = sel.contains(start)) > -1 &&
(cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) &&
(cmp(contained.to(), start) > 0 || start.xRel < 0))
leftButtonStartDrag(cm, e, start, modifier);
else
leftButtonSelect(cm, e, start, type, modifier);
}
// Start a text drag. When it ends, see if any dragging actually
// happen, and treat as a click if it didn't.
function leftButtonStartDrag(cm, e, start, modifier) {
var display = cm.display, startTime = +new Date;
var dragEnd = operation(cm, function(e2) {
if (webkit) display.scroller.draggable = false;
cm.state.draggingText = false;
off(document, "mouseup", dragEnd);
off(display.scroller, "drop", dragEnd);
if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
e_preventDefault(e2);
if (!modifier && +new Date - 200 < startTime)
extendSelection(cm.doc, start);
// Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
if (webkit || ie && ie_version == 9)
setTimeout(function() {document.body.focus(); display.input.focus();}, 20);
else
display.input.focus();
}
});
// Let the drag handler handle this.
if (webkit) display.scroller.draggable = true;
cm.state.draggingText = dragEnd;
// IE's approach to draggable
if (display.scroller.dragDrop) display.scroller.dragDrop();
on(document, "mouseup", dragEnd);
on(display.scroller, "drop", dragEnd);
}
// Normal selection, as opposed to text dragging.
function leftButtonSelect(cm, e, start, type, addNew) {
var display = cm.display, doc = cm.doc;
e_preventDefault(e);
var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
if (addNew && !e.shiftKey) {
ourIndex = doc.sel.contains(start);
if (ourIndex > -1)
ourRange = ranges[ourIndex];
else
ourRange = new Range(start, start);
} else {
ourRange = doc.sel.primary();
ourIndex = doc.sel.primIndex;
}
if (e.altKey) {
type = "rect";
if (!addNew) ourRange = new Range(start, start);
start = posFromMouse(cm, e, true, true);
ourIndex = -1;
} else if (type == "double") {
var word = cm.findWordAt(start);
if (cm.display.shift || doc.extend)
ourRange = extendRange(doc, ourRange, word.anchor, word.head);
else
ourRange = word;
} else if (type == "triple") {
var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
if (cm.display.shift || doc.extend)
ourRange = extendRange(doc, ourRange, line.anchor, line.head);
else
ourRange = line;
} else {
ourRange = extendRange(doc, ourRange, start);
}
if (!addNew) {
ourIndex = 0;
setSelection(doc, new Selection([ourRange], 0), sel_mouse);
startSel = doc.sel;
} else if (ourIndex == -1) {
ourIndex = ranges.length;
setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
{scroll: false, origin: "*mouse"});
} else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
{scroll: false, origin: "*mouse"});
startSel = doc.sel;
} else {
replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
}
var lastPos = start;
function extendTo(pos) {
if (cmp(lastPos, pos) == 0) return;
lastPos = pos;
if (type == "rect") {
var ranges = [], tabSize = cm.options.tabSize;
var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
line <= end; line++) {
var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
if (left == right)
ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
else if (text.length > leftPos)
ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
}
if (!ranges.length) ranges.push(new Range(start, start));
setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
{origin: "*mouse", scroll: false});
cm.scrollIntoView(pos);
} else {
var oldRange = ourRange;
var anchor = oldRange.anchor, head = pos;
if (type != "single") {
if (type == "double")
var range = cm.findWordAt(pos);
else
var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
if (cmp(range.anchor, anchor) > 0) {
head = range.head;
anchor = minPos(oldRange.from(), range.anchor);
} else {
head = range.anchor;
anchor = maxPos(oldRange.to(), range.head);
}
}
var ranges = startSel.ranges.slice(0);
ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
}
}
var editorSize = display.wrapper.getBoundingClientRect();
// Used to ensure timeout re-tries don't fire when another extend
// happened in the meantime (clearTimeout isn't reliable -- at
// least on Chrome, the timeouts still happen even when cleared,
// if the clear happens after their scheduled firing time).
var counter = 0;
function extend(e) {
var curCount = ++counter;
var cur = posFromMouse(cm, e, true, type == "rect");
if (!cur) return;
if (cmp(cur, lastPos) != 0) {
cm.curOp.focus = activeElt();
extendTo(cur);
var visible = visibleLines(display, doc);
if (cur.line >= visible.to || cur.line < visible.from)
setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
} else {
var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
if (outside) setTimeout(operation(cm, function() {
if (counter != curCount) return;
display.scroller.scrollTop += outside;
extend(e);
}), 50);
}
}
function done(e) {
cm.state.selectingText = false;
counter = Infinity;
e_preventDefault(e);
display.input.focus();
off(document, "mousemove", move);
off(document, "mouseup", up);
doc.history.lastSelOrigin = null;
}
var move = operation(cm, function(e) {
if (!e_button(e)) done(e);
else extend(e);
});
var up = operation(cm, done);
cm.state.selectingText = up;
on(document, "mousemove", move);
on(document, "mouseup", up);
}
// Determines whether an event happened in the gutter, and fires the
// handlers for the corresponding event.
function gutterEvent(cm, e, type, prevent, signalfn) {
try { var mX = e.clientX, mY = e.clientY; }
catch(e) { return false; }
if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
if (prevent) e_preventDefault(e);
var display = cm.display;
var lineBox = display.lineDiv.getBoundingClientRect();
if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
mY -= lineBox.top - display.viewOffset;
for (var i = 0; i < cm.options.gutters.length; ++i) {
var g = display.gutters.childNodes[i];
if (g && g.getBoundingClientRect().right >= mX) {
var line = lineAtHeight(cm.doc, mY);
var gutter = cm.options.gutters[i];
signalfn(cm, type, cm, line, gutter, e);
return e_defaultPrevented(e);
}
}
}
function clickInGutter(cm, e) {
return gutterEvent(cm, e, "gutterClick", true, signalLater);
}
// Kludge to work around strange IE behavior where it'll sometimes
// re-fire a series of drag-related events right after the drop (#1551)
var lastDrop = 0;
function onDrop(e) {
var cm = this;
clearDragCursor(cm);
if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
return;
e_preventDefault(e);
if (ie) lastDrop = +new Date;
var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
if (!pos || isReadOnly(cm)) return;
// Might be a file drop, in which case we simply extract the text
// and insert it.
if (files && files.length && window.FileReader && window.File) {
var n = files.length, text = Array(n), read = 0;
var loadFile = function(file, i) {
var reader = new FileReader;
reader.onload = operation(cm, function() {
text[i] = reader.result;
if (++read == n) {
pos = clipPos(cm.doc, pos);
var change = {from: pos, to: pos,
text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
origin: "paste"};
makeChange(cm.doc, change);
setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
}
});
reader.readAsText(file);
};
for (var i = 0; i < n; ++i) loadFile(files[i], i);
} else { // Normal drop
// Don't do a replace if the drop happened inside of the selected text.
if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
cm.state.draggingText(e);
// Ensure the editor is re-focused
setTimeout(function() {cm.display.input.focus();}, 20);
return;
}
try {
var text = e.dataTransfer.getData("Text");
if (text) {
if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey))
var selected = cm.listSelections();
setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
if (selected) for (var i = 0; i < selected.length; ++i)
replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
cm.replaceSelection(text, "around", "paste");
cm.display.input.focus();
}
}
catch(e){}
}
}
function onDragStart(cm, e) {
if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
e.dataTransfer.setData("Text", cm.getSelection());
// Use dummy image instead of default browsers image.
// Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
if (e.dataTransfer.setDragImage && !safari) {
var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
if (presto) {
img.width = img.height = 1;
cm.display.wrapper.appendChild(img);
// Force a relayout, or Opera won't use our image for some obscure reason
img._top = img.offsetTop;
}
e.dataTransfer.setDragImage(img, 0, 0);
if (presto) img.parentNode.removeChild(img);
}
}
function onDragOver(cm, e) {
var pos = posFromMouse(cm, e);
if (!pos) return;
var frag = document.createDocumentFragment();
drawSelectionCursor(cm, pos, frag);
if (!cm.display.dragCursor) {
cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
}
removeChildrenAndAdd(cm.display.dragCursor, frag);
}
function clearDragCursor(cm) {
if (cm.display.dragCursor) {
cm.display.lineSpace.removeChild(cm.display.dragCursor);
cm.display.dragCursor = null;
}
}
// SCROLL EVENTS
// Sync the scrollable area and scrollbars, ensure the viewport
// covers the visible area.
function setScrollTop(cm, val) {
if (Math.abs(cm.doc.scrollTop - val) < 2) return;
cm.doc.scrollTop = val;
if (!gecko) updateDisplaySimple(cm, {top: val});
if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
cm.display.scrollbars.setScrollTop(val);
if (gecko) updateDisplaySimple(cm);
startWorker(cm, 100);
}
// Sync scroller and scrollbar, ensure the gutter elements are
// aligned.
function setScrollLeft(cm, val, isScroller) {
if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
cm.doc.scrollLeft = val;
alignHorizontally(cm);
if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
cm.display.scrollbars.setScrollLeft(val);
}
// Since the delta values reported on mouse wheel events are
// unstandardized between browsers and even browser versions, and
// generally horribly unpredictable, this code starts by measuring
// the scroll effect that the first few mouse wheel events have,
// and, from that, detects the way it can convert deltas to pixel
// offsets afterwards.
//
// The reason we want to know the amount a wheel event will scroll
// is that it gives us a chance to update the display before the
// actual scrolling happens, reducing flickering.
var wheelSamples = 0, wheelPixelsPerUnit = null;
// Fill in a browser-detected starting value on browsers where we
// know one. These don't have to be accurate -- the result of them
// being wrong would just be a slight flicker on the first wheel
// scroll (if it is large enough).
if (ie) wheelPixelsPerUnit = -.53;
else if (gecko) wheelPixelsPerUnit = 15;
else if (chrome) wheelPixelsPerUnit = -.7;
else if (safari) wheelPixelsPerUnit = -1/3;
var wheelEventDelta = function(e) {
var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
else if (dy == null) dy = e.wheelDelta;
return {x: dx, y: dy};
};
CodeMirror.wheelEventPixels = function(e) {
var delta = wheelEventDelta(e);
delta.x *= wheelPixelsPerUnit;
delta.y *= wheelPixelsPerUnit;
return delta;
};
function onScrollWheel(cm, e) {
var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
var display = cm.display, scroll = display.scroller;
// Quit if there's nothing to scroll here
if (!(dx && scroll.scrollWidth > scroll.clientWidth ||
dy && scroll.scrollHeight > scroll.clientHeight)) return;
// Webkit browsers on OS X abort momentum scrolls when the target
// of the scroll event is removed from the scrollable element.
// This hack (see related code in patchDisplay) makes sure the
// element is kept around.
if (dy && mac && webkit) {
outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
for (var i = 0; i < view.length; i++) {
if (view[i].node == cur) {
cm.display.currentWheelTarget = cur;
break outer;
}
}
}
}
// On some browsers, horizontal scrolling will cause redraws to
// happen before the gutter has been realigned, causing it to
// wriggle around in a most unseemly way. When we have an
// estimated pixels/delta value, we just handle horizontal
// scrolling entirely here. It'll be slightly off from native, but
// better than glitching out.
if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
if (dy)
setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
e_preventDefault(e);
display.wheelStartX = null; // Abort measurement, if in progress
return;
}
// 'Project' the visible viewport to cover the area that is being
// scrolled into view (if we know enough to estimate it).
if (dy && wheelPixelsPerUnit != null) {
var pixels = dy * wheelPixelsPerUnit;
var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
if (pixels < 0) top = Math.max(0, top + pixels - 50);
else bot = Math.min(cm.doc.height, bot + pixels + 50);
updateDisplaySimple(cm, {top: top, bottom: bot});
}
if (wheelSamples < 20) {
if (display.wheelStartX == null) {
display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
display.wheelDX = dx; display.wheelDY = dy;
setTimeout(function() {
if (display.wheelStartX == null) return;
var movedX = scroll.scrollLeft - display.wheelStartX;
var movedY = scroll.scrollTop - display.wheelStartY;
var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
(movedX && display.wheelDX && movedX / display.wheelDX);
display.wheelStartX = display.wheelStartY = null;
if (!sample) return;
wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
++wheelSamples;
}, 200);
} else {
display.wheelDX += dx; display.wheelDY += dy;
}
}
}
// KEY EVENTS
// Run a handler that was bound to a key.
function doHandleBinding(cm, bound, dropShift) {
if (typeof bound == "string") {
bound = commands[bound];
if (!bound) return false;
}
// Ensure previous input has been read, so that the handler sees a
// consistent view of the document
cm.display.input.ensurePolled();
var prevShift = cm.display.shift, done = false;
try {
if (isReadOnly(cm)) cm.state.suppressEdits = true;
if (dropShift) cm.display.shift = false;
done = bound(cm) != Pass;
} finally {
cm.display.shift = prevShift;
cm.state.suppressEdits = false;
}
return done;
}
function lookupKeyForEditor(cm, name, handle) {
for (var i = 0; i < cm.state.keyMaps.length; i++) {
var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
if (result) return result;
}
return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
|| lookupKey(name, cm.options.keyMap, handle, cm);
}
var stopSeq = new Delayed;
function dispatchKey(cm, name, e, handle) {
var seq = cm.state.keySeq;
if (seq) {
if (isModifierKey(name)) return "handled";
stopSeq.set(50, function() {
if (cm.state.keySeq == seq) {
cm.state.keySeq = null;
cm.display.input.reset();
}
});
name = seq + " " + name;
}
var result = lookupKeyForEditor(cm, name, handle);
if (result == "multi")
cm.state.keySeq = name;
if (result == "handled")
signalLater(cm, "keyHandled", cm, name, e);
if (result == "handled" || result == "multi") {
e_preventDefault(e);
restartBlink(cm);
}
if (seq && !result && /\'$/.test(name)) {
e_preventDefault(e);
return true;
}
return !!result;
}
// Handle a key from the keydown event.
function handleKeyBinding(cm, e) {
var name = keyName(e, true);
if (!name) return false;
if (e.shiftKey && !cm.state.keySeq) {
// First try to resolve full name (including 'Shift-'). Failing
// that, see if there is a cursor-motion command (starting with
// 'go') bound to the keyname without 'Shift-'.
return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);})
|| dispatchKey(cm, name, e, function(b) {
if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
return doHandleBinding(cm, b);
});
} else {
return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });
}
}
// Handle a key from the keypress event
function handleCharBinding(cm, e, ch) {
return dispatchKey(cm, "'" + ch + "'", e,
function(b) { return doHandleBinding(cm, b, true); });
}
var lastStoppedKey = null;
function onKeyDown(e) {
var cm = this;
cm.curOp.focus = activeElt();
if (signalDOMEvent(cm, e)) return;
// IE does strange things with escape.
if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
var code = e.keyCode;
cm.display.shift = code == 16 || e.shiftKey;
var handled = handleKeyBinding(cm, e);
if (presto) {
lastStoppedKey = handled ? code : null;
// Opera has no cut event... we try to at least catch the key combo
if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
cm.replaceSelection("", null, "cut");
}
// Turn mouse into crosshair when Alt is held on Mac.
if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
showCrossHair(cm);
}
function showCrossHair(cm) {
var lineDiv = cm.display.lineDiv;
addClass(lineDiv, "CodeMirror-crosshair");
function up(e) {
if (e.keyCode == 18 || !e.altKey) {
rmClass(lineDiv, "CodeMirror-crosshair");
off(document, "keyup", up);
off(document, "mouseover", up);
}
}
on(document, "keyup", up);
on(document, "mouseover", up);
}
function onKeyUp(e) {
if (e.keyCode == 16) this.doc.sel.shift = false;
signalDOMEvent(this, e);
}
function onKeyPress(e) {
var cm = this;
if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;
var keyCode = e.keyCode, charCode = e.charCode;
if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return;
var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
if (handleCharBinding(cm, e, ch)) return;
cm.display.input.onKeyPress(e);
}
// FOCUS/BLUR EVENTS
function delayBlurEvent(cm) {
cm.state.delayingBlurEvent = true;
setTimeout(function() {
if (cm.state.delayingBlurEvent) {
cm.state.delayingBlurEvent = false;
onBlur(cm);
}
}, 100);
}
function onFocus(cm) {
if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
if (cm.options.readOnly == "nocursor") return;
if (!cm.state.focused) {
signal(cm, "focus", cm);
cm.state.focused = true;
addClass(cm.display.wrapper, "CodeMirror-focused");
// This test prevents this from firing when a context
// menu is closed (since the input reset would kill the
// select-all detection hack)
if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
cm.display.input.reset();
if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730
}
cm.display.input.receivedFocus();
}
restartBlink(cm);
}
function onBlur(cm) {
if (cm.state.delayingBlurEvent) return;
if (cm.state.focused) {
signal(cm, "blur", cm);
cm.state.focused = false;
rmClass(cm.display.wrapper, "CodeMirror-focused");
}
clearInterval(cm.display.blinker);
setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
}
// CONTEXT MENU HANDLING
// To make the context menu work, we need to briefly unhide the
// textarea (making it as unobtrusive as possible) to let the
// right-click take effect on it.
function onContextMenu(cm, e) {
if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
cm.display.input.onContextMenu(e);
}
function contextMenuInGutter(cm, e) {
if (!hasHandler(cm, "gutterContextMenu")) return false;
return gutterEvent(cm, e, "gutterContextMenu", false, signal);
}
// UPDATING
// Compute the position of the end of a change (its 'to' property
// refers to the pre-change end).
var changeEnd = CodeMirror.changeEnd = function(change) {
if (!change.text) return change.to;
return Pos(change.from.line + change.text.length - 1,
lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
};
// Adjust a position to refer to the post-change position of the
// same text, or the end of the change if the change covers it.
function adjustForChange(pos, change) {
if (cmp(pos, change.from) < 0) return pos;
if (cmp(pos, change.to) <= 0) return changeEnd(change);
var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
return Pos(line, ch);
}
function computeSelAfterChange(doc, change) {
var out = [];
for (var i = 0; i < doc.sel.ranges.length; i++) {
var range = doc.sel.ranges[i];
out.push(new Range(adjustForChange(range.anchor, change),
adjustForChange(range.head, change)));
}
return normalizeSelection(out, doc.sel.primIndex);
}
function offsetPos(pos, old, nw) {
if (pos.line == old.line)
return Pos(nw.line, pos.ch - old.ch + nw.ch);
else
return Pos(nw.line + (pos.line - old.line), pos.ch);
}
// Used by replaceSelections to allow moving the selection to the
// start or around the replaced test. Hint may be "start" or "around".
function computeReplacedSel(doc, changes, hint) {
var out = [];
var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
for (var i = 0; i < changes.length; i++) {
var change = changes[i];
var from = offsetPos(change.from, oldPrev, newPrev);
var to = offsetPos(changeEnd(change), oldPrev, newPrev);
oldPrev = change.to;
newPrev = to;
if (hint == "around") {
var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
out[i] = new Range(inv ? to : from, inv ? from : to);
} else {
out[i] = new Range(from, from);
}
}
return new Selection(out, doc.sel.primIndex);
}
// Allow "beforeChange" event handlers to influence a change
function filterChange(doc, change, update) {
var obj = {
canceled: false,
from: change.from,
to: change.to,
text: change.text,
origin: change.origin,
cancel: function() { this.canceled = true; }
};
if (update) obj.update = function(from, to, text, origin) {
if (from) this.from = clipPos(doc, from);
if (to) this.to = clipPos(doc, to);
if (text) this.text = text;
if (origin !== undefined) this.origin = origin;
};
signal(doc, "beforeChange", doc, obj);
if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
if (obj.canceled) return null;
return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
}
// Apply a change to a document, and add it to the document's
// history, and propagating it to all linked documents.
function makeChange(doc, change, ignoreReadOnly) {
if (doc.cm) {
if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
if (doc.cm.state.suppressEdits) return;
}
if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
change = filterChange(doc, change, true);
if (!change) return;
}
// Possibly split or suppress the update based on the presence
// of read-only spans in its range.
var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
if (split) {
for (var i = split.length - 1; i >= 0; --i)
makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
} else {
makeChangeInner(doc, change);
}
}
function makeChangeInner(doc, change) {
if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
var selAfter = computeSelAfterChange(doc, change);
addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
var rebased = [];
linkedDocs(doc, function(doc, sharedHist) {
if (!sharedHist && indexOf(rebased, doc.history) == -1) {
rebaseHist(doc.history, change);
rebased.push(doc.history);
}
makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
});
}
// Revert a change stored in a document's history.
function makeChangeFromHistory(doc, type, allowSelectionOnly) {
if (doc.cm && doc.cm.state.suppressEdits) return;
var hist = doc.history, event, selAfter = doc.sel;
var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
// Verify that there is a useable event (so that ctrl-z won't
// needlessly clear selection events)
for (var i = 0; i < source.length; i++) {
event = source[i];
if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
break;
}
if (i == source.length) return;
hist.lastOrigin = hist.lastSelOrigin = null;
for (;;) {
event = source.pop();
if (event.ranges) {
pushSelectionToHistory(event, dest);
if (allowSelectionOnly && !event.equals(doc.sel)) {
setSelection(doc, event, {clearRedo: false});
return;
}
selAfter = event;
}
else break;
}
// Build up a reverse change object to add to the opposite history
// stack (redo when undoing, and vice versa).
var antiChanges = [];
pushSelectionToHistory(selAfter, dest);
dest.push({changes: antiChanges, generation: hist.generation});
hist.generation = event.generation || ++hist.maxGeneration;
var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
for (var i = event.changes.length - 1; i >= 0; --i) {
var change = event.changes[i];
change.origin = type;
if (filter && !filterChange(doc, change, false)) {
source.length = 0;
return;
}
antiChanges.push(historyChangeFromChange(doc, change));
var after = i ? computeSelAfterChange(doc, change) : lst(source);
makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
var rebased = [];
// Propagate to the linked documents
linkedDocs(doc, function(doc, sharedHist) {
if (!sharedHist && indexOf(rebased, doc.history) == -1) {
rebaseHist(doc.history, change);
rebased.push(doc.history);
}
makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
});
}
}
// Sub-views need their line numbers shifted when text is added
// above or below them in the parent document.
function shiftDoc(doc, distance) {
if (distance == 0) return;
doc.first += distance;
doc.sel = new Selection(map(doc.sel.ranges, function(range) {
return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
Pos(range.head.line + distance, range.head.ch));
}), doc.sel.primIndex);
if (doc.cm) {
regChange(doc.cm, doc.first, doc.first - distance, distance);
for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
regLineChange(doc.cm, l, "gutter");
}
}
// More lower-level change function, handling only a single document
// (not linked ones).
function makeChangeSingleDoc(doc, change, selAfter, spans) {
if (doc.cm && !doc.cm.curOp)
return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
if (change.to.line < doc.first) {
shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
return;
}
if (change.from.line > doc.lastLine()) return;
// Clip the change to the size of this doc
if (change.from.line < doc.first) {
var shift = change.text.length - 1 - (doc.first - change.from.line);
shiftDoc(doc, shift);
change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
text: [lst(change.text)], origin: change.origin};
}
var last = doc.lastLine();
if (change.to.line > last) {
change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
text: [change.text[0]], origin: change.origin};
}
change.removed = getBetween(doc, change.from, change.to);
if (!selAfter) selAfter = computeSelAfterChange(doc, change);
if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
else updateDoc(doc, change, spans);
setSelectionNoUndo(doc, selAfter, sel_dontScroll);
}
// Handle the interaction of a change to a document with the editor
// that this document is part of.
function makeChangeSingleDocInEditor(cm, change, spans) {
var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
var recomputeMaxLength = false, checkWidthStart = from.line;
if (!cm.options.lineWrapping) {
checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
doc.iter(checkWidthStart, to.line + 1, function(line) {
if (line == display.maxLine) {
recomputeMaxLength = true;
return true;
}
});
}
if (doc.sel.contains(change.from, change.to) > -1)
signalCursorActivity(cm);
updateDoc(doc, change, spans, estimateHeight(cm));
if (!cm.options.lineWrapping) {
doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
var len = lineLength(line);
if (len > display.maxLineLength) {
display.maxLine = line;
display.maxLineLength = len;
display.maxLineChanged = true;
recomputeMaxLength = false;
}
});
if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
}
// Adjust frontier, schedule worker
doc.frontier = Math.min(doc.frontier, from.line);
startWorker(cm, 400);
var lendiff = change.text.length - (to.line - from.line) - 1;
// Remember that these lines changed, for updating the display
if (change.full)
regChange(cm);
else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
regLineChange(cm, from.line, "text");
else
regChange(cm, from.line, to.line + 1, lendiff);
var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
if (changeHandler || changesHandler) {
var obj = {
from: from, to: to,
text: change.text,
removed: change.removed,
origin: change.origin
};
if (changeHandler) signalLater(cm, "change", cm, obj);
if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
}
cm.display.selForContextMenu = null;
}
function replaceRange(doc, code, from, to, origin) {
if (!to) to = from;
if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
if (typeof code == "string") code = doc.splitLines(code);
makeChange(doc, {from: from, to: to, text: code, origin: origin});
}
// SCROLLING THINGS INTO VIEW
// If an editor sits on the top or bottom of the window, partially
// scrolled out of view, this ensures that the cursor is visible.
function maybeScrollWindow(cm, coords) {
if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
if (coords.top + box.top < 0) doScroll = true;
else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
if (doScroll != null && !phantom) {
var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
(coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
(coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
coords.left + "px; width: 2px;");
cm.display.lineSpace.appendChild(scrollNode);
scrollNode.scrollIntoView(doScroll);
cm.display.lineSpace.removeChild(scrollNode);
}
}
// Scroll a given position into view (immediately), verifying that
// it actually became visible (as line heights are accurately
// measured, the position of something may 'drift' during drawing).
function scrollPosIntoView(cm, pos, end, margin) {
if (margin == null) margin = 0;
for (var limit = 0; limit < 5; limit++) {
var changed = false, coords = cursorCoords(cm, pos);
var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
Math.min(coords.top, endCoords.top) - margin,
Math.max(coords.left, endCoords.left),
Math.max(coords.bottom, endCoords.bottom) + margin);
var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
if (scrollPos.scrollTop != null) {
setScrollTop(cm, scrollPos.scrollTop);
if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
}
if (scrollPos.scrollLeft != null) {
setScrollLeft(cm, scrollPos.scrollLeft);
if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
}
if (!changed) break;
}
return coords;
}
// Scroll a given set of coordinates into view (immediately).
function scrollIntoView(cm, x1, y1, x2, y2) {
var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
}
// Calculate a new scroll position needed to scroll the given
// rectangle into view. Returns an object with scrollTop and
// scrollLeft properties. When these are undefined, the
// vertical/horizontal position does not need to be adjusted.
function calculateScrollPos(cm, x1, y1, x2, y2) {
var display = cm.display, snapMargin = textHeight(cm.display);
if (y1 < 0) y1 = 0;
var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
var screen = displayHeight(cm), result = {};
if (y2 - y1 > screen) y2 = y1 + screen;
var docBottom = cm.doc.height + paddingVert(display);
var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
if (y1 < screentop) {
result.scrollTop = atTop ? 0 : y1;
} else if (y2 > screentop + screen) {
var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
if (newTop != screentop) result.scrollTop = newTop;
}
var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
var tooWide = x2 - x1 > screenw;
if (tooWide) x2 = x1 + screenw;
if (x1 < 10)
result.scrollLeft = 0;
else if (x1 < screenleft)
result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
else if (x2 > screenw + screenleft - 3)
result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
return result;
}
// Store a relative adjustment to the scroll position in the current
// operation (to be applied when the operation finishes).
function addToScrollPos(cm, left, top) {
if (left != null || top != null) resolveScrollToPos(cm);
if (left != null)
cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
if (top != null)
cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
}
// Make sure that at the end of the operation the current cursor is
// shown.
function ensureCursorVisible(cm) {
resolveScrollToPos(cm);
var cur = cm.getCursor(), from = cur, to = cur;
if (!cm.options.lineWrapping) {
from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
to = Pos(cur.line, cur.ch + 1);
}
cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
}
// When an operation has its scrollToPos property set, and another
// scroll action is applied before the end of the operation, this
// 'simulates' scrolling that position into view in a cheap way, so
// that the effect of intermediate scroll commands is not ignored.
function resolveScrollToPos(cm) {
var range = cm.curOp.scrollToPos;
if (range) {
cm.curOp.scrollToPos = null;
var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
Math.min(from.top, to.top) - range.margin,
Math.max(from.right, to.right),
Math.max(from.bottom, to.bottom) + range.margin);
cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
}
}
// API UTILITIES
// Indent the given line. The how parameter can be "smart",
// "add"/null, "subtract", or "prev". When aggressive is false
// (typically set to true for forced single-line indents), empty
// lines are not indented, and places where the mode returns Pass
// are left alone.
function indentLine(cm, n, how, aggressive) {
var doc = cm.doc, state;
if (how == null) how = "add";
if (how == "smart") {
// Fall back to "prev" when the mode doesn't have an indentation
// method.
if (!doc.mode.indent) how = "prev";
else state = getStateBefore(cm, n);
}
var tabSize = cm.options.tabSize;
var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
if (line.stateAfter) line.stateAfter = null;
var curSpaceString = line.text.match(/^\s*/)[0], indentation;
if (!aggressive && !/\S/.test(line.text)) {
indentation = 0;
how = "not";
} else if (how == "smart") {
indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
if (indentation == Pass || indentation > 150) {
if (!aggressive) return;
how = "prev";
}
}
if (how == "prev") {
if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
else indentation = 0;
} else if (how == "add") {
indentation = curSpace + cm.options.indentUnit;
} else if (how == "subtract") {
indentation = curSpace - cm.options.indentUnit;
} else if (typeof how == "number") {
indentation = curSpace + how;
}
indentation = Math.max(0, indentation);
var indentString = "", pos = 0;
if (cm.options.indentWithTabs)
for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
if (pos < indentation) indentString += spaceStr(indentation - pos);
if (indentString != curSpaceString) {
replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
line.stateAfter = null;
return true;
} else {
// Ensure that, if the cursor was in the whitespace at the start
// of the line, it is moved to the end of that space.
for (var i = 0; i < doc.sel.ranges.length; i++) {
var range = doc.sel.ranges[i];
if (range.head.line == n && range.head.ch < curSpaceString.length) {
var pos = Pos(n, curSpaceString.length);
replaceOneSelection(doc, i, new Range(pos, pos));
break;
}
}
}
}
// Utility for applying a change to a line by handle or number,
// returning the number and optionally registering the line as
// changed.
function changeLine(doc, handle, changeType, op) {
var no = handle, line = handle;
if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
else no = lineNo(handle);
if (no == null) return null;
if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);
return line;
}
// Helper for deleting text near the selection(s), used to implement
// backspace, delete, and similar functionality.
function deleteNearSelection(cm, compute) {
var ranges = cm.doc.sel.ranges, kill = [];
// Build up a set of ranges to kill first, merging overlapping
// ranges.
for (var i = 0; i < ranges.length; i++) {
var toKill = compute(ranges[i]);
while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
var replaced = kill.pop();
if (cmp(replaced.from, toKill.from) < 0) {
toKill.from = replaced.from;
break;
}
}
kill.push(toKill);
}
// Next, remove those actual ranges.
runInOp(cm, function() {
for (var i = kill.length - 1; i >= 0; i--)
replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
ensureCursorVisible(cm);
});
}
// Used for horizontal relative motion. Dir is -1 or 1 (left or
// right), unit can be "char", "column" (like char, but doesn't
// cross line boundaries), "word" (across next word), or "group" (to
// the start of next group of word or non-word-non-whitespace
// chars). The visually param controls whether, in right-to-left
// text, direction 1 means to move towards the next index in the
// string, or towards the character to the right of the current
// position. The resulting position will have a hitSide=true
// property if it reached the end of the document.
function findPosH(doc, pos, dir, unit, visually) {
var line = pos.line, ch = pos.ch, origDir = dir;
var lineObj = getLine(doc, line);
var possible = true;
function findNextLine() {
var l = line + dir;
if (l < doc.first || l >= doc.first + doc.size) return (possible = false);
line = l;
return lineObj = getLine(doc, l);
}
function moveOnce(boundToLine) {
var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
if (next == null) {
if (!boundToLine && findNextLine()) {
if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
else ch = dir < 0 ? lineObj.text.length : 0;
} else return (possible = false);
} else ch = next;
return true;
}
if (unit == "char") moveOnce();
else if (unit == "column") moveOnce(true);
else if (unit == "word" || unit == "group") {
var sawType = null, group = unit == "group";
var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
for (var first = true;; first = false) {
if (dir < 0 && !moveOnce(!first)) break;
var cur = lineObj.text.charAt(ch) || "\n";
var type = isWordChar(cur, helper) ? "w"
: group && cur == "\n" ? "n"
: !group || /\s/.test(cur) ? null
: "p";
if (group && !first && !type) type = "s";
if (sawType && sawType != type) {
if (dir < 0) {dir = 1; moveOnce();}
break;
}
if (type) sawType = type;
if (dir > 0 && !moveOnce(!first)) break;
}
}
var result = skipAtomic(doc, Pos(line, ch), origDir, true);
if (!possible) result.hitSide = true;
return result;
}
// For relative vertical movement. Dir may be -1 or 1. Unit can be
// "page" or "line". The resulting position will have a hitSide=true
// property if it reached the end of the document.
function findPosV(cm, pos, dir, unit) {
var doc = cm.doc, x = pos.left, y;
if (unit == "page") {
var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
} else if (unit == "line") {
y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
}
for (;;) {
var target = coordsChar(cm, x, y);
if (!target.outside) break;
if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
y += dir * 5;
}
return target;
}
// EDITOR METHODS
// The publicly visible API. Note that methodOp(f) means
// 'wrap f in an operation, performed on its `this` parameter'.
// This is not the complete set of editor methods. Most of the
// methods defined on the Doc type are also injected into
// CodeMirror.prototype, for backwards compatibility and
// convenience.
CodeMirror.prototype = {
constructor: CodeMirror,
focus: function(){window.focus(); this.display.input.focus();},
setOption: function(option, value) {
var options = this.options, old = options[option];
if (options[option] == value && option != "mode") return;
options[option] = value;
if (optionHandlers.hasOwnProperty(option))
operation(this, optionHandlers[option])(this, value, old);
},
getOption: function(option) {return this.options[option];},
getDoc: function() {return this.doc;},
addKeyMap: function(map, bottom) {
this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
},
removeKeyMap: function(map) {
var maps = this.state.keyMaps;
for (var i = 0; i < maps.length; ++i)
if (maps[i] == map || maps[i].name == map) {
maps.splice(i, 1);
return true;
}
},
addOverlay: methodOp(function(spec, options) {
var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
if (mode.startState) throw new Error("Overlays may not be stateful.");
this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
this.state.modeGen++;
regChange(this);
}),
removeOverlay: methodOp(function(spec) {
var overlays = this.state.overlays;
for (var i = 0; i < overlays.length; ++i) {
var cur = overlays[i].modeSpec;
if (cur == spec || typeof spec == "string" && cur.name == spec) {
overlays.splice(i, 1);
this.state.modeGen++;
regChange(this);
return;
}
}
}),
indentLine: methodOp(function(n, dir, aggressive) {
if (typeof dir != "string" && typeof dir != "number") {
if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
else dir = dir ? "add" : "subtract";
}
if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
}),
indentSelection: methodOp(function(how) {
var ranges = this.doc.sel.ranges, end = -1;
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (!range.empty()) {
var from = range.from(), to = range.to();
var start = Math.max(end, from.line);
end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
for (var j = start; j < end; ++j)
indentLine(this, j, how);
var newRanges = this.doc.sel.ranges;
if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
} else if (range.head.line > end) {
indentLine(this, range.head.line, how, true);
end = range.head.line;
if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
}
}
}),
// Fetch the parser token for a given character. Useful for hacks
// that want to inspect the mode state (say, for completion).
getTokenAt: function(pos, precise) {
return takeToken(this, pos, precise);
},
getLineTokens: function(line, precise) {
return takeToken(this, Pos(line), precise, true);
},
getTokenTypeAt: function(pos) {
pos = clipPos(this.doc, pos);
var styles = getLineStyles(this, getLine(this.doc, pos.line));
var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
var type;
if (ch == 0) type = styles[2];
else for (;;) {
var mid = (before + after) >> 1;
if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
else if (styles[mid * 2 + 1] < ch) before = mid + 1;
else { type = styles[mid * 2 + 2]; break; }
}
var cut = type ? type.indexOf("cm-overlay ") : -1;
return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
},
getModeAt: function(pos) {
var mode = this.doc.mode;
if (!mode.innerMode) return mode;
return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
},
getHelper: function(pos, type) {
return this.getHelpers(pos, type)[0];
},
getHelpers: function(pos, type) {
var found = [];
if (!helpers.hasOwnProperty(type)) return found;
var help = helpers[type], mode = this.getModeAt(pos);
if (typeof mode[type] == "string") {
if (help[mode[type]]) found.push(help[mode[type]]);
} else if (mode[type]) {
for (var i = 0; i < mode[type].length; i++) {
var val = help[mode[type][i]];
if (val) found.push(val);
}
} else if (mode.helperType && help[mode.helperType]) {
found.push(help[mode.helperType]);
} else if (help[mode.name]) {
found.push(help[mode.name]);
}
for (var i = 0; i < help._global.length; i++) {
var cur = help._global[i];
if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
found.push(cur.val);
}
return found;
},
getStateAfter: function(line, precise) {
var doc = this.doc;
line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
return getStateBefore(this, line + 1, precise);
},
cursorCoords: function(start, mode) {
var pos, range = this.doc.sel.primary();
if (start == null) pos = range.head;
else if (typeof start == "object") pos = clipPos(this.doc, start);
else pos = start ? range.from() : range.to();
return cursorCoords(this, pos, mode || "page");
},
charCoords: function(pos, mode) {
return charCoords(this, clipPos(this.doc, pos), mode || "page");
},
coordsChar: function(coords, mode) {
coords = fromCoordSystem(this, coords, mode || "page");
return coordsChar(this, coords.left, coords.top);
},
lineAtHeight: function(height, mode) {
height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
return lineAtHeight(this.doc, height + this.display.viewOffset);
},
heightAtLine: function(line, mode) {
var end = false, lineObj;
if (typeof line == "number") {
var last = this.doc.first + this.doc.size - 1;
if (line < this.doc.first) line = this.doc.first;
else if (line > last) { line = last; end = true; }
lineObj = getLine(this.doc, line);
} else {
lineObj = line;
}
return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
(end ? this.doc.height - heightAtLine(lineObj) : 0);
},
defaultTextHeight: function() { return textHeight(this.display); },
defaultCharWidth: function() { return charWidth(this.display); },
setGutterMarker: methodOp(function(line, gutterID, value) {
return changeLine(this.doc, line, "gutter", function(line) {
var markers = line.gutterMarkers || (line.gutterMarkers = {});
markers[gutterID] = value;
if (!value && isEmpty(markers)) line.gutterMarkers = null;
return true;
});
}),
clearGutter: methodOp(function(gutterID) {
var cm = this, doc = cm.doc, i = doc.first;
doc.iter(function(line) {
if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
line.gutterMarkers[gutterID] = null;
regLineChange(cm, i, "gutter");
if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
}
++i;
});
}),
lineInfo: function(line) {
if (typeof line == "number") {
if (!isLine(this.doc, line)) return null;
var n = line;
line = getLine(this.doc, line);
if (!line) return null;
} else {
var n = lineNo(line);
if (n == null) return null;
}
return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
widgets: line.widgets};
},
getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
addWidget: function(pos, node, scroll, vert, horiz) {
var display = this.display;
pos = cursorCoords(this, clipPos(this.doc, pos));
var top = pos.bottom, left = pos.left;
node.style.position = "absolute";
node.setAttribute("cm-ignore-events", "true");
this.display.input.setUneditable(node);
display.sizer.appendChild(node);
if (vert == "over") {
top = pos.top;
} else if (vert == "above" || vert == "near") {
var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
// Default to positioning above (if specified and possible); otherwise default to positioning below
if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
top = pos.top - node.offsetHeight;
else if (pos.bottom + node.offsetHeight <= vspace)
top = pos.bottom;
if (left + node.offsetWidth > hspace)
left = hspace - node.offsetWidth;
}
node.style.top = top + "px";
node.style.left = node.style.right = "";
if (horiz == "right") {
left = display.sizer.clientWidth - node.offsetWidth;
node.style.right = "0px";
} else {
if (horiz == "left") left = 0;
else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
node.style.left = left + "px";
}
if (scroll)
scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
},
triggerOnKeyDown: methodOp(onKeyDown),
triggerOnKeyPress: methodOp(onKeyPress),
triggerOnKeyUp: onKeyUp,
execCommand: function(cmd) {
if (commands.hasOwnProperty(cmd))
return commands[cmd].call(null, this);
},
triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
findPosH: function(from, amount, unit, visually) {
var dir = 1;
if (amount < 0) { dir = -1; amount = -amount; }
for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
cur = findPosH(this.doc, cur, dir, unit, visually);
if (cur.hitSide) break;
}
return cur;
},
moveH: methodOp(function(dir, unit) {
var cm = this;
cm.extendSelectionsBy(function(range) {
if (cm.display.shift || cm.doc.extend || range.empty())
return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
else
return dir < 0 ? range.from() : range.to();
}, sel_move);
}),
deleteH: methodOp(function(dir, unit) {
var sel = this.doc.sel, doc = this.doc;
if (sel.somethingSelected())
doc.replaceSelection("", null, "+delete");
else
deleteNearSelection(this, function(range) {
var other = findPosH(doc, range.head, dir, unit, false);
return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
});
}),
findPosV: function(from, amount, unit, goalColumn) {
var dir = 1, x = goalColumn;
if (amount < 0) { dir = -1; amount = -amount; }
for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
var coords = cursorCoords(this, cur, "div");
if (x == null) x = coords.left;
else coords.left = x;
cur = findPosV(this, coords, dir, unit);
if (cur.hitSide) break;
}
return cur;
},
moveV: methodOp(function(dir, unit) {
var cm = this, doc = this.doc, goals = [];
var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
doc.extendSelectionsBy(function(range) {
if (collapse)
return dir < 0 ? range.from() : range.to();
var headPos = cursorCoords(cm, range.head, "div");
if (range.goalColumn != null) headPos.left = range.goalColumn;
goals.push(headPos.left);
var pos = findPosV(cm, headPos, dir, unit);
if (unit == "page" && range == doc.sel.primary())
addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
return pos;
}, sel_move);
if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
doc.sel.ranges[i].goalColumn = goals[i];
}),
// Find the word at the given position (as returned by coordsChar).
findWordAt: function(pos) {
var doc = this.doc, line = getLine(doc, pos.line).text;
var start = pos.ch, end = pos.ch;
if (line) {
var helper = this.getHelper(pos, "wordChars");
if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
var startChar = line.charAt(start);
var check = isWordChar(startChar, helper)
? function(ch) { return isWordChar(ch, helper); }
: /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
: function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
while (start > 0 && check(line.charAt(start - 1))) --start;
while (end < line.length && check(line.charAt(end))) ++end;
}
return new Range(Pos(pos.line, start), Pos(pos.line, end));
},
toggleOverwrite: function(value) {
if (value != null && value == this.state.overwrite) return;
if (this.state.overwrite = !this.state.overwrite)
addClass(this.display.cursorDiv, "CodeMirror-overwrite");
else
rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
signal(this, "overwriteToggle", this, this.state.overwrite);
},
hasFocus: function() { return this.display.input.getField() == activeElt(); },
scrollTo: methodOp(function(x, y) {
if (x != null || y != null) resolveScrollToPos(this);
if (x != null) this.curOp.scrollLeft = x;
if (y != null) this.curOp.scrollTop = y;
}),
getScrollInfo: function() {
var scroller = this.display.scroller;
return {left: scroller.scrollLeft, top: scroller.scrollTop,
height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
},
scrollIntoView: methodOp(function(range, margin) {
if (range == null) {
range = {from: this.doc.sel.primary().head, to: null};
if (margin == null) margin = this.options.cursorScrollMargin;
} else if (typeof range == "number") {
range = {from: Pos(range, 0), to: null};
} else if (range.from == null) {
range = {from: range, to: null};
}
if (!range.to) range.to = range.from;
range.margin = margin || 0;
if (range.from.line != null) {
resolveScrollToPos(this);
this.curOp.scrollToPos = range;
} else {
var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
Math.min(range.from.top, range.to.top) - range.margin,
Math.max(range.from.right, range.to.right),
Math.max(range.from.bottom, range.to.bottom) + range.margin);
this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
}
}),
setSize: methodOp(function(width, height) {
var cm = this;
function interpret(val) {
return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
}
if (width != null) cm.display.wrapper.style.width = interpret(width);
if (height != null) cm.display.wrapper.style.height = interpret(height);
if (cm.options.lineWrapping) clearLineMeasurementCache(this);
var lineNo = cm.display.viewFrom;
cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
if (line.widgets) for (var i = 0; i < line.widgets.length; i++)
if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
++lineNo;
});
cm.curOp.forceUpdate = true;
signal(cm, "refresh", this);
}),
operation: function(f){return runInOp(this, f);},
refresh: methodOp(function() {
var oldHeight = this.display.cachedTextHeight;
regChange(this);
this.curOp.forceUpdate = true;
clearCaches(this);
this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
updateGutterSpace(this);
if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
estimateLineHeights(this);
signal(this, "refresh", this);
}),
swapDoc: methodOp(function(doc) {
var old = this.doc;
old.cm = null;
attachDoc(this, doc);
clearCaches(this);
this.display.input.reset();
this.scrollTo(doc.scrollLeft, doc.scrollTop);
this.curOp.forceScroll = true;
signalLater(this, "swapDoc", this, old);
return old;
}),
getInputField: function(){return this.display.input.getField();},
getWrapperElement: function(){return this.display.wrapper;},
getScrollerElement: function(){return this.display.scroller;},
getGutterElement: function(){return this.display.gutters;}
};
eventMixin(CodeMirror);
// OPTION DEFAULTS
// The default configuration options.
var defaults = CodeMirror.defaults = {};
// Functions to run when options are changed.
var optionHandlers = CodeMirror.optionHandlers = {};
function option(name, deflt, handle, notOnInit) {
CodeMirror.defaults[name] = deflt;
if (handle) optionHandlers[name] =
notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
}
// Passed to option handlers when there is no old value.
var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
// These two are, on init, called from the constructor because they
// have to be initialized before the editor can start at all.
option("value", "", function(cm, val) {
cm.setValue(val);
}, true);
option("mode", null, function(cm, val) {
cm.doc.modeOption = val;
loadMode(cm);
}, true);
option("indentUnit", 2, loadMode, true);
option("indentWithTabs", false);
option("smartIndent", true);
option("tabSize", 4, function(cm) {
resetModeState(cm);
clearCaches(cm);
regChange(cm);
}, true);
option("lineSeparator", null, function(cm, val) {
cm.doc.lineSep = val;
if (!val) return;
var newBreaks = [], lineNo = cm.doc.first;
cm.doc.iter(function(line) {
for (var pos = 0;;) {
var found = line.text.indexOf(val, pos);
if (found == -1) break;
pos = found + val.length;
newBreaks.push(Pos(lineNo, found));
}
lineNo++;
});
for (var i = newBreaks.length - 1; i >= 0; i--)
replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length))
});
option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) {
cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
if (old != CodeMirror.Init) cm.refresh();
});
option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
option("electricChars", true);
option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
}, true);
option("rtlMoveVisually", !windows);
option("wholeLineUpdateBefore", true);
option("theme", "default", function(cm) {
themeChanged(cm);
guttersChanged(cm);
}, true);
option("keyMap", "default", function(cm, val, old) {
var next = getKeyMap(val);
var prev = old != CodeMirror.Init && getKeyMap(old);
if (prev && prev.detach) prev.detach(cm, next);
if (next.attach) next.attach(cm, prev || null);
});
option("extraKeys", null);
option("lineWrapping", false, wrappingChanged, true);
option("gutters", [], function(cm) {
setGuttersForLineNumbers(cm.options);
guttersChanged(cm);
}, true);
option("fixedGutter", true, function(cm, val) {
cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
cm.refresh();
}, true);
option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);
option("scrollbarStyle", "native", function(cm) {
initScrollbars(cm);
updateScrollbars(cm);
cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
}, true);
option("lineNumbers", false, function(cm) {
setGuttersForLineNumbers(cm.options);
guttersChanged(cm);
}, true);
option("firstLineNumber", 1, guttersChanged, true);
option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
option("showCursorWhenSelecting", false, updateSelection, true);
option("resetSelectionOnContextMenu", true);
option("lineWiseCopyCut", true);
option("readOnly", false, function(cm, val) {
if (val == "nocursor") {
onBlur(cm);
cm.display.input.blur();
cm.display.disabled = true;
} else {
cm.display.disabled = false;
}
cm.display.input.readOnlyChanged(val)
});
option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
option("dragDrop", true, dragDropChanged);
option("cursorBlinkRate", 530);
option("cursorScrollMargin", 0);
option("cursorHeight", 1, updateSelection, true);
option("singleCursorHeightPerLine", true, updateSelection, true);
option("workTime", 100);
option("workDelay", 100);
option("flattenSpans", true, resetModeState, true);
option("addModeClass", false, resetModeState, true);
option("pollInterval", 100);
option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
option("historyEventDelay", 1250);
option("viewportMargin", 10, function(cm){cm.refresh();}, true);
option("maxHighlightLength", 10000, resetModeState, true);
option("moveInputWithCursor", true, function(cm, val) {
if (!val) cm.display.input.resetPosition();
});
option("tabindex", null, function(cm, val) {
cm.display.input.getField().tabIndex = val || "";
});
option("autofocus", null);
// MODE DEFINITION AND QUERYING
// Known modes, by name and by MIME
var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
// Extra arguments are stored as the mode's dependencies, which is
// used by (legacy) mechanisms like loadmode.js to automatically
// load a mode. (Preferred mechanism is the require/define calls.)
CodeMirror.defineMode = function(name, mode) {
if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
if (arguments.length > 2)
mode.dependencies = Array.prototype.slice.call(arguments, 2);
modes[name] = mode;
};
CodeMirror.defineMIME = function(mime, spec) {
mimeModes[mime] = spec;
};
// Given a MIME type, a {name, ...options} config object, or a name
// string, return a mode config object.
CodeMirror.resolveMode = function(spec) {
if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
spec = mimeModes[spec];
} else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
var found = mimeModes[spec.name];
if (typeof found == "string") found = {name: found};
spec = createObj(found, spec);
spec.name = found.name;
} else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
return CodeMirror.resolveMode("application/xml");
}
if (typeof spec == "string") return {name: spec};
else return spec || {name: "null"};
};
// Given a mode spec (anything that resolveMode accepts), find and
// initialize an actual mode object.
CodeMirror.getMode = function(options, spec) {
var spec = CodeMirror.resolveMode(spec);
var mfactory = modes[spec.name];
if (!mfactory) return CodeMirror.getMode(options, "text/plain");
var modeObj = mfactory(options, spec);
if (modeExtensions.hasOwnProperty(spec.name)) {
var exts = modeExtensions[spec.name];
for (var prop in exts) {
if (!exts.hasOwnProperty(prop)) continue;
if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
modeObj[prop] = exts[prop];
}
}
modeObj.name = spec.name;
if (spec.helperType) modeObj.helperType = spec.helperType;
if (spec.modeProps) for (var prop in spec.modeProps)
modeObj[prop] = spec.modeProps[prop];
return modeObj;
};
// Minimal default mode.
CodeMirror.defineMode("null", function() {
return {token: function(stream) {stream.skipToEnd();}};
});
CodeMirror.defineMIME("text/plain", "null");
// This can be used to attach properties to mode objects from
// outside the actual mode definition.
var modeExtensions = CodeMirror.modeExtensions = {};
CodeMirror.extendMode = function(mode, properties) {
var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
copyObj(properties, exts);
};
// EXTENSIONS
CodeMirror.defineExtension = function(name, func) {
CodeMirror.prototype[name] = func;
};
CodeMirror.defineDocExtension = function(name, func) {
Doc.prototype[name] = func;
};
CodeMirror.defineOption = option;
var initHooks = [];
CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
var helpers = CodeMirror.helpers = {};
CodeMirror.registerHelper = function(type, name, value) {
if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
helpers[type][name] = value;
};
CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
CodeMirror.registerHelper(type, name, value);
helpers[type]._global.push({pred: predicate, val: value});
};
// MODE STATE HANDLING
// Utility functions for working with state. Exported because nested
// modes need to do this for their inner modes.
var copyState = CodeMirror.copyState = function(mode, state) {
if (state === true) return state;
if (mode.copyState) return mode.copyState(state);
var nstate = {};
for (var n in state) {
var val = state[n];
if (val instanceof Array) val = val.concat([]);
nstate[n] = val;
}
return nstate;
};
var startState = CodeMirror.startState = function(mode, a1, a2) {
return mode.startState ? mode.startState(a1, a2) : true;
};
// Given a mode and a state (for that mode), find the inner mode and
// state at the position that the state refers to.
CodeMirror.innerMode = function(mode, state) {
while (mode.innerMode) {
var info = mode.innerMode(state);
if (!info || info.mode == mode) break;
state = info.state;
mode = info.mode;
}
return info || {mode: mode, state: state};
};
// STANDARD COMMANDS
// Commands are parameter-less actions that can be performed on an
// editor, mostly used for keybindings.
var commands = CodeMirror.commands = {
selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
singleSelection: function(cm) {
cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
},
killLine: function(cm) {
deleteNearSelection(cm, function(range) {
if (range.empty()) {
var len = getLine(cm.doc, range.head.line).text.length;
if (range.head.ch == len && range.head.line < cm.lastLine())
return {from: range.head, to: Pos(range.head.line + 1, 0)};
else
return {from: range.head, to: Pos(range.head.line, len)};
} else {
return {from: range.from(), to: range.to()};
}
});
},
deleteLine: function(cm) {
deleteNearSelection(cm, function(range) {
return {from: Pos(range.from().line, 0),
to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
});
},
delLineLeft: function(cm) {
deleteNearSelection(cm, function(range) {
return {from: Pos(range.from().line, 0), to: range.from()};
});
},
delWrappedLineLeft: function(cm) {
deleteNearSelection(cm, function(range) {
var top = cm.charCoords(range.head, "div").top + 5;
var leftPos = cm.coordsChar({left: 0, top: top}, "div");
return {from: leftPos, to: range.from()};
});
},
delWrappedLineRight: function(cm) {
deleteNearSelection(cm, function(range) {
var top = cm.charCoords(range.head, "div").top + 5;
var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
return {from: range.from(), to: rightPos };
});
},
undo: function(cm) {cm.undo();},
redo: function(cm) {cm.redo();},
undoSelection: function(cm) {cm.undoSelection();},
redoSelection: function(cm) {cm.redoSelection();},
goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
goLineStart: function(cm) {
cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
{origin: "+move", bias: 1});
},
goLineStartSmart: function(cm) {
cm.extendSelectionsBy(function(range) {
return lineStartSmart(cm, range.head);
}, {origin: "+move", bias: 1});
},
goLineEnd: function(cm) {
cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
{origin: "+move", bias: -1});
},
goLineRight: function(cm) {
cm.extendSelectionsBy(function(range) {
var top = cm.charCoords(range.head, "div").top + 5;
return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
}, sel_move);
},
goLineLeft: function(cm) {
cm.extendSelectionsBy(function(range) {
var top = cm.charCoords(range.head, "div").top + 5;
return cm.coordsChar({left: 0, top: top}, "div");
}, sel_move);
},
goLineLeftSmart: function(cm) {
cm.extendSelectionsBy(function(range) {
var top = cm.charCoords(range.head, "div").top + 5;
var pos = cm.coordsChar({left: 0, top: top}, "div");
if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
return pos;
}, sel_move);
},
goLineUp: function(cm) {cm.moveV(-1, "line");},
goLineDown: function(cm) {cm.moveV(1, "line");},
goPageUp: function(cm) {cm.moveV(-1, "page");},
goPageDown: function(cm) {cm.moveV(1, "page");},
goCharLeft: function(cm) {cm.moveH(-1, "char");},
goCharRight: function(cm) {cm.moveH(1, "char");},
goColumnLeft: function(cm) {cm.moveH(-1, "column");},
goColumnRight: function(cm) {cm.moveH(1, "column");},
goWordLeft: function(cm) {cm.moveH(-1, "word");},
goGroupRight: function(cm) {cm.moveH(1, "group");},
goGroupLeft: function(cm) {cm.moveH(-1, "group");},
goWordRight: function(cm) {cm.moveH(1, "word");},
delCharBefore: function(cm) {cm.deleteH(-1, "char");},
delCharAfter: function(cm) {cm.deleteH(1, "char");},
delWordBefore: function(cm) {cm.deleteH(-1, "word");},
delWordAfter: function(cm) {cm.deleteH(1, "word");},
delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
delGroupAfter: function(cm) {cm.deleteH(1, "group");},
indentAuto: function(cm) {cm.indentSelection("smart");},
indentMore: function(cm) {cm.indentSelection("add");},
indentLess: function(cm) {cm.indentSelection("subtract");},
insertTab: function(cm) {cm.replaceSelection("\t");},
insertSoftTab: function(cm) {
var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
for (var i = 0; i < ranges.length; i++) {
var pos = ranges[i].from();
var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
spaces.push(new Array(tabSize - col % tabSize + 1).join(" "));
}
cm.replaceSelections(spaces);
},
defaultTab: function(cm) {
if (cm.somethingSelected()) cm.indentSelection("add");
else cm.execCommand("insertTab");
},
transposeChars: function(cm) {
runInOp(cm, function() {
var ranges = cm.listSelections(), newSel = [];
for (var i = 0; i < ranges.length; i++) {
var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
if (line) {
if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
if (cur.ch > 0) {
cur = new Pos(cur.line, cur.ch + 1);
cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
Pos(cur.line, cur.ch - 2), cur, "+transpose");
} else if (cur.line > cm.doc.first) {
var prev = getLine(cm.doc, cur.line - 1).text;
if (prev)
cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
prev.charAt(prev.length - 1),
Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
}
}
newSel.push(new Range(cur, cur));
}
cm.setSelections(newSel);
});
},
newlineAndIndent: function(cm) {
runInOp(cm, function() {
var len = cm.listSelections().length;
for (var i = 0; i < len; i++) {
var range = cm.listSelections()[i];
cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, "+input");
cm.indentLine(range.from().line + 1, null, true);
ensureCursorVisible(cm);
}
});
},
toggleOverwrite: function(cm) {cm.toggleOverwrite();}
};
// STANDARD KEYMAPS
var keyMap = CodeMirror.keyMap = {};
keyMap.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"
};
// Note that the save and find-related commands aren't defined by
// default. User code or addons can define them. Unknown commands
// are simply ignored.
keyMap.pcDefault = {
"Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
"Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
"Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
"Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
"Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
"Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
"Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
fallthrough: "basic"
};
// Very basic readline/emacs-style bindings, which are standard on Mac.
keyMap.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"
};
keyMap.macDefault = {
"Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
"Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
"Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
"Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
"Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
"Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
"Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
fallthrough: ["basic", "emacsy"]
};
keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
// KEYMAP DISPATCH
function normalizeKeyName(name) {
var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
var alt, ctrl, shift, cmd;
for (var i = 0; i < parts.length - 1; i++) {
var mod = parts[i];
if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
else if (/^a(lt)?$/i.test(mod)) alt = true;
else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
else if (/^s(hift)$/i.test(mod)) shift = true;
else throw new Error("Unrecognized modifier name: " + mod);
}
if (alt) name = "Alt-" + name;
if (ctrl) name = "Ctrl-" + name;
if (cmd) name = "Cmd-" + name;
if (shift) name = "Shift-" + name;
return name;
}
// This is a kludge to keep keymaps mostly working as raw objects
// (backwards compatibility) while at the same time support features
// like normalization and multi-stroke key bindings. It compiles a
// new normalized keymap, and then updates the old object to reflect
// this.
CodeMirror.normalizeKeyMap = function(keymap) {
var copy = {};
for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
var value = keymap[keyname];
if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
if (value == "...") { delete keymap[keyname]; continue; }
var keys = map(keyname.split(" "), normalizeKeyName);
for (var i = 0; i < keys.length; i++) {
var val, name;
if (i == keys.length - 1) {
name = keys.join(" ");
val = value;
} else {
name = keys.slice(0, i + 1).join(" ");
val = "...";
}
var prev = copy[name];
if (!prev) copy[name] = val;
else if (prev != val) throw new Error("Inconsistent bindings for " + name);
}
delete keymap[keyname];
}
for (var prop in copy) keymap[prop] = copy[prop];
return keymap;
};
var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
map = getKeyMap(map);
var found = map.call ? map.call(key, context) : map[key];
if (found === false) return "nothing";
if (found === "...") return "multi";
if (found != null && handle(found)) return "handled";
if (map.fallthrough) {
if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
return lookupKey(key, map.fallthrough, handle, context);
for (var i = 0; i < map.fallthrough.length; i++) {
var result = lookupKey(key, map.fallthrough[i], handle, context);
if (result) return result;
}
}
};
// Modifier key presses don't count as 'real' key presses for the
// purpose of keymap fallthrough.
var isModifierKey = CodeMirror.isModifierKey = function(value) {
var name = typeof value == "string" ? value : keyNames[value.keyCode];
return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
};
// Look up the name of a key as indicated by an event object.
var keyName = CodeMirror.keyName = function(event, noShift) {
if (presto && event.keyCode == 34 && event["char"]) return false;
var base = keyNames[event.keyCode], name = base;
if (name == null || event.altGraphKey) return false;
if (event.altKey && base != "Alt") name = "Alt-" + name;
if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;
if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;
if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;
return name;
};
function getKeyMap(val) {
return typeof val == "string" ? keyMap[val] : val;
}
// FROMTEXTAREA
CodeMirror.fromTextArea = function(textarea, options) {
options = options ? copyObj(options) : {};
options.value = textarea.value;
if (!options.tabindex && textarea.tabIndex)
options.tabindex = textarea.tabIndex;
if (!options.placeholder && textarea.placeholder)
options.placeholder = textarea.placeholder;
// Set autofocus to true if this textarea is focused, or if it has
// autofocus and no other element is focused.
if (options.autofocus == null) {
var hasFocus = activeElt();
options.autofocus = hasFocus == textarea ||
textarea.getAttribute("autofocus") != null && hasFocus == document.body;
}
function save() {textarea.value = cm.getValue();}
if (textarea.form) {
on(textarea.form, "submit", save);
// Deplorable hack to make the submit method do the right thing.
if (!options.leaveSubmitMethodAlone) {
var form = textarea.form, realSubmit = form.submit;
try {
var wrappedSubmit = form.submit = function() {
save();
form.submit = realSubmit;
form.submit();
form.submit = wrappedSubmit;
};
} catch(e) {}
}
}
options.finishInit = function(cm) {
cm.save = save;
cm.getTextArea = function() { return textarea; };
cm.toTextArea = function() {
cm.toTextArea = isNaN; // Prevent this from being ran twice
save();
textarea.parentNode.removeChild(cm.getWrapperElement());
textarea.style.display = "";
if (textarea.form) {
off(textarea.form, "submit", save);
if (typeof textarea.form.submit == "function")
textarea.form.submit = realSubmit;
}
};
};
textarea.style.display = "none";
var cm = CodeMirror(function(node) {
textarea.parentNode.insertBefore(node, textarea.nextSibling);
}, options);
return cm;
};
// STRING STREAM
// Fed to the mode parsers, provides helper functions to make
// parsers more succinct.
var StringStream = CodeMirror.StringStream = function(string, tabSize) {
this.pos = this.start = 0;
this.string = string;
this.tabSize = tabSize || 8;
this.lastColumnPos = this.lastColumnValue = 0;
this.lineStart = 0;
};
StringStream.prototype = {
eol: function() {return this.pos >= this.string.length;},
sol: function() {return this.pos == this.lineStart;},
peek: function() {return this.string.charAt(this.pos) || undefined;},
next: function() {
if (this.pos < this.string.length)
return this.string.charAt(this.pos++);
},
eat: function(match) {
var ch = this.string.charAt(this.pos);
if (typeof match == "string") var ok = ch == match;
else var ok = ch && (match.test ? match.test(ch) : match(ch));
if (ok) {++this.pos; return ch;}
},
eatWhile: function(match) {
var start = this.pos;
while (this.eat(match)){}
return this.pos > start;
},
eatSpace: function() {
var start = this.pos;
while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
return this.pos > start;
},
skipToEnd: function() {this.pos = this.string.length;},
skipTo: function(ch) {
var found = this.string.indexOf(ch, this.pos);
if (found > -1) {this.pos = found; return true;}
},
backUp: function(n) {this.pos -= n;},
column: function() {
if (this.lastColumnPos < this.start) {
this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
this.lastColumnPos = this.start;
}
return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
},
indentation: function() {
return countColumn(this.string, null, this.tabSize) -
(this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
},
match: function(pattern, consume, caseInsensitive) {
if (typeof pattern == "string") {
var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
var substr = this.string.substr(this.pos, pattern.length);
if (cased(substr) == cased(pattern)) {
if (consume !== false) this.pos += pattern.length;
return true;
}
} else {
var match = this.string.slice(this.pos).match(pattern);
if (match && match.index > 0) return null;
if (match && consume !== false) this.pos += match[0].length;
return match;
}
},
current: function(){return this.string.slice(this.start, this.pos);},
hideFirstChars: function(n, inner) {
this.lineStart += n;
try { return inner(); }
finally { this.lineStart -= n; }
}
};
// TEXTMARKERS
// Created with markText and setBookmark methods. A TextMarker is a
// handle that can be used to clear or find a marked position in the
// document. Line objects hold arrays (markedSpans) containing
// {from, to, marker} object pointing to such marker objects, and
// indicating that such a marker is present on that line. Multiple
// lines may point to the same marker when it spans across lines.
// The spans will have null for their from/to properties when the
// marker continues beyond the start/end of the line. Markers have
// links back to the lines they currently touch.
var nextMarkerId = 0;
var TextMarker = CodeMirror.TextMarker = function(doc, type) {
this.lines = [];
this.type = type;
this.doc = doc;
this.id = ++nextMarkerId;
};
eventMixin(TextMarker);
// Clear the marker.
TextMarker.prototype.clear = function() {
if (this.explicitlyCleared) return;
var cm = this.doc.cm, withOp = cm && !cm.curOp;
if (withOp) startOperation(cm);
if (hasHandler(this, "clear")) {
var found = this.find();
if (found) signalLater(this, "clear", found.from, found.to);
}
var min = null, max = null;
for (var i = 0; i < this.lines.length; ++i) {
var line = this.lines[i];
var span = getMarkedSpanFor(line.markedSpans, this);
if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
else if (cm) {
if (span.to != null) max = lineNo(line);
if (span.from != null) min = lineNo(line);
}
line.markedSpans = removeMarkedSpan(line.markedSpans, span);
if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
updateLineHeight(line, textHeight(cm.display));
}
if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
var visual = visualLine(this.lines[i]), len = lineLength(visual);
if (len > cm.display.maxLineLength) {
cm.display.maxLine = visual;
cm.display.maxLineLength = len;
cm.display.maxLineChanged = true;
}
}
if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
this.lines.length = 0;
this.explicitlyCleared = true;
if (this.atomic && this.doc.cantEdit) {
this.doc.cantEdit = false;
if (cm) reCheckSelection(cm.doc);
}
if (cm) signalLater(cm, "markerCleared", cm, this);
if (withOp) endOperation(cm);
if (this.parent) this.parent.clear();
};
// Find the position of the marker in the document. Returns a {from,
// to} object by default. Side can be passed to get a specific side
// -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
// Pos objects returned contain a line object, rather than a line
// number (used to prevent looking up the same line twice).
TextMarker.prototype.find = function(side, lineObj) {
if (side == null && this.type == "bookmark") side = 1;
var from, to;
for (var i = 0; i < this.lines.length; ++i) {
var line = this.lines[i];
var span = getMarkedSpanFor(line.markedSpans, this);
if (span.from != null) {
from = Pos(lineObj ? line : lineNo(line), span.from);
if (side == -1) return from;
}
if (span.to != null) {
to = Pos(lineObj ? line : lineNo(line), span.to);
if (side == 1) return to;
}
}
return from && {from: from, to: to};
};
// Signals that the marker's widget changed, and surrounding layout
// should be recomputed.
TextMarker.prototype.changed = function() {
var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
if (!pos || !cm) return;
runInOp(cm, function() {
var line = pos.line, lineN = lineNo(pos.line);
var view = findViewForLine(cm, lineN);
if (view) {
clearLineMeasurementCacheFor(view);
cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
}
cm.curOp.updateMaxLine = true;
if (!lineIsHidden(widget.doc, line) && widget.height != null) {
var oldHeight = widget.height;
widget.height = null;
var dHeight = widgetHeight(widget) - oldHeight;
if (dHeight)
updateLineHeight(line, line.height + dHeight);
}
});
};
TextMarker.prototype.attachLine = function(line) {
if (!this.lines.length && this.doc.cm) {
var op = this.doc.cm.curOp;
if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
(op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
}
this.lines.push(line);
};
TextMarker.prototype.detachLine = function(line) {
this.lines.splice(indexOf(this.lines, line), 1);
if (!this.lines.length && this.doc.cm) {
var op = this.doc.cm.curOp;
(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
}
};
// Collapsed markers have unique ids, in order to be able to order
// them, which is needed for uniquely determining an outer marker
// when they overlap (they may nest, but not partially overlap).
var nextMarkerId = 0;
// Create a marker, wire it up to the right lines, and
function markText(doc, from, to, options, type) {
// Shared markers (across linked documents) are handled separately
// (markTextShared will call out to this again, once per
// document).
if (options && options.shared) return markTextShared(doc, from, to, options, type);
// Ensure we are in an operation.
if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
var marker = new TextMarker(doc, type), diff = cmp(from, to);
if (options) copyObj(options, marker, false);
// Don't connect empty markers unless clearWhenEmpty is false
if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
return marker;
if (marker.replacedWith) {
// Showing up as a widget implies collapsed (widget replaces text)
marker.collapsed = true;
marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
if (options.insertLeft) marker.widgetNode.insertLeft = true;
}
if (marker.collapsed) {
if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
throw new Error("Inserting collapsed marker partially overlapping an existing one");
sawCollapsedSpans = true;
}
if (marker.addToHistory)
addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
var curLine = from.line, cm = doc.cm, updateMaxLine;
doc.iter(curLine, to.line + 1, function(line) {
if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
updateMaxLine = true;
if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
addMarkedSpan(line, new MarkedSpan(marker,
curLine == from.line ? from.ch : null,
curLine == to.line ? to.ch : null));
++curLine;
});
// lineIsHidden depends on the presence of the spans, so needs a second pass
if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
});
if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
if (marker.readOnly) {
sawReadOnlySpans = true;
if (doc.history.done.length || doc.history.undone.length)
doc.clearHistory();
}
if (marker.collapsed) {
marker.id = ++nextMarkerId;
marker.atomic = true;
}
if (cm) {
// Sync editor state
if (updateMaxLine) cm.curOp.updateMaxLine = true;
if (marker.collapsed)
regChange(cm, from.line, to.line + 1);
else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
if (marker.atomic) reCheckSelection(cm.doc);
signalLater(cm, "markerAdded", cm, marker);
}
return marker;
}
// SHARED TEXTMARKERS
// A shared marker spans multiple linked documents. It is
// implemented as a meta-marker-object controlling multiple normal
// markers.
var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
this.markers = markers;
this.primary = primary;
for (var i = 0; i < markers.length; ++i)
markers[i].parent = this;
};
eventMixin(SharedTextMarker);
SharedTextMarker.prototype.clear = function() {
if (this.explicitlyCleared) return;
this.explicitlyCleared = true;
for (var i = 0; i < this.markers.length; ++i)
this.markers[i].clear();
signalLater(this, "clear");
};
SharedTextMarker.prototype.find = function(side, lineObj) {
return this.primary.find(side, lineObj);
};
function markTextShared(doc, from, to, options, type) {
options = copyObj(options);
options.shared = false;
var markers = [markText(doc, from, to, options, type)], primary = markers[0];
var widget = options.widgetNode;
linkedDocs(doc, function(doc) {
if (widget) options.widgetNode = widget.cloneNode(true);
markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
for (var i = 0; i < doc.linked.length; ++i)
if (doc.linked[i].isParent) return;
primary = lst(markers);
});
return new SharedTextMarker(markers, primary);
}
function findSharedMarkers(doc) {
return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
function(m) { return m.parent; });
}
function copySharedMarkers(doc, markers) {
for (var i = 0; i < markers.length; i++) {
var marker = markers[i], pos = marker.find();
var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
if (cmp(mFrom, mTo)) {
var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
marker.markers.push(subMark);
subMark.parent = marker;
}
}
}
function detachSharedMarkers(markers) {
for (var i = 0; i < markers.length; i++) {
var marker = markers[i], linked = [marker.primary.doc];;
linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
for (var j = 0; j < marker.markers.length; j++) {
var subMarker = marker.markers[j];
if (indexOf(linked, subMarker.doc) == -1) {
subMarker.parent = null;
marker.markers.splice(j--, 1);
}
}
}
}
// TEXTMARKER SPANS
function MarkedSpan(marker, from, to) {
this.marker = marker;
this.from = from; this.to = to;
}
// Search an array of spans for a span matching the given marker.
function getMarkedSpanFor(spans, marker) {
if (spans) for (var i = 0; i < spans.length; ++i) {
var span = spans[i];
if (span.marker == marker) return span;
}
}
// Remove a span from an array, returning undefined if no spans are
// left (we don't store arrays for lines without spans).
function removeMarkedSpan(spans, span) {
for (var r, i = 0; i < spans.length; ++i)
if (spans[i] != span) (r || (r = [])).push(spans[i]);
return r;
}
// Add a span to a line.
function addMarkedSpan(line, span) {
line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
span.marker.attachLine(line);
}
// Used for the algorithm that adjusts markers for a change in the
// document. These functions cut an array of spans at a given
// character position, returning an array of remaining chunks (or
// undefined if nothing remains).
function markedSpansBefore(old, startCh, isInsert) {
if (old) for (var i = 0, nw; i < old.length; ++i) {
var span = old[i], marker = span.marker;
var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
}
}
return nw;
}
function markedSpansAfter(old, endCh, isInsert) {
if (old) for (var i = 0, nw; i < old.length; ++i) {
var span = old[i], marker = span.marker;
var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
span.to == null ? null : span.to - endCh));
}
}
return nw;
}
// Given a change object, compute the new set of marker spans that
// cover the line in which the change took place. Removes spans
// entirely within the change, reconnects spans belonging to the
// same marker that appear on both sides of the change, and cuts off
// spans partially within the change. Returns an array of span
// arrays with one element for each line in (after) the change.
function stretchSpansOverChange(doc, change) {
if (change.full) return null;
var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
if (!oldFirst && !oldLast) return null;
var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
// Get the spans that 'stick out' on both sides
var first = markedSpansBefore(oldFirst, startCh, isInsert);
var last = markedSpansAfter(oldLast, endCh, isInsert);
// Next, merge those two ends
var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
if (first) {
// Fix up .to properties of first
for (var i = 0; i < first.length; ++i) {
var span = first[i];
if (span.to == null) {
var found = getMarkedSpanFor(last, span.marker);
if (!found) span.to = startCh;
else if (sameLine) span.to = found.to == null ? null : found.to + offset;
}
}
}
if (last) {
// Fix up .from in last (or move them into first in case of sameLine)
for (var i = 0; i < last.length; ++i) {
var span = last[i];
if (span.to != null) span.to += offset;
if (span.from == null) {
var found = getMarkedSpanFor(first, span.marker);
if (!found) {
span.from = offset;
if (sameLine) (first || (first = [])).push(span);
}
} else {
span.from += offset;
if (sameLine) (first || (first = [])).push(span);
}
}
}
// Make sure we didn't create any zero-length spans
if (first) first = clearEmptySpans(first);
if (last && last != first) last = clearEmptySpans(last);
var newMarkers = [first];
if (!sameLine) {
// Fill gap with whole-line-spans
var gap = change.text.length - 2, gapMarkers;
if (gap > 0 && first)
for (var i = 0; i < first.length; ++i)
if (first[i].to == null)
(gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
for (var i = 0; i < gap; ++i)
newMarkers.push(gapMarkers);
newMarkers.push(last);
}
return newMarkers;
}
// Remove spans that are empty and don't have a clearWhenEmpty
// option of false.
function clearEmptySpans(spans) {
for (var i = 0; i < spans.length; ++i) {
var span = spans[i];
if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
spans.splice(i--, 1);
}
if (!spans.length) return null;
return spans;
}
// Used for un/re-doing changes from the history. Combines the
// result of computing the existing spans with the set of spans that
// existed in the history (so that deleting around a span and then
// undoing brings back the span).
function mergeOldSpans(doc, change) {
var old = getOldSpans(doc, change);
var stretched = stretchSpansOverChange(doc, change);
if (!old) return stretched;
if (!stretched) return old;
for (var i = 0; i < old.length; ++i) {
var oldCur = old[i], stretchCur = stretched[i];
if (oldCur && stretchCur) {
spans: for (var j = 0; j < stretchCur.length; ++j) {
var span = stretchCur[j];
for (var k = 0; k < oldCur.length; ++k)
if (oldCur[k].marker == span.marker) continue spans;
oldCur.push(span);
}
} else if (stretchCur) {
old[i] = stretchCur;
}
}
return old;
}
// Used to 'clip' out readOnly ranges when making a change.
function removeReadOnlyRanges(doc, from, to) {
var markers = null;
doc.iter(from.line, to.line + 1, function(line) {
if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
var mark = line.markedSpans[i].marker;
if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
(markers || (markers = [])).push(mark);
}
});
if (!markers) return null;
var parts = [{from: from, to: to}];
for (var i = 0; i < markers.length; ++i) {
var mk = markers[i], m = mk.find(0);
for (var j = 0; j < parts.length; ++j) {
var p = parts[j];
if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
newParts.push({from: p.from, to: m.from});
if (dto > 0 || !mk.inclusiveRight && !dto)
newParts.push({from: m.to, to: p.to});
parts.splice.apply(parts, newParts);
j += newParts.length - 1;
}
}
return parts;
}
// Connect or disconnect spans from a line.
function detachMarkedSpans(line) {
var spans = line.markedSpans;
if (!spans) return;
for (var i = 0; i < spans.length; ++i)
spans[i].marker.detachLine(line);
line.markedSpans = null;
}
function attachMarkedSpans(line, spans) {
if (!spans) return;
for (var i = 0; i < spans.length; ++i)
spans[i].marker.attachLine(line);
line.markedSpans = spans;
}
// Helpers used when computing which overlapping collapsed span
// counts as the larger one.
function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
// Returns a number indicating which of two overlapping collapsed
// spans is larger (and thus includes the other). Falls back to
// comparing ids when the spans cover exactly the same range.
function compareCollapsedMarkers(a, b) {
var lenDiff = a.lines.length - b.lines.length;
if (lenDiff != 0) return lenDiff;
var aPos = a.find(), bPos = b.find();
var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
if (fromCmp) return -fromCmp;
var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
if (toCmp) return toCmp;
return b.id - a.id;
}
// Find out whether a line ends or starts in a collapsed span. If
// so, return the marker for that span.
function collapsedSpanAtSide(line, start) {
var sps = sawCollapsedSpans && line.markedSpans, found;
if (sps) for (var sp, i = 0; i < sps.length; ++i) {
sp = sps[i];
if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
(!found || compareCollapsedMarkers(found, sp.marker) < 0))
found = sp.marker;
}
return found;
}
function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
// Test whether there exists a collapsed span that partially
// overlaps (covers the start or end, but not both) of a new span.
// Such overlap is not allowed.
function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
var line = getLine(doc, lineNo);
var sps = sawCollapsedSpans && line.markedSpans;
if (sps) for (var i = 0; i < sps.length; ++i) {
var sp = sps[i];
if (!sp.marker.collapsed) continue;
var found = sp.marker.find(0);
var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) ||
fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight)))
return true;
}
}
// A visual line is a line as drawn on the screen. Folding, for
// example, can cause multiple logical lines to appear on the same
// visual line. This finds the start of the visual line that the
// given line is part of (usually that is the line itself).
function visualLine(line) {
var merged;
while (merged = collapsedSpanAtStart(line))
line = merged.find(-1, true).line;
return line;
}
// Returns an array of logical lines that continue the visual line
// started by the argument, or undefined if there are no such lines.
function visualLineContinued(line) {
var merged, lines;
while (merged = collapsedSpanAtEnd(line)) {
line = merged.find(1, true).line;
(lines || (lines = [])).push(line);
}
return lines;
}
// Get the line number of the start of the visual line that the
// given line number is part of.
function visualLineNo(doc, lineN) {
var line = getLine(doc, lineN), vis = visualLine(line);
if (line == vis) return lineN;
return lineNo(vis);
}
// Get the line number of the start of the next visual line after
// the given line.
function visualLineEndNo(doc, lineN) {
if (lineN > doc.lastLine()) return lineN;
var line = getLine(doc, lineN), merged;
if (!lineIsHidden(doc, line)) return lineN;
while (merged = collapsedSpanAtEnd(line))
line = merged.find(1, true).line;
return lineNo(line) + 1;
}
// Compute whether a line is hidden. Lines count as hidden when they
// are part of a visual line that starts with another line, or when
// they are entirely covered by collapsed, non-widget span.
function lineIsHidden(doc, line) {
var sps = sawCollapsedSpans && line.markedSpans;
if (sps) for (var sp, i = 0; i < sps.length; ++i) {
sp = sps[i];
if (!sp.marker.collapsed) continue;
if (sp.from == null) return true;
if (sp.marker.widgetNode) continue;
if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
return true;
}
}
function lineIsHiddenInner(doc, line, span) {
if (span.to == null) {
var end = span.marker.find(1, true);
return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
}
if (span.marker.inclusiveRight && span.to == line.text.length)
return true;
for (var sp, i = 0; i < line.markedSpans.length; ++i) {
sp = line.markedSpans[i];
if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
(sp.to == null || sp.to != span.from) &&
(sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
lineIsHiddenInner(doc, line, sp)) return true;
}
}
// LINE WIDGETS
// Line widgets are block elements displayed above or below a line.
var LineWidget = CodeMirror.LineWidget = function(doc, node, options) {
if (options) for (var opt in options) if (options.hasOwnProperty(opt))
this[opt] = options[opt];
this.doc = doc;
this.node = node;
};
eventMixin(LineWidget);
function adjustScrollWhenAboveVisible(cm, line, diff) {
if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
addToScrollPos(cm, null, diff);
}
LineWidget.prototype.clear = function() {
var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
if (no == null || !ws) return;
for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
if (!ws.length) line.widgets = null;
var height = widgetHeight(this);
updateLineHeight(line, Math.max(0, line.height - height));
if (cm) runInOp(cm, function() {
adjustScrollWhenAboveVisible(cm, line, -height);
regLineChange(cm, no, "widget");
});
};
LineWidget.prototype.changed = function() {
var oldH = this.height, cm = this.doc.cm, line = this.line;
this.height = null;
var diff = widgetHeight(this) - oldH;
if (!diff) return;
updateLineHeight(line, line.height + diff);
if (cm) runInOp(cm, function() {
cm.curOp.forceUpdate = true;
adjustScrollWhenAboveVisible(cm, line, diff);
});
};
function widgetHeight(widget) {
if (widget.height != null) return widget.height;
var cm = widget.doc.cm;
if (!cm) return 0;
if (!contains(document.body, widget.node)) {
var parentStyle = "position: relative;";
if (widget.coverGutter)
parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
if (widget.noHScroll)
parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
}
return widget.height = widget.node.offsetHeight;
}
function addLineWidget(doc, handle, node, options) {
var widget = new LineWidget(doc, node, options);
var cm = doc.cm;
if (cm && widget.noHScroll) cm.display.alignWidgets = true;
changeLine(doc, handle, "widget", function(line) {
var widgets = line.widgets || (line.widgets = []);
if (widget.insertAt == null) widgets.push(widget);
else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
widget.line = line;
if (cm && !lineIsHidden(doc, line)) {
var aboveVisible = heightAtLine(line) < doc.scrollTop;
updateLineHeight(line, line.height + widgetHeight(widget));
if (aboveVisible) addToScrollPos(cm, null, widget.height);
cm.curOp.forceUpdate = true;
}
return true;
});
return widget;
}
// LINE DATA STRUCTURE
// Line objects. These hold state related to a line, including
// highlighting info (the styles array).
var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
this.text = text;
attachMarkedSpans(this, markedSpans);
this.height = estimateHeight ? estimateHeight(this) : 1;
};
eventMixin(Line);
Line.prototype.lineNo = function() { return lineNo(this); };
// Change the content (text, markers) of a line. Automatically
// invalidates cached information and tries to re-estimate the
// line's height.
function updateLine(line, text, markedSpans, estimateHeight) {
line.text = text;
if (line.stateAfter) line.stateAfter = null;
if (line.styles) line.styles = null;
if (line.order != null) line.order = null;
detachMarkedSpans(line);
attachMarkedSpans(line, markedSpans);
var estHeight = estimateHeight ? estimateHeight(line) : 1;
if (estHeight != line.height) updateLineHeight(line, estHeight);
}
// Detach a line from the document tree and its markers.
function cleanUpLine(line) {
line.parent = null;
detachMarkedSpans(line);
}
function extractLineClasses(type, output) {
if (type) for (;;) {
var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
if (!lineClass) break;
type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
var prop = lineClass[1] ? "bgClass" : "textClass";
if (output[prop] == null)
output[prop] = lineClass[2];
else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
output[prop] += " " + lineClass[2];
}
return type;
}
function callBlankLine(mode, state) {
if (mode.blankLine) return mode.blankLine(state);
if (!mode.innerMode) return;
var inner = CodeMirror.innerMode(mode, state);
if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
}
function readToken(mode, stream, state, inner) {
for (var i = 0; i < 10; i++) {
if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
var style = mode.token(stream, state);
if (stream.pos > stream.start) return style;
}
throw new Error("Mode " + mode.name + " failed to advance stream.");
}
// Utility for getTokenAt and getLineTokens
function takeToken(cm, pos, precise, asArray) {
function getObj(copy) {
return {start: stream.start, end: stream.pos,
string: stream.current(),
type: style || null,
state: copy ? copyState(doc.mode, state) : state};
}
var doc = cm.doc, mode = doc.mode, style;
pos = clipPos(doc, pos);
var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
var stream = new StringStream(line.text, cm.options.tabSize), tokens;
if (asArray) tokens = [];
while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
stream.start = stream.pos;
style = readToken(mode, stream, state);
if (asArray) tokens.push(getObj(true));
}
return asArray ? tokens : getObj();
}
// Run the given mode's parser over a line, calling f for each token.
function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
var flattenSpans = mode.flattenSpans;
if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
var curStart = 0, curStyle = null;
var stream = new StringStream(text, cm.options.tabSize), style;
var inner = cm.options.addModeClass && [null];
if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
while (!stream.eol()) {
if (stream.pos > cm.options.maxHighlightLength) {
flattenSpans = false;
if (forceToEnd) processLine(cm, text, state, stream.pos);
stream.pos = text.length;
style = null;
} else {
style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
}
if (inner) {
var mName = inner[0].name;
if (mName) style = "m-" + (style ? mName + " " + style : mName);
}
if (!flattenSpans || curStyle != style) {
while (curStart < stream.start) {
curStart = Math.min(stream.start, curStart + 50000);
f(curStart, curStyle);
}
curStyle = style;
}
stream.start = stream.pos;
}
while (curStart < stream.pos) {
// Webkit seems to refuse to render text nodes longer than 57444 characters
var pos = Math.min(stream.pos, curStart + 50000);
f(pos, curStyle);
curStart = pos;
}
}
// Compute a style array (an array starting with a mode generation
// -- for invalidation -- followed by pairs of end positions and
// style strings), which is used to highlight the tokens on the
// line.
function highlightLine(cm, line, state, forceToEnd) {
// A styles array always starts with a number identifying the
// mode/overlays that it is based on (for easy invalidation).
var st = [cm.state.modeGen], lineClasses = {};
// Compute the base array of styles
runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
st.push(end, style);
}, lineClasses, forceToEnd);
// Run overlays, adjust style array.
for (var o = 0; o < cm.state.overlays.length; ++o) {
var overlay = cm.state.overlays[o], i = 1, at = 0;
runMode(cm, line.text, overlay.mode, true, function(end, style) {
var start = i;
// Ensure there's a token end at the current position, and that i points at it
while (at < end) {
var i_end = st[i];
if (i_end > end)
st.splice(i, 1, end, st[i+1], i_end);
i += 2;
at = Math.min(end, i_end);
}
if (!style) return;
if (overlay.opaque) {
st.splice(start, i - start, end, "cm-overlay " + style);
i = start + 2;
} else {
for (; start < i; start += 2) {
var cur = st[start+1];
st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
}
}
}, lineClasses);
}
return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
}
function getLineStyles(cm, line, updateFrontier) {
if (!line.styles || line.styles[0] != cm.state.modeGen) {
var state = getStateBefore(cm, lineNo(line));
var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state);
line.stateAfter = state;
line.styles = result.styles;
if (result.classes) line.styleClasses = result.classes;
else if (line.styleClasses) line.styleClasses = null;
if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
}
return line.styles;
}
// Lightweight form of highlight -- proceed over this line and
// update state, but don't save a style array. Used for lines that
// aren't currently visible.
function processLine(cm, text, state, startAt) {
var mode = cm.doc.mode;
var stream = new StringStream(text, cm.options.tabSize);
stream.start = stream.pos = startAt || 0;
if (text == "") callBlankLine(mode, state);
while (!stream.eol()) {
readToken(mode, stream, state);
stream.start = stream.pos;
}
}
// Convert a style as returned by a mode (either null, or a string
// containing one or more styles) to a CSS style. This is cached,
// and also looks for line-wide styles.
var styleToClassCache = {}, styleToClassCacheWithMode = {};
function interpretTokenStyle(style, options) {
if (!style || /^\s*$/.test(style)) return null;
var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
return cache[style] ||
(cache[style] = style.replace(/\S+/g, "cm-$&"));
}
// Render the DOM representation of the text of a line. Also builds
// up a 'line map', which points at the DOM nodes that represent
// specific stretches of text, and is used by the measuring code.
// The returned object contains the DOM node, this map, and
// information about line-wide styles that were set by the mode.
function buildLineContent(cm, lineView) {
// The padding-right forces the element to have a 'border', which
// is needed on Webkit to be able to get line-level bounding
// rectangles for it (in measureChar).
var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content,
col: 0, pos: 0, cm: cm,
splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
lineView.measure = {};
// Iterate over the logical lines that make up this visual line.
for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
var line = i ? lineView.rest[i - 1] : lineView.line, order;
builder.pos = 0;
builder.addToken = buildToken;
// Optionally wire in some hacks into the token-rendering
// algorithm, to deal with browser quirks.
if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
builder.addToken = buildTokenBadBidi(builder.addToken, order);
builder.map = [];
var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
if (line.styleClasses) {
if (line.styleClasses.bgClass)
builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
if (line.styleClasses.textClass)
builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
}
// Ensure at least a single node is present, for measuring.
if (builder.map.length == 0)
builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
// Store the map and a cache object for the current logical line
if (i == 0) {
lineView.measure.map = builder.map;
lineView.measure.cache = {};
} else {
(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
(lineView.measure.caches || (lineView.measure.caches = [])).push({});
}
}
// See issue #2901
if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className))
builder.content.className = "cm-tab-wrap-hack";
signal(cm, "renderLine", cm, lineView.line, builder.pre);
if (builder.pre.className)
builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
return builder;
}
function defaultSpecialCharPlaceholder(ch) {
var token = elt("span", "\u2022", "cm-invalidchar");
token.title = "\\u" + ch.charCodeAt(0).toString(16);
token.setAttribute("aria-label", token.title);
return token;
}
// Build up the DOM representation for a single token, and add it to
// the line map. Takes care to render special characters separately.
function buildToken(builder, text, style, startStyle, endStyle, title, css) {
if (!text) return;
var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text;
var special = builder.cm.state.specialChars, mustWrap = false;
if (!special.test(text)) {
builder.col += text.length;
var content = document.createTextNode(displayText);
builder.map.push(builder.pos, builder.pos + text.length, content);
if (ie && ie_version < 9) mustWrap = true;
builder.pos += text.length;
} else {
var content = document.createDocumentFragment(), pos = 0;
while (true) {
special.lastIndex = pos;
var m = special.exec(text);
var skipped = m ? m.index - pos : text.length - pos;
if (skipped) {
var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
else content.appendChild(txt);
builder.map.push(builder.pos, builder.pos + skipped, txt);
builder.col += skipped;
builder.pos += skipped;
}
if (!m) break;
pos += skipped + 1;
if (m[0] == "\t") {
var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
txt.setAttribute("role", "presentation");
txt.setAttribute("cm-text", "\t");
builder.col += tabWidth;
} else if (m[0] == "\r" || m[0] == "\n") {
var txt = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
txt.setAttribute("cm-text", m[0]);
builder.col += 1;
} else {
var txt = builder.cm.options.specialCharPlaceholder(m[0]);
txt.setAttribute("cm-text", m[0]);
if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
else content.appendChild(txt);
builder.col += 1;
}
builder.map.push(builder.pos, builder.pos + 1, txt);
builder.pos++;
}
}
if (style || startStyle || endStyle || mustWrap || css) {
var fullStyle = style || "";
if (startStyle) fullStyle += startStyle;
if (endStyle) fullStyle += endStyle;
var token = elt("span", [content], fullStyle, css);
if (title) token.title = title;
return builder.content.appendChild(token);
}
builder.content.appendChild(content);
}
function splitSpaces(old) {
var out = " ";
for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
out += " ";
return out;
}
// Work around nonsense dimensions being reported for stretches of
// right-to-left text.
function buildTokenBadBidi(inner, order) {
return function(builder, text, style, startStyle, endStyle, title, css) {
style = style ? style + " cm-force-border" : "cm-force-border";
var start = builder.pos, end = start + text.length;
for (;;) {
// Find the part that overlaps with the start of this text
for (var i = 0; i < order.length; i++) {
var part = order[i];
if (part.to > start && part.from <= start) break;
}
if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css);
inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
startStyle = null;
text = text.slice(part.to - start);
start = part.to;
}
};
}
function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
var widget = !ignoreWidget && marker.widgetNode;
if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
if (!widget)
widget = builder.content.appendChild(document.createElement("span"));
widget.setAttribute("cm-marker", marker.id);
}
if (widget) {
builder.cm.display.input.setUneditable(widget);
builder.content.appendChild(widget);
}
builder.pos += size;
}
// Outputs a number of spans to make up a line, taking highlighting
// and marked text into account.
function insertLineContent(line, builder, styles) {
var spans = line.markedSpans, allText = line.text, at = 0;
if (!spans) {
for (var i = 1; i < styles.length; i+=2)
builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
return;
}
var len = allText.length, pos = 0, i = 1, text = "", style, css;
var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
for (;;) {
if (nextChange == pos) { // Update current marker set
spanStyle = spanEndStyle = spanStartStyle = title = css = "";
collapsed = null; nextChange = Infinity;
var foundBookmarks = [];
for (var j = 0; j < spans.length; ++j) {
var sp = spans[j], m = sp.marker;
if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
foundBookmarks.push(m);
} else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
if (sp.to != null && sp.to != pos && nextChange > sp.to) {
nextChange = sp.to;
spanEndStyle = "";
}
if (m.className) spanStyle += " " + m.className;
if (m.css) css = m.css;
if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle;
if (m.title && !title) title = m.title;
if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
collapsed = sp;
} else if (sp.from > pos && nextChange > sp.from) {
nextChange = sp.from;
}
}
if (collapsed && (collapsed.from || 0) == pos) {
buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
collapsed.marker, collapsed.from == null);
if (collapsed.to == null) return;
if (collapsed.to == pos) collapsed = false;
}
if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)
buildCollapsedSpan(builder, 0, foundBookmarks[j]);
}
if (pos >= len) break;
var upto = Math.min(len, nextChange);
while (true) {
if (text) {
var end = pos + text.length;
if (!collapsed) {
var tokenText = end > upto ? text.slice(0, upto - pos) : text;
builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
}
if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
pos = end;
spanStartStyle = "";
}
text = allText.slice(at, at = styles[i++]);
style = interpretTokenStyle(styles[i++], builder.cm.options);
}
}
}
// DOCUMENT DATA STRUCTURE
// By default, updates that start and end at the beginning of a line
// are treated specially, in order to make the association of line
// widgets and marker elements with the text behave more intuitive.
function isWholeLineUpdate(doc, change) {
return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
(!doc.cm || doc.cm.options.wholeLineUpdateBefore);
}
// Perform a change on the document data structure.
function updateDoc(doc, change, markedSpans, estimateHeight) {
function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
function update(line, text, spans) {
updateLine(line, text, spans, estimateHeight);
signalLater(line, "change", line, change);
}
function linesFor(start, end) {
for (var i = start, result = []; i < end; ++i)
result.push(new Line(text[i], spansFor(i), estimateHeight));
return result;
}
var from = change.from, to = change.to, text = change.text;
var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
// Adjust the line structure
if (change.full) {
doc.insert(0, linesFor(0, text.length));
doc.remove(text.length, doc.size - text.length);
} else if (isWholeLineUpdate(doc, change)) {
// This is a whole-line replace. Treated specially to make
// sure line objects move the way they are supposed to.
var added = linesFor(0, text.length - 1);
update(lastLine, lastLine.text, lastSpans);
if (nlines) doc.remove(from.line, nlines);
if (added.length) doc.insert(from.line, added);
} else if (firstLine == lastLine) {
if (text.length == 1) {
update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
} else {
var added = linesFor(1, text.length - 1);
added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
doc.insert(from.line + 1, added);
}
} else if (text.length == 1) {
update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
doc.remove(from.line + 1, nlines);
} else {
update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
var added = linesFor(1, text.length - 1);
if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
doc.insert(from.line + 1, added);
}
signalLater(doc, "change", doc, change);
}
// The document is represented as a BTree consisting of leaves, with
// chunk of lines in them, and branches, with up to ten leaves or
// other branch nodes below them. The top node is always a branch
// node, and is the document object itself (meaning it has
// additional methods and properties).
//
// All nodes have parent links. The tree is used both to go from
// line numbers to line objects, and to go from objects to numbers.
// It also indexes by height, and is used to convert between height
// and line object, and to find the total height of the document.
//
// See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
function LeafChunk(lines) {
this.lines = lines;
this.parent = null;
for (var i = 0, height = 0; i < lines.length; ++i) {
lines[i].parent = this;
height += lines[i].height;
}
this.height = height;
}
LeafChunk.prototype = {
chunkSize: function() { return this.lines.length; },
// Remove the n lines at offset 'at'.
removeInner: function(at, n) {
for (var i = at, e = at + n; i < e; ++i) {
var line = this.lines[i];
this.height -= line.height;
cleanUpLine(line);
signalLater(line, "delete");
}
this.lines.splice(at, n);
},
// Helper used to collapse a small branch into a single leaf.
collapse: function(lines) {
lines.push.apply(lines, this.lines);
},
// Insert the given array of lines at offset 'at', count them as
// having the given height.
insertInner: function(at, lines, height) {
this.height += height;
this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
},
// Used to iterate over a part of the tree.
iterN: function(at, n, op) {
for (var e = at + n; at < e; ++at)
if (op(this.lines[at])) return true;
}
};
function BranchChunk(children) {
this.children = children;
var size = 0, height = 0;
for (var i = 0; i < children.length; ++i) {
var ch = children[i];
size += ch.chunkSize(); height += ch.height;
ch.parent = this;
}
this.size = size;
this.height = height;
this.parent = null;
}
BranchChunk.prototype = {
chunkSize: function() { return this.size; },
removeInner: function(at, n) {
this.size -= n;
for (var i = 0; i < this.children.length; ++i) {
var child = this.children[i], sz = child.chunkSize();
if (at < sz) {
var rm = Math.min(n, sz - at), oldHeight = child.height;
child.removeInner(at, rm);
this.height -= oldHeight - child.height;
if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
if ((n -= rm) == 0) break;
at = 0;
} else at -= sz;
}
// If the result is smaller than 25 lines, ensure that it is a
// single leaf node.
if (this.size - n < 25 &&
(this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
var lines = [];
this.collapse(lines);
this.children = [new LeafChunk(lines)];
this.children[0].parent = this;
}
},
collapse: function(lines) {
for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
},
insertInner: function(at, lines, height) {
this.size += lines.length;
this.height += height;
for (var i = 0; i < this.children.length; ++i) {
var child = this.children[i], sz = child.chunkSize();
if (at <= sz) {
child.insertInner(at, lines, height);
if (child.lines && child.lines.length > 50) {
while (child.lines.length > 50) {
var spilled = child.lines.splice(child.lines.length - 25, 25);
var newleaf = new LeafChunk(spilled);
child.height -= newleaf.height;
this.children.splice(i + 1, 0, newleaf);
newleaf.parent = this;
}
this.maybeSpill();
}
break;
}
at -= sz;
}
},
// When a node has grown, check whether it should be split.
maybeSpill: function() {
if (this.children.length <= 10) return;
var me = this;
do {
var spilled = me.children.splice(me.children.length - 5, 5);
var sibling = new BranchChunk(spilled);
if (!me.parent) { // Become the parent node
var copy = new BranchChunk(me.children);
copy.parent = me;
me.children = [copy, sibling];
me = copy;
} else {
me.size -= sibling.size;
me.height -= sibling.height;
var myIndex = indexOf(me.parent.children, me);
me.parent.children.splice(myIndex + 1, 0, sibling);
}
sibling.parent = me.parent;
} while (me.children.length > 10);
me.parent.maybeSpill();
},
iterN: function(at, n, op) {
for (var i = 0; i < this.children.length; ++i) {
var child = this.children[i], sz = child.chunkSize();
if (at < sz) {
var used = Math.min(n, sz - at);
if (child.iterN(at, used, op)) return true;
if ((n -= used) == 0) break;
at = 0;
} else at -= sz;
}
}
};
var nextDocId = 0;
var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) {
if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep);
if (firstLine == null) firstLine = 0;
BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
this.first = firstLine;
this.scrollTop = this.scrollLeft = 0;
this.cantEdit = false;
this.cleanGeneration = 1;
this.frontier = firstLine;
var start = Pos(firstLine, 0);
this.sel = simpleSelection(start);
this.history = new History(null);
this.id = ++nextDocId;
this.modeOption = mode;
this.lineSep = lineSep;
if (typeof text == "string") text = this.splitLines(text);
updateDoc(this, {from: start, to: start, text: text});
setSelection(this, simpleSelection(start), sel_dontScroll);
};
Doc.prototype = createObj(BranchChunk.prototype, {
constructor: Doc,
// Iterate over the document. Supports two forms -- with only one
// argument, it calls that for each line in the document. With
// three, it iterates over the range given by the first two (with
// the second being non-inclusive).
iter: function(from, to, op) {
if (op) this.iterN(from - this.first, to - from, op);
else this.iterN(this.first, this.first + this.size, from);
},
// Non-public interface for adding and removing lines.
insert: function(at, lines) {
var height = 0;
for (var i = 0; i < lines.length; ++i) height += lines[i].height;
this.insertInner(at - this.first, lines, height);
},
remove: function(at, n) { this.removeInner(at - this.first, n); },
// From here, the methods are part of the public interface. Most
// are also available from CodeMirror (editor) instances.
getValue: function(lineSep) {
var lines = getLines(this, this.first, this.first + this.size);
if (lineSep === false) return lines;
return lines.join(lineSep || this.lineSeparator());
},
setValue: docMethodOp(function(code) {
var top = Pos(this.first, 0), last = this.first + this.size - 1;
makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
text: this.splitLines(code), origin: "setValue", full: true}, true);
setSelection(this, simpleSelection(top));
}),
replaceRange: function(code, from, to, origin) {
from = clipPos(this, from);
to = to ? clipPos(this, to) : from;
replaceRange(this, code, from, to, origin);
},
getRange: function(from, to, lineSep) {
var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
if (lineSep === false) return lines;
return lines.join(lineSep || this.lineSeparator());
},
getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
getLineNumber: function(line) {return lineNo(line);},
getLineHandleVisualStart: function(line) {
if (typeof line == "number") line = getLine(this, line);
return visualLine(line);
},
lineCount: function() {return this.size;},
firstLine: function() {return this.first;},
lastLine: function() {return this.first + this.size - 1;},
clipPos: function(pos) {return clipPos(this, pos);},
getCursor: function(start) {
var range = this.sel.primary(), pos;
if (start == null || start == "head") pos = range.head;
else if (start == "anchor") pos = range.anchor;
else if (start == "end" || start == "to" || start === false) pos = range.to();
else pos = range.from();
return pos;
},
listSelections: function() { return this.sel.ranges; },
somethingSelected: function() {return this.sel.somethingSelected();},
setCursor: docMethodOp(function(line, ch, options) {
setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
}),
setSelection: docMethodOp(function(anchor, head, options) {
setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
}),
extendSelection: docMethodOp(function(head, other, options) {
extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
}),
extendSelections: docMethodOp(function(heads, options) {
extendSelections(this, clipPosArray(this, heads, options));
}),
extendSelectionsBy: docMethodOp(function(f, options) {
extendSelections(this, map(this.sel.ranges, f), options);
}),
setSelections: docMethodOp(function(ranges, primary, options) {
if (!ranges.length) return;
for (var i = 0, out = []; i < ranges.length; i++)
out[i] = new Range(clipPos(this, ranges[i].anchor),
clipPos(this, ranges[i].head));
if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
setSelection(this, normalizeSelection(out, primary), options);
}),
addSelection: docMethodOp(function(anchor, head, options) {
var ranges = this.sel.ranges.slice(0);
ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
}),
getSelection: function(lineSep) {
var ranges = this.sel.ranges, lines;
for (var i = 0; i < ranges.length; i++) {
var sel = getBetween(this, ranges[i].from(), ranges[i].to());
lines = lines ? lines.concat(sel) : sel;
}
if (lineSep === false) return lines;
else return lines.join(lineSep || this.lineSeparator());
},
getSelections: function(lineSep) {
var parts = [], ranges = this.sel.ranges;
for (var i = 0; i < ranges.length; i++) {
var sel = getBetween(this, ranges[i].from(), ranges[i].to());
if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator());
parts[i] = sel;
}
return parts;
},
replaceSelection: function(code, collapse, origin) {
var dup = [];
for (var i = 0; i < this.sel.ranges.length; i++)
dup[i] = code;
this.replaceSelections(dup, collapse, origin || "+input");
},
replaceSelections: docMethodOp(function(code, collapse, origin) {
var changes = [], sel = this.sel;
for (var i = 0; i < sel.ranges.length; i++) {
var range = sel.ranges[i];
changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
}
var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
for (var i = changes.length - 1; i >= 0; i--)
makeChange(this, changes[i]);
if (newSel) setSelectionReplaceHistory(this, newSel);
else if (this.cm) ensureCursorVisible(this.cm);
}),
undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
setExtending: function(val) {this.extend = val;},
getExtending: function() {return this.extend;},
historySize: function() {
var hist = this.history, done = 0, undone = 0;
for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
return {undo: done, redo: undone};
},
clearHistory: function() {this.history = new History(this.history.maxGeneration);},
markClean: function() {
this.cleanGeneration = this.changeGeneration(true);
},
changeGeneration: function(forceSplit) {
if (forceSplit)
this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
return this.history.generation;
},
isClean: function (gen) {
return this.history.generation == (gen || this.cleanGeneration);
},
getHistory: function() {
return {done: copyHistoryArray(this.history.done),
undone: copyHistoryArray(this.history.undone)};
},
setHistory: function(histData) {
var hist = this.history = new History(this.history.maxGeneration);
hist.done = copyHistoryArray(histData.done.slice(0), null, true);
hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
},
addLineClass: docMethodOp(function(handle, where, cls) {
return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
var prop = where == "text" ? "textClass"
: where == "background" ? "bgClass"
: where == "gutter" ? "gutterClass" : "wrapClass";
if (!line[prop]) line[prop] = cls;
else if (classTest(cls).test(line[prop])) return false;
else line[prop] += " " + cls;
return true;
});
}),
removeLineClass: docMethodOp(function(handle, where, cls) {
return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
var prop = where == "text" ? "textClass"
: where == "background" ? "bgClass"
: where == "gutter" ? "gutterClass" : "wrapClass";
var cur = line[prop];
if (!cur) return false;
else if (cls == null) line[prop] = null;
else {
var found = cur.match(classTest(cls));
if (!found) return false;
var end = found.index + found[0].length;
line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
}
return true;
});
}),
addLineWidget: docMethodOp(function(handle, node, options) {
return addLineWidget(this, handle, node, options);
}),
removeLineWidget: function(widget) { widget.clear(); },
markText: function(from, to, options) {
return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
},
setBookmark: function(pos, options) {
var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
insertLeft: options && options.insertLeft,
clearWhenEmpty: false, shared: options && options.shared,
handleMouseEvents: options && options.handleMouseEvents};
pos = clipPos(this, pos);
return markText(this, pos, pos, realOpts, "bookmark");
},
findMarksAt: function(pos) {
pos = clipPos(this, pos);
var markers = [], spans = getLine(this, pos.line).markedSpans;
if (spans) for (var i = 0; i < spans.length; ++i) {
var span = spans[i];
if ((span.from == null || span.from <= pos.ch) &&
(span.to == null || span.to >= pos.ch))
markers.push(span.marker.parent || span.marker);
}
return markers;
},
findMarks: function(from, to, filter) {
from = clipPos(this, from); to = clipPos(this, to);
var found = [], lineNo = from.line;
this.iter(from.line, to.line + 1, function(line) {
var spans = line.markedSpans;
if (spans) for (var i = 0; i < spans.length; i++) {
var span = spans[i];
if (!(lineNo == from.line && from.ch > span.to ||
span.from == null && lineNo != from.line||
lineNo == to.line && span.from > to.ch) &&
(!filter || filter(span.marker)))
found.push(span.marker.parent || span.marker);
}
++lineNo;
});
return found;
},
getAllMarks: function() {
var markers = [];
this.iter(function(line) {
var sps = line.markedSpans;
if (sps) for (var i = 0; i < sps.length; ++i)
if (sps[i].from != null) markers.push(sps[i].marker);
});
return markers;
},
posFromIndex: function(off) {
var ch, lineNo = this.first;
this.iter(function(line) {
var sz = line.text.length + 1;
if (sz > off) { ch = off; return true; }
off -= sz;
++lineNo;
});
return clipPos(this, Pos(lineNo, ch));
},
indexFromPos: function (coords) {
coords = clipPos(this, coords);
var index = coords.ch;
if (coords.line < this.first || coords.ch < 0) return 0;
this.iter(this.first, coords.line, function (line) {
index += line.text.length + 1;
});
return index;
},
copy: function(copyHistory) {
var doc = new Doc(getLines(this, this.first, this.first + this.size),
this.modeOption, this.first, this.lineSep);
doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
doc.sel = this.sel;
doc.extend = false;
if (copyHistory) {
doc.history.undoDepth = this.history.undoDepth;
doc.setHistory(this.getHistory());
}
return doc;
},
linkedDoc: function(options) {
if (!options) options = {};
var from = this.first, to = this.first + this.size;
if (options.from != null && options.from > from) from = options.from;
if (options.to != null && options.to < to) to = options.to;
var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep);
if (options.sharedHist) copy.history = this.history;
(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
copySharedMarkers(copy, findSharedMarkers(this));
return copy;
},
unlinkDoc: function(other) {
if (other instanceof CodeMirror) other = other.doc;
if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
var link = this.linked[i];
if (link.doc != other) continue;
this.linked.splice(i, 1);
other.unlinkDoc(this);
detachSharedMarkers(findSharedMarkers(this));
break;
}
// If the histories were shared, split them again
if (other.history == this.history) {
var splitIds = [other.id];
linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
other.history = new History(null);
other.history.done = copyHistoryArray(this.history.done, splitIds);
other.history.undone = copyHistoryArray(this.history.undone, splitIds);
}
},
iterLinkedDocs: function(f) {linkedDocs(this, f);},
getMode: function() {return this.mode;},
getEditor: function() {return this.cm;},
splitLines: function(str) {
if (this.lineSep) return str.split(this.lineSep);
return splitLinesAuto(str);
},
lineSeparator: function() { return this.lineSep || "\n"; }
});
// Public alias.
Doc.prototype.eachLine = Doc.prototype.iter;
// Set up methods on CodeMirror's prototype to redirect to the editor's document.
var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
CodeMirror.prototype[prop] = (function(method) {
return function() {return method.apply(this.doc, arguments);};
})(Doc.prototype[prop]);
eventMixin(Doc);
// Call f for all linked documents.
function linkedDocs(doc, f, sharedHistOnly) {
function propagate(doc, skip, sharedHist) {
if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
var rel = doc.linked[i];
if (rel.doc == skip) continue;
var shared = sharedHist && rel.sharedHist;
if (sharedHistOnly && !shared) continue;
f(rel.doc, shared);
propagate(rel.doc, doc, shared);
}
}
propagate(doc, null, true);
}
// Attach a document to an editor.
function attachDoc(cm, doc) {
if (doc.cm) throw new Error("This document is already in use.");
cm.doc = doc;
doc.cm = cm;
estimateLineHeights(cm);
loadMode(cm);
if (!cm.options.lineWrapping) findMaxLine(cm);
cm.options.mode = doc.modeOption;
regChange(cm);
}
// LINE UTILITIES
// Find the line object corresponding to the given line number.
function getLine(doc, n) {
n -= doc.first;
if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
for (var chunk = doc; !chunk.lines;) {
for (var i = 0;; ++i) {
var child = chunk.children[i], sz = child.chunkSize();
if (n < sz) { chunk = child; break; }
n -= sz;
}
}
return chunk.lines[n];
}
// Get the part of a document between two positions, as an array of
// strings.
function getBetween(doc, start, end) {
var out = [], n = start.line;
doc.iter(start.line, end.line + 1, function(line) {
var text = line.text;
if (n == end.line) text = text.slice(0, end.ch);
if (n == start.line) text = text.slice(start.ch);
out.push(text);
++n;
});
return out;
}
// Get the lines between from and to, as array of strings.
function getLines(doc, from, to) {
var out = [];
doc.iter(from, to, function(line) { out.push(line.text); });
return out;
}
// Update the height of a line, propagating the height change
// upwards to parent nodes.
function updateLineHeight(line, height) {
var diff = height - line.height;
if (diff) for (var n = line; n; n = n.parent) n.height += diff;
}
// Given a line object, find its line number by walking up through
// its parent links.
function lineNo(line) {
if (line.parent == null) return null;
var cur = line.parent, no = indexOf(cur.lines, line);
for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
for (var i = 0;; ++i) {
if (chunk.children[i] == cur) break;
no += chunk.children[i].chunkSize();
}
}
return no + cur.first;
}
// Find the line at the given vertical position, using the height
// information in the document tree.
function lineAtHeight(chunk, h) {
var n = chunk.first;
outer: do {
for (var i = 0; i < chunk.children.length; ++i) {
var child = chunk.children[i], ch = child.height;
if (h < ch) { chunk = child; continue outer; }
h -= ch;
n += child.chunkSize();
}
return n;
} while (!chunk.lines);
for (var i = 0; i < chunk.lines.length; ++i) {
var line = chunk.lines[i], lh = line.height;
if (h < lh) break;
h -= lh;
}
return n + i;
}
// Find the height above the given line.
function heightAtLine(lineObj) {
lineObj = visualLine(lineObj);
var h = 0, chunk = lineObj.parent;
for (var i = 0; i < chunk.lines.length; ++i) {
var line = chunk.lines[i];
if (line == lineObj) break;
else h += line.height;
}
for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
for (var i = 0; i < p.children.length; ++i) {
var cur = p.children[i];
if (cur == chunk) break;
else h += cur.height;
}
}
return h;
}
// Get the bidi ordering for the given line (and cache it). Returns
// false for lines that are fully left-to-right, and an array of
// BidiSpan objects otherwise.
function getOrder(line) {
var order = line.order;
if (order == null) order = line.order = bidiOrdering(line.text);
return order;
}
// HISTORY
function History(startGen) {
// Arrays of change events and selections. Doing something adds an
// event to done and clears undo. Undoing moves events from done
// to undone, redoing moves them in the other direction.
this.done = []; this.undone = [];
this.undoDepth = Infinity;
// Used to track when changes can be merged into a single undo
// event
this.lastModTime = this.lastSelTime = 0;
this.lastOp = this.lastSelOp = null;
this.lastOrigin = this.lastSelOrigin = null;
// Used by the isClean() method
this.generation = this.maxGeneration = startGen || 1;
}
// Create a history change event from an updateDoc-style change
// object.
function historyChangeFromChange(doc, change) {
var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
return histChange;
}
// Pop all selection events off the end of a history array. Stop at
// a change event.
function clearSelectionEvents(array) {
while (array.length) {
var last = lst(array);
if (last.ranges) array.pop();
else break;
}
}
// Find the top change event in the history. Pop off selection
// events that are in the way.
function lastChangeEvent(hist, force) {
if (force) {
clearSelectionEvents(hist.done);
return lst(hist.done);
} else if (hist.done.length && !lst(hist.done).ranges) {
return lst(hist.done);
} else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
hist.done.pop();
return lst(hist.done);
}
}
// Register a change in the history. Merges changes that are within
// a single operation, ore are close together with an origin that
// allows merging (starting with "+") into a single event.
function addChangeToHistory(doc, change, selAfter, opId) {
var hist = doc.history;
hist.undone.length = 0;
var time = +new Date, cur;
if ((hist.lastOp == opId ||
hist.lastOrigin == change.origin && change.origin &&
((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
change.origin.charAt(0) == "*")) &&
(cur = lastChangeEvent(hist, hist.lastOp == opId))) {
// Merge this change into the last event
var last = lst(cur.changes);
if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
// Optimized case for simple insertion -- don't want to add
// new changesets for every character typed
last.to = changeEnd(change);
} else {
// Add new sub-event
cur.changes.push(historyChangeFromChange(doc, change));
}
} else {
// Can not be merged, start a new event.
var before = lst(hist.done);
if (!before || !before.ranges)
pushSelectionToHistory(doc.sel, hist.done);
cur = {changes: [historyChangeFromChange(doc, change)],
generation: hist.generation};
hist.done.push(cur);
while (hist.done.length > hist.undoDepth) {
hist.done.shift();
if (!hist.done[0].ranges) hist.done.shift();
}
}
hist.done.push(selAfter);
hist.generation = ++hist.maxGeneration;
hist.lastModTime = hist.lastSelTime = time;
hist.lastOp = hist.lastSelOp = opId;
hist.lastOrigin = hist.lastSelOrigin = change.origin;
if (!last) signal(doc, "historyAdded");
}
function selectionEventCanBeMerged(doc, origin, prev, sel) {
var ch = origin.charAt(0);
return ch == "*" ||
ch == "+" &&
prev.ranges.length == sel.ranges.length &&
prev.somethingSelected() == sel.somethingSelected() &&
new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
}
// Called whenever the selection changes, sets the new selection as
// the pending selection in the history, and pushes the old pending
// selection into the 'done' array when it was significantly
// different (in number of selected ranges, emptiness, or time).
function addSelectionToHistory(doc, sel, opId, options) {
var hist = doc.history, origin = options && options.origin;
// A new event is started when the previous origin does not match
// the current, or the origins don't allow matching. Origins
// starting with * are always merged, those starting with + are
// merged when similar and close together in time.
if (opId == hist.lastSelOp ||
(origin && hist.lastSelOrigin == origin &&
(hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
hist.done[hist.done.length - 1] = sel;
else
pushSelectionToHistory(sel, hist.done);
hist.lastSelTime = +new Date;
hist.lastSelOrigin = origin;
hist.lastSelOp = opId;
if (options && options.clearRedo !== false)
clearSelectionEvents(hist.undone);
}
function pushSelectionToHistory(sel, dest) {
var top = lst(dest);
if (!(top && top.ranges && top.equals(sel)))
dest.push(sel);
}
// Used to store marked span information in the history.
function attachLocalSpans(doc, change, from, to) {
var existing = change["spans_" + doc.id], n = 0;
doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
if (line.markedSpans)
(existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
++n;
});
}
// When un/re-doing restores text containing marked spans, those
// that have been explicitly cleared should not be restored.
function removeClearedSpans(spans) {
if (!spans) return null;
for (var i = 0, out; i < spans.length; ++i) {
if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
else if (out) out.push(spans[i]);
}
return !out ? spans : out.length ? out : null;
}
// Retrieve and filter the old marked spans stored in a change event.
function getOldSpans(doc, change) {
var found = change["spans_" + doc.id];
if (!found) return null;
for (var i = 0, nw = []; i < change.text.length; ++i)
nw.push(removeClearedSpans(found[i]));
return nw;
}
// Used both to provide a JSON-safe object in .getHistory, and, when
// detaching a document, to split the history in two
function copyHistoryArray(events, newGroup, instantiateSel) {
for (var i = 0, copy = []; i < events.length; ++i) {
var event = events[i];
if (event.ranges) {
copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
continue;
}
var changes = event.changes, newChanges = [];
copy.push({changes: newChanges});
for (var j = 0; j < changes.length; ++j) {
var change = changes[j], m;
newChanges.push({from: change.from, to: change.to, text: change.text});
if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
if (indexOf(newGroup, Number(m[1])) > -1) {
lst(newChanges)[prop] = change[prop];
delete change[prop];
}
}
}
}
return copy;
}
// Rebasing/resetting history to deal with externally-sourced changes
function rebaseHistSelSingle(pos, from, to, diff) {
if (to < pos.line) {
pos.line += diff;
} else if (from < pos.line) {
pos.line = from;
pos.ch = 0;
}
}
// Tries to rebase an array of history events given a change in the
// document. If the change touches the same lines as the event, the
// event, and everything 'behind' it, is discarded. If the change is
// before the event, the event's positions are updated. Uses a
// copy-on-write scheme for the positions, to avoid having to
// reallocate them all on every rebase, but also avoid problems with
// shared position objects being unsafely updated.
function rebaseHistArray(array, from, to, diff) {
for (var i = 0; i < array.length; ++i) {
var sub = array[i], ok = true;
if (sub.ranges) {
if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
for (var j = 0; j < sub.ranges.length; j++) {
rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
}
continue;
}
for (var j = 0; j < sub.changes.length; ++j) {
var cur = sub.changes[j];
if (to < cur.from.line) {
cur.from = Pos(cur.from.line + diff, cur.from.ch);
cur.to = Pos(cur.to.line + diff, cur.to.ch);
} else if (from <= cur.to.line) {
ok = false;
break;
}
}
if (!ok) {
array.splice(0, i + 1);
i = 0;
}
}
}
function rebaseHist(hist, change) {
var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
rebaseHistArray(hist.done, from, to, diff);
rebaseHistArray(hist.undone, from, to, diff);
}
// EVENT UTILITIES
// Due to the fact that we still support jurassic IE versions, some
// compatibility wrappers are needed.
var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
if (e.preventDefault) e.preventDefault();
else e.returnValue = false;
};
var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
if (e.stopPropagation) e.stopPropagation();
else e.cancelBubble = true;
};
function e_defaultPrevented(e) {
return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
}
var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
function e_target(e) {return e.target || e.srcElement;}
function e_button(e) {
var b = e.which;
if (b == null) {
if (e.button & 1) b = 1;
else if (e.button & 2) b = 3;
else if (e.button & 4) b = 2;
}
if (mac && e.ctrlKey && b == 1) b = 3;
return b;
}
// EVENT HANDLING
// Lightweight event framework. on/off also work on DOM nodes,
// registering native DOM handlers.
var on = CodeMirror.on = function(emitter, type, f) {
if (emitter.addEventListener)
emitter.addEventListener(type, f, false);
else if (emitter.attachEvent)
emitter.attachEvent("on" + type, f);
else {
var map = emitter._handlers || (emitter._handlers = {});
var arr = map[type] || (map[type] = []);
arr.push(f);
}
};
var off = CodeMirror.off = function(emitter, type, f) {
if (emitter.removeEventListener)
emitter.removeEventListener(type, f, false);
else if (emitter.detachEvent)
emitter.detachEvent("on" + type, f);
else {
var arr = emitter._handlers && emitter._handlers[type];
if (!arr) return;
for (var i = 0; i < arr.length; ++i)
if (arr[i] == f) { arr.splice(i, 1); break; }
}
};
var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
var arr = emitter._handlers && emitter._handlers[type];
if (!arr) return;
var args = Array.prototype.slice.call(arguments, 2);
for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args);
};
var orphanDelayedCallbacks = null;
// Often, we want to signal events at a point where we are in the
// middle of some work, but don't want the handler to start calling
// other methods on the editor, which might be in an inconsistent
// state or simply not expect any other events to happen.
// signalLater looks whether there are any handlers, and schedules
// them to be executed when the last operation ends, or, if no
// operation is active, when a timeout fires.
function signalLater(emitter, type /*, values...*/) {
var arr = emitter._handlers && emitter._handlers[type];
if (!arr) return;
var args = Array.prototype.slice.call(arguments, 2), list;
if (operationGroup) {
list = operationGroup.delayedCallbacks;
} else if (orphanDelayedCallbacks) {
list = orphanDelayedCallbacks;
} else {
list = orphanDelayedCallbacks = [];
setTimeout(fireOrphanDelayed, 0);
}
function bnd(f) {return function(){f.apply(null, args);};};
for (var i = 0; i < arr.length; ++i)
list.push(bnd(arr[i]));
}
function fireOrphanDelayed() {
var delayed = orphanDelayedCallbacks;
orphanDelayedCallbacks = null;
for (var i = 0; i < delayed.length; ++i) delayed[i]();
}
// The DOM events that CodeMirror handles can be overridden by
// registering a (non-DOM) handler on the editor for the event name,
// and preventDefault-ing the event in that handler.
function signalDOMEvent(cm, e, override) {
if (typeof e == "string")
e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};
signal(cm, override || e.type, cm, e);
return e_defaultPrevented(e) || e.codemirrorIgnore;
}
function signalCursorActivity(cm) {
var arr = cm._handlers && cm._handlers.cursorActivity;
if (!arr) return;
var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
set.push(arr[i]);
}
function hasHandler(emitter, type) {
var arr = emitter._handlers && emitter._handlers[type];
return arr && arr.length > 0;
}
// Add on and off methods to a constructor's prototype, to make
// registering events on such objects more convenient.
function eventMixin(ctor) {
ctor.prototype.on = function(type, f) {on(this, type, f);};
ctor.prototype.off = function(type, f) {off(this, type, f);};
}
// MISC UTILITIES
// Number of pixels added to scroller and sizer to hide scrollbar
var scrollerGap = 30;
// Returned or thrown by various protocols to signal 'I'm not
// handling this'.
var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
// Reused option objects for setSelection & friends
var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
function Delayed() {this.id = null;}
Delayed.prototype.set = function(ms, f) {
clearTimeout(this.id);
this.id = setTimeout(f, ms);
};
// Counts the column offset in a string, taking tabs into account.
// Used mostly to find indentation.
var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
if (end == null) {
end = string.search(/[^\s\u00a0]/);
if (end == -1) end = string.length;
}
for (var i = startIndex || 0, n = startValue || 0;;) {
var nextTab = string.indexOf("\t", i);
if (nextTab < 0 || nextTab >= end)
return n + (end - i);
n += nextTab - i;
n += tabSize - (n % tabSize);
i = nextTab + 1;
}
};
// The inverse of countColumn -- find the offset that corresponds to
// a particular column.
var findColumn = CodeMirror.findColumn = function(string, goal, tabSize) {
for (var pos = 0, col = 0;;) {
var nextTab = string.indexOf("\t", pos);
if (nextTab == -1) nextTab = string.length;
var skipped = nextTab - pos;
if (nextTab == string.length || col + skipped >= goal)
return pos + Math.min(skipped, goal - col);
col += nextTab - pos;
col += tabSize - (col % tabSize);
pos = nextTab + 1;
if (col >= goal) return pos;
}
}
var spaceStrs = [""];
function spaceStr(n) {
while (spaceStrs.length <= n)
spaceStrs.push(lst(spaceStrs) + " ");
return spaceStrs[n];
}
function lst(arr) { return arr[arr.length-1]; }
var selectInput = function(node) { node.select(); };
if (ios) // Mobile Safari apparently has a bug where select() is broken.
selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
else if (ie) // Suppress mysterious IE10 errors
selectInput = function(node) { try { node.select(); } catch(_e) {} };
function indexOf(array, elt) {
for (var i = 0; i < array.length; ++i)
if (array[i] == elt) return i;
return -1;
}
function map(array, f) {
var out = [];
for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
return out;
}
function nothing() {}
function createObj(base, props) {
var inst;
if (Object.create) {
inst = Object.create(base);
} else {
nothing.prototype = base;
inst = new nothing();
}
if (props) copyObj(props, inst);
return inst;
};
function copyObj(obj, target, overwrite) {
if (!target) target = {};
for (var prop in obj)
if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
target[prop] = obj[prop];
return target;
}
function bind(f) {
var args = Array.prototype.slice.call(arguments, 1);
return function(){return f.apply(null, args);};
}
var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
return /\w/.test(ch) || ch > "\x80" &&
(ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
};
function isWordChar(ch, helper) {
if (!helper) return isWordCharBasic(ch);
if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
return helper.test(ch);
}
function isEmpty(obj) {
for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
return true;
}
// Extending unicode characters. A series of a non-extending char +
// any number of extending chars is treated as a single unit as far
// as editing and measuring is concerned. This is not fully correct,
// since some scripts/fonts/browsers also treat other configurations
// of code points as a group.
var extendingChars = /[\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]/;
function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
// DOM UTILITIES
function elt(tag, content, className, style) {
var e = document.createElement(tag);
if (className) e.className = className;
if (style) e.style.cssText = style;
if (typeof content == "string") e.appendChild(document.createTextNode(content));
else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
return e;
}
var range;
if (document.createRange) range = function(node, start, end, endNode) {
var r = document.createRange();
r.setEnd(endNode || node, end);
r.setStart(node, start);
return r;
};
else range = function(node, start, end) {
var r = document.body.createTextRange();
try { r.moveToElementText(node.parentNode); }
catch(e) { return r; }
r.collapse(true);
r.moveEnd("character", end);
r.moveStart("character", start);
return r;
};
function removeChildren(e) {
for (var count = e.childNodes.length; count > 0; --count)
e.removeChild(e.firstChild);
return e;
}
function removeChildrenAndAdd(parent, e) {
return removeChildren(parent).appendChild(e);
}
var contains = CodeMirror.contains = function(parent, child) {
if (child.nodeType == 3) // Android browser always returns false when child is a textnode
child = child.parentNode;
if (parent.contains)
return parent.contains(child);
do {
if (child.nodeType == 11) child = child.host;
if (child == parent) return true;
} while (child = child.parentNode);
};
function activeElt() {
var activeElement = document.activeElement;
while (activeElement && activeElement.root && activeElement.root.activeElement)
activeElement = activeElement.root.activeElement;
return activeElement;
}
// Older versions of IE throws unspecified error when touching
// document.activeElement in some cases (during loading, in iframe)
if (ie && ie_version < 11) activeElt = function() {
try { return document.activeElement; }
catch(e) { return document.body; }
};
function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
var rmClass = CodeMirror.rmClass = function(node, cls) {
var current = node.className;
var match = classTest(cls).exec(current);
if (match) {
var after = current.slice(match.index + match[0].length);
node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
}
};
var addClass = CodeMirror.addClass = function(node, cls) {
var current = node.className;
if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
};
function joinClasses(a, b) {
var as = a.split(" ");
for (var i = 0; i < as.length; i++)
if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
return b;
}
// WINDOW-WIDE EVENTS
// These must be handled carefully, because naively registering a
// handler for each editor will cause the editors to never be
// garbage collected.
function forEachCodeMirror(f) {
if (!document.body.getElementsByClassName) return;
var byClass = document.body.getElementsByClassName("CodeMirror");
for (var i = 0; i < byClass.length; i++) {
var cm = byClass[i].CodeMirror;
if (cm) f(cm);
}
}
var globalsRegistered = false;
function ensureGlobalHandlers() {
if (globalsRegistered) return;
registerGlobalHandlers();
globalsRegistered = true;
}
function registerGlobalHandlers() {
// When the window resizes, we need to refresh active editors.
var resizeTimer;
on(window, "resize", function() {
if (resizeTimer == null) resizeTimer = setTimeout(function() {
resizeTimer = null;
forEachCodeMirror(onResize);
}, 100);
});
// When the window loses focus, we want to show the editor as blurred
on(window, "blur", function() {
forEachCodeMirror(onBlur);
});
}
// FEATURE DETECTION
// Detect drag-and-drop
var dragAndDrop = function() {
// There is *some* kind of drag-and-drop support in IE6-8, but I
// couldn't get it to work yet.
if (ie && ie_version < 9) return false;
var div = elt('div');
return "draggable" in div || "dragDrop" in div;
}();
var zwspSupported;
function zeroWidthElement(measure) {
if (zwspSupported == null) {
var test = elt("span", "\u200b");
removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
if (measure.firstChild.offsetHeight != 0)
zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
}
var node = zwspSupported ? elt("span", "\u200b") :
elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
node.setAttribute("cm-text", "");
return node;
}
// Feature-detect IE's crummy client rect reporting for bidi text
var badBidiRects;
function hasBadBidiRects(measure) {
if (badBidiRects != null) return badBidiRects;
var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
var r0 = range(txt, 0, 1).getBoundingClientRect();
if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
var r1 = range(txt, 1, 2).getBoundingClientRect();
return badBidiRects = (r1.right - r0.right < 3);
}
// See if "".split is the broken IE version, if so, provide an
// alternative way to split lines.
var splitLinesAuto = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
var pos = 0, result = [], l = string.length;
while (pos <= l) {
var nl = string.indexOf("\n", pos);
if (nl == -1) nl = string.length;
var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
var rt = line.indexOf("\r");
if (rt != -1) {
result.push(line.slice(0, rt));
pos += rt + 1;
} else {
result.push(line);
pos = nl + 1;
}
}
return result;
} : function(string){return string.split(/\r\n?|\n/);};
var hasSelection = window.getSelection ? function(te) {
try { return te.selectionStart != te.selectionEnd; }
catch(e) { return false; }
} : function(te) {
try {var range = te.ownerDocument.selection.createRange();}
catch(e) {}
if (!range || range.parentElement() != te) return false;
return range.compareEndPoints("StartToEnd", range) != 0;
};
var hasCopyEvent = (function() {
var e = elt("div");
if ("oncopy" in e) return true;
e.setAttribute("oncopy", "return;");
return typeof e.oncopy == "function";
})();
var badZoomedRects = null;
function hasBadZoomedRects(measure) {
if (badZoomedRects != null) return badZoomedRects;
var node = removeChildrenAndAdd(measure, elt("span", "x"));
var normal = node.getBoundingClientRect();
var fromRange = range(node, 0, 1).getBoundingClientRect();
return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
}
// KEY NAMES
var keyNames = CodeMirror.keyNames = {
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",
106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 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"
};
(function() {
// Number keys
for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
// Alphabetic keys
for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
// Function keys
for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
})();
// BIDI HELPERS
function iterateBidiSections(order, from, to, f) {
if (!order) return f(from, to, "ltr");
var found = false;
for (var i = 0; i < order.length; ++i) {
var part = order[i];
if (part.from < to && part.to > from || from == to && part.to == from) {
f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
found = true;
}
}
if (!found) f(from, to, "ltr");
}
function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
function lineRight(line) {
var order = getOrder(line);
if (!order) return line.text.length;
return bidiRight(lst(order));
}
function lineStart(cm, lineN) {
var line = getLine(cm.doc, lineN);
var visual = visualLine(line);
if (visual != line) lineN = lineNo(visual);
var order = getOrder(visual);
var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
return Pos(lineN, ch);
}
function lineEnd(cm, lineN) {
var merged, line = getLine(cm.doc, lineN);
while (merged = collapsedSpanAtEnd(line)) {
line = merged.find(1, true).line;
lineN = null;
}
var order = getOrder(line);
var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
return Pos(lineN == null ? lineNo(line) : lineN, ch);
}
function lineStartSmart(cm, pos) {
var start = lineStart(cm, pos.line);
var line = getLine(cm.doc, start.line);
var order = getOrder(line);
if (!order || order[0].level == 0) {
var firstNonWS = Math.max(0, line.text.search(/\S/));
var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
return Pos(start.line, inWS ? 0 : firstNonWS);
}
return start;
}
function compareBidiLevel(order, a, b) {
var linedir = order[0].level;
if (a == linedir) return true;
if (b == linedir) return false;
return a < b;
}
var bidiOther;
function getBidiPartAt(order, pos) {
bidiOther = null;
for (var i = 0, found; i < order.length; ++i) {
var cur = order[i];
if (cur.from < pos && cur.to > pos) return i;
if ((cur.from == pos || cur.to == pos)) {
if (found == null) {
found = i;
} else if (compareBidiLevel(order, cur.level, order[found].level)) {
if (cur.from != cur.to) bidiOther = found;
return i;
} else {
if (cur.from != cur.to) bidiOther = i;
return found;
}
}
}
return found;
}
function moveInLine(line, pos, dir, byUnit) {
if (!byUnit) return pos + dir;
do pos += dir;
while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
return pos;
}
// This is needed in order to move 'visually' through bi-directional
// text -- i.e., pressing left should make the cursor go left, even
// when in RTL text. The tricky part is the 'jumps', where RTL and
// LTR text touch each other. This often requires the cursor offset
// to move more than one unit, in order to visually move one unit.
function moveVisually(line, start, dir, byUnit) {
var bidi = getOrder(line);
if (!bidi) return moveLogically(line, start, dir, byUnit);
var pos = getBidiPartAt(bidi, start), part = bidi[pos];
var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
for (;;) {
if (target > part.from && target < part.to) return target;
if (target == part.from || target == part.to) {
if (getBidiPartAt(bidi, target) == pos) return target;
part = bidi[pos += dir];
return (dir > 0) == part.level % 2 ? part.to : part.from;
} else {
part = bidi[pos += dir];
if (!part) return null;
if ((dir > 0) == part.level % 2)
target = moveInLine(line, part.to, -1, byUnit);
else
target = moveInLine(line, part.from, 1, byUnit);
}
}
}
function moveLogically(line, start, dir, byUnit) {
var target = start + dir;
if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
return target < 0 || target > line.text.length ? null : target;
}
// Bidirectional ordering algorithm
// See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
// that this (partially) implements.
// One-char codes used for character types:
// L (L): Left-to-Right
// R (R): Right-to-Left
// r (AL): Right-to-Left Arabic
// 1 (EN): European Number
// + (ES): European Number Separator
// % (ET): European Number Terminator
// n (AN): Arabic Number
// , (CS): Common Number Separator
// m (NSM): Non-Spacing Mark
// b (BN): Boundary Neutral
// s (B): Paragraph Separator
// t (S): Segment Separator
// w (WS): Whitespace
// N (ON): Other Neutrals
// Returns null if characters are ordered as they appear
// (left-to-right), or an array of sections ({from, to, level}
// objects) in the order in which they occur visually.
var bidiOrdering = (function() {
// Character types for codepoints 0 to 0xff
var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
// Character types for codepoints 0x600 to 0x6ff
var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
function charType(code) {
if (code <= 0xf7) return lowTypes.charAt(code);
else if (0x590 <= code && code <= 0x5f4) return "R";
else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
else if (0x6ee <= code && code <= 0x8ac) return "r";
else if (0x2000 <= code && code <= 0x200b) return "w";
else if (code == 0x200c) return "b";
else return "L";
}
var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
// Browsers seem to always treat the boundaries of block elements as being L.
var outerType = "L";
function BidiSpan(level, from, to) {
this.level = level;
this.from = from; this.to = to;
}
return function(str) {
if (!bidiRE.test(str)) return false;
var len = str.length, types = [];
for (var i = 0, type; i < len; ++i)
types.push(type = charType(str.charCodeAt(i)));
// W1. Examine each non-spacing mark (NSM) in the level run, and
// change the type of the NSM to the type of the previous
// character. If the NSM is at the start of the level run, it will
// get the type of sor.
for (var i = 0, prev = outerType; i < len; ++i) {
var type = types[i];
if (type == "m") types[i] = prev;
else prev = type;
}
// W2. Search backwards from each instance of a European number
// until the first strong type (R, L, AL, or sor) is found. If an
// AL is found, change the type of the European number to Arabic
// number.
// W3. Change all ALs to R.
for (var i = 0, cur = outerType; i < len; ++i) {
var type = types[i];
if (type == "1" && cur == "r") types[i] = "n";
else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
}
// W4. A single European separator between two European numbers
// changes to a European number. A single common separator between
// two numbers of the same type changes to that type.
for (var i = 1, prev = types[0]; i < len - 1; ++i) {
var type = types[i];
if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
else if (type == "," && prev == types[i+1] &&
(prev == "1" || prev == "n")) types[i] = prev;
prev = type;
}
// W5. A sequence of European terminators adjacent to European
// numbers changes to all European numbers.
// W6. Otherwise, separators and terminators change to Other
// Neutral.
for (var i = 0; i < len; ++i) {
var type = types[i];
if (type == ",") types[i] = "N";
else if (type == "%") {
for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
for (var j = i; j < end; ++j) types[j] = replace;
i = end - 1;
}
}
// W7. Search backwards from each instance of a European number
// until the first strong type (R, L, or sor) is found. If an L is
// found, then change the type of the European number to L.
for (var i = 0, cur = outerType; i < len; ++i) {
var type = types[i];
if (cur == "L" && type == "1") types[i] = "L";
else if (isStrong.test(type)) cur = type;
}
// N1. A sequence of neutrals takes the direction of the
// surrounding strong text if the text on both sides has the same
// direction. European and Arabic numbers act as if they were R in
// terms of their influence on neutrals. Start-of-level-run (sor)
// and end-of-level-run (eor) are used at level run boundaries.
// N2. Any remaining neutrals take the embedding direction.
for (var i = 0; i < len; ++i) {
if (isNeutral.test(types[i])) {
for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
var before = (i ? types[i-1] : outerType) == "L";
var after = (end < len ? types[end] : outerType) == "L";
var replace = before || after ? "L" : "R";
for (var j = i; j < end; ++j) types[j] = replace;
i = end - 1;
}
}
// Here we depart from the documented algorithm, in order to avoid
// building up an actual levels array. Since there are only three
// levels (0, 1, 2) in an implementation that doesn't take
// explicit embedding into account, we can build up the order on
// the fly, without following the level-based algorithm.
var order = [], m;
for (var i = 0; i < len;) {
if (countsAsLeft.test(types[i])) {
var start = i;
for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
order.push(new BidiSpan(0, start, i));
} else {
var pos = i, at = order.length;
for (++i; i < len && types[i] != "L"; ++i) {}
for (var j = pos; j < i;) {
if (countsAsNum.test(types[j])) {
if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
var nstart = j;
for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
order.splice(at, 0, new BidiSpan(2, nstart, j));
pos = j;
} else ++j;
}
if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
}
}
if (order[0].level == 1 && (m = str.match(/^\s+/))) {
order[0].from = m[0].length;
order.unshift(new BidiSpan(0, 0, m[0].length));
}
if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
lst(order).to -= m[0].length;
order.push(new BidiSpan(0, len - m[0].length, len));
}
if (order[0].level == 2)
order.unshift(new BidiSpan(1, order[0].to, order[0].to));
if (order[0].level != lst(order).level)
order.push(new BidiSpan(order[0].level, len, len));
return order;
};
})();
// THE END
CodeMirror.version = "5.7.0";
return CodeMirror;
});
},{}],26:[function(require,module,exports){
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
// TODO actually recognize syntax of TypeScript constructs
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
CodeMirror.defineMode("javascript", function(config, parserConfig) {
var indentUnit = config.indentUnit;
var statementIndent = parserConfig.statementIndent;
var jsonldMode = parserConfig.jsonld;
var jsonMode = parserConfig.json || jsonldMode;
var isTS = parserConfig.typescript;
var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;
// Tokenizer
var keywords = function(){
function kw(type) {return {type: type, style: "keyword"};}
var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
var operator = kw("operator"), atom = {type: "atom", style: "atom"};
var jsKeywords = {
"if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
"return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C, "debugger": C,
"var": kw("var"), "const": kw("var"), "let": kw("var"),
"async": kw("async"), "function": kw("function"), "catch": kw("catch"),
"for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
"in": operator, "typeof": operator, "instanceof": operator,
"true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
"this": kw("this"), "class": kw("class"), "super": kw("atom"),
"await": C, "yield": C, "export": kw("export"), "import": kw("import"), "extends": C
};
// Extend the 'normal' keywords with the TypeScript language extensions
if (isTS) {
var type = {type: "variable", style: "variable-3"};
var tsKeywords = {
// object-like things
"interface": kw("interface"),
"extends": kw("extends"),
"constructor": kw("constructor"),
// scope modifiers
"public": kw("public"),
"private": kw("private"),
"protected": kw("protected"),
"static": kw("static"),
// types
"string": type, "number": type, "bool": type, "any": type
};
for (var attr in tsKeywords) {
jsKeywords[attr] = tsKeywords[attr];
}
}
return jsKeywords;
}();
var isOperatorChar = /[+\-*&%=<>!?|~^]/;
var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;
function readRegexp(stream) {
var escaped = false, next, inSet = false;
while ((next = stream.next()) != null) {
if (!escaped) {
if (next == "/" && !inSet) return;
if (next == "[") inSet = true;
else if (inSet && next == "]") inSet = false;
}
escaped = !escaped && next == "\\";
}
}
// Used as scratch variables to communicate multiple values without
// consing up tons of objects.
var type, content;
function ret(tp, style, cont) {
type = tp; content = cont;
return style;
}
function tokenBase(stream, state) {
var ch = stream.next();
if (ch == '"' || ch == "'") {
state.tokenize = tokenString(ch);
return state.tokenize(stream, state);
} else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) {
return ret("number", "number");
} else if (ch == "." && stream.match("..")) {
return ret("spread", "meta");
} else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
return ret(ch);
} else if (ch == "=" && stream.eat(">")) {
return ret("=>", "operator");
} else if (ch == "0" && stream.eat(/x/i)) {
stream.eatWhile(/[\da-f]/i);
return ret("number", "number");
} else if (ch == "0" && stream.eat(/o/i)) {
stream.eatWhile(/[0-7]/i);
return ret("number", "number");
} else if (ch == "0" && stream.eat(/b/i)) {
stream.eatWhile(/[01]/i);
return ret("number", "number");
} else if (/\d/.test(ch)) {
stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
return ret("number", "number");
} else if (ch == "/") {
if (stream.eat("*")) {
state.tokenize = tokenComment;
return tokenComment(stream, state);
} else if (stream.eat("/")) {
stream.skipToEnd();
return ret("comment", "comment");
} else if (state.lastType == "operator" || state.lastType == "keyword c" ||
state.lastType == "sof" || /^[\[{}\(,;:]$/.test(state.lastType)) {
readRegexp(stream);
stream.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/);
return ret("regexp", "string-2");
} else {
stream.eatWhile(isOperatorChar);
return ret("operator", "operator", stream.current());
}
} else if (ch == "`") {
state.tokenize = tokenQuasi;
return tokenQuasi(stream, state);
} else if (ch == "#") {
stream.skipToEnd();
return ret("error", "error");
} else if (isOperatorChar.test(ch)) {
stream.eatWhile(isOperatorChar);
return ret("operator", "operator", stream.current());
} else if (wordRE.test(ch)) {
stream.eatWhile(wordRE);
var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
return (known && state.lastType != ".") ? ret(known.type, known.style, word) :
ret("variable", "variable", word);
}
}
function tokenString(quote) {
return function(stream, state) {
var escaped = false, next;
if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
state.tokenize = tokenBase;
return ret("jsonld-keyword", "meta");
}
while ((next = stream.next()) != null) {
if (next == quote && !escaped) break;
escaped = !escaped && next == "\\";
}
if (!escaped) state.tokenize = tokenBase;
return ret("string", "string");
};
}
function tokenComment(stream, state) {
var maybeEnd = false, ch;
while (ch = stream.next()) {
if (ch == "/" && maybeEnd) {
state.tokenize = tokenBase;
break;
}
maybeEnd = (ch == "*");
}
return ret("comment", "comment");
}
function tokenQuasi(stream, state) {
var escaped = false, next;
while ((next = stream.next()) != null) {
if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
state.tokenize = tokenBase;
break;
}
escaped = !escaped && next == "\\";
}
return ret("quasi", "string-2", stream.current());
}
var brackets = "([{}])";
// This is a crude lookahead trick to try and notice that we're
// parsing the argument patterns for a fat-arrow function before we
// actually hit the arrow token. It only works if the arrow is on
// the same line as the arguments and there's no strange noise
// (comments) in between. Fallback is to only notice when we hit the
// arrow, and not declare the arguments as locals for the arrow
// body.
function findFatArrow(stream, state) {
if (state.fatArrowAt) state.fatArrowAt = null;
var arrow = stream.string.indexOf("=>", stream.start);
if (arrow < 0) return;
var depth = 0, sawSomething = false;
for (var pos = arrow - 1; pos >= 0; --pos) {
var ch = stream.string.charAt(pos);
var bracket = brackets.indexOf(ch);
if (bracket >= 0 && bracket < 3) {
if (!depth) { ++pos; break; }
if (--depth == 0) break;
} else if (bracket >= 3 && bracket < 6) {
++depth;
} else if (wordRE.test(ch)) {
sawSomething = true;
} else if (/["'\/]/.test(ch)) {
return;
} else if (sawSomething && !depth) {
++pos;
break;
}
}
if (sawSomething && !depth) state.fatArrowAt = pos;
}
// Parser
var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true};
function JSLexical(indented, column, type, align, prev, info) {
this.indented = indented;
this.column = column;
this.type = type;
this.prev = prev;
this.info = info;
if (align != null) this.align = align;
}
function inScope(state, varname) {
for (var v = state.localVars; v; v = v.next)
if (v.name == varname) return true;
for (var cx = state.context; cx; cx = cx.prev) {
for (var v = cx.vars; v; v = v.next)
if (v.name == varname) return true;
}
}
function parseJS(state, style, type, content, stream) {
var cc = state.cc;
// Communicate our context to the combinators.
// (Less wasteful than consing up a hundred closures on every call.)
cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;
if (!state.lexical.hasOwnProperty("align"))
state.lexical.align = true;
while(true) {
var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
if (combinator(type, content)) {
while(cc.length && cc[cc.length - 1].lex)
cc.pop()();
if (cx.marked) return cx.marked;
if (type == "variable" && inScope(state, content)) return "variable-2";
return style;
}
}
}
// Combinator utils
var cx = {state: null, column: null, marked: null, cc: null};
function pass() {
for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
}
function cont() {
pass.apply(null, arguments);
return true;
}
function register(varname) {
function inList(list) {
for (var v = list; v; v = v.next)
if (v.name == varname) return true;
return false;
}
var state = cx.state;
if (state.context) {
cx.marked = "def";
if (inList(state.localVars)) return;
state.localVars = {name: varname, next: state.localVars};
} else {
if (inList(state.globalVars)) return;
if (parserConfig.globalVars)
state.globalVars = {name: varname, next: state.globalVars};
}
}
// Combinators
var defaultVars = {name: "this", next: {name: "arguments"}};
function pushcontext() {
cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
cx.state.localVars = defaultVars;
}
function popcontext() {
cx.state.localVars = cx.state.context.vars;
cx.state.context = cx.state.context.prev;
}
function pushlex(type, info) {
var result = function() {
var state = cx.state, indent = state.indented;
if (state.lexical.type == "stat") indent = state.lexical.indented;
else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev)
indent = outer.indented;
state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
};
result.lex = true;
return result;
}
function poplex() {
var state = cx.state;
if (state.lexical.prev) {
if (state.lexical.type == ")")
state.indented = state.lexical.indented;
state.lexical = state.lexical.prev;
}
}
poplex.lex = true;
function expect(wanted) {
function exp(type) {
if (type == wanted) return cont();
else if (wanted == ";") return pass();
else return cont(exp);
};
return exp;
}
function statement(type, value) {
if (type == "var") return cont(pushlex("vardef", value.length), vardef, expect(";"), poplex);
if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
if (type == "{") return cont(pushlex("}"), block, poplex);
if (type == ";") return cont();
if (type == "if") {
if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
cx.state.cc.pop()();
return cont(pushlex("form"), expression, statement, poplex, maybeelse);
}
if (type == "function") return cont(functiondef);
if (type == "for") return cont(pushlex("form"), forspec, statement, poplex);
if (type == "variable") return cont(pushlex("stat"), maybelabel);
if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
block, poplex, poplex);
if (type == "case") return cont(expression, expect(":"));
if (type == "default") return cont(expect(":"));
if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
statement, poplex, popcontext);
if (type == "class") return cont(pushlex("form"), className, poplex);
if (type == "export") return cont(pushlex("stat"), afterExport, poplex);
if (type == "import") return cont(pushlex("stat"), afterImport, poplex);
return pass(pushlex("stat"), expression, expect(";"), poplex);
}
function expression(type) {
return expressionInner(type, false);
}
function expressionNoComma(type) {
return expressionInner(type, true);
}
function expressionInner(type, noComma) {
if (cx.state.fatArrowAt == cx.stream.start) {
var body = noComma ? arrowBodyNoComma : arrowBody;
if (type == "(") return cont(pushcontext, pushlex(")"), commasep(pattern, ")"), poplex, expect("=>"), body, popcontext);
else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
}
var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
if (type == "async") return cont(expression);
if (type == "function") return cont(functiondef, maybeop);
if (type == "keyword c") return cont(noComma ? maybeexpressionNoComma : maybeexpression);
if (type == "(") return cont(pushlex(")"), maybeexpression, comprehension, expect(")"), poplex, maybeop);
if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
if (type == "{") return contCommasep(objprop, "}", null, maybeop);
if (type == "quasi") { return pass(quasi, maybeop); }
return cont();
}
function maybeexpression(type) {
if (type.match(/[;\}\)\],]/)) return pass();
return pass(expression);
}
function maybeexpressionNoComma(type) {
if (type.match(/[;\}\)\],]/)) return pass();
return pass(expressionNoComma);
}
function maybeoperatorComma(type, value) {
if (type == ",") return cont(expression);
return maybeoperatorNoComma(type, value, false);
}
function maybeoperatorNoComma(type, value, noComma) {
var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
var expr = noComma == false ? expression : expressionNoComma;
if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
if (type == "operator") {
if (/\+\+|--/.test(value)) return cont(me);
if (value == "?") return cont(expression, expect(":"), expr);
return cont(expr);
}
if (type == "quasi") { return pass(quasi, me); }
if (type == ";") return;
if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
if (type == ".") return cont(property, me);
if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
}
function quasi(type, value) {
if (type != "quasi") return pass();
if (value.slice(value.length - 2) != "${") return cont(quasi);
return cont(expression, continueQuasi);
}
function continueQuasi(type) {
if (type == "}") {
cx.marked = "string-2";
cx.state.tokenize = tokenQuasi;
return cont(quasi);
}
}
function arrowBody(type) {
findFatArrow(cx.stream, cx.state);
return pass(type == "{" ? statement : expression);
}
function arrowBodyNoComma(type) {
findFatArrow(cx.stream, cx.state);
return pass(type == "{" ? statement : expressionNoComma);
}
function maybelabel(type) {
if (type == ":") return cont(poplex, statement);
return pass(maybeoperatorComma, expect(";"), poplex);
}
function property(type) {
if (type == "variable") {cx.marked = "property"; return cont();}
}
function objprop(type, value) {
if (type == "async") {
return cont(objprop);
} else if (type == "variable" || cx.style == "keyword") {
cx.marked = "property";
if (value == "get" || value == "set") return cont(getterSetter);
return cont(afterprop);
} else if (type == "number" || type == "string") {
cx.marked = jsonldMode ? "property" : (cx.style + " property");
return cont(afterprop);
} else if (type == "jsonld-keyword") {
return cont(afterprop);
} else if (type == "[") {
return cont(expression, expect("]"), afterprop);
}
}
function getterSetter(type) {
if (type != "variable") return pass(afterprop);
cx.marked = "property";
return cont(functiondef);
}
function afterprop(type) {
if (type == ":") return cont(expressionNoComma);
if (type == "(") return pass(functiondef);
}
function commasep(what, end) {
function proceed(type) {
if (type == ",") {
var lex = cx.state.lexical;
if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
return cont(what, proceed);
}
if (type == end) return cont();
return cont(expect(end));
}
return function(type) {
if (type == end) return cont();
return pass(what, proceed);
};
}
function contCommasep(what, end, info) {
for (var i = 3; i < arguments.length; i++)
cx.cc.push(arguments[i]);
return cont(pushlex(end, info), commasep(what, end), poplex);
}
function block(type) {
if (type == "}") return cont();
return pass(statement, block);
}
function maybetype(type) {
if (isTS && type == ":") return cont(typedef);
}
function maybedefault(_, value) {
if (value == "=") return cont(expressionNoComma);
}
function typedef(type) {
if (type == "variable") {cx.marked = "variable-3"; return cont();}
}
function vardef() {
return pass(pattern, maybetype, maybeAssign, vardefCont);
}
function pattern(type, value) {
if (type == "variable") { register(value); return cont(); }
if (type == "[") return contCommasep(pattern, "]");
if (type == "{") return contCommasep(proppattern, "}");
}
function proppattern(type, value) {
if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
register(value);
return cont(maybeAssign);
}
if (type == "variable") cx.marked = "property";
return cont(expect(":"), pattern, maybeAssign);
}
function maybeAssign(_type, value) {
if (value == "=") return cont(expressionNoComma);
}
function vardefCont(type) {
if (type == ",") return cont(vardef);
}
function maybeelse(type, value) {
if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
}
function forspec(type) {
if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex);
}
function forspec1(type) {
if (type == "var") return cont(vardef, expect(";"), forspec2);
if (type == ";") return cont(forspec2);
if (type == "variable") return cont(formaybeinof);
return pass(expression, expect(";"), forspec2);
}
function formaybeinof(_type, value) {
if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
return cont(maybeoperatorComma, forspec2);
}
function forspec2(type, value) {
if (type == ";") return cont(forspec3);
if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
return pass(expression, expect(";"), forspec3);
}
function forspec3(type) {
if (type != ")") cont(expression);
}
function functiondef(type, value) {
if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
if (type == "variable") {register(value); return cont(functiondef);}
if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, statement, popcontext);
}
function funarg(type) {
if (type == "spread") return cont(funarg);
return pass(pattern, maybetype, maybedefault);
}
function className(type, value) {
if (type == "variable") {register(value); return cont(classNameAfter);}
}
function classNameAfter(type, value) {
if (value == "extends") return cont(expression, classNameAfter);
if (type == "{") return cont(pushlex("}"), classBody, poplex);
}
function classBody(type, value) {
if (type == "variable" || cx.style == "keyword") {
if (value == "static") {
cx.marked = "keyword";
return cont(classBody);
}
cx.marked = "property";
if (value == "get" || value == "set") return cont(classGetterSetter, functiondef, classBody);
return cont(functiondef, classBody);
}
if (value == "*") {
cx.marked = "keyword";
return cont(classBody);
}
if (type == ";") return cont(classBody);
if (type == "}") return cont();
}
function classGetterSetter(type) {
if (type != "variable") return pass();
cx.marked = "property";
return cont();
}
function afterExport(_type, value) {
if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
return pass(statement);
}
function afterImport(type) {
if (type == "string") return cont();
return pass(importSpec, maybeFrom);
}
function importSpec(type, value) {
if (type == "{") return contCommasep(importSpec, "}");
if (type == "variable") register(value);
if (value == "*") cx.marked = "keyword";
return cont(maybeAs);
}
function maybeAs(_type, value) {
if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
}
function maybeFrom(_type, value) {
if (value == "from") { cx.marked = "keyword"; return cont(expression); }
}
function arrayLiteral(type) {
if (type == "]") return cont();
return pass(expressionNoComma, maybeArrayComprehension);
}
function maybeArrayComprehension(type) {
if (type == "for") return pass(comprehension, expect("]"));
if (type == ",") return cont(commasep(maybeexpressionNoComma, "]"));
return pass(commasep(expressionNoComma, "]"));
}
function comprehension(type) {
if (type == "for") return cont(forspec, comprehension);
if (type == "if") return cont(expression, comprehension);
}
function isContinuedStatement(state, textAfter) {
return state.lastType == "operator" || state.lastType == "," ||
isOperatorChar.test(textAfter.charAt(0)) ||
/[,.]/.test(textAfter.charAt(0));
}
// Interface
return {
startState: function(basecolumn) {
var state = {
tokenize: tokenBase,
lastType: "sof",
cc: [],
lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
localVars: parserConfig.localVars,
context: parserConfig.localVars && {vars: parserConfig.localVars},
indented: 0
};
if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
state.globalVars = parserConfig.globalVars;
return state;
},
token: function(stream, state) {
if (stream.sol()) {
if (!state.lexical.hasOwnProperty("align"))
state.lexical.align = false;
state.indented = stream.indentation();
findFatArrow(stream, state);
}
if (state.tokenize != tokenComment && stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
if (type == "comment") return style;
state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
return parseJS(state, style, type, content, stream);
},
indent: function(state, textAfter) {
if (state.tokenize == tokenComment) return CodeMirror.Pass;
if (state.tokenize != tokenBase) return 0;
var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;
// Kludge to prevent 'maybelse' from blocking lexical scope pops
if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
var c = state.cc[i];
if (c == poplex) lexical = lexical.prev;
else if (c != maybeelse) break;
}
if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev;
if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
lexical = lexical.prev;
var type = lexical.type, closing = firstChar == type;
if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info + 1 : 0);
else if (type == "form" && firstChar == "{") return lexical.indented;
else if (type == "form") return lexical.indented + indentUnit;
else if (type == "stat")
return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
else if (lexical.align) return lexical.column + (closing ? 0 : 1);
else return lexical.indented + (closing ? 0 : indentUnit);
},
electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
blockCommentStart: jsonMode ? null : "/*",
blockCommentEnd: jsonMode ? null : "*/",
lineComment: jsonMode ? null : "//",
fold: "brace",
closeBrackets: "()[]{}''\"\"``",
helperType: jsonMode ? "json" : "javascript",
jsonldMode: jsonldMode,
jsonMode: jsonMode
};
});
CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);
CodeMirror.defineMIME("text/javascript", "javascript");
CodeMirror.defineMIME("text/ecmascript", "javascript");
CodeMirror.defineMIME("application/javascript", "javascript");
CodeMirror.defineMIME("application/x-javascript", "javascript");
CodeMirror.defineMIME("application/ecmascript", "javascript");
CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true});
CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
});
},{"../../lib/codemirror":25}],27:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _get = require('babel-runtime/helpers/get')['default'];
var _inherits = require('babel-runtime/helpers/inherits')['default'];
var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
var _language = require('../language');
var GraphQLError = (function (_Error) {
_inherits(GraphQLError, _Error);
function GraphQLError(message,
// A flow bug keeps us from declaring nodes as an array of Node
nodes, /* Node */stack, source, positions) {
_classCallCheck(this, GraphQLError);
_get(Object.getPrototypeOf(GraphQLError.prototype), 'constructor', this).call(this, message);
this.message = message;
Object.defineProperty(this, 'stack', { value: stack || message });
Object.defineProperty(this, 'nodes', { value: nodes });
// Note: flow does not yet know about Object.defineProperty with `get`.
Object.defineProperty(this, 'source', {
get: function get() {
if (source) {
return source;
}
if (nodes && nodes.length > 0) {
var node = nodes[0];
return node && node.loc && node.loc.source;
}
}
});
Object.defineProperty(this, 'positions', {
get: function get() {
if (positions) {
return positions;
}
if (nodes) {
var nodePositions = nodes.map(function (node) {
return node.loc && node.loc.start;
});
if (nodePositions.some(function (p) {
return p;
})) {
return nodePositions;
}
}
}
});
Object.defineProperty(this, 'locations', {
get: function get() {
var _this = this;
if (this.positions && this.source) {
return this.positions.map(function (pos) {
return (0, _language.getLocation)(_this.source, pos);
});
}
}
});
}
return GraphQLError;
})(Error);
exports.GraphQLError = GraphQLError;
},{"../language":37,"babel-runtime/helpers/class-call-check":55,"babel-runtime/helpers/get":58,"babel-runtime/helpers/inherits":59}],28:[function(require,module,exports){
/**
* Copyright (c) 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.
*/
/**
* Given a GraphQLError, format it according to the rules described by the
* Response Format, Errors section of the GraphQL Specification.
*/
'use strict';
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.formatError = formatError;
var _jsutilsInvariant = require('../jsutils/invariant');
var _jsutilsInvariant2 = _interopRequireDefault(_jsutilsInvariant);
function formatError(error) {
(0, _jsutilsInvariant2['default'])(error, 'Received null or undefined error.');
return {
message: error.message,
locations: error.locations
};
}
},{"../jsutils/invariant":33,"babel-runtime/helpers/interop-require-default":60}],29:[function(require,module,exports){
/**
* Copyright (c) 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';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _GraphQLError = require('./GraphQLError');
Object.defineProperty(exports, 'GraphQLError', {
enumerable: true,
get: function get() {
return _GraphQLError.GraphQLError;
}
});
var _syntaxError = require('./syntaxError');
Object.defineProperty(exports, 'syntaxError', {
enumerable: true,
get: function get() {
return _syntaxError.syntaxError;
}
});
var _locatedError = require('./locatedError');
Object.defineProperty(exports, 'locatedError', {
enumerable: true,
get: function get() {
return _locatedError.locatedError;
}
});
var _formatError = require('./formatError');
Object.defineProperty(exports, 'formatError', {
enumerable: true,
get: function get() {
return _formatError.formatError;
}
});
},{"./GraphQLError":27,"./formatError":28,"./locatedError":30,"./syntaxError":31}],30:[function(require,module,exports){
/**
* Copyright (c) 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';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.locatedError = locatedError;
var _GraphQLError = require('./GraphQLError');
/**
* Given an arbitrary Error, presumably thrown while attempting to execute a
* GraphQL operation, produce a new GraphQLError aware of the location in the
* document responsible for the original Error.
*/
function locatedError(error, nodes) {
var message = error ? error.message || String(error) : 'An unknown error occurred.';
var stack = error ? error.stack : null;
return new _GraphQLError.GraphQLError(message, nodes, stack);
}
},{"./GraphQLError":27}],31:[function(require,module,exports){
/**
* Copyright (c) 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';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.syntaxError = syntaxError;
var _languageLocation = require('../language/location');
var _GraphQLError = require('./GraphQLError');
/**
* Produces a GraphQLError representing a syntax error, containing useful
* descriptive information about the syntax error's position in the source.
*/
function syntaxError(source, position, description) {
var location = (0, _languageLocation.getLocation)(source, position);
var error = new _GraphQLError.GraphQLError('Syntax Error ' + source.name + ' (' + location.line + ':' + location.column + ') ' + description + '\n\n' + highlightSourceAtLocation(source, location), undefined, undefined, source, [position]);
return error;
}
/**
* Render a helpful description of the location of the error in the GraphQL
* Source document.
*/
function highlightSourceAtLocation(source, location) {
var line = location.line;
var prevLineNum = (line - 1).toString();
var lineNum = line.toString();
var nextLineNum = (line + 1).toString();
var padLen = nextLineNum.length;
var lines = source.body.split(/\r\n|[\n\r\u2028\u2029]/g);
return (line >= 2 ? lpad(padLen, prevLineNum) + ': ' + lines[line - 2] + '\n' : '') + lpad(padLen, lineNum) + ': ' + lines[line - 1] + '\n' + Array(2 + padLen + location.column).join(' ') + '^\n' + (line < lines.length ? lpad(padLen, nextLineNum) + ': ' + lines[line] + '\n' : '');
}
function lpad(len, str) {
return Array(len - str.length + 1).join(' ') + str;
}
},{"../language/location":40,"./GraphQLError":27}],32:[function(require,module,exports){
/**
* Copyright (c) 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";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = find;
function find(list, predicate) {
for (var i = 0; i < list.length; i++) {
if (predicate(list[i])) {
return list[i];
}
}
}
module.exports = exports["default"];
},{}],33:[function(require,module,exports){
/**
* Copyright (c) 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";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = invariant;
function invariant(condition, message) {
if (!condition) {
throw new Error(message);
}
}
module.exports = exports["default"];
},{}],34:[function(require,module,exports){
/**
* Copyright (c) 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.
*/
/**
* Returns true if a value is null, undefined, or NaN.
*/
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = isNullish;
function isNullish(value) {
return value === null || value === undefined || value !== value;
}
module.exports = exports["default"];
},{}],35:[function(require,module,exports){
/**
* Copyright (c) 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.
*/
/**
* Creates a keyed JS object from an array, given a function to produce the keys
* for each value in the array.
*
* This provides a convenient lookup for the array items if the key function
* produces unique results.
*
* var phoneBook = [
* { name: 'Jon', num: '555-1234' },
* { name: 'Jenny', num: '867-5309' }
* ]
*
* // { Jon: { name: 'Jon', num: '555-1234' },
* // Jenny: { name: 'Jenny', num: '867-5309' } }
* var entriesByName = keyMap(
* phoneBook,
* entry => entry.name
* )
*
* // { name: 'Jenny', num: '857-6309' }
* var jennyEntry = entriesByName['Jenny']
*
*/
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = keyMap;
function keyMap(list, keyFn) {
return list.reduce(function (map, item) {
return (map[keyFn(item)] = item, map);
}, {});
}
module.exports = exports["default"];
},{}],36:[function(require,module,exports){
/**
* Copyright (c) 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.
*/
/**
* Creates a keyed JS object from an array, given a function to produce the keys
* and a function to produce the values from each item in the array.
*
* var phoneBook = [
* { name: 'Jon', num: '555-1234' },
* { name: 'Jenny', num: '867-5309' }
* ]
*
* // { Jon: '555-1234', Jenny: '867-5309' }
* var phonesByName = keyValMap(
* phoneBook,
* entry => entry.name,
* entry => entry.num
* )
*
*/
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = keyValMap;
function keyValMap(list, keyFn, valFn) {
return list.reduce(function (map, item) {
return (map[keyFn(item)] = valFn(item), map);
}, {});
}
module.exports = exports["default"];
},{}],37:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _interopRequireWildcard = require('babel-runtime/helpers/interop-require-wildcard')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
var _kinds = require('./kinds');
var Kind = _interopRequireWildcard(_kinds);
var _location = require('./location');
Object.defineProperty(exports, 'getLocation', {
enumerable: true,
get: function get() {
return _location.getLocation;
}
});
exports.Kind = Kind;
var _lexer = require('./lexer');
Object.defineProperty(exports, 'lex', {
enumerable: true,
get: function get() {
return _lexer.lex;
}
});
var _parser = require('./parser');
Object.defineProperty(exports, 'parse', {
enumerable: true,
get: function get() {
return _parser.parse;
}
});
Object.defineProperty(exports, 'parseValue', {
enumerable: true,
get: function get() {
return _parser.parseValue;
}
});
var _printer = require('./printer');
Object.defineProperty(exports, 'print', {
enumerable: true,
get: function get() {
return _printer.print;
}
});
var _source = require('./source');
Object.defineProperty(exports, 'Source', {
enumerable: true,
get: function get() {
return _source.Source;
}
});
var _visitor = require('./visitor');
Object.defineProperty(exports, 'visit', {
enumerable: true,
get: function get() {
return _visitor.visit;
}
});
Object.defineProperty(exports, 'BREAK', {
enumerable: true,
get: function get() {
return _visitor.BREAK;
}
});
},{"./kinds":38,"./lexer":39,"./location":40,"./parser":41,"./printer":42,"./source":43,"./visitor":44,"babel-runtime/helpers/interop-require-wildcard":61}],38:[function(require,module,exports){
/**
* Copyright (c) 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.
*/
// Name
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var NAME = 'Name';
exports.NAME = NAME;
// Document
var DOCUMENT = 'Document';
exports.DOCUMENT = DOCUMENT;
var OPERATION_DEFINITION = 'OperationDefinition';
exports.OPERATION_DEFINITION = OPERATION_DEFINITION;
var VARIABLE_DEFINITION = 'VariableDefinition';
exports.VARIABLE_DEFINITION = VARIABLE_DEFINITION;
var VARIABLE = 'Variable';
exports.VARIABLE = VARIABLE;
var SELECTION_SET = 'SelectionSet';
exports.SELECTION_SET = SELECTION_SET;
var FIELD = 'Field';
exports.FIELD = FIELD;
var ARGUMENT = 'Argument';
exports.ARGUMENT = ARGUMENT;
// Fragments
var FRAGMENT_SPREAD = 'FragmentSpread';
exports.FRAGMENT_SPREAD = FRAGMENT_SPREAD;
var INLINE_FRAGMENT = 'InlineFragment';
exports.INLINE_FRAGMENT = INLINE_FRAGMENT;
var FRAGMENT_DEFINITION = 'FragmentDefinition';
exports.FRAGMENT_DEFINITION = FRAGMENT_DEFINITION;
// Values
var INT = 'IntValue';
exports.INT = INT;
var FLOAT = 'FloatValue';
exports.FLOAT = FLOAT;
var STRING = 'StringValue';
exports.STRING = STRING;
var BOOLEAN = 'BooleanValue';
exports.BOOLEAN = BOOLEAN;
var ENUM = 'EnumValue';
exports.ENUM = ENUM;
var LIST = 'ListValue';
exports.LIST = LIST;
var OBJECT = 'ObjectValue';
exports.OBJECT = OBJECT;
var OBJECT_FIELD = 'ObjectField';
exports.OBJECT_FIELD = OBJECT_FIELD;
// Directives
var DIRECTIVE = 'Directive';
exports.DIRECTIVE = DIRECTIVE;
// Types
var NAMED_TYPE = 'NamedType';
exports.NAMED_TYPE = NAMED_TYPE;
var LIST_TYPE = 'ListType';
exports.LIST_TYPE = LIST_TYPE;
var NON_NULL_TYPE = 'NonNullType';
exports.NON_NULL_TYPE = NON_NULL_TYPE;
// Type Definitions
var OBJECT_TYPE_DEFINITION = 'ObjectTypeDefinition';
exports.OBJECT_TYPE_DEFINITION = OBJECT_TYPE_DEFINITION;
var FIELD_DEFINITION = 'FieldDefinition';
exports.FIELD_DEFINITION = FIELD_DEFINITION;
var INPUT_VALUE_DEFINITION = 'InputValueDefinition';
exports.INPUT_VALUE_DEFINITION = INPUT_VALUE_DEFINITION;
var INTERFACE_TYPE_DEFINITION = 'InterfaceTypeDefinition';
exports.INTERFACE_TYPE_DEFINITION = INTERFACE_TYPE_DEFINITION;
var UNION_TYPE_DEFINITION = 'UnionTypeDefinition';
exports.UNION_TYPE_DEFINITION = UNION_TYPE_DEFINITION;
var SCALAR_TYPE_DEFINITION = 'ScalarTypeDefinition';
exports.SCALAR_TYPE_DEFINITION = SCALAR_TYPE_DEFINITION;
var ENUM_TYPE_DEFINITION = 'EnumTypeDefinition';
exports.ENUM_TYPE_DEFINITION = ENUM_TYPE_DEFINITION;
var ENUM_VALUE_DEFINITION = 'EnumValueDefinition';
exports.ENUM_VALUE_DEFINITION = ENUM_VALUE_DEFINITION;
var INPUT_OBJECT_TYPE_DEFINITION = 'InputObjectTypeDefinition';
exports.INPUT_OBJECT_TYPE_DEFINITION = INPUT_OBJECT_TYPE_DEFINITION;
var TYPE_EXTENSION_DEFINITION = 'TypeExtensionDefinition';
exports.TYPE_EXTENSION_DEFINITION = TYPE_EXTENSION_DEFINITION;
},{}],39:[function(require,module,exports){
/* /
/**
* Copyright (c) 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';
/**
* A representation of a lexed Token. Value is optional, is it is
* not needed for punctuators like BANG or PAREN_L.
*/
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.lex = lex;
exports.getTokenDesc = getTokenDesc;
exports.getTokenKindDesc = getTokenKindDesc;
var _error = require('../error');
/**
* Given a Source object, this returns a Lexer for that source.
* A Lexer is a function that acts like a generator in that every time
* it is called, it returns the next token in the Source. Assuming the
* source lexes, the final Token emitted by the lexer will be of kind
* EOF, after which the lexer will repeatedly return EOF tokens whenever
* called.
*
* The argument to the lexer function is optional, and can be used to
* rewind or fast forward the lexer to a new position in the source.
*/
function lex(source) {
var prevPosition = 0;
return function nextToken(resetPosition) {
var token = readToken(source, resetPosition === undefined ? prevPosition : resetPosition);
prevPosition = token.end;
return token;
};
}
/**
* An enum describing the different kinds of tokens that the lexer emits.
*/
var TokenKind = {
EOF: 1,
BANG: 2,
DOLLAR: 3,
PAREN_L: 4,
PAREN_R: 5,
SPREAD: 6,
COLON: 7,
EQUALS: 8,
AT: 9,
BRACKET_L: 10,
BRACKET_R: 11,
BRACE_L: 12,
PIPE: 13,
BRACE_R: 14,
NAME: 15,
VARIABLE: 16,
INT: 17,
FLOAT: 18,
STRING: 19
};
exports.TokenKind = TokenKind;
/**
* A helper function to describe a token as a string for debugging
*/
function getTokenDesc(token) {
return token.value ? getTokenKindDesc(token.kind) + ' "' + token.value + '"' : getTokenKindDesc(token.kind);
}
/**
* A helper function to describe a token kind as a string for debugging
*/
function getTokenKindDesc(kind) {
return tokenDescription[kind];
}
var tokenDescription = {};
tokenDescription[TokenKind.EOF] = 'EOF';
tokenDescription[TokenKind.BANG] = '!';
tokenDescription[TokenKind.DOLLAR] = '$';
tokenDescription[TokenKind.PAREN_L] = '(';
tokenDescription[TokenKind.PAREN_R] = ')';
tokenDescription[TokenKind.SPREAD] = '...';
tokenDescription[TokenKind.COLON] = ':';
tokenDescription[TokenKind.EQUALS] = '=';
tokenDescription[TokenKind.AT] = '@';
tokenDescription[TokenKind.BRACKET_L] = '[';
tokenDescription[TokenKind.BRACKET_R] = ']';
tokenDescription[TokenKind.BRACE_L] = '{';
tokenDescription[TokenKind.PIPE] = '|';
tokenDescription[TokenKind.BRACE_R] = '}';
tokenDescription[TokenKind.NAME] = 'Name';
tokenDescription[TokenKind.VARIABLE] = 'Variable';
tokenDescription[TokenKind.INT] = 'Int';
tokenDescription[TokenKind.FLOAT] = 'Float';
tokenDescription[TokenKind.STRING] = 'String';
var charCodeAt = String.prototype.charCodeAt;
var slice = String.prototype.slice;
/**
* Helper function for constructing the Token object.
*/
function makeToken(kind, start, end, value) {
return { kind: kind, start: start, end: end, value: value };
}
function printCharCode(code) {
return(
// NaN/undefined represents access beyond the end of the file.
isNaN(code) ? '<EOF>' :
// Trust JSON for ASCII.
code < 0x007F ? JSON.stringify(String.fromCharCode(code)) :
// Otherwise print the escaped form.
'"\\u' + ('00' + code.toString(16).toUpperCase()).slice(-4) + '"'
);
}
/**
* Gets the next token from the source starting at the given position.
*
* This skips over whitespace and comments until it finds the next lexable
* token, then lexes punctuators immediately or calls the appropriate helper
* function for more complicated tokens.
*/
function readToken(source, fromPosition) {
var body = source.body;
var bodyLength = body.length;
var position = positionAfterWhitespace(body, fromPosition);
if (position >= bodyLength) {
return makeToken(TokenKind.EOF, position, position);
}
var code = charCodeAt.call(body, position);
// SourceCharacter
if (code < 0x0020 && code !== 0x0009 && code !== 0x000A && code !== 0x000D) {
throw (0, _error.syntaxError)(source, position, 'Invalid character ' + printCharCode(code) + '.');
}
switch (code) {
// !
case 33:
return makeToken(TokenKind.BANG, position, position + 1);
// $
case 36:
return makeToken(TokenKind.DOLLAR, position, position + 1);
// (
case 40:
return makeToken(TokenKind.PAREN_L, position, position + 1);
// )
case 41:
return makeToken(TokenKind.PAREN_R, position, position + 1);
// .
case 46:
if (charCodeAt.call(body, position + 1) === 46 && charCodeAt.call(body, position + 2) === 46) {
return makeToken(TokenKind.SPREAD, position, position + 3);
}
break;
// :
case 58:
return makeToken(TokenKind.COLON, position, position + 1);
// =
case 61:
return makeToken(TokenKind.EQUALS, position, position + 1);
// @
case 64:
return makeToken(TokenKind.AT, position, position + 1);
// [
case 91:
return makeToken(TokenKind.BRACKET_L, position, position + 1);
// ]
case 93:
return makeToken(TokenKind.BRACKET_R, position, position + 1);
// {
case 123:
return makeToken(TokenKind.BRACE_L, position, position + 1);
// |
case 124:
return makeToken(TokenKind.PIPE, position, position + 1);
// }
case 125:
return makeToken(TokenKind.BRACE_R, position, position + 1);
// A-Z
case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:
case 73:case 74:case 75:case 76:case 77:case 78:case 79:case 80:
case 81:case 82:case 83:case 84:case 85:case 86:case 87:case 88:
case 89:case 90:
// _
case 95:
// a-z
case 97:case 98:case 99:case 100:case 101:case 102:case 103:case 104:
case 105:case 106:case 107:case 108:case 109:case 110:case 111:
case 112:case 113:case 114:case 115:case 116:case 117:case 118:
case 119:case 120:case 121:case 122:
return readName(source, position);
// -
case 45:
// 0-9
case 48:case 49:case 50:case 51:case 52:
case 53:case 54:case 55:case 56:case 57:
return readNumber(source, position, code);
// "
case 34:
return readString(source, position);
}
throw (0, _error.syntaxError)(source, position, 'Unexpected character ' + printCharCode(code) + '.');
}
/**
* Reads from body starting at startPosition until it finds a non-whitespace
* or commented character, then returns the position of that character for
* lexing.
*/
function positionAfterWhitespace(body, startPosition) {
var bodyLength = body.length;
var position = startPosition;
while (position < bodyLength) {
var code = charCodeAt.call(body, position);
// Skip Ignored
if (
// BOM
code === 0xFEFF ||
// White Space
code === 0x0009 || // tab
code === 0x0020 || // space
// Line Terminator
code === 0x000A || // new line
code === 0x000D || // carriage return
// Comma
code === 0x002C) {
++position;
// Skip comments
} else if (code === 35) {
// #
++position;
while (position < bodyLength && (code = charCodeAt.call(body, position)) !== null && (
// SourceCharacter but not LineTerminator
code > 0x001F || code === 0x0009) && code !== 0x000A && code !== 0x000D) {
++position;
}
} else {
break;
}
}
return position;
}
/**
* Reads a number token from the source file, either a float
* or an int depending on whether a decimal point appears.
*
* Int: -?(0|[1-9][0-9]*)
* Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)?
*/
function readNumber(source, start, firstCode) {
var code = firstCode;
var body = source.body;
var position = start;
var isFloat = false;
if (code === 45) {
// -
code = charCodeAt.call(body, ++position);
}
if (code === 48) {
// 0
code = charCodeAt.call(body, ++position);
if (code >= 48 && code <= 57) {
throw (0, _error.syntaxError)(source, position, 'Invalid number, unexpected digit after 0: ' + printCharCode(code) + '.');
}
} else {
position = readDigits(source, position, code);
code = charCodeAt.call(body, position);
}
if (code === 46) {
// .
isFloat = true;
code = charCodeAt.call(body, ++position);
position = readDigits(source, position, code);
code = charCodeAt.call(body, position);
}
if (code === 69 || code === 101) {
// E e
isFloat = true;
code = charCodeAt.call(body, ++position);
if (code === 43 || code === 45) {
// + -
code = charCodeAt.call(body, ++position);
}
position = readDigits(source, position, code);
}
return makeToken(isFloat ? TokenKind.FLOAT : TokenKind.INT, start, position, slice.call(body, start, position));
}
/**
* Returns the new position in the source after reading digits.
*/
function readDigits(source, start, firstCode) {
var body = source.body;
var position = start;
var code = firstCode;
if (code >= 48 && code <= 57) {
// 0 - 9
do {
code = charCodeAt.call(body, ++position);
} while (code >= 48 && code <= 57); // 0 - 9
return position;
}
throw (0, _error.syntaxError)(source, position, 'Invalid number, expected digit but got: ' + printCharCode(code) + '.');
}
/**
* Reads a string token from the source file.
*
* "([^"\\\u000A\u000D\u2028\u2029]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*"
*/
function readString(source, start) {
var body = source.body;
var position = start + 1;
var chunkStart = position;
var code = 0;
var value = '';
while (position < body.length && (code = charCodeAt.call(body, position)) !== null &&
// not LineTerminator
code !== 0x000A && code !== 0x000D &&
// not Quote (")
code !== 34) {
// SourceCharacter
if (code < 0x0020 && code !== 0x0009) {
throw (0, _error.syntaxError)(source, position, 'Invalid character within String: ' + printCharCode(code) + '.');
}
++position;
if (code === 92) {
// \
value += slice.call(body, chunkStart, position - 1);
code = charCodeAt.call(body, position);
switch (code) {
case 34:
value += '"';break;
case 47:
value += '\/';break;
case 92:
value += '\\';break;
case 98:
value += '\b';break;
case 102:
value += '\f';break;
case 110:
value += '\n';break;
case 114:
value += '\r';break;
case 116:
value += '\t';break;
case 117:
// u
var charCode = uniCharCode(charCodeAt.call(body, position + 1), charCodeAt.call(body, position + 2), charCodeAt.call(body, position + 3), charCodeAt.call(body, position + 4));
if (charCode < 0) {
throw (0, _error.syntaxError)(source, position, 'Invalid character escape sequence: ' + ('\\u' + body.slice(position + 1, position + 5) + '.'));
}
value += String.fromCharCode(charCode);
position += 4;
break;
default:
throw (0, _error.syntaxError)(source, position, 'Invalid character escape sequence: \\' + String.fromCharCode(code) + '.');
}
++position;
chunkStart = position;
}
}
if (code !== 34) {
// quote (")
throw (0, _error.syntaxError)(source, position, 'Unterminated string.');
}
value += slice.call(body, chunkStart, position);
return makeToken(TokenKind.STRING, start, position + 1, value);
}
/**
* Converts four hexidecimal chars to the integer that the
* string represents. For example, uniCharCode('0','0','0','f')
* will return 15, and uniCharCode('0','0','f','f') returns 255.
*
* Returns a negative number on error, if a char was invalid.
*
* This is implemented by noting that char2hex() returns -1 on error,
* which means the result of ORing the char2hex() will also be negative.
*/
function uniCharCode(a, b, c, d) {
return char2hex(a) << 12 | char2hex(b) << 8 | char2hex(c) << 4 | char2hex(d);
}
/**
* Converts a hex character to its integer value.
* '0' becomes 0, '9' becomes 9
* 'A' becomes 10, 'F' becomes 15
* 'a' becomes 10, 'f' becomes 15
*
* Returns -1 on error.
*/
function char2hex(a) {
return a >= 48 && a <= 57 ? a - 48 : // 0-9
a >= 65 && a <= 70 ? a - 55 : // A-F
a >= 97 && a <= 102 ? a - 87 : // a-f
-1;
}
/**
* Reads an alphanumeric + underscore name from the source.
*
* [_A-Za-z][_0-9A-Za-z]*
*/
function readName(source, position) {
var body = source.body;
var bodyLength = body.length;
var end = position + 1;
var code = 0;
while (end !== bodyLength && (code = charCodeAt.call(body, end)) !== null && (code === 95 || // _
code >= 48 && code <= 57 || // 0-9
code >= 65 && code <= 90 || // A-Z
code >= 97 && code <= 122) // a-z
) {
++end;
}
return makeToken(TokenKind.NAME, position, end, slice.call(body, position, end));
}
},{"../error":29}],40:[function(require,module,exports){
/**
* Copyright (c) 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.
*/
/**
* Represents a location in a Source.
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.getLocation = getLocation;
/**
* Takes a Source and a UTF-8 character offset, and returns the corresponding
* line and column as a SourceLocation.
*/
function getLocation(source, position) {
var line = 1;
var column = position + 1;
var lineRegexp = /\r\n|[\n\r\u2028\u2029]/g;
var match;
while ((match = lineRegexp.exec(source.body)) && match.index < position) {
line += 1;
column = position + 1 - (match.index + match[0].length);
}
return { line: line, column: column };
}
},{}],41:[function(require,module,exports){
/**
* Copyright (c) 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';
/**
* Configuration options to control parser behavior
*/
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.parse = parse;
exports.parseValue = parseValue;
exports.parseConstValue = parseConstValue;
exports.parseType = parseType;
exports.parseNamedType = parseNamedType;
var _source = require('./source');
var _error = require('../error');
var _lexer = require('./lexer');
var _kinds = require('./kinds');
/**
* Given a GraphQL source, parses it into a Document.
* Throws GraphQLError if a syntax error is encountered.
*/
function parse(source, options) {
var sourceObj = source instanceof _source.Source ? source : new _source.Source(source);
var parser = makeParser(sourceObj, options || {});
return parseDocument(parser);
}
/**
* Given a string containing a GraphQL value, parse the AST for that value.
* Throws GraphQLError if a syntax error is encountered.
*
* This is useful within tools that operate upon GraphQL Values directly and
* in isolation of complete GraphQL documents.
*/
function parseValue(source, options) {
var sourceObj = source instanceof _source.Source ? source : new _source.Source(source);
var parser = makeParser(sourceObj, options || {});
return parseValueLiteral(parser);
}
/**
* Converts a name lex token into a name parse node.
*/
function parseName(parser) {
var token = expect(parser, _lexer.TokenKind.NAME);
return {
kind: _kinds.NAME,
value: token.value,
loc: loc(parser, token.start)
};
}
// Implements the parsing rules in the Document section.
/**
* Document : Definition+
*/
function parseDocument(parser) {
var start = parser.token.start;
var definitions = [];
do {
definitions.push(parseDefinition(parser));
} while (!skip(parser, _lexer.TokenKind.EOF));
return {
kind: _kinds.DOCUMENT,
definitions: definitions,
loc: loc(parser, start)
};
}
/**
* Definition :
* - OperationDefinition
* - FragmentDefinition
* - TypeDefinition
*/
function parseDefinition(parser) {
if (peek(parser, _lexer.TokenKind.BRACE_L)) {
return parseOperationDefinition(parser);
}
if (peek(parser, _lexer.TokenKind.NAME)) {
switch (parser.token.value) {
case 'query':
case 'mutation':
// Note: subscription is an experimental non-spec addition.
case 'subscription':
return parseOperationDefinition(parser);
case 'fragment':
return parseFragmentDefinition(parser);
case 'type':
case 'interface':
case 'union':
case 'scalar':
case 'enum':
case 'input':
case 'extend':
return parseTypeDefinition(parser);
}
}
throw unexpected(parser);
}
// Implements the parsing rules in the Operations section.
/**
* OperationDefinition :
* - SelectionSet
* - OperationType Name? VariableDefinitions? Directives? SelectionSet
*
* OperationType : one of query mutation
*/
function parseOperationDefinition(parser) {
var start = parser.token.start;
if (peek(parser, _lexer.TokenKind.BRACE_L)) {
return {
kind: _kinds.OPERATION_DEFINITION,
operation: 'query',
name: null,
variableDefinitions: null,
directives: [],
selectionSet: parseSelectionSet(parser),
loc: loc(parser, start)
};
}
var operationToken = expect(parser, _lexer.TokenKind.NAME);
var operation = operationToken.value;
var name;
if (peek(parser, _lexer.TokenKind.NAME)) {
name = parseName(parser);
}
return {
kind: _kinds.OPERATION_DEFINITION,
operation: operation,
name: name,
variableDefinitions: parseVariableDefinitions(parser),
directives: parseDirectives(parser),
selectionSet: parseSelectionSet(parser),
loc: loc(parser, start)
};
}
/**
* VariableDefinitions : ( VariableDefinition+ )
*/
function parseVariableDefinitions(parser) {
return peek(parser, _lexer.TokenKind.PAREN_L) ? many(parser, _lexer.TokenKind.PAREN_L, parseVariableDefinition, _lexer.TokenKind.PAREN_R) : [];
}
/**
* VariableDefinition : Variable : Type DefaultValue?
*/
function parseVariableDefinition(parser) {
var start = parser.token.start;
return {
kind: _kinds.VARIABLE_DEFINITION,
variable: parseVariable(parser),
type: (expect(parser, _lexer.TokenKind.COLON), parseType(parser)),
defaultValue: skip(parser, _lexer.TokenKind.EQUALS) ? parseValueLiteral(parser, true) : null,
loc: loc(parser, start)
};
}
/**
* Variable : $ Name
*/
function parseVariable(parser) {
var start = parser.token.start;
expect(parser, _lexer.TokenKind.DOLLAR);
return {
kind: _kinds.VARIABLE,
name: parseName(parser),
loc: loc(parser, start)
};
}
/**
* SelectionSet : { Selection+ }
*/
function parseSelectionSet(parser) {
var start = parser.token.start;
return {
kind: _kinds.SELECTION_SET,
selections: many(parser, _lexer.TokenKind.BRACE_L, parseSelection, _lexer.TokenKind.BRACE_R),
loc: loc(parser, start)
};
}
/**
* Selection :
* - Field
* - FragmentSpread
* - InlineFragment
*/
function parseSelection(parser) {
return peek(parser, _lexer.TokenKind.SPREAD) ? parseFragment(parser) : parseField(parser);
}
/**
* Field : Alias? Name Arguments? Directives? SelectionSet?
*
* Alias : Name :
*/
function parseField(parser) {
var start = parser.token.start;
var nameOrAlias = parseName(parser);
var alias;
var name;
if (skip(parser, _lexer.TokenKind.COLON)) {
alias = nameOrAlias;
name = parseName(parser);
} else {
alias = null;
name = nameOrAlias;
}
return {
kind: _kinds.FIELD,
alias: alias,
name: name,
arguments: parseArguments(parser),
directives: parseDirectives(parser),
selectionSet: peek(parser, _lexer.TokenKind.BRACE_L) ? parseSelectionSet(parser) : null,
loc: loc(parser, start)
};
}
/**
* Arguments : ( Argument+ )
*/
function parseArguments(parser) {
return peek(parser, _lexer.TokenKind.PAREN_L) ? many(parser, _lexer.TokenKind.PAREN_L, parseArgument, _lexer.TokenKind.PAREN_R) : [];
}
/**
* Argument : Name : Value
*/
function parseArgument(parser) {
var start = parser.token.start;
return {
kind: _kinds.ARGUMENT,
name: parseName(parser),
value: (expect(parser, _lexer.TokenKind.COLON), parseValueLiteral(parser, false)),
loc: loc(parser, start)
};
}
// Implements the parsing rules in the Fragments section.
/**
* Corresponds to both FragmentSpread and InlineFragment in the spec.
*
* FragmentSpread : ... FragmentName Directives?
*
* InlineFragment : ... TypeCondition? Directives? SelectionSet
*/
function parseFragment(parser) {
var start = parser.token.start;
expect(parser, _lexer.TokenKind.SPREAD);
if (peek(parser, _lexer.TokenKind.NAME) && parser.token.value !== 'on') {
return {
kind: _kinds.FRAGMENT_SPREAD,
name: parseFragmentName(parser),
directives: parseDirectives(parser),
loc: loc(parser, start)
};
}
var typeCondition = null;
if (parser.token.value === 'on') {
advance(parser);
typeCondition = parseNamedType(parser);
}
return {
kind: _kinds.INLINE_FRAGMENT,
typeCondition: typeCondition,
directives: parseDirectives(parser),
selectionSet: parseSelectionSet(parser),
loc: loc(parser, start)
};
}
/**
* FragmentDefinition :
* - fragment FragmentName on TypeCondition Directives? SelectionSet
*
* TypeCondition : NamedType
*/
function parseFragmentDefinition(parser) {
var start = parser.token.start;
expectKeyword(parser, 'fragment');
return {
kind: _kinds.FRAGMENT_DEFINITION,
name: parseFragmentName(parser),
typeCondition: (expectKeyword(parser, 'on'), parseNamedType(parser)),
directives: parseDirectives(parser),
selectionSet: parseSelectionSet(parser),
loc: loc(parser, start)
};
}
/**
* FragmentName : Name but not `on`
*/
function parseFragmentName(parser) {
if (parser.token.value === 'on') {
throw unexpected(parser);
}
return parseName(parser);
}
// Implements the parsing rules in the Values section.
/**
* Value[Const] :
* - [~Const] Variable
* - IntValue
* - FloatValue
* - StringValue
* - BooleanValue
* - EnumValue
* - ListValue[?Const]
* - ObjectValue[?Const]
*
* BooleanValue : one of `true` `false`
*
* EnumValue : Name but not `true`, `false` or `null`
*/
function parseValueLiteral(parser, isConst) {
var token = parser.token;
switch (token.kind) {
case _lexer.TokenKind.BRACKET_L:
return parseList(parser, isConst);
case _lexer.TokenKind.BRACE_L:
return parseObject(parser, isConst);
case _lexer.TokenKind.INT:
advance(parser);
return {
kind: _kinds.INT,
value: token.value,
loc: loc(parser, token.start)
};
case _lexer.TokenKind.FLOAT:
advance(parser);
return {
kind: _kinds.FLOAT,
value: token.value,
loc: loc(parser, token.start)
};
case _lexer.TokenKind.STRING:
advance(parser);
return {
kind: _kinds.STRING,
value: token.value,
loc: loc(parser, token.start)
};
case _lexer.TokenKind.NAME:
if (token.value === 'true' || token.value === 'false') {
advance(parser);
return {
kind: _kinds.BOOLEAN,
value: token.value === 'true',
loc: loc(parser, token.start)
};
} else if (token.value !== 'null') {
advance(parser);
return {
kind: _kinds.ENUM,
value: token.value,
loc: loc(parser, token.start)
};
}
break;
case _lexer.TokenKind.DOLLAR:
if (!isConst) {
return parseVariable(parser);
}
break;
}
throw unexpected(parser);
}
function parseConstValue(parser) {
return parseValueLiteral(parser, true);
}
function parseValueValue(parser) {
return parseValueLiteral(parser, false);
}
/**
* ListValue[Const] :
* - [ ]
* - [ Value[?Const]+ ]
*/
function parseList(parser, isConst) {
var start = parser.token.start;
var item = isConst ? parseConstValue : parseValueValue;
return {
kind: _kinds.LIST,
values: any(parser, _lexer.TokenKind.BRACKET_L, item, _lexer.TokenKind.BRACKET_R),
loc: loc(parser, start)
};
}
/**
* ObjectValue[Const] :
* - { }
* - { ObjectField[?Const]+ }
*/
function parseObject(parser, isConst) {
var start = parser.token.start;
expect(parser, _lexer.TokenKind.BRACE_L);
var fields = [];
while (!skip(parser, _lexer.TokenKind.BRACE_R)) {
fields.push(parseObjectField(parser, isConst));
}
return {
kind: _kinds.OBJECT,
fields: fields,
loc: loc(parser, start)
};
}
/**
* ObjectField[Const] : Name : Value[?Const]
*/
function parseObjectField(parser, isConst) {
var start = parser.token.start;
return {
kind: _kinds.OBJECT_FIELD,
name: parseName(parser),
value: (expect(parser, _lexer.TokenKind.COLON), parseValueLiteral(parser, isConst)),
loc: loc(parser, start)
};
}
// Implements the parsing rules in the Directives section.
/**
* Directives : Directive+
*/
function parseDirectives(parser) {
var directives = [];
while (peek(parser, _lexer.TokenKind.AT)) {
directives.push(parseDirective(parser));
}
return directives;
}
/**
* Directive : @ Name Arguments?
*/
function parseDirective(parser) {
var start = parser.token.start;
expect(parser, _lexer.TokenKind.AT);
return {
kind: _kinds.DIRECTIVE,
name: parseName(parser),
arguments: parseArguments(parser),
loc: loc(parser, start)
};
}
// Implements the parsing rules in the Types section.
/**
* Type :
* - NamedType
* - ListType
* - NonNullType
*/
function parseType(parser) {
var start = parser.token.start;
var type;
if (skip(parser, _lexer.TokenKind.BRACKET_L)) {
type = parseType(parser);
expect(parser, _lexer.TokenKind.BRACKET_R);
type = {
kind: _kinds.LIST_TYPE,
type: type,
loc: loc(parser, start)
};
} else {
type = parseNamedType(parser);
}
if (skip(parser, _lexer.TokenKind.BANG)) {
return {
kind: _kinds.NON_NULL_TYPE,
type: type,
loc: loc(parser, start)
};
}
return type;
}
/**
* NamedType : Name
*/
function parseNamedType(parser) {
var start = parser.token.start;
return {
kind: _kinds.NAMED_TYPE,
name: parseName(parser),
loc: loc(parser, start)
};
}
// Implements the parsing rules in the Type Definition section.
/**
* TypeDefinition :
* - ObjectTypeDefinition
* - InterfaceTypeDefinition
* - UnionTypeDefinition
* - ScalarTypeDefinition
* - EnumTypeDefinition
* - InputObjectTypeDefinition
* - TypeExtensionDefinition
*/
function parseTypeDefinition(parser) {
if (!peek(parser, _lexer.TokenKind.NAME)) {
throw unexpected(parser);
}
switch (parser.token.value) {
case 'type':
return parseObjectTypeDefinition(parser);
case 'interface':
return parseInterfaceTypeDefinition(parser);
case 'union':
return parseUnionTypeDefinition(parser);
case 'scalar':
return parseScalarTypeDefinition(parser);
case 'enum':
return parseEnumTypeDefinition(parser);
case 'input':
return parseInputObjectTypeDefinition(parser);
case 'extend':
return parseTypeExtensionDefinition(parser);
default:
throw unexpected(parser);
}
}
/**
* ObjectTypeDefinition : type Name ImplementsInterfaces? { FieldDefinition+ }
*/
function parseObjectTypeDefinition(parser) {
var start = parser.token.start;
expectKeyword(parser, 'type');
var name = parseName(parser);
var interfaces = parseImplementsInterfaces(parser);
var fields = any(parser, _lexer.TokenKind.BRACE_L, parseFieldDefinition, _lexer.TokenKind.BRACE_R);
return {
kind: _kinds.OBJECT_TYPE_DEFINITION,
name: name,
interfaces: interfaces,
fields: fields,
loc: loc(parser, start)
};
}
/**
* ImplementsInterfaces : implements NamedType+
*/
function parseImplementsInterfaces(parser) {
var types = [];
if (parser.token.value === 'implements') {
advance(parser);
do {
types.push(parseNamedType(parser));
} while (!peek(parser, _lexer.TokenKind.BRACE_L));
}
return types;
}
/**
* FieldDefinition : Name ArgumentsDefinition? : Type
*/
function parseFieldDefinition(parser) {
var start = parser.token.start;
var name = parseName(parser);
var args = parseArgumentDefs(parser);
expect(parser, _lexer.TokenKind.COLON);
var type = parseType(parser);
return {
kind: _kinds.FIELD_DEFINITION,
name: name,
arguments: args,
type: type,
loc: loc(parser, start)
};
}
/**
* ArgumentsDefinition : ( InputValueDefinition+ )
*/
function parseArgumentDefs(parser) {
if (!peek(parser, _lexer.TokenKind.PAREN_L)) {
return [];
}
return many(parser, _lexer.TokenKind.PAREN_L, parseInputValueDef, _lexer.TokenKind.PAREN_R);
}
/**
* InputValueDefinition : Name : Type DefaultValue?
*/
function parseInputValueDef(parser) {
var start = parser.token.start;
var name = parseName(parser);
expect(parser, _lexer.TokenKind.COLON);
var type = parseType(parser, false);
var defaultValue = null;
if (skip(parser, _lexer.TokenKind.EQUALS)) {
defaultValue = parseConstValue(parser);
}
return {
kind: _kinds.INPUT_VALUE_DEFINITION,
name: name,
type: type,
defaultValue: defaultValue,
loc: loc(parser, start)
};
}
/**
* InterfaceTypeDefinition : interface Name { FieldDefinition+ }
*/
function parseInterfaceTypeDefinition(parser) {
var start = parser.token.start;
expectKeyword(parser, 'interface');
var name = parseName(parser);
var fields = any(parser, _lexer.TokenKind.BRACE_L, parseFieldDefinition, _lexer.TokenKind.BRACE_R);
return {
kind: _kinds.INTERFACE_TYPE_DEFINITION,
name: name,
fields: fields,
loc: loc(parser, start)
};
}
/**
* UnionTypeDefinition : union Name = UnionMembers
*/
function parseUnionTypeDefinition(parser) {
var start = parser.token.start;
expectKeyword(parser, 'union');
var name = parseName(parser);
expect(parser, _lexer.TokenKind.EQUALS);
var types = parseUnionMembers(parser);
return {
kind: _kinds.UNION_TYPE_DEFINITION,
name: name,
types: types,
loc: loc(parser, start)
};
}
/**
* UnionMembers :
* - NamedType
* - UnionMembers | NamedType
*/
function parseUnionMembers(parser) {
var members = [];
do {
members.push(parseNamedType(parser));
} while (skip(parser, _lexer.TokenKind.PIPE));
return members;
}
/**
* ScalarTypeDefinition : scalar Name
*/
function parseScalarTypeDefinition(parser) {
var start = parser.token.start;
expectKeyword(parser, 'scalar');
var name = parseName(parser);
return {
kind: _kinds.SCALAR_TYPE_DEFINITION,
name: name,
loc: loc(parser, start)
};
}
/**
* EnumTypeDefinition : enum Name { EnumValueDefinition+ }
*/
function parseEnumTypeDefinition(parser) {
var start = parser.token.start;
expectKeyword(parser, 'enum');
var name = parseName(parser);
var values = many(parser, _lexer.TokenKind.BRACE_L, parseEnumValueDefinition, _lexer.TokenKind.BRACE_R);
return {
kind: _kinds.ENUM_TYPE_DEFINITION,
name: name,
values: values,
loc: loc(parser, start)
};
}
/**
* EnumValueDefinition : EnumValue
*
* EnumValue : Name
*/
function parseEnumValueDefinition(parser) {
var start = parser.token.start;
var name = parseName(parser);
return {
kind: _kinds.ENUM_VALUE_DEFINITION,
name: name,
loc: loc(parser, start)
};
}
/**
* InputObjectTypeDefinition : input Name { InputValueDefinition+ }
*/
function parseInputObjectTypeDefinition(parser) {
var start = parser.token.start;
expectKeyword(parser, 'input');
var name = parseName(parser);
var fields = any(parser, _lexer.TokenKind.BRACE_L, parseInputValueDef, _lexer.TokenKind.BRACE_R);
return {
kind: _kinds.INPUT_OBJECT_TYPE_DEFINITION,
name: name,
fields: fields,
loc: loc(parser, start)
};
}
/**
* TypeExtensionDefinition : extend ObjectTypeDefinition
*/
function parseTypeExtensionDefinition(parser) {
var start = parser.token.start;
expectKeyword(parser, 'extend');
var definition = parseObjectTypeDefinition(parser);
return {
kind: _kinds.TYPE_EXTENSION_DEFINITION,
definition: definition,
loc: loc(parser, start)
};
}
// Core parsing utility functions
/**
* Returns the parser object that is used to store state throughout the
* process of parsing.
*/
function makeParser(source, options) {
var _lexToken = (0, _lexer.lex)(source);
return {
_lexToken: _lexToken,
source: source,
options: options,
prevEnd: 0,
token: _lexToken()
};
}
/**
* Returns a location object, used to identify the place in
* the source that created a given parsed object.
*/
function loc(parser, start) {
if (parser.options.noLocation) {
return null;
}
if (parser.options.noSource) {
return { start: start, end: parser.prevEnd };
}
return { start: start, end: parser.prevEnd, source: parser.source };
}
/**
* Moves the internal parser object to the next lexed token.
*/
function advance(parser) {
var prevEnd = parser.token.end;
parser.prevEnd = prevEnd;
parser.token = parser._lexToken(prevEnd);
}
/**
* Determines if the next token is of a given kind
*/
function peek(parser, kind) {
return parser.token.kind === kind;
}
/**
* If the next token is of the given kind, return true after advancing
* the parser. Otherwise, do not change the parser state and return false.
*/
function skip(parser, kind) {
var match = parser.token.kind === kind;
if (match) {
advance(parser);
}
return match;
}
/**
* If the next token is of the given kind, return that token after advancing
* the parser. Otherwise, do not change the parser state and return false.
*/
function expect(parser, kind) {
var token = parser.token;
if (token.kind === kind) {
advance(parser);
return token;
}
throw (0, _error.syntaxError)(parser.source, token.start, 'Expected ' + (0, _lexer.getTokenKindDesc)(kind) + ', found ' + (0, _lexer.getTokenDesc)(token));
}
/**
* If the next token is a keyword with the given value, return that token after
* advancing the parser. Otherwise, do not change the parser state and return
* false.
*/
function expectKeyword(parser, value) {
var token = parser.token;
if (token.kind === _lexer.TokenKind.NAME && token.value === value) {
advance(parser);
return token;
}
throw (0, _error.syntaxError)(parser.source, token.start, 'Expected "' + value + '", found ' + (0, _lexer.getTokenDesc)(token));
}
/**
* Helper function for creating an error when an unexpected lexed token
* is encountered.
*/
function unexpected(parser, atToken) {
var token = atToken || parser.token;
return (0, _error.syntaxError)(parser.source, token.start, 'Unexpected ' + (0, _lexer.getTokenDesc)(token));
}
/**
* Returns a possibly empty list of parse nodes, determined by
* the parseFn. This list begins with a lex token of openKind
* and ends with a lex token of closeKind. Advances the parser
* to the next lex token after the closing token.
*/
function any(parser, openKind, parseFn, closeKind) {
expect(parser, openKind);
var nodes = [];
while (!skip(parser, closeKind)) {
nodes.push(parseFn(parser));
}
return nodes;
}
/**
* Returns a non-empty list of parse nodes, determined by
* the parseFn. This list begins with a lex token of openKind
* and ends with a lex token of closeKind. Advances the parser
* to the next lex token after the closing token.
*/
function many(parser, openKind, parseFn, closeKind) {
expect(parser, openKind);
var nodes = [parseFn(parser)];
while (!skip(parser, closeKind)) {
nodes.push(parseFn(parser));
}
return nodes;
}
/**
* By default, the parser creates AST nodes that know the location
* in the source that they correspond to. This configuration flag
* disables that behavior for performance or testing.
*/
/**
* By default, the parser creates AST nodes that contain a reference
* to the source that they were created from. This configuration flag
* disables that behavior for performance or testing.
*/
},{"../error":29,"./kinds":38,"./lexer":39,"./source":43}],42:[function(require,module,exports){
/**
* Copyright (c) 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';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.print = print;
var _visitor = require('./visitor');
/**
* Converts an AST into a string, using one set of reasonable
* formatting rules.
*/
function print(ast) {
return (0, _visitor.visit)(ast, { leave: printDocASTReducer });
}
var printDocASTReducer = {
Name: function Name(node) {
return node.value;
},
Variable: function Variable(node) {
return '$' + node.name;
},
// Document
Document: function Document(node) {
return join(node.definitions, '\n\n') + '\n';
},
OperationDefinition: function OperationDefinition(node) {
var op = node.operation;
var name = node.name;
var defs = wrap('(', join(node.variableDefinitions, ', '), ')');
var directives = join(node.directives, ' ');
var selectionSet = node.selectionSet;
return !name ? selectionSet : join([op, join([name, defs]), directives, selectionSet], ' ');
},
VariableDefinition: function VariableDefinition(_ref) {
var variable = _ref.variable;
var type = _ref.type;
var defaultValue = _ref.defaultValue;
return variable + ': ' + type + wrap(' = ', defaultValue);
},
SelectionSet: function SelectionSet(_ref2) {
var selections = _ref2.selections;
return block(selections);
},
Field: function Field(_ref3) {
var alias = _ref3.alias;
var name = _ref3.name;
var args = _ref3.arguments;
var directives = _ref3.directives;
var selectionSet = _ref3.selectionSet;
return join([wrap('', alias, ': ') + name + wrap('(', join(args, ', '), ')'), join(directives, ' '), selectionSet], ' ');
},
Argument: function Argument(_ref4) {
var name = _ref4.name;
var value = _ref4.value;
return name + ': ' + value;
},
// Fragments
FragmentSpread: function FragmentSpread(_ref5) {
var name = _ref5.name;
var directives = _ref5.directives;
return '...' + name + wrap(' ', join(directives, ' '));
},
InlineFragment: function InlineFragment(_ref6) {
var typeCondition = _ref6.typeCondition;
var directives = _ref6.directives;
var selectionSet = _ref6.selectionSet;
return join(['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], ' ');
},
FragmentDefinition: function FragmentDefinition(_ref7) {
var name = _ref7.name;
var typeCondition = _ref7.typeCondition;
var directives = _ref7.directives;
var selectionSet = _ref7.selectionSet;
return 'fragment ' + name + ' on ' + typeCondition + ' ' + wrap('', join(directives, ' '), ' ') + selectionSet;
},
// Value
IntValue: function IntValue(_ref8) {
var value = _ref8.value;
return value;
},
FloatValue: function FloatValue(_ref9) {
var value = _ref9.value;
return value;
},
StringValue: function StringValue(_ref10) {
var value = _ref10.value;
return JSON.stringify(value);
},
BooleanValue: function BooleanValue(_ref11) {
var value = _ref11.value;
return JSON.stringify(value);
},
EnumValue: function EnumValue(_ref12) {
var value = _ref12.value;
return value;
},
ListValue: function ListValue(_ref13) {
var values = _ref13.values;
return '[' + join(values, ', ') + ']';
},
ObjectValue: function ObjectValue(_ref14) {
var fields = _ref14.fields;
return '{' + join(fields, ', ') + '}';
},
ObjectField: function ObjectField(_ref15) {
var name = _ref15.name;
var value = _ref15.value;
return name + ': ' + value;
},
// Directive
Directive: function Directive(_ref16) {
var name = _ref16.name;
var args = _ref16.arguments;
return '@' + name + wrap('(', join(args, ', '), ')');
},
// Type
NamedType: function NamedType(_ref17) {
var name = _ref17.name;
return name;
},
ListType: function ListType(_ref18) {
var type = _ref18.type;
return '[' + type + ']';
},
NonNullType: function NonNullType(_ref19) {
var type = _ref19.type;
return type + '!';
},
// Type Definitions
ObjectTypeDefinition: function ObjectTypeDefinition(_ref20) {
var name = _ref20.name;
var interfaces = _ref20.interfaces;
var fields = _ref20.fields;
return 'type ' + name + ' ' + wrap('implements ', join(interfaces, ', '), ' ') + block(fields);
},
FieldDefinition: function FieldDefinition(_ref21) {
var name = _ref21.name;
var args = _ref21.arguments;
var type = _ref21.type;
return name + wrap('(', join(args, ', '), ')') + ': ' + type;
},
InputValueDefinition: function InputValueDefinition(_ref22) {
var name = _ref22.name;
var type = _ref22.type;
var defaultValue = _ref22.defaultValue;
return name + ': ' + type + wrap(' = ', defaultValue);
},
InterfaceTypeDefinition: function InterfaceTypeDefinition(_ref23) {
var name = _ref23.name;
var fields = _ref23.fields;
return 'interface ' + name + ' ' + block(fields);
},
UnionTypeDefinition: function UnionTypeDefinition(_ref24) {
var name = _ref24.name;
var types = _ref24.types;
return 'union ' + name + ' = ' + join(types, ' | ');
},
ScalarTypeDefinition: function ScalarTypeDefinition(_ref25) {
var name = _ref25.name;
return 'scalar ' + name;
},
EnumTypeDefinition: function EnumTypeDefinition(_ref26) {
var name = _ref26.name;
var values = _ref26.values;
return 'enum ' + name + ' ' + block(values);
},
EnumValueDefinition: function EnumValueDefinition(_ref27) {
var name = _ref27.name;
return name;
},
InputObjectTypeDefinition: function InputObjectTypeDefinition(_ref28) {
var name = _ref28.name;
var fields = _ref28.fields;
return 'input ' + name + ' ' + block(fields);
},
TypeExtensionDefinition: function TypeExtensionDefinition(_ref29) {
var definition = _ref29.definition;
return 'extend ' + definition;
}
};
/**
* Given maybeArray, print an empty string if it is null or empty, otherwise
* print all items together separated by separator if provided
*/
function join(maybeArray, separator) {
return maybeArray ? maybeArray.filter(function (x) {
return x;
}).join(separator || '') : '';
}
/**
* Given maybeArray, print an empty string if it is null or empty, otherwise
* print each item on it's own line, wrapped in an indented "{ }" block.
*/
function block(maybeArray) {
return length(maybeArray) ? indent('{\n' + join(maybeArray, '\n')) + '\n}' : '';
}
/**
* If maybeString is not null or empty, then wrap with start and end, otherwise
* print an empty string.
*/
function wrap(start, maybeString, end) {
return maybeString ? start + maybeString + (end || '') : '';
}
function indent(maybeString) {
return maybeString && maybeString.replace(/\n/g, '\n ');
}
function length(maybeArray) {
return maybeArray ? maybeArray.length : 0;
}
},{"./visitor":44}],43:[function(require,module,exports){
/**
* Copyright (c) 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.
*/
/**
* A representation of source input to GraphQL. The name is optional,
* but is mostly useful for clients who store GraphQL documents in
* source files; for example, if the GraphQL input is in a file Foo.graphql,
* it might be useful for name to be "Foo.graphql".
*/
'use strict';
var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
var Source = function Source(body, name) {
_classCallCheck(this, Source);
this.body = body;
this.name = name || 'GraphQL';
};
exports.Source = Source;
},{"babel-runtime/helpers/class-call-check":55}],44:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _slicedToArray = require('babel-runtime/helpers/sliced-to-array')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.visit = visit;
exports.getVisitFn = getVisitFn;
var QueryDocumentKeys = {
Name: [],
Document: ['definitions'],
OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'],
VariableDefinition: ['variable', 'type', 'defaultValue'],
Variable: ['name'],
SelectionSet: ['selections'],
Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'],
Argument: ['name', 'value'],
FragmentSpread: ['name', 'directives'],
InlineFragment: ['typeCondition', 'directives', 'selectionSet'],
FragmentDefinition: ['name', 'typeCondition', 'directives', 'selectionSet'],
IntValue: [],
FloatValue: [],
StringValue: [],
BooleanValue: [],
EnumValue: [],
ListValue: ['values'],
ObjectValue: ['fields'],
ObjectField: ['name', 'value'],
Directive: ['name', 'arguments'],
NamedType: ['name'],
ListType: ['type'],
NonNullType: ['type'],
ObjectTypeDefinition: ['name', 'interfaces', 'fields'],
FieldDefinition: ['name', 'arguments', 'type'],
InputValueDefinition: ['name', 'type', 'defaultValue'],
InterfaceTypeDefinition: ['name', 'fields'],
UnionTypeDefinition: ['name', 'types'],
ScalarTypeDefinition: ['name'],
EnumTypeDefinition: ['name', 'values'],
EnumValueDefinition: ['name'],
InputObjectTypeDefinition: ['name', 'fields'],
TypeExtensionDefinition: ['definition']
};
exports.QueryDocumentKeys = QueryDocumentKeys;
var BREAK = {};
exports.BREAK = BREAK;
/**
* visit() will walk through an AST using a depth first traversal, calling
* the visitor's enter function at each node in the traversal, and calling the
* leave function after visiting that node and all of it's child nodes.
*
* By returning different values from the enter and leave functions, the
* behavior of the visitor can be altered, including skipping over a sub-tree of
* the AST (by returning false), editing the AST by returning a value or null
* to remove the value, or to stop the whole traversal by returning BREAK.
*
* When using visit() to edit an AST, the original AST will not be modified, and
* a new version of the AST with the changes applied will be returned from the
* visit function.
*
* var editedAST = visit(ast, {
* enter(node, key, parent, path, ancestors) {
* // @return
* // undefined: no action
* // false: skip visiting this node
* // visitor.BREAK: stop visiting altogether
* // null: delete this node
* // any value: replace this node with the returned value
* },
* leave(node, key, parent, path, ancestors) {
* // @return
* // undefined: no action
* // false: no action
* // visitor.BREAK: stop visiting altogether
* // null: delete this node
* // any value: replace this node with the returned value
* }
* });
*
* Alternatively to providing enter() and leave() functions, a visitor can
* instead provide functions named the same as the kinds of AST nodes, or
* enter/leave visitors at a named key, leading to four permutations of
* visitor API:
*
* 1) Named visitors triggered when entering a node a specific kind.
*
* visit(ast, {
* Kind(node) {
* // enter the "Kind" node
* }
* })
*
* 2) Named visitors that trigger upon entering and leaving a node of
* a specific kind.
*
* visit(ast, {
* Kind: {
* enter(node) {
* // enter the "Kind" node
* }
* leave(node) {
* // leave the "Kind" node
* }
* }
* })
*
* 3) Generic visitors that trigger upon entering and leaving any node.
*
* visit(ast, {
* enter(node) {
* // enter any node
* },
* leave(node) {
* // leave any node
* }
* })
*
* 4) Parallel visitors for entering and leaving nodes of a specific kind.
*
* visit(ast, {
* enter: {
* Kind(node) {
* // enter the "Kind" node
* }
* },
* leave: {
* Kind(node) {
* // leave the "Kind" node
* }
* }
* })
*/
function visit(root, visitor, keyMap) {
var visitorKeys = keyMap || QueryDocumentKeys;
var stack;
var inArray = Array.isArray(root);
var keys = [root];
var index = -1;
var edits = [];
var parent;
var path = [];
var ancestors = [];
var newRoot = root;
do {
index++;
var isLeaving = index === keys.length;
var key;
var node;
var isEdited = isLeaving && edits.length !== 0;
if (isLeaving) {
key = ancestors.length === 0 ? undefined : path.pop();
node = parent;
parent = ancestors.pop();
if (isEdited) {
if (inArray) {
node = node.slice();
} else {
var clone = {};
for (var k in node) {
if (node.hasOwnProperty(k)) {
clone[k] = node[k];
}
}
node = clone;
}
var editOffset = 0;
for (var ii = 0; ii < edits.length; ii++) {
var _edits$ii = _slicedToArray(edits[ii], 2);
var editKey = _edits$ii[0];
var editValue = _edits$ii[1];
if (inArray) {
editKey -= editOffset;
}
if (inArray && editValue === null) {
node.splice(editKey, 1);
editOffset++;
} else {
node[editKey] = editValue;
}
}
}
index = stack.index;
keys = stack.keys;
edits = stack.edits;
inArray = stack.inArray;
stack = stack.prev;
} else {
key = parent ? inArray ? index : keys[index] : undefined;
node = parent ? parent[key] : newRoot;
if (node === null || node === undefined) {
continue;
}
if (parent) {
path.push(key);
}
}
var result = undefined;
if (!Array.isArray(node)) {
if (!isNode(node)) {
throw new Error('Invalid AST Node: ' + JSON.stringify(node));
}
var visitFn = getVisitFn(visitor, isLeaving, node.kind);
if (visitFn) {
result = visitFn.call(visitor, node, key, parent, path, ancestors);
if (result === BREAK) {
break;
}
if (result === false) {
if (!isLeaving) {
path.pop();
continue;
}
} else if (result !== undefined) {
edits.push([key, result]);
if (!isLeaving) {
if (isNode(result)) {
node = result;
} else {
path.pop();
continue;
}
}
}
}
}
if (result === undefined && isEdited) {
edits.push([key, node]);
}
if (!isLeaving) {
stack = { inArray: inArray, index: index, keys: keys, edits: edits, prev: stack };
inArray = Array.isArray(node);
keys = inArray ? node : visitorKeys[node.kind] || [];
index = -1;
edits = [];
if (parent) {
ancestors.push(parent);
}
parent = node;
}
} while (stack !== undefined);
if (edits.length !== 0) {
newRoot = edits[0][1];
}
return newRoot;
}
function isNode(maybeNode) {
return maybeNode && typeof maybeNode.kind === 'string';
}
function getVisitFn(visitor, isLeaving, kind) {
var kindVisitor = visitor[kind];
if (kindVisitor) {
if (!isLeaving && typeof kindVisitor === 'function') {
// { Kind() {} }
return kindVisitor;
}
var kindSpecificVisitor = isLeaving ? kindVisitor.leave : kindVisitor.enter;
if (typeof kindSpecificVisitor === 'function') {
// { Kind: { enter() {}, leave() {} } }
return kindSpecificVisitor;
}
return;
}
var specificVisitor = isLeaving ? visitor.leave : visitor.enter;
if (specificVisitor) {
if (typeof specificVisitor === 'function') {
// { enter() {}, leave() {} }
return specificVisitor;
}
var specificKindVisitor = specificVisitor[kind];
if (typeof specificKindVisitor === 'function') {
// { enter: { Kind() {} }, leave: { Kind() {} } }
return specificKindVisitor;
}
}
}
},{"babel-runtime/helpers/sliced-to-array":62}],45:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/get-iterator"), __esModule: true };
},{"core-js/library/fn/get-iterator":63}],46:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/is-iterable"), __esModule: true };
},{"core-js/library/fn/is-iterable":64}],47:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/map"), __esModule: true };
},{"core-js/library/fn/map":65}],48:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/assign"), __esModule: true };
},{"core-js/library/fn/object/assign":66}],49:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/create"), __esModule: true };
},{"core-js/library/fn/object/create":67}],50:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/define-property"), __esModule: true };
},{"core-js/library/fn/object/define-property":68}],51:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/get-own-property-descriptor"), __esModule: true };
},{"core-js/library/fn/object/get-own-property-descriptor":69}],52:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/keys"), __esModule: true };
},{"core-js/library/fn/object/keys":70}],53:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/set-prototype-of"), __esModule: true };
},{"core-js/library/fn/object/set-prototype-of":71}],54:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/set"), __esModule: true };
},{"core-js/library/fn/set":72}],55:[function(require,module,exports){
"use strict";
exports["default"] = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
exports.__esModule = true;
},{}],56:[function(require,module,exports){
"use strict";
var _Object$defineProperty = require("babel-runtime/core-js/object/define-property")["default"];
exports["default"] = (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;
};
})();
exports.__esModule = true;
},{"babel-runtime/core-js/object/define-property":50}],57:[function(require,module,exports){
"use strict";
var _Object$assign = require("babel-runtime/core-js/object/assign")["default"];
exports["default"] = _Object$assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
exports.__esModule = true;
},{"babel-runtime/core-js/object/assign":48}],58:[function(require,module,exports){
"use strict";
var _Object$getOwnPropertyDescriptor = require("babel-runtime/core-js/object/get-own-property-descriptor")["default"];
exports["default"] = function get(_x, _x2, _x3) {
var _again = true;
_function: while (_again) {
var object = _x,
property = _x2,
receiver = _x3;
desc = parent = getter = undefined;
_again = false;
if (object === null) object = Function.prototype;
var desc = _Object$getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return undefined;
} else {
_x = parent;
_x2 = property;
_x3 = receiver;
_again = true;
continue _function;
}
} else if ("value" in desc) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
}
};
exports.__esModule = true;
},{"babel-runtime/core-js/object/get-own-property-descriptor":51}],59:[function(require,module,exports){
"use strict";
var _Object$create = require("babel-runtime/core-js/object/create")["default"];
var _Object$setPrototypeOf = require("babel-runtime/core-js/object/set-prototype-of")["default"];
exports["default"] = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = _Object$create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) _Object$setPrototypeOf ? _Object$setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
exports.__esModule = true;
},{"babel-runtime/core-js/object/create":49,"babel-runtime/core-js/object/set-prototype-of":53}],60:[function(require,module,exports){
"use strict";
exports["default"] = function (obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
};
exports.__esModule = true;
},{}],61:[function(require,module,exports){
"use strict";
exports["default"] = function (obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
}
newObj["default"] = obj;
return newObj;
}
};
exports.__esModule = true;
},{}],62:[function(require,module,exports){
"use strict";
var _getIterator = require("babel-runtime/core-js/get-iterator")["default"];
var _isIterable = require("babel-runtime/core-js/is-iterable")["default"];
exports["default"] = (function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = _getIterator(arr), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (_isIterable(Object(arr))) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
})();
exports.__esModule = true;
},{"babel-runtime/core-js/get-iterator":45,"babel-runtime/core-js/is-iterable":46}],63:[function(require,module,exports){
require('../modules/web.dom.iterable');
require('../modules/es6.string.iterator');
module.exports = require('../modules/core.get-iterator');
},{"../modules/core.get-iterator":120,"../modules/es6.string.iterator":130,"../modules/web.dom.iterable":133}],64:[function(require,module,exports){
require('../modules/web.dom.iterable');
require('../modules/es6.string.iterator');
module.exports = require('../modules/core.is-iterable');
},{"../modules/core.is-iterable":121,"../modules/es6.string.iterator":130,"../modules/web.dom.iterable":133}],65:[function(require,module,exports){
require('../modules/es6.object.to-string');
require('../modules/es6.string.iterator');
require('../modules/web.dom.iterable');
require('../modules/es6.map');
require('../modules/es7.map.to-json');
module.exports = require('../modules/$.core').Map;
},{"../modules/$.core":81,"../modules/es6.map":123,"../modules/es6.object.to-string":128,"../modules/es6.string.iterator":130,"../modules/es7.map.to-json":131,"../modules/web.dom.iterable":133}],66:[function(require,module,exports){
require('../../modules/es6.object.assign');
module.exports = require('../../modules/$.core').Object.assign;
},{"../../modules/$.core":81,"../../modules/es6.object.assign":124}],67:[function(require,module,exports){
var $ = require('../../modules/$');
module.exports = function create(P, D){
return $.create(P, D);
};
},{"../../modules/$":99}],68:[function(require,module,exports){
var $ = require('../../modules/$');
module.exports = function defineProperty(it, key, desc){
return $.setDesc(it, key, desc);
};
},{"../../modules/$":99}],69:[function(require,module,exports){
var $ = require('../../modules/$');
require('../../modules/es6.object.get-own-property-descriptor');
module.exports = function getOwnPropertyDescriptor(it, key){
return $.getDesc(it, key);
};
},{"../../modules/$":99,"../../modules/es6.object.get-own-property-descriptor":125}],70:[function(require,module,exports){
require('../../modules/es6.object.keys');
module.exports = require('../../modules/$.core').Object.keys;
},{"../../modules/$.core":81,"../../modules/es6.object.keys":126}],71:[function(require,module,exports){
require('../../modules/es6.object.set-prototype-of');
module.exports = require('../../modules/$.core').Object.setPrototypeOf;
},{"../../modules/$.core":81,"../../modules/es6.object.set-prototype-of":127}],72:[function(require,module,exports){
require('../modules/es6.object.to-string');
require('../modules/es6.string.iterator');
require('../modules/web.dom.iterable');
require('../modules/es6.set');
require('../modules/es7.set.to-json');
module.exports = require('../modules/$.core').Set;
},{"../modules/$.core":81,"../modules/es6.object.to-string":128,"../modules/es6.set":129,"../modules/es6.string.iterator":130,"../modules/es7.set.to-json":132,"../modules/web.dom.iterable":133}],73:[function(require,module,exports){
module.exports = function(it){
if(typeof it != 'function')throw TypeError(it + ' is not a function!');
return it;
};
},{}],74:[function(require,module,exports){
var isObject = require('./$.is-object');
module.exports = function(it){
if(!isObject(it))throw TypeError(it + ' is not an object!');
return it;
};
},{"./$.is-object":93}],75:[function(require,module,exports){
// 19.1.2.1 Object.assign(target, source, ...)
var toObject = require('./$.to-object')
, IObject = require('./$.iobject')
, enumKeys = require('./$.enum-keys')
, has = require('./$.has');
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = require('./$.fails')(function(){
var a = Object.assign
, A = {}
, B = {}
, S = Symbol()
, K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function(k){ B[k] = k; });
return a({}, A)[S] != 7 || Object.keys(a({}, B)).join('') != K;
}) ? function assign(target, source){ // eslint-disable-line no-unused-vars
var T = toObject(target)
, l = arguments.length
, i = 1;
while(l > i){
var S = IObject(arguments[i++])
, keys = enumKeys(S)
, length = keys.length
, j = 0
, key;
while(length > j)if(has(S, key = keys[j++]))T[key] = S[key];
}
return T;
} : Object.assign;
},{"./$.enum-keys":85,"./$.fails":86,"./$.has":89,"./$.iobject":91,"./$.to-object":115}],76:[function(require,module,exports){
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = require('./$.cof')
, TAG = require('./$.wks')('toStringTag')
// ES3 wrong here
, ARG = cof(function(){ return arguments; }()) == 'Arguments';
module.exports = function(it){
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = (O = Object(it))[TAG]) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
},{"./$.cof":77,"./$.wks":118}],77:[function(require,module,exports){
var toString = {}.toString;
module.exports = function(it){
return toString.call(it).slice(8, -1);
};
},{}],78:[function(require,module,exports){
'use strict';
var $ = require('./$')
, hide = require('./$.hide')
, ctx = require('./$.ctx')
, species = require('./$.species')
, strictNew = require('./$.strict-new')
, defined = require('./$.defined')
, forOf = require('./$.for-of')
, step = require('./$.iter-step')
, ID = require('./$.uid')('id')
, $has = require('./$.has')
, isObject = require('./$.is-object')
, isExtensible = Object.isExtensible || isObject
, SUPPORT_DESC = require('./$.support-desc')
, SIZE = SUPPORT_DESC ? '_s' : 'size'
, id = 0;
var fastKey = function(it, create){
// return primitive with prefix
if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if(!$has(it, 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];
};
var getEntry = function(that, key){
// fast case
var index = fastKey(key), entry;
if(index !== 'F')return that._i[index];
// frozen object case
for(entry = that._f; entry; entry = entry.n){
if(entry.k == key)return entry;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
strictNew(that, C, NAME);
that._i = $.create(null); // index
that._f = undefined; // first entry
that._l = undefined; // last entry
that[SIZE] = 0; // size
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
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._i, entry = that._f; entry; entry = entry.n){
entry.r = true;
if(entry.p)entry.p = entry.p.n = undefined;
delete data[entry.i];
}
that._f = that._l = undefined;
that[SIZE] = 0;
},
// 23.1.3.3 Map.prototype.delete(key)
// 23.2.3.4 Set.prototype.delete(value)
'delete': function(key){
var that = this
, entry = getEntry(that, key);
if(entry){
var next = entry.n
, prev = entry.p;
delete that._i[entry.i];
entry.r = true;
if(prev)prev.n = next;
if(next)next.p = prev;
if(that._f == entry)that._f = next;
if(that._l == entry)that._l = prev;
that[SIZE]--;
} return !!entry;
},
// 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
// 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
forEach: function forEach(callbackfn /*, that = undefined */){
var f = ctx(callbackfn, arguments[1], 3)
, entry;
while(entry = entry ? entry.n : this._f){
f(entry.v, entry.k, this);
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
}
},
// 23.1.3.7 Map.prototype.has(key)
// 23.2.3.7 Set.prototype.has(value)
has: function has(key){
return !!getEntry(this, key);
}
});
if(SUPPORT_DESC)$.setDesc(C.prototype, 'size', {
get: function(){
return defined(this[SIZE]);
}
});
return C;
},
def: function(that, key, value){
var entry = getEntry(that, key)
, prev, index;
// change existing entry
if(entry){
entry.v = value;
// create new entry
} else {
that._l = entry = {
i: index = fastKey(key, true), // <- index
k: key, // <- key
v: value, // <- value
p: prev = that._l, // <- previous entry
n: undefined, // <- next entry
r: false // <- removed
};
if(!that._f)that._f = entry;
if(prev)prev.n = entry;
that[SIZE]++;
// add to index
if(index !== 'F')that._i[index] = entry;
} return that;
},
getEntry: getEntry,
setStrong: function(C, NAME, IS_MAP){
// add .keys, .values, .entries, [@@iterator]
// 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
require('./$.iter-define')(C, NAME, function(iterated, kind){
this._t = iterated; // target
this._k = kind; // kind
this._l = undefined; // previous
}, function(){
var that = this
, kind = that._k
, entry = that._l;
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
// get next entry
if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){
// or finish the iteration
that._t = undefined;
return step(1);
}
// return step by kind
if(kind == 'keys' )return step(0, entry.k);
if(kind == 'values')return step(0, entry.v);
return step(0, [entry.k, entry.v]);
}, IS_MAP ? 'entries' : 'values' , !IS_MAP, true);
// add [@@species], 23.1.2.2, 23.2.2.2
species(C);
species(require('./$.core')[NAME]); // for wrapper
}
};
},{"./$":99,"./$.core":81,"./$.ctx":82,"./$.defined":84,"./$.for-of":87,"./$.has":89,"./$.hide":90,"./$.is-object":93,"./$.iter-define":96,"./$.iter-step":97,"./$.mix":101,"./$.species":107,"./$.strict-new":108,"./$.support-desc":110,"./$.uid":116}],79:[function(require,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var forOf = require('./$.for-of')
, classof = require('./$.classof');
module.exports = function(NAME){
return function toJSON(){
if(classof(this) != NAME)throw TypeError(NAME + "#toJSON isn't generic");
var arr = [];
forOf(this, false, arr.push, arr);
return arr;
};
};
},{"./$.classof":76,"./$.for-of":87}],80:[function(require,module,exports){
'use strict';
var $ = require('./$')
, $def = require('./$.def')
, hide = require('./$.hide')
, forOf = require('./$.for-of')
, strictNew = require('./$.strict-new');
module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){
var Base = require('./$.global')[NAME]
, C = Base
, ADDER = IS_MAP ? 'set' : 'add'
, proto = C && C.prototype
, O = {};
if(!require('./$.support-desc') || typeof C != 'function'
|| !(IS_WEAK || proto.forEach && !require('./$.fails')(function(){ new C().entries().next(); }))
){
// create collection constructor
C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
require('./$.mix')(C.prototype, methods);
} else {
C = wrapper(function(target, iterable){
strictNew(target, C, NAME);
target._c = new Base;
if(iterable != undefined)forOf(iterable, IS_MAP, target[ADDER], target);
});
$.each.call('add,clear,delete,forEach,get,has,set,keys,values,entries'.split(','),function(KEY){
var chain = KEY == 'add' || KEY == 'set';
if(KEY in proto && !(IS_WEAK && KEY == 'clear'))hide(C.prototype, KEY, function(a, b){
var result = this._c[KEY](a === 0 ? 0 : a, b);
return chain ? this : result;
});
});
if('size' in proto)$.setDesc(C.prototype, 'size', {
get: function(){
return this._c.size;
}
});
}
require('./$.tag')(C, NAME);
O[NAME] = C;
$def($def.G + $def.W + $def.F, O);
if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP);
return C;
};
},{"./$":99,"./$.def":83,"./$.fails":86,"./$.for-of":87,"./$.global":88,"./$.hide":90,"./$.mix":101,"./$.strict-new":108,"./$.support-desc":110,"./$.tag":111}],81:[function(require,module,exports){
var core = module.exports = {version: '1.2.1'};
if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
},{}],82:[function(require,module,exports){
// optional / simple context binding
var aFunction = require('./$.a-function');
module.exports = function(fn, that, length){
aFunction(fn);
if(that === undefined)return fn;
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
case 2: return function(a, b){
return fn.call(that, a, b);
};
case 3: return function(a, b, c){
return fn.call(that, a, b, c);
};
}
return function(/* ...args */){
return fn.apply(that, arguments);
};
};
},{"./$.a-function":73}],83:[function(require,module,exports){
var global = require('./$.global')
, core = require('./$.core')
, PROTOTYPE = 'prototype';
var ctx = function(fn, that){
return function(){
return fn.apply(that, arguments);
};
};
var $def = function(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;
if(own && key in exports)continue;
// export native or passed
out = own ? target[key] : source[key];
// prevent global pollution for namespaces
if(isGlobal && typeof target[key] != 'function')exp = source[key];
// bind timers to global for call from export context
else if(type & $def.B && own)exp = ctx(out, global);
// wrap global constructors for prevent change them in library
else if(type & $def.W && target[key] == out)!function(C){
exp = function(param){
return this instanceof C ? new C(param) : C(param);
};
exp[PROTOTYPE] = C[PROTOTYPE];
}(out);
else exp = isProto && typeof out == 'function' ? ctx(Function.call, out) : out;
// export
exports[key] = exp;
if(isProto)(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[key] = out;
}
};
// 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
module.exports = $def;
},{"./$.core":81,"./$.global":88}],84:[function(require,module,exports){
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
};
},{}],85:[function(require,module,exports){
// all enumerable object keys, includes symbols
var $ = require('./$');
module.exports = function(it){
var keys = $.getKeys(it)
, getSymbols = $.getSymbols;
if(getSymbols){
var symbols = getSymbols(it)
, isEnum = $.isEnum
, i = 0
, key;
while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))keys.push(key);
}
return keys;
};
},{"./$":99}],86:[function(require,module,exports){
module.exports = function(exec){
try {
return !!exec();
} catch(e){
return true;
}
};
},{}],87:[function(require,module,exports){
var ctx = require('./$.ctx')
, call = require('./$.iter-call')
, isArrayIter = require('./$.is-array-iter')
, anObject = require('./$.an-object')
, toLength = require('./$.to-length')
, getIterFn = require('./core.get-iterator-method');
module.exports = function(iterable, entries, fn, that){
var iterFn = getIterFn(iterable)
, f = ctx(fn, that, entries ? 2 : 1)
, index = 0
, length, step, iterator;
if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!');
// fast case for arrays with default iterator
if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){
entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
} else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){
call(iterator, f, step.value, entries);
}
};
},{"./$.an-object":74,"./$.ctx":82,"./$.is-array-iter":92,"./$.iter-call":94,"./$.to-length":114,"./core.get-iterator-method":119}],88:[function(require,module,exports){
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var UNDEFINED = 'undefined';
var global = module.exports = typeof window != UNDEFINED && window.Math == Math
? window : typeof self != UNDEFINED && self.Math == Math ? self : Function('return this')();
if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
},{}],89:[function(require,module,exports){
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function(it, key){
return hasOwnProperty.call(it, key);
};
},{}],90:[function(require,module,exports){
var $ = require('./$')
, createDesc = require('./$.property-desc');
module.exports = require('./$.support-desc') ? function(object, key, value){
return $.setDesc(object, key, createDesc(1, value));
} : function(object, key, value){
object[key] = value;
return object;
};
},{"./$":99,"./$.property-desc":103,"./$.support-desc":110}],91:[function(require,module,exports){
// indexed object, fallback for non-array-like ES3 strings
var cof = require('./$.cof');
module.exports = 0 in Object('z') ? Object : function(it){
return cof(it) == 'String' ? it.split('') : Object(it);
};
},{"./$.cof":77}],92:[function(require,module,exports){
// check on default Array iterator
var Iterators = require('./$.iterators')
, ITERATOR = require('./$.wks')('iterator');
module.exports = function(it){
return (Iterators.Array || Array.prototype[ITERATOR]) === it;
};
},{"./$.iterators":98,"./$.wks":118}],93:[function(require,module,exports){
module.exports = function(it){
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
},{}],94:[function(require,module,exports){
// call something on iterator step with safe closing on error
var anObject = require('./$.an-object');
module.exports = function(iterator, fn, value, entries){
try {
return entries ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch(e){
var ret = iterator['return'];
if(ret !== undefined)anObject(ret.call(iterator));
throw e;
}
};
},{"./$.an-object":74}],95:[function(require,module,exports){
'use strict';
var $ = require('./$')
, IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
require('./$.hide')(IteratorPrototype, require('./$.wks')('iterator'), function(){ return this; });
module.exports = function(Constructor, NAME, next){
Constructor.prototype = $.create(IteratorPrototype, {next: require('./$.property-desc')(1,next)});
require('./$.tag')(Constructor, NAME + ' Iterator');
};
},{"./$":99,"./$.hide":90,"./$.property-desc":103,"./$.tag":111,"./$.wks":118}],96:[function(require,module,exports){
'use strict';
var LIBRARY = require('./$.library')
, $def = require('./$.def')
, $redef = require('./$.redef')
, hide = require('./$.hide')
, has = require('./$.has')
, SYMBOL_ITERATOR = require('./$.wks')('iterator')
, Iterators = require('./$.iterators')
, BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next`
, FF_ITERATOR = '@@iterator'
, KEYS = 'keys'
, VALUES = 'values';
var returnThis = function(){ return this; };
module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCE){
require('./$.iter-create')(Constructor, NAME, next);
var createMethod = function(kind){
switch(kind){
case KEYS: return function keys(){ return new Constructor(this, kind); };
case VALUES: return function values(){ return new Constructor(this, kind); };
} return function entries(){ return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator'
, 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 = require('./$').getProto(_default.call(new Base));
// Set @@toStringTag to native iterators
require('./$.tag')(IteratorPrototype, TAG, true);
// FF fix
if(!LIBRARY && has(proto, FF_ITERATOR))hide(IteratorPrototype, SYMBOL_ITERATOR, returnThis);
}
// Define iterator
if(!LIBRARY || FORCE)hide(proto, SYMBOL_ITERATOR, _default);
// Plug for library
Iterators[NAME] = _default;
Iterators[TAG] = returnThis;
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 * BUGGY, NAME, methods);
}
};
},{"./$":99,"./$.def":83,"./$.has":89,"./$.hide":90,"./$.iter-create":95,"./$.iterators":98,"./$.library":100,"./$.redef":104,"./$.tag":111,"./$.wks":118}],97:[function(require,module,exports){
module.exports = function(done, value){
return {value: value, done: !!done};
};
},{}],98:[function(require,module,exports){
module.exports = {};
},{}],99:[function(require,module,exports){
var $Object = Object;
module.exports = {
create: $Object.create,
getProto: $Object.getPrototypeOf,
isEnum: {}.propertyIsEnumerable,
getDesc: $Object.getOwnPropertyDescriptor,
setDesc: $Object.defineProperty,
setDescs: $Object.defineProperties,
getKeys: $Object.keys,
getNames: $Object.getOwnPropertyNames,
getSymbols: $Object.getOwnPropertySymbols,
each: [].forEach
};
},{}],100:[function(require,module,exports){
module.exports = true;
},{}],101:[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":104}],102:[function(require,module,exports){
// most Object methods by ES6 should accept primitives
module.exports = function(KEY, exec){
var $def = require('./$.def')
, fn = (require('./$.core').Object || {})[KEY] || Object[KEY]
, exp = {};
exp[KEY] = exec(fn);
$def($def.S + $def.F * require('./$.fails')(function(){ fn(1); }), 'Object', exp);
};
},{"./$.core":81,"./$.def":83,"./$.fails":86}],103:[function(require,module,exports){
module.exports = function(bitmap, value){
return {
enumerable : !(bitmap & 1),
configurable: !(bitmap & 2),
writable : !(bitmap & 4),
value : value
};
};
},{}],104:[function(require,module,exports){
module.exports = require('./$.hide');
},{"./$.hide":90}],105:[function(require,module,exports){
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var getDesc = require('./$').getDesc
, isObject = require('./$.is-object')
, anObject = require('./$.an-object');
var check = function(O, proto){
anObject(O);
if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line no-proto
function(test, buggy, set){
try {
set = require('./$.ctx')(Function.call, getDesc(Object.prototype, '__proto__').set, 2);
set(test, []);
buggy = !(test instanceof Array);
} catch(e){ buggy = true; }
return function setPrototypeOf(O, proto){
check(O, proto);
if(buggy)O.__proto__ = proto;
else set(O, proto);
return O;
};
}({}, false) : undefined),
check: check
};
},{"./$":99,"./$.an-object":74,"./$.ctx":82,"./$.is-object":93}],106:[function(require,module,exports){
var global = require('./$.global')
, SHARED = '__core-js_shared__'
, store = global[SHARED] || (global[SHARED] = {});
module.exports = function(key){
return store[key] || (store[key] = {});
};
},{"./$.global":88}],107:[function(require,module,exports){
'use strict';
var $ = require('./$')
, SPECIES = require('./$.wks')('species');
module.exports = function(C){
if(require('./$.support-desc') && !(SPECIES in C))$.setDesc(C, SPECIES, {
configurable: true,
get: function(){ return this; }
});
};
},{"./$":99,"./$.support-desc":110,"./$.wks":118}],108:[function(require,module,exports){
module.exports = function(it, Constructor, name){
if(!(it instanceof Constructor))throw TypeError(name + ": use the 'new' operator!");
return it;
};
},{}],109:[function(require,module,exports){
// true -> String#at
// false -> String#codePointAt
var toInteger = require('./$.to-integer')
, defined = require('./$.defined');
module.exports = function(TO_STRING){
return function(that, pos){
var s = String(defined(that))
, i = toInteger(pos)
, l = s.length
, a, b;
if(i < 0 || i >= l)return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l
|| (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
},{"./$.defined":84,"./$.to-integer":112}],110:[function(require,module,exports){
// Thank's IE8 for his funny defineProperty
module.exports = !require('./$.fails')(function(){
return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
});
},{"./$.fails":86}],111:[function(require,module,exports){
var has = require('./$.has')
, hide = require('./$.hide')
, TAG = require('./$.wks')('toStringTag');
module.exports = function(it, tag, stat){
if(it && !has(it = stat ? it : it.prototype, TAG))hide(it, TAG, tag);
};
},{"./$.has":89,"./$.hide":90,"./$.wks":118}],112:[function(require,module,exports){
// 7.1.4 ToInteger
var ceil = Math.ceil
, floor = Math.floor;
module.exports = function(it){
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
},{}],113:[function(require,module,exports){
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = require('./$.iobject')
, defined = require('./$.defined');
module.exports = function(it){
return IObject(defined(it));
};
},{"./$.defined":84,"./$.iobject":91}],114:[function(require,module,exports){
// 7.1.15 ToLength
var toInteger = require('./$.to-integer')
, min = Math.min;
module.exports = function(it){
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
},{"./$.to-integer":112}],115:[function(require,module,exports){
// 7.1.13 ToObject(argument)
var defined = require('./$.defined');
module.exports = function(it){
return Object(defined(it));
};
},{"./$.defined":84}],116:[function(require,module,exports){
var id = 0
, px = Math.random();
module.exports = function(key){
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
},{}],117:[function(require,module,exports){
module.exports = function(){ /* empty */ };
},{}],118:[function(require,module,exports){
var store = require('./$.shared')('wks')
, Symbol = require('./$.global').Symbol;
module.exports = function(name){
return store[name] || (store[name] =
Symbol && Symbol[name] || (Symbol || require('./$.uid'))('Symbol.' + name));
};
},{"./$.global":88,"./$.shared":106,"./$.uid":116}],119:[function(require,module,exports){
var classof = require('./$.classof')
, ITERATOR = require('./$.wks')('iterator')
, Iterators = require('./$.iterators');
module.exports = require('./$.core').getIteratorMethod = function(it){
if(it != undefined)return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)];
};
},{"./$.classof":76,"./$.core":81,"./$.iterators":98,"./$.wks":118}],120:[function(require,module,exports){
var anObject = require('./$.an-object')
, get = require('./core.get-iterator-method');
module.exports = require('./$.core').getIterator = function(it){
var iterFn = get(it);
if(typeof iterFn != 'function')throw TypeError(it + ' is not iterable!');
return anObject(iterFn.call(it));
};
},{"./$.an-object":74,"./$.core":81,"./core.get-iterator-method":119}],121:[function(require,module,exports){
var classof = require('./$.classof')
, ITERATOR = require('./$.wks')('iterator')
, Iterators = require('./$.iterators');
module.exports = require('./$.core').isIterable = function(it){
var O = Object(it);
return ITERATOR in O || '@@iterator' in O || Iterators.hasOwnProperty(classof(O));
};
},{"./$.classof":76,"./$.core":81,"./$.iterators":98,"./$.wks":118}],122:[function(require,module,exports){
'use strict';
var setUnscope = require('./$.unscope')
, step = require('./$.iter-step')
, Iterators = require('./$.iterators')
, toIObject = require('./$.to-iobject');
// 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){
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function(){
var O = this._t
, kind = this._k
, index = this._i++;
if(!O || index >= O.length){
this._t = undefined;
return step(1);
}
if(kind == 'keys' )return step(0, index);
if(kind == 'values')return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
setUnscope('keys');
setUnscope('values');
setUnscope('entries');
},{"./$.iter-define":96,"./$.iter-step":97,"./$.iterators":98,"./$.to-iobject":113,"./$.unscope":117}],123:[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":80,"./$.collection-strong":78}],124:[function(require,module,exports){
// 19.1.3.1 Object.assign(target, source)
var $def = require('./$.def');
$def($def.S + $def.F, 'Object', {assign: require('./$.assign')});
},{"./$.assign":75,"./$.def":83}],125:[function(require,module,exports){
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
var toIObject = require('./$.to-iobject');
require('./$.object-sap')('getOwnPropertyDescriptor', function($getOwnPropertyDescriptor){
return function getOwnPropertyDescriptor(it, key){
return $getOwnPropertyDescriptor(toIObject(it), key);
};
});
},{"./$.object-sap":102,"./$.to-iobject":113}],126:[function(require,module,exports){
// 19.1.2.14 Object.keys(O)
var toObject = require('./$.to-object');
require('./$.object-sap')('keys', function($keys){
return function keys(it){
return $keys(toObject(it));
};
});
},{"./$.object-sap":102,"./$.to-object":115}],127:[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":83,"./$.set-proto":105}],128:[function(require,module,exports){
},{}],129:[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":80,"./$.collection-strong":78}],130:[function(require,module,exports){
'use strict';
var $at = require('./$.string-at')(true);
// 21.1.3.27 String.prototype[@@iterator]()
require('./$.iter-define')(String, 'String', function(iterated){
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function(){
var O = this._t
, index = this._i
, point;
if(index >= O.length)return {value: undefined, done: true};
point = $at(O, index);
this._i += point.length;
return {value: point, done: false};
});
},{"./$.iter-define":96,"./$.string-at":109}],131:[function(require,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $def = require('./$.def');
$def($def.P, 'Map', {toJSON: require('./$.collection-to-json')('Map')});
},{"./$.collection-to-json":79,"./$.def":83}],132:[function(require,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $def = require('./$.def');
$def($def.P, 'Set', {toJSON: require('./$.collection-to-json')('Set')});
},{"./$.collection-to-json":79,"./$.def":83}],133:[function(require,module,exports){
require('./es6.array.iterator');
var Iterators = require('./$.iterators');
Iterators.NodeList = Iterators.HTMLCollection = Iterators.Array;
},{"./$.iterators":98,"./es6.array.iterator":122}],134:[function(require,module,exports){
/**
* Copyright (c) 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.
*/
// Predicates
/**
* These are all of the possible kinds of types.
*/
'use strict';
var _createClass = require('babel-runtime/helpers/create-class')['default'];
var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default'];
var _extends = require('babel-runtime/helpers/extends')['default'];
var _Object$keys = require('babel-runtime/core-js/object/keys')['default'];
var _Map = require('babel-runtime/core-js/map')['default'];
var _Object$create = require('babel-runtime/core-js/object/create')['default'];
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.isType = isType;
/**
* These types may be used as input types for arguments and directives.
*/
exports.isInputType = isInputType;
/**
* These types may be used as output types as the result of fields.
*/
exports.isOutputType = isOutputType;
/**
* These types may describe types which may be leaf values.
*/
exports.isLeafType = isLeafType;
/**
* These types may describe the parent context of a selection set.
*/
exports.isCompositeType = isCompositeType;
/**
* These types may describe the parent context of a selection set.
*/
exports.isAbstractType = isAbstractType;
/**
* These types can all accept null as a value.
*/
exports.getNullableType = getNullableType;
/**
* These named types do not include modifiers like List or NonNull.
*/
exports.getNamedType = getNamedType;
var _jsutilsInvariant = require('../jsutils/invariant');
var _jsutilsInvariant2 = _interopRequireDefault(_jsutilsInvariant);
var _jsutilsIsNullish = require('../jsutils/isNullish');
var _jsutilsIsNullish2 = _interopRequireDefault(_jsutilsIsNullish);
var _jsutilsKeyMap = require('../jsutils/keyMap');
var _jsutilsKeyMap2 = _interopRequireDefault(_jsutilsKeyMap);
var _languageKinds = require('../language/kinds');
function isType(type) {
return type instanceof GraphQLScalarType || type instanceof GraphQLObjectType || type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType || type instanceof GraphQLEnumType || type instanceof GraphQLInputObjectType || type instanceof GraphQLList || type instanceof GraphQLNonNull;
}
function isInputType(type) {
var namedType = getNamedType(type);
return namedType instanceof GraphQLScalarType || namedType instanceof GraphQLEnumType || namedType instanceof GraphQLInputObjectType;
}
function isOutputType(type) {
var namedType = getNamedType(type);
return namedType instanceof GraphQLScalarType || namedType instanceof GraphQLObjectType || namedType instanceof GraphQLInterfaceType || namedType instanceof GraphQLUnionType || namedType instanceof GraphQLEnumType;
}
function isLeafType(type) {
var namedType = getNamedType(type);
return namedType instanceof GraphQLScalarType || namedType instanceof GraphQLEnumType;
}
function isCompositeType(type) {
return type instanceof GraphQLObjectType || type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType;
}
function isAbstractType(type) {
return type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType;
}
function getNullableType(type) {
return type instanceof GraphQLNonNull ? type.ofType : type;
}
function getNamedType(type) {
var unmodifiedType = type;
while (unmodifiedType instanceof GraphQLList || unmodifiedType instanceof GraphQLNonNull) {
unmodifiedType = unmodifiedType.ofType;
}
return unmodifiedType;
}
/**
* Scalar Type Definition
*
* The leaf values of any request and input values to arguments are
* Scalars (or Enums) and are defined with a name and a series of functions
* used to parse input from ast or variables and to ensure validity.
*
* Example:
*
* var OddType = new GraphQLScalarType({
* name: 'Odd',
* serialize(value) {
* return value % 2 === 1 ? value : null;
* }
* });
*
*/
var GraphQLScalarType /* <T> */ = (function () {
/* <T> */
function GraphQLScalarType(config /* <T> */) {
_classCallCheck(this, GraphQLScalarType);
(0, _jsutilsInvariant2['default'])(config.name, 'Type must be named.');
assertValidName(config.name);
this.name = config.name;
this.description = config.description;
(0, _jsutilsInvariant2['default'])(typeof config.serialize === 'function', this + ' must provide "serialize" function. If this custom Scalar is ' + 'also used as an input type, ensure "parseValue" and "parseLiteral" ' + 'functions are also provided.');
if (config.parseValue || config.parseLiteral) {
(0, _jsutilsInvariant2['default'])(typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function', this + ' must provide both "parseValue" and "parseLiteral" functions.');
}
this._scalarConfig = config;
}
_createClass(GraphQLScalarType, [{
key: 'serialize',
value: function serialize(value) /* T */{
var serializer = this._scalarConfig.serialize;
return serializer(value);
}
}, {
key: 'parseValue',
value: function parseValue(value) /* T */{
var parser = this._scalarConfig.parseValue;
return parser ? parser(value) : null;
}
}, {
key: 'parseLiteral',
value: function parseLiteral(valueAST) /* T */{
var parser = this._scalarConfig.parseLiteral;
return parser ? parser(valueAST) : null;
}
}, {
key: 'toString',
value: function toString() {
return this.name;
}
}]);
return GraphQLScalarType;
})();
exports.GraphQLScalarType = GraphQLScalarType;
/* T */
/**
* Object Type Definition
*
* Almost all of the GraphQL types you define will be object types. Object types
* have a name, but most importantly describe their fields.
*
* Example:
*
* var AddressType = new GraphQLObjectType({
* name: 'Address',
* fields: {
* street: { type: GraphQLString },
* number: { type: GraphQLInt },
* formatted: {
* type: GraphQLString,
* resolve(obj) {
* return obj.number + ' ' + obj.street
* }
* }
* }
* });
*
* When two types need to refer to each other, or a type needs to refer to
* itself in a field, you can use a function expression (aka a closure or a
* thunk) to supply the fields lazily.
*
* Example:
*
* var PersonType = new GraphQLObjectType({
* name: 'Person',
* fields: () => ({
* name: { type: GraphQLString },
* bestFriend: { type: PersonType },
* })
* });
*
*/
var GraphQLObjectType = (function () {
function GraphQLObjectType(config) {
_classCallCheck(this, GraphQLObjectType);
(0, _jsutilsInvariant2['default'])(config.name, 'Type must be named.');
assertValidName(config.name);
this.name = config.name;
this.description = config.description;
if (config.isTypeOf) {
(0, _jsutilsInvariant2['default'])(typeof config.isTypeOf === 'function', this + ' must provide "isTypeOf" as a function.');
}
this.isTypeOf = config.isTypeOf;
this._typeConfig = config;
addImplementationToInterfaces(this);
}
_createClass(GraphQLObjectType, [{
key: 'getFields',
value: function getFields() {
return this._fields || (this._fields = defineFieldMap(this, this._typeConfig.fields));
}
}, {
key: 'getInterfaces',
value: function getInterfaces() {
return this._interfaces || (this._interfaces = defineInterfaces(this, this._typeConfig.interfaces));
}
}, {
key: 'toString',
value: function toString() {
return this.name;
}
}]);
return GraphQLObjectType;
})();
exports.GraphQLObjectType = GraphQLObjectType;
function resolveMaybeThunk(thingOrThunk) {
return typeof thingOrThunk === 'function' ? thingOrThunk() : thingOrThunk;
}
function defineInterfaces(type, interfacesOrThunk) {
var interfaces = resolveMaybeThunk(interfacesOrThunk);
if (!interfaces) {
return [];
}
(0, _jsutilsInvariant2['default'])(Array.isArray(interfaces), type + ' interfaces must be an Array or a function which returns an Array.');
interfaces.forEach(function (iface) {
(0, _jsutilsInvariant2['default'])(iface instanceof GraphQLInterfaceType, type + ' may only implement Interface types, it cannot ' + ('implement: ' + iface + '.'));
if (typeof iface.resolveType !== 'function') {
(0, _jsutilsInvariant2['default'])(typeof type.isTypeOf === 'function', 'Interface Type ' + iface + ' does not provide a "resolveType" function ' + ('and implementing Type ' + type + ' does not provide a "isTypeOf" ') + 'function. There is no way to resolve this implementing type ' + 'during execution.');
}
});
return interfaces;
}
function defineFieldMap(type, fields) {
var fieldMap = resolveMaybeThunk(fields);
(0, _jsutilsInvariant2['default'])(isPlainObj(fieldMap), type + ' fields must be an object with field names as keys or a ' + 'function which returns such an object.');
var fieldNames = _Object$keys(fieldMap);
(0, _jsutilsInvariant2['default'])(fieldNames.length > 0, type + ' fields must be an object with field names as keys or a ' + 'function which returns such an object.');
var resultFieldMap = {};
fieldNames.forEach(function (fieldName) {
assertValidName(fieldName);
var field = _extends({}, fieldMap[fieldName], {
name: fieldName
});
(0, _jsutilsInvariant2['default'])(!field.hasOwnProperty('isDeprecated'), type + '.' + fieldName + ' should provide "deprecationReason" instead ' + 'of "isDeprecated".');
(0, _jsutilsInvariant2['default'])(isOutputType(field.type), type + '.' + fieldName + ' field type must be Output Type but ' + ('got: ' + field.type + '.'));
if (!field.args) {
field.args = [];
} else {
(0, _jsutilsInvariant2['default'])(isPlainObj(field.args), type + '.' + fieldName + ' args must be an object with argument names ' + 'as keys.');
field.args = _Object$keys(field.args).map(function (argName) {
assertValidName(argName);
var arg = field.args[argName];
(0, _jsutilsInvariant2['default'])(isInputType(arg.type), type + '.' + fieldName + '(' + argName + ':) argument type must be ' + ('Input Type but got: ' + arg.type + '.'));
return {
name: argName,
description: arg.description === undefined ? null : arg.description,
type: arg.type,
defaultValue: arg.defaultValue === undefined ? null : arg.defaultValue
};
});
}
resultFieldMap[fieldName] = field;
});
return resultFieldMap;
}
function isPlainObj(obj) {
return obj && typeof obj === 'object' && !Array.isArray(obj);
}
/**
* Update the interfaces to know about this implementation.
* This is an rare and unfortunate use of mutation in the type definition
* implementations, but avoids an expensive "getPossibleTypes"
* implementation for Interface types.
*/
function addImplementationToInterfaces(impl) {
impl.getInterfaces().forEach(function (type) {
type._implementations.push(impl);
});
}
/**
* Interface Type Definition
*
* When a field can return one of a heterogeneous set of types, a Interface type
* is used to describe what types are possible, what fields are in common across
* all types, as well as a function to determine which type is actually used
* when the field is resolved.
*
* Example:
*
* var EntityType = new GraphQLInterfaceType({
* name: 'Entity',
* fields: {
* name: { type: GraphQLString }
* }
* });
*
*/
var GraphQLInterfaceType = (function () {
function GraphQLInterfaceType(config) {
_classCallCheck(this, GraphQLInterfaceType);
(0, _jsutilsInvariant2['default'])(config.name, 'Type must be named.');
assertValidName(config.name);
this.name = config.name;
this.description = config.description;
if (config.resolveType) {
(0, _jsutilsInvariant2['default'])(typeof config.resolveType === 'function', this + ' must provide "resolveType" as a function.');
}
this.resolveType = config.resolveType;
this._typeConfig = config;
this._implementations = [];
}
_createClass(GraphQLInterfaceType, [{
key: 'getFields',
value: function getFields() {
return this._fields || (this._fields = defineFieldMap(this, this._typeConfig.fields));
}
}, {
key: 'getPossibleTypes',
value: function getPossibleTypes() {
return this._implementations;
}
}, {
key: 'isPossibleType',
value: function isPossibleType(type) {
var possibleTypes = this._possibleTypes || (this._possibleTypes = (0, _jsutilsKeyMap2['default'])(this.getPossibleTypes(), function (possibleType) {
return possibleType.name;
}));
return Boolean(possibleTypes[type.name]);
}
}, {
key: 'getObjectType',
value: function getObjectType(value, info) {
var resolver = this.resolveType;
return resolver ? resolver(value, info) : getTypeOf(value, info, this);
}
}, {
key: 'toString',
value: function toString() {
return this.name;
}
}]);
return GraphQLInterfaceType;
})();
exports.GraphQLInterfaceType = GraphQLInterfaceType;
function getTypeOf(value, info, abstractType) {
var possibleTypes = abstractType.getPossibleTypes();
for (var i = 0; i < possibleTypes.length; i++) {
var type = possibleTypes[i];
if (typeof type.isTypeOf === 'function' && type.isTypeOf(value, info)) {
return type;
}
}
}
/**
* Union Type Definition
*
* When a field can return one of a heterogeneous set of types, a Union type
* is used to describe what types are possible as well as providing a function
* to determine which type is actually used when the field is resolved.
*
* Example:
*
* var PetType = new GraphQLUnionType({
* name: 'Pet',
* types: [ DogType, CatType ],
* resolveType(value) {
* if (value instanceof Dog) {
* return DogType;
* }
* if (value instanceof Cat) {
* return CatType;
* }
* }
* });
*
*/
var GraphQLUnionType = (function () {
function GraphQLUnionType(config) {
var _this = this;
_classCallCheck(this, GraphQLUnionType);
(0, _jsutilsInvariant2['default'])(config.name, 'Type must be named.');
assertValidName(config.name);
this.name = config.name;
this.description = config.description;
if (config.resolveType) {
(0, _jsutilsInvariant2['default'])(typeof config.resolveType === 'function', this + ' must provide "resolveType" as a function.');
}
this.resolveType = config.resolveType;
(0, _jsutilsInvariant2['default'])(Array.isArray(config.types) && config.types.length > 0, 'Must provide Array of types for Union ' + config.name + '.');
config.types.forEach(function (type) {
(0, _jsutilsInvariant2['default'])(type instanceof GraphQLObjectType, _this + ' may only contain Object types, it cannot contain: ' + type + '.');
if (typeof _this.resolveType !== 'function') {
(0, _jsutilsInvariant2['default'])(typeof type.isTypeOf === 'function', 'Union Type ' + _this + ' does not provide a "resolveType" function ' + ('and possible Type ' + type + ' does not provide a "isTypeOf" ') + 'function. There is no way to resolve this possible type ' + 'during execution.');
}
});
this._types = config.types;
this._typeConfig = config;
}
_createClass(GraphQLUnionType, [{
key: 'getPossibleTypes',
value: function getPossibleTypes() {
return this._types;
}
}, {
key: 'isPossibleType',
value: function isPossibleType(type) {
var possibleTypeNames = this._possibleTypeNames;
if (!possibleTypeNames) {
this._possibleTypeNames = possibleTypeNames = this.getPossibleTypes().reduce(function (map, possibleType) {
return (map[possibleType.name] = true, map);
}, {});
}
return possibleTypeNames[type.name] === true;
}
}, {
key: 'getObjectType',
value: function getObjectType(value, info) {
var resolver = this._typeConfig.resolveType;
return resolver ? resolver(value, info) : getTypeOf(value, info, this);
}
}, {
key: 'toString',
value: function toString() {
return this.name;
}
}]);
return GraphQLUnionType;
})();
exports.GraphQLUnionType = GraphQLUnionType;
/**
* Enum Type Definition
*
* Some leaf values of requests and input values are Enums. GraphQL serializes
* Enum values as strings, however internally Enums can be represented by any
* kind of type, often integers.
*
* Example:
*
* var RGBType = new GraphQLEnumType({
* name: 'RGB',
* values: {
* RED: { value: 0 },
* GREEN: { value: 1 },
* BLUE: { value: 2 }
* }
* });
*
* Note: If a value is not provided in a definition, the name of the enum value
* will be used as it's internal value.
*/
var GraphQLEnumType /* <T> */ = (function () {
function GraphQLEnumType(config /* <T> */) {
_classCallCheck(this, GraphQLEnumType);
this.name = config.name;
assertValidName(config.name);
this.description = config.description;
this._values = defineEnumValues(this, config.values);
this._enumConfig = config;
}
_createClass(GraphQLEnumType, [{
key: 'getValues',
value: function getValues() /* <T> */{
return this._values;
}
}, {
key: 'serialize',
value: function serialize(value /* T */) {
var enumValue = this._getValueLookup().get(value);
return enumValue ? enumValue.name : null;
}
}, {
key: 'parseValue',
value: function parseValue(value) /* T */{
var enumValue = this._getNameLookup()[value];
if (enumValue) {
return enumValue.value;
}
}
}, {
key: 'parseLiteral',
value: function parseLiteral(valueAST) /* T */{
if (valueAST.kind === _languageKinds.ENUM) {
var enumValue = this._getNameLookup()[valueAST.value];
if (enumValue) {
return enumValue.value;
}
}
}
}, {
key: '_getValueLookup',
value: function _getValueLookup() {
if (!this._valueLookup) {
var lookup = new _Map();
this.getValues().forEach(function (value) {
lookup.set(value.value, value);
});
this._valueLookup = lookup;
}
return this._valueLookup;
}
}, {
key: '_getNameLookup',
value: function _getNameLookup() {
if (!this._nameLookup) {
var lookup = _Object$create(null);
this.getValues().forEach(function (value) {
lookup[value.name] = value;
});
this._nameLookup = lookup;
}
return this._nameLookup;
}
}, {
key: 'toString',
value: function toString() {
return this.name;
}
}]);
return GraphQLEnumType;
})();
exports.GraphQLEnumType = GraphQLEnumType;
function defineEnumValues(type, valueMap /* <T> */
) /* <T> */{
(0, _jsutilsInvariant2['default'])(isPlainObj(valueMap), type + ' values must be an object with value names as keys.');
var valueNames = _Object$keys(valueMap);
(0, _jsutilsInvariant2['default'])(valueNames.length > 0, type + ' values must be an object with value names as keys.');
return valueNames.map(function (valueName) {
assertValidName(valueName);
var value = valueMap[valueName];
(0, _jsutilsInvariant2['default'])(isPlainObj(value), type + '.' + valueName + ' must refer to an object with a "value" key ' + ('representing an internal value but got: ' + value + '.'));
(0, _jsutilsInvariant2['default'])(!value.hasOwnProperty('isDeprecated'), type + '.' + valueName + ' should provide "deprecationReason" instead ' + 'of "isDeprecated".');
value.name = valueName;
if ((0, _jsutilsIsNullish2['default'])(value.value)) {
value.value = valueName;
}
return value;
});
}
/* <T> */
/**
* Input Object Type Definition
*
* An input object defines a structured collection of fields which may be
* supplied to a field argument.
*
* Using `NonNull` will ensure that a value must be provided by the query
*
* Example:
*
* var GeoPoint = new GraphQLInputObjectType({
* name: 'GeoPoint',
* fields: {
* lat: { type: new GraphQLNonNull(GraphQLFloat) },
* lon: { type: new GraphQLNonNull(GraphQLFloat) },
* alt: { type: GraphQLFloat, defaultValue: 0 },
* }
* });
*
*/
var GraphQLInputObjectType = (function () {
function GraphQLInputObjectType(config) {
_classCallCheck(this, GraphQLInputObjectType);
(0, _jsutilsInvariant2['default'])(config.name, 'Type must be named.');
assertValidName(config.name);
this.name = config.name;
this.description = config.description;
this._typeConfig = config;
}
_createClass(GraphQLInputObjectType, [{
key: 'getFields',
value: function getFields() {
return this._fields || (this._fields = this._defineFieldMap());
}
}, {
key: '_defineFieldMap',
value: function _defineFieldMap() {
var _this2 = this;
var fieldMap = resolveMaybeThunk(this._typeConfig.fields);
(0, _jsutilsInvariant2['default'])(isPlainObj(fieldMap), this + ' fields must be an object with field names as keys or a ' + 'function which returns such an object.');
var fieldNames = _Object$keys(fieldMap);
(0, _jsutilsInvariant2['default'])(fieldNames.length > 0, this + ' fields must be an object with field names as keys or a ' + 'function which returns such an object.');
var resultFieldMap = {};
fieldNames.forEach(function (fieldName) {
assertValidName(fieldName);
var field = _extends({}, fieldMap[fieldName], {
name: fieldName
});
(0, _jsutilsInvariant2['default'])(isInputType(field.type), _this2 + '.' + fieldName + ' field type must be Input Type but ' + ('got: ' + field.type + '.'));
resultFieldMap[fieldName] = field;
});
return resultFieldMap;
}
}, {
key: 'toString',
value: function toString() {
return this.name;
}
}]);
return GraphQLInputObjectType;
})();
exports.GraphQLInputObjectType = GraphQLInputObjectType;
/**
* List Modifier
*
* A list is a kind of type marker, a wrapping type which points to another
* type. Lists are often created within the context of defining the fields of
* an object type.
*
* Example:
*
* var PersonType = new GraphQLObjectType({
* name: 'Person',
* fields: () => ({
* parents: { type: new GraphQLList(Person) },
* children: { type: new GraphQLList(Person) },
* })
* })
*
*/
var GraphQLList = (function () {
function GraphQLList(type) {
_classCallCheck(this, GraphQLList);
(0, _jsutilsInvariant2['default'])(isType(type), 'Can only create List of a GraphQLType but got: ' + type + '.');
this.ofType = type;
}
/**
* Non-Null Modifier
*
* A non-null is a kind of type marker, a wrapping type which points to another
* type. Non-null types enforce that their values are never null and can ensure
* an error is raised if this ever occurs during a request. It is useful for
* fields which you can make a strong guarantee on non-nullability, for example
* usually the id field of a database row will never be null.
*
* Example:
*
* var RowType = new GraphQLObjectType({
* name: 'Row',
* fields: () => ({
* id: { type: new GraphQLNonNull(GraphQLString) },
* })
* })
*
* Note: the enforcement of non-nullability occurs within the executor.
*/
_createClass(GraphQLList, [{
key: 'toString',
value: function toString() {
return '[' + String(this.ofType) + ']';
}
}]);
return GraphQLList;
})();
exports.GraphQLList = GraphQLList;
var GraphQLNonNull = (function () {
function GraphQLNonNull(type) {
_classCallCheck(this, GraphQLNonNull);
(0, _jsutilsInvariant2['default'])(isType(type) && !(type instanceof GraphQLNonNull), 'Can only create NonNull of a Nullable GraphQLType but got: ' + type + '.');
this.ofType = type;
}
_createClass(GraphQLNonNull, [{
key: 'toString',
value: function toString() {
return this.ofType.toString() + '!';
}
}]);
return GraphQLNonNull;
})();
exports.GraphQLNonNull = GraphQLNonNull;
var NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
// Helper to assert that provided names are valid.
function assertValidName(name) {
(0, _jsutilsInvariant2['default'])(NAME_RX.test(name), 'Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "' + name + '" does not.');
}
/* <T> */ /* T */ /* T */
/**
* Optionally provide a custom type resolver function. If one is not provided,
* the default implementation will call `isTypeOf` on each implementing
* Object type.
*/
/**
* Optionally provide a custom type resolver function. If one is not provided,
* the default implementation will call `isTypeOf` on each implementing
* Object type.
*/
/* <T> */ /* <T> */ /* T */ /* T */ /* <T> */ /* <T> */ /* <T> */ /* <T> */ /* T */ /* <T> */ /* T */
},{"../jsutils/invariant":33,"../jsutils/isNullish":34,"../jsutils/keyMap":35,"../language/kinds":38,"babel-runtime/core-js/map":47,"babel-runtime/core-js/object/create":49,"babel-runtime/core-js/object/keys":52,"babel-runtime/helpers/class-call-check":55,"babel-runtime/helpers/create-class":56,"babel-runtime/helpers/extends":57,"babel-runtime/helpers/interop-require-default":60}],135:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
var _definition = require('./definition');
var _scalars = require('./scalars');
/**
* Directives are used by the GraphQL runtime as a way of modifying execution
* behavior. Type system creators will usually not create these directly.
*/
var GraphQLDirective = function GraphQLDirective(config) {
_classCallCheck(this, GraphQLDirective);
this.name = config.name;
this.description = config.description;
this.args = config.args;
this.onOperation = config.onOperation;
this.onFragment = config.onFragment;
this.onField = config.onField;
};
exports.GraphQLDirective = GraphQLDirective;
/**
* Used to conditionally include fields or fragments
*/
var GraphQLIncludeDirective = new GraphQLDirective({
name: 'include',
description: 'Directs the executor to include this field or fragment only when ' + 'the `if` argument is true.',
args: [{ name: 'if',
type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean),
description: 'Included when true.' }],
onOperation: false,
onFragment: true,
onField: true
});
exports.GraphQLIncludeDirective = GraphQLIncludeDirective;
/**
* Used to conditionally skip (exclude) fields or fragments
*/
var GraphQLSkipDirective = new GraphQLDirective({
name: 'skip',
description: 'Directs the executor to skip this field or fragment when the `if` ' + 'argument is true.',
args: [{ name: 'if',
type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean),
description: 'Skipped when true.' }],
onOperation: false,
onFragment: true,
onField: true
});
exports.GraphQLSkipDirective = GraphQLSkipDirective;
},{"./definition":134,"./scalars":138,"babel-runtime/helpers/class-call-check":55}],136:[function(require,module,exports){
/**
* Copyright (c) 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.
*/
// GraphQL Schema definition
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _schema = require('./schema');
Object.defineProperty(exports, 'GraphQLSchema', {
enumerable: true,
get: function get() {
return _schema.GraphQLSchema;
}
});
var _definition = require('./definition');
Object.defineProperty(exports, 'isType', {
enumerable: true,
get: function get() {
return _definition.isType;
}
});
Object.defineProperty(exports, 'isInputType', {
enumerable: true,
get: function get() {
return _definition.isInputType;
}
});
Object.defineProperty(exports, 'isOutputType', {
enumerable: true,
get: function get() {
return _definition.isOutputType;
}
});
Object.defineProperty(exports, 'isLeafType', {
enumerable: true,
get: function get() {
return _definition.isLeafType;
}
});
Object.defineProperty(exports, 'isCompositeType', {
enumerable: true,
get: function get() {
return _definition.isCompositeType;
}
});
Object.defineProperty(exports, 'isAbstractType', {
enumerable: true,
get: function get() {
return _definition.isAbstractType;
}
});
Object.defineProperty(exports, 'getNullableType', {
enumerable: true,
get: function get() {
return _definition.getNullableType;
}
});
Object.defineProperty(exports, 'getNamedType', {
enumerable: true,
get: function get() {
return _definition.getNamedType;
}
});
Object.defineProperty(exports, 'GraphQLScalarType', {
enumerable: true,
get: function get() {
return _definition.GraphQLScalarType;
}
});
Object.defineProperty(exports, 'GraphQLObjectType', {
enumerable: true,
get: function get() {
return _definition.GraphQLObjectType;
}
});
Object.defineProperty(exports, 'GraphQLInterfaceType', {
enumerable: true,
get: function get() {
return _definition.GraphQLInterfaceType;
}
});
Object.defineProperty(exports, 'GraphQLUnionType', {
enumerable: true,
get: function get() {
return _definition.GraphQLUnionType;
}
});
Object.defineProperty(exports, 'GraphQLEnumType', {
enumerable: true,
get: function get() {
return _definition.GraphQLEnumType;
}
});
Object.defineProperty(exports, 'GraphQLInputObjectType', {
enumerable: true,
get: function get() {
return _definition.GraphQLInputObjectType;
}
});
Object.defineProperty(exports, 'GraphQLList', {
enumerable: true,
get: function get() {
return _definition.GraphQLList;
}
});
Object.defineProperty(exports, 'GraphQLNonNull', {
enumerable: true,
get: function get() {
return _definition.GraphQLNonNull;
}
});
// Common built-in scalar instances.
var _scalars = require('./scalars');
Object.defineProperty(exports, 'GraphQLInt', {
enumerable: true,
get: function get() {
return _scalars.GraphQLInt;
}
});
Object.defineProperty(exports, 'GraphQLFloat', {
enumerable: true,
get: function get() {
return _scalars.GraphQLFloat;
}
});
Object.defineProperty(exports, 'GraphQLString', {
enumerable: true,
get: function get() {
return _scalars.GraphQLString;
}
});
Object.defineProperty(exports, 'GraphQLBoolean', {
enumerable: true,
get: function get() {
return _scalars.GraphQLBoolean;
}
});
Object.defineProperty(exports, 'GraphQLID', {
enumerable: true,
get: function get() {
return _scalars.GraphQLID;
}
});
// Predicates
// Un-modifiers
// Definitions
},{"./definition":134,"./scalars":138,"./schema":139}],137:[function(require,module,exports){
/* weak */
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _Object$keys = require('babel-runtime/core-js/object/keys')['default'];
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
var _jsutilsIsNullish = require('../jsutils/isNullish');
var _jsutilsIsNullish2 = _interopRequireDefault(_jsutilsIsNullish);
var _utilitiesAstFromValue = require('../utilities/astFromValue');
var _languagePrinter = require('../language/printer');
var _definition = require('./definition');
var _scalars = require('./scalars');
var __Schema = new _definition.GraphQLObjectType({
name: '__Schema',
description: 'A GraphQL Schema defines the capabilities of a GraphQL server. It ' + 'exposes all available types and directives on the server, as well as ' + 'the entry points for query and mutation operations.',
fields: function fields() {
return {
types: {
description: 'A list of all types supported by this server.',
type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type))),
resolve: function resolve(schema) {
var typeMap = schema.getTypeMap();
return _Object$keys(typeMap).map(function (key) {
return typeMap[key];
});
}
},
queryType: {
description: 'The type that query operations will be rooted at.',
type: new _definition.GraphQLNonNull(__Type),
resolve: function resolve(schema) {
return schema.getQueryType();
}
},
mutationType: {
description: 'If this server supports mutation, the type that ' + 'mutation operations will be rooted at.',
type: __Type,
resolve: function resolve(schema) {
return schema.getMutationType();
}
},
directives: {
description: 'A list of all directives supported by this server.',
type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__Directive))),
resolve: function resolve(schema) {
return schema.getDirectives();
}
}
};
}
});
exports.__Schema = __Schema;
var __Directive = new _definition.GraphQLObjectType({
name: '__Directive',
description: 'A Directives provides a way to describe alternate runtime execution and ' + 'type validation behavior in a GraphQL document.' + '\n\nIn some cases, you need to provide options to alter GraphQL’s ' + 'execution behavior in ways field arguments will not suffice, such as ' + 'conditionally including or skipping a field. Directives provide this by ' + 'describing additional information to the executor.',
fields: function fields() {
return {
name: { type: new _definition.GraphQLNonNull(_scalars.GraphQLString) },
description: { type: _scalars.GraphQLString },
args: {
type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue))),
resolve: function resolve(directive) {
return directive.args || [];
}
},
onOperation: { type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean) },
onFragment: { type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean) },
onField: { type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean) }
};
}
});
var __Type = new _definition.GraphQLObjectType({
name: '__Type',
description: 'The fundamental unit of any GraphQL Schema is the type. There are ' + 'many kinds of types in GraphQL as represented by the `__TypeKind` enum.' + '\n\nDepending on the kind of a type, certain fields describe ' + 'information about that type. Scalar types provide no information ' + 'beyond a name and description, while Enum types provide their values. ' + 'Object and Interface types provide the fields they describe. Abstract ' + 'types, Union and Interface, provide the Object types possible ' + 'at runtime. List and NonNull types compose other types.',
fields: function fields() {
return {
kind: {
type: new _definition.GraphQLNonNull(__TypeKind),
resolve: function resolve(type) {
if (type instanceof _definition.GraphQLScalarType) {
return TypeKind.SCALAR;
} else if (type instanceof _definition.GraphQLObjectType) {
return TypeKind.OBJECT;
} else if (type instanceof _definition.GraphQLInterfaceType) {
return TypeKind.INTERFACE;
} else if (type instanceof _definition.GraphQLUnionType) {
return TypeKind.UNION;
} else if (type instanceof _definition.GraphQLEnumType) {
return TypeKind.ENUM;
} else if (type instanceof _definition.GraphQLInputObjectType) {
return TypeKind.INPUT_OBJECT;
} else if (type instanceof _definition.GraphQLList) {
return TypeKind.LIST;
} else if (type instanceof _definition.GraphQLNonNull) {
return TypeKind.NON_NULL;
}
throw new Error('Unknown kind of type: ' + type);
}
},
name: { type: _scalars.GraphQLString },
description: { type: _scalars.GraphQLString },
fields: {
type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Field)),
args: {
includeDeprecated: { type: _scalars.GraphQLBoolean, defaultValue: false }
},
resolve: function resolve(type, _ref) {
var includeDeprecated = _ref.includeDeprecated;
if (type instanceof _definition.GraphQLObjectType || type instanceof _definition.GraphQLInterfaceType) {
var fieldMap = type.getFields();
var fields = _Object$keys(fieldMap).map(function (fieldName) {
return fieldMap[fieldName];
});
if (!includeDeprecated) {
fields = fields.filter(function (field) {
return !field.deprecationReason;
});
}
return fields;
}
return null;
}
},
interfaces: {
type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)),
resolve: function resolve(type) {
if (type instanceof _definition.GraphQLObjectType) {
return type.getInterfaces();
}
}
},
possibleTypes: {
type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)),
resolve: function resolve(type) {
if (type instanceof _definition.GraphQLInterfaceType || type instanceof _definition.GraphQLUnionType) {
return type.getPossibleTypes();
}
}
},
enumValues: {
type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__EnumValue)),
args: {
includeDeprecated: { type: _scalars.GraphQLBoolean, defaultValue: false }
},
resolve: function resolve(type, _ref2) {
var includeDeprecated = _ref2.includeDeprecated;
if (type instanceof _definition.GraphQLEnumType) {
var values = type.getValues();
if (!includeDeprecated) {
values = values.filter(function (value) {
return !value.deprecationReason;
});
}
return values;
}
}
},
inputFields: {
type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue)),
resolve: function resolve(type) {
if (type instanceof _definition.GraphQLInputObjectType) {
var fieldMap = type.getFields();
return _Object$keys(fieldMap).map(function (fieldName) {
return fieldMap[fieldName];
});
}
}
},
ofType: { type: __Type }
};
}
});
var __Field = new _definition.GraphQLObjectType({
name: '__Field',
description: 'Object and Interface types are described by a list of Fields, each of ' + 'which has a name, potentially a list of arguments, and a return type.',
fields: function fields() {
return {
name: { type: new _definition.GraphQLNonNull(_scalars.GraphQLString) },
description: { type: _scalars.GraphQLString },
args: {
type: new _definition.GraphQLNonNull(new _definition.GraphQLList(new _definition.GraphQLNonNull(__InputValue))),
resolve: function resolve(field) {
return field.args || [];
}
},
type: { type: new _definition.GraphQLNonNull(__Type) },
isDeprecated: {
type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean),
resolve: function resolve(field) {
return !(0, _jsutilsIsNullish2['default'])(field.deprecationReason);
}
},
deprecationReason: {
type: _scalars.GraphQLString
}
};
}
});
var __InputValue = new _definition.GraphQLObjectType({
name: '__InputValue',
description: 'Arguments provided to Fields or Directives and the input fields of an ' + 'InputObject are represented as Input Values which describe their type ' + 'and optionally a default value.',
fields: function fields() {
return {
name: { type: new _definition.GraphQLNonNull(_scalars.GraphQLString) },
description: { type: _scalars.GraphQLString },
type: { type: new _definition.GraphQLNonNull(__Type) },
defaultValue: {
type: _scalars.GraphQLString,
description: 'A GraphQL-formatted string representing the default value for this ' + 'input value.',
resolve: function resolve(inputVal) {
return inputVal.defaultValue == null ? null : (0, _languagePrinter.print)((0, _utilitiesAstFromValue.astFromValue)(inputVal.defaultValue, inputVal));
}
}
};
}
});
var __EnumValue = new _definition.GraphQLObjectType({
name: '__EnumValue',
description: 'One possible value for a given Enum. Enum values are unique values, not ' + 'a placeholder for a string or numeric value. However an Enum value is ' + 'returned in a JSON response as a string.',
fields: {
name: { type: new _definition.GraphQLNonNull(_scalars.GraphQLString) },
description: { type: _scalars.GraphQLString },
isDeprecated: {
type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean),
resolve: function resolve(enumValue) {
return !(0, _jsutilsIsNullish2['default'])(enumValue.deprecationReason);
}
},
deprecationReason: {
type: _scalars.GraphQLString
}
}
});
var TypeKind = {
SCALAR: 'SCALAR',
OBJECT: 'OBJECT',
INTERFACE: 'INTERFACE',
UNION: 'UNION',
ENUM: 'ENUM',
INPUT_OBJECT: 'INPUT_OBJECT',
LIST: 'LIST',
NON_NULL: 'NON_NULL'
};
exports.TypeKind = TypeKind;
var __TypeKind = new _definition.GraphQLEnumType({
name: '__TypeKind',
description: 'An enum describing what kind of type a given `__Type` is.',
values: {
SCALAR: {
value: TypeKind.SCALAR,
description: 'Indicates this type is a scalar.'
},
OBJECT: {
value: TypeKind.OBJECT,
description: 'Indicates this type is an object. ' + '`fields` and `interfaces` are valid fields.'
},
INTERFACE: {
value: TypeKind.INTERFACE,
description: 'Indicates this type is an interface. ' + '`fields` and `possibleTypes` are valid fields.'
},
UNION: {
value: TypeKind.UNION,
description: 'Indicates this type is a union. ' + '`possibleTypes` is a valid field.'
},
ENUM: {
value: TypeKind.ENUM,
description: 'Indicates this type is an enum. ' + '`enumValues` is a valid field.'
},
INPUT_OBJECT: {
value: TypeKind.INPUT_OBJECT,
description: 'Indicates this type is an input object. ' + '`inputFields` is a valid field.'
},
LIST: {
value: TypeKind.LIST,
description: 'Indicates this type is a list. ' + '`ofType` is a valid field.'
},
NON_NULL: {
value: TypeKind.NON_NULL,
description: 'Indicates this type is a non-null. ' + '`ofType` is a valid field.'
}
}
});
/**
* Note that these are GraphQLFieldDefinition and not GraphQLFieldConfig,
* so the format for args is different.
*/
var SchemaMetaFieldDef = {
name: '__schema',
type: new _definition.GraphQLNonNull(__Schema),
description: 'Access the current type schema of this server.',
args: [],
resolve: function resolve(source, args, _ref3) {
var schema = _ref3.schema;
return schema;
}
};
exports.SchemaMetaFieldDef = SchemaMetaFieldDef;
var TypeMetaFieldDef = {
name: '__type',
type: __Type,
description: 'Request the type information of a single type.',
args: [{ name: 'name', type: new _definition.GraphQLNonNull(_scalars.GraphQLString) }],
resolve: function resolve(source, _ref4, _ref5) {
var name = _ref4.name;
var schema = _ref5.schema;
return schema.getType(name);
}
};
exports.TypeMetaFieldDef = TypeMetaFieldDef;
var TypeNameMetaFieldDef = {
name: '__typename',
type: new _definition.GraphQLNonNull(_scalars.GraphQLString),
description: 'The name of the current Object type at runtime.',
args: [],
resolve: function resolve(source, args, _ref6) {
var parentType = _ref6.parentType;
return parentType.name;
}
};
exports.TypeNameMetaFieldDef = TypeNameMetaFieldDef;
},{"../jsutils/isNullish":34,"../language/printer":42,"../utilities/astFromValue":141,"./definition":134,"./scalars":138,"babel-runtime/core-js/object/keys":52,"babel-runtime/helpers/interop-require-default":60}],138:[function(require,module,exports){
/**
* Copyright (c) 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';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _definition = require('./definition');
var _language = require('../language');
// Integers are only safe when between -(2^53 - 1) and 2^53 - 1 due to being
// encoded in JavaScript and represented in JSON as double-precision floating
// point numbers, as specified by IEEE 754.
var MAX_INT = 9007199254740991;
var MIN_INT = -9007199254740991;
function coerceInt(value) {
var num = Number(value);
if (num === num && num <= MAX_INT && num >= MIN_INT) {
return (num < 0 ? Math.ceil : Math.floor)(num);
}
return null;
}
var GraphQLInt = new _definition.GraphQLScalarType({
name: 'Int',
description: 'The `Int` scalar type represents non-fractional signed whole numeric ' + 'values. Int can represent values between -(2^53 - 1) and 2^53 - 1 since ' + 'represented in JSON as double-precision floating point numbers specified' + 'by [IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point).',
serialize: coerceInt,
parseValue: coerceInt,
parseLiteral: function parseLiteral(ast) {
if (ast.kind === _language.Kind.INT) {
var num = parseInt(ast.value, 10);
if (num <= MAX_INT && num >= MIN_INT) {
return num;
}
}
return null;
}
});
exports.GraphQLInt = GraphQLInt;
function coerceFloat(value) {
var num = Number(value);
return num === num ? num : null;
}
var GraphQLFloat = new _definition.GraphQLScalarType({
name: 'Float',
description: 'The `Float` scalar type represents signed double-precision fractional ' + 'values as specified by ' + '[IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point). ',
serialize: coerceFloat,
parseValue: coerceFloat,
parseLiteral: function parseLiteral(ast) {
return ast.kind === _language.Kind.FLOAT || ast.kind === _language.Kind.INT ? parseFloat(ast.value) : null;
}
});
exports.GraphQLFloat = GraphQLFloat;
var GraphQLString = new _definition.GraphQLScalarType({
name: 'String',
description: 'The `String` scalar type represents textual data, represented as UTF-8 ' + 'character sequences. The String type is most often used by GraphQL to ' + 'represent free-form human-readable text.',
serialize: String,
parseValue: String,
parseLiteral: function parseLiteral(ast) {
return ast.kind === _language.Kind.STRING ? ast.value : null;
}
});
exports.GraphQLString = GraphQLString;
var GraphQLBoolean = new _definition.GraphQLScalarType({
name: 'Boolean',
description: 'The `Boolean` scalar type represents `true` or `false`.',
serialize: Boolean,
parseValue: Boolean,
parseLiteral: function parseLiteral(ast) {
return ast.kind === _language.Kind.BOOLEAN ? ast.value : null;
}
});
exports.GraphQLBoolean = GraphQLBoolean;
var GraphQLID = new _definition.GraphQLScalarType({
name: 'ID',
description: 'The `ID` scalar type represents a unique identifier, often used to ' + 'refetch an object or as key for a cache. The ID type appears in a JSON ' + 'response as a String; however, it is not intended to be human-readable. ' + 'When expected as an input type, any string (such as `"4"`) or integer ' + '(such as `4`) input value will be accepted as an ID.',
serialize: String,
parseValue: String,
parseLiteral: function parseLiteral(ast) {
return ast.kind === _language.Kind.STRING || ast.kind === _language.Kind.INT ? ast.value : null;
}
});
exports.GraphQLID = GraphQLID;
},{"../language":37,"./definition":134}],139:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _createClass = require('babel-runtime/helpers/create-class')['default'];
var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default'];
var _Object$keys = require('babel-runtime/core-js/object/keys')['default'];
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
var _definition = require('./definition');
var _directives = require('./directives');
var _introspection = require('./introspection');
var _jsutilsFind = require('../jsutils/find');
var _jsutilsFind2 = _interopRequireDefault(_jsutilsFind);
var _jsutilsInvariant = require('../jsutils/invariant');
var _jsutilsInvariant2 = _interopRequireDefault(_jsutilsInvariant);
/**
* Schema Definition
*
* A Schema is created by supplying the root types of each type of operation,
* query and mutation (optional). A schema definition is then supplied to the
* validator and executor.
*
* Example:
*
* var MyAppSchema = new GraphQLSchema({
* query: MyAppQueryRootType
* mutation: MyAppMutationRootType
* });
*
*/
var GraphQLSchema = (function () {
function GraphQLSchema(config) {
var _this = this;
_classCallCheck(this, GraphQLSchema);
(0, _jsutilsInvariant2['default'])(typeof config === 'object', 'Must provide configuration object.');
(0, _jsutilsInvariant2['default'])(config.query instanceof _definition.GraphQLObjectType, 'Schema query must be Object Type but got: ' + config.query + '.');
(0, _jsutilsInvariant2['default'])(!config.mutation || config.mutation instanceof _definition.GraphQLObjectType, 'Schema mutation must be Object Type if provided but ' + ('got: ' + config.mutation + '.'));
this._schemaConfig = config;
// Build type map now to detect any errors within this schema.
this._typeMap = [this.getQueryType(), this.getMutationType(), _introspection.__Schema].reduce(typeMapReducer, {});
// Enforce correct interface implementations
_Object$keys(this._typeMap).forEach(function (typeName) {
var type = _this._typeMap[typeName];
if (type instanceof _definition.GraphQLObjectType) {
type.getInterfaces().forEach(function (iface) {
return assertObjectImplementsInterface(type, iface);
});
}
});
}
_createClass(GraphQLSchema, [{
key: 'getQueryType',
value: function getQueryType() {
return this._schemaConfig.query;
}
}, {
key: 'getMutationType',
value: function getMutationType() {
return this._schemaConfig.mutation;
}
}, {
key: 'getTypeMap',
value: function getTypeMap() {
return this._typeMap;
}
}, {
key: 'getType',
value: function getType(name) {
return this.getTypeMap()[name];
}
}, {
key: 'getDirectives',
value: function getDirectives() {
return this._directives || (this._directives = [_directives.GraphQLIncludeDirective, _directives.GraphQLSkipDirective]);
}
}, {
key: 'getDirective',
value: function getDirective(name) {
return (0, _jsutilsFind2['default'])(this.getDirectives(), function (directive) {
return directive.name === name;
});
}
}]);
return GraphQLSchema;
})();
exports.GraphQLSchema = GraphQLSchema;
function typeMapReducer(_x, _x2) {
var _again = true;
_function: while (_again) {
var map = _x,
type = _x2;
reducedMap = fieldMap = undefined;
_again = false;
if (!type) {
return map;
}
if (type instanceof _definition.GraphQLList || type instanceof _definition.GraphQLNonNull) {
_x = map;
_x2 = type.ofType;
_again = true;
continue _function;
}
if (map[type.name]) {
(0, _jsutilsInvariant2['default'])(map[type.name] === type, 'Schema must contain unique named types but contains multiple ' + ('types named "' + type + '".'));
return map;
}
map[type.name] = type;
var reducedMap = map;
if (type instanceof _definition.GraphQLUnionType || type instanceof _definition.GraphQLInterfaceType) {
reducedMap = type.getPossibleTypes().reduce(typeMapReducer, reducedMap);
}
if (type instanceof _definition.GraphQLObjectType) {
reducedMap = type.getInterfaces().reduce(typeMapReducer, reducedMap);
}
if (type instanceof _definition.GraphQLObjectType || type instanceof _definition.GraphQLInterfaceType || type instanceof _definition.GraphQLInputObjectType) {
var fieldMap = type.getFields();
_Object$keys(fieldMap).forEach(function (fieldName) {
var field = fieldMap[fieldName];
if (field.args) {
var fieldArgTypes = field.args.map(function (arg) {
return arg.type;
});
reducedMap = fieldArgTypes.reduce(typeMapReducer, reducedMap);
}
reducedMap = typeMapReducer(reducedMap, field.type);
});
}
return reducedMap;
}
}
function assertObjectImplementsInterface(object, iface) {
var objectFieldMap = object.getFields();
var ifaceFieldMap = iface.getFields();
// Assert each interface field is implemented.
_Object$keys(ifaceFieldMap).forEach(function (fieldName) {
var objectField = objectFieldMap[fieldName];
var ifaceField = ifaceFieldMap[fieldName];
// Assert interface field exists on object.
(0, _jsutilsInvariant2['default'])(objectField, '"' + iface + '" expects field "' + fieldName + '" but "' + object + '" does not ' + 'provide it.');
// Assert interface field type matches object field type. (invariant)
(0, _jsutilsInvariant2['default'])(isEqualType(ifaceField.type, objectField.type), iface + '.' + fieldName + ' expects type "' + ifaceField.type + '" but ' + (object + '.' + fieldName + ' provides type "' + objectField.type + '".'));
// Assert each interface field arg is implemented.
ifaceField.args.forEach(function (ifaceArg) {
var argName = ifaceArg.name;
var objectArg = (0, _jsutilsFind2['default'])(objectField.args, function (arg) {
return arg.name === argName;
});
// Assert interface field arg exists on object field.
(0, _jsutilsInvariant2['default'])(objectArg, iface + '.' + fieldName + ' expects argument "' + argName + '" but ' + (object + '.' + fieldName + ' does not provide it.'));
// Assert interface field arg type matches object field arg type.
// (invariant)
(0, _jsutilsInvariant2['default'])(isEqualType(ifaceArg.type, objectArg.type), iface + '.' + fieldName + '(' + argName + ':) expects type "' + ifaceArg.type + '" ' + ('but ' + object + '.' + fieldName + '(' + argName + ':) provides ') + ('type "' + objectArg.type + '".'));
});
// Assert argument set invariance.
objectField.args.forEach(function (objectArg) {
var argName = objectArg.name;
var ifaceArg = (0, _jsutilsFind2['default'])(ifaceField.args, function (arg) {
return arg.name === argName;
});
(0, _jsutilsInvariant2['default'])(ifaceArg, iface + '.' + fieldName + ' does not define argument "' + argName + '" but ' + (object + '.' + fieldName + ' provides it.'));
});
});
}
function isEqualType(_x3, _x4) {
var _again2 = true;
_function2: while (_again2) {
var typeA = _x3,
typeB = _x4;
_again2 = false;
if (typeA instanceof _definition.GraphQLNonNull && typeB instanceof _definition.GraphQLNonNull) {
_x3 = typeA.ofType;
_x4 = typeB.ofType;
_again2 = true;
continue _function2;
}
if (typeA instanceof _definition.GraphQLList && typeB instanceof _definition.GraphQLList) {
_x3 = typeA.ofType;
_x4 = typeB.ofType;
_again2 = true;
continue _function2;
}
return typeA === typeB;
}
}
},{"../jsutils/find":32,"../jsutils/invariant":33,"./definition":134,"./directives":135,"./introspection":137,"babel-runtime/core-js/object/keys":52,"babel-runtime/helpers/class-call-check":55,"babel-runtime/helpers/create-class":56,"babel-runtime/helpers/interop-require-default":60}],140:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _createClass = require('babel-runtime/helpers/create-class')['default'];
var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default'];
var _interopRequireWildcard = require('babel-runtime/helpers/interop-require-wildcard')['default'];
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
var _languageKinds = require('../language/kinds');
var Kind = _interopRequireWildcard(_languageKinds);
var _typeDefinition = require('../type/definition');
var _typeIntrospection = require('../type/introspection');
var _typeFromAST = require('./typeFromAST');
var _jsutilsFind = require('../jsutils/find');
var _jsutilsFind2 = _interopRequireDefault(_jsutilsFind);
/**
* TypeInfo is a utility class which, given a GraphQL schema, can keep track
* of the current field and type definitions at any point in a GraphQL document
* AST during a recursive descent by calling `enter(node)` and `leave(node)`.
*/
var TypeInfo = (function () {
function TypeInfo(schema) {
_classCallCheck(this, TypeInfo);
this._schema = schema;
this._typeStack = [];
this._parentTypeStack = [];
this._inputTypeStack = [];
this._fieldDefStack = [];
this._directive = null;
this._argument = null;
}
/**
* Not exactly the same as the executor's definition of getFieldDef, in this
* statically evaluated environment we do not always have an Object type,
* and need to handle Interface and Union types.
*/
_createClass(TypeInfo, [{
key: 'getType',
value: function getType() {
if (this._typeStack.length > 0) {
return this._typeStack[this._typeStack.length - 1];
}
}
}, {
key: 'getParentType',
value: function getParentType() {
if (this._parentTypeStack.length > 0) {
return this._parentTypeStack[this._parentTypeStack.length - 1];
}
}
}, {
key: 'getInputType',
value: function getInputType() {
if (this._inputTypeStack.length > 0) {
return this._inputTypeStack[this._inputTypeStack.length - 1];
}
}
}, {
key: 'getFieldDef',
value: function getFieldDef() {
if (this._fieldDefStack.length > 0) {
return this._fieldDefStack[this._fieldDefStack.length - 1];
}
}
}, {
key: 'getDirective',
value: function getDirective() {
return this._directive;
}
}, {
key: 'getArgument',
value: function getArgument() {
return this._argument;
}
// Flow does not yet handle this case.
}, {
key: 'enter',
value: function enter(node /* Node */) {
var schema = this._schema;
var type;
switch (node.kind) {
case Kind.SELECTION_SET:
var namedType = (0, _typeDefinition.getNamedType)(this.getType());
var compositeType;
if ((0, _typeDefinition.isCompositeType)(namedType)) {
// isCompositeType is a type refining predicate, so this is safe.
compositeType = namedType;
}
this._parentTypeStack.push(compositeType);
break;
case Kind.FIELD:
var parentType = this.getParentType();
var fieldDef;
if (parentType) {
fieldDef = getFieldDef(schema, parentType, node);
}
this._fieldDefStack.push(fieldDef);
this._typeStack.push(fieldDef && fieldDef.type);
break;
case Kind.DIRECTIVE:
this._directive = schema.getDirective(node.name.value);
break;
case Kind.OPERATION_DEFINITION:
if (node.operation === 'query') {
type = schema.getQueryType();
} else if (node.operation === 'mutation') {
type = schema.getMutationType();
}
this._typeStack.push(type);
break;
case Kind.INLINE_FRAGMENT:
case Kind.FRAGMENT_DEFINITION:
var typeConditionAST = node.typeCondition;
type = typeConditionAST ? (0, _typeFromAST.typeFromAST)(schema, typeConditionAST) : this.getType();
this._typeStack.push(type);
break;
case Kind.VARIABLE_DEFINITION:
this._inputTypeStack.push((0, _typeFromAST.typeFromAST)(schema, node.type));
break;
case Kind.ARGUMENT:
var argDef;
var argType;
var fieldOrDirective = this.getDirective() || this.getFieldDef();
if (fieldOrDirective) {
argDef = (0, _jsutilsFind2['default'])(fieldOrDirective.args, function (arg) {
return arg.name === node.name.value;
});
if (argDef) {
argType = argDef.type;
}
}
this._argument = argDef;
this._inputTypeStack.push(argType);
break;
case Kind.LIST:
var listType = (0, _typeDefinition.getNullableType)(this.getInputType());
this._inputTypeStack.push(listType instanceof _typeDefinition.GraphQLList ? listType.ofType : undefined);
break;
case Kind.OBJECT_FIELD:
var objectType = (0, _typeDefinition.getNamedType)(this.getInputType());
var fieldType;
if (objectType instanceof _typeDefinition.GraphQLInputObjectType) {
var inputField = objectType.getFields()[node.name.value];
fieldType = inputField ? inputField.type : undefined;
}
this._inputTypeStack.push(fieldType);
break;
}
}
}, {
key: 'leave',
value: function leave(node) {
switch (node.kind) {
case Kind.SELECTION_SET:
this._parentTypeStack.pop();
break;
case Kind.FIELD:
this._fieldDefStack.pop();
this._typeStack.pop();
break;
case Kind.DIRECTIVE:
this._directive = null;
break;
case Kind.OPERATION_DEFINITION:
case Kind.INLINE_FRAGMENT:
case Kind.FRAGMENT_DEFINITION:
this._typeStack.pop();
break;
case Kind.VARIABLE_DEFINITION:
this._inputTypeStack.pop();
break;
case Kind.ARGUMENT:
this._argument = null;
this._inputTypeStack.pop();
break;
case Kind.LIST:
case Kind.OBJECT_FIELD:
this._inputTypeStack.pop();
break;
}
}
}]);
return TypeInfo;
})();
exports.TypeInfo = TypeInfo;
function getFieldDef(schema, parentType, fieldAST) {
var name = fieldAST.name.value;
if (name === _typeIntrospection.SchemaMetaFieldDef.name && schema.getQueryType() === parentType) {
return _typeIntrospection.SchemaMetaFieldDef;
}
if (name === _typeIntrospection.TypeMetaFieldDef.name && schema.getQueryType() === parentType) {
return _typeIntrospection.TypeMetaFieldDef;
}
if (name === _typeIntrospection.TypeNameMetaFieldDef.name && (parentType instanceof _typeDefinition.GraphQLObjectType || parentType instanceof _typeDefinition.GraphQLInterfaceType || parentType instanceof _typeDefinition.GraphQLUnionType)) {
return _typeIntrospection.TypeNameMetaFieldDef;
}
if (parentType instanceof _typeDefinition.GraphQLObjectType || parentType instanceof _typeDefinition.GraphQLInterfaceType) {
return parentType.getFields()[name];
}
}
},{"../jsutils/find":32,"../language/kinds":38,"../type/definition":134,"../type/introspection":137,"./typeFromAST":150,"babel-runtime/helpers/class-call-check":55,"babel-runtime/helpers/create-class":56,"babel-runtime/helpers/interop-require-default":60,"babel-runtime/helpers/interop-require-wildcard":61}],141:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _Object$keys = require('babel-runtime/core-js/object/keys')['default'];
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.astFromValue = astFromValue;
var _jsutilsInvariant = require('../jsutils/invariant');
var _jsutilsInvariant2 = _interopRequireDefault(_jsutilsInvariant);
var _jsutilsIsNullish = require('../jsutils/isNullish');
var _jsutilsIsNullish2 = _interopRequireDefault(_jsutilsIsNullish);
var _languageKinds = require('../language/kinds');
var _typeDefinition = require('../type/definition');
var _typeScalars = require('../type/scalars');
/**
* Produces a GraphQL Value AST given a JavaScript value.
*
* Optionally, a GraphQL type may be provided, which will be used to
* disambiguate between value primitives.
*
* | JSON Value | GraphQL Value |
* | ------------- | -------------------- |
* | Object | Input Object |
* | Array | List |
* | Boolean | Boolean |
* | String | String / Enum Value |
* | Number | Int / Float |
*
*/
function astFromValue(_x, _x2) {
var _again = true;
_function: while (_again) {
var value = _x,
type = _x2;
itemType = stringNum = isIntValue = fields = undefined;
_again = false;
if (type instanceof _typeDefinition.GraphQLNonNull) {
// Note: we're not checking that the result is non-null.
// This function is not responsible for validating the input value.
_x = value;
_x2 = type.ofType;
_again = true;
continue _function;
}
if ((0, _jsutilsIsNullish2['default'])(value)) {
return null;
}
// Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but
// the value is not an array, convert the value using the list's item type.
if (Array.isArray(value)) {
var itemType = type instanceof _typeDefinition.GraphQLList ? type.ofType : null;
return {
kind: _languageKinds.LIST,
values: value.map(function (item) {
return astFromValue(item, itemType);
})
};
} else if (type instanceof _typeDefinition.GraphQLList) {
// Because GraphQL will accept single values as a "list of one" when
// expecting a list, if there's a non-array value and an expected list type,
// create an AST using the list's item type.
_x = value;
_x2 = type.ofType;
_again = true;
continue _function;
}
if (typeof value === 'boolean') {
return { kind: _languageKinds.BOOLEAN, value: value };
}
// JavaScript numbers can be Float or Int values. Use the GraphQLType to
// differentiate if available, otherwise prefer Int if the value is a
// valid Int.
if (typeof value === 'number') {
var stringNum = String(value);
var isIntValue = /^[0-9]+$/.test(stringNum);
if (isIntValue) {
if (type === _typeScalars.GraphQLFloat) {
return { kind: _languageKinds.FLOAT, value: stringNum + '.0' };
}
return { kind: _languageKinds.INT, value: stringNum };
}
return { kind: _languageKinds.FLOAT, value: stringNum };
}
// JavaScript strings can be Enum values or String values. Use the
// GraphQLType to differentiate if possible.
if (typeof value === 'string') {
if (type instanceof _typeDefinition.GraphQLEnumType && /^[_a-zA-Z][_a-zA-Z0-9]*$/.test(value)) {
return { kind: _languageKinds.ENUM, value: value };
}
// Use JSON stringify, which uses the same string encoding as GraphQL,
// then remove the quotes.
return { kind: _languageKinds.STRING, value: JSON.stringify(value).slice(1, -1) };
}
// last remaining possible typeof
(0, _jsutilsInvariant2['default'])(typeof value === 'object');
// Populate the fields of the input object by creating ASTs from each value
// in the JavaScript object.
var fields = [];
_Object$keys(value).forEach(function (fieldName) {
var fieldType;
if (type instanceof _typeDefinition.GraphQLInputObjectType) {
var fieldDef = type.getFields()[fieldName];
fieldType = fieldDef && fieldDef.type;
}
var fieldValue = astFromValue(value[fieldName], fieldType);
if (fieldValue) {
fields.push({
kind: _languageKinds.OBJECT_FIELD,
name: { kind: _languageKinds.NAME, value: fieldName },
value: fieldValue
});
}
});
return { kind: _languageKinds.OBJECT, fields: fields };
}
}
},{"../jsutils/invariant":33,"../jsutils/isNullish":34,"../language/kinds":38,"../type/definition":134,"../type/scalars":138,"babel-runtime/core-js/object/keys":52,"babel-runtime/helpers/interop-require-default":60}],142:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.buildASTSchema = buildASTSchema;
var _jsutilsIsNullish = require('../jsutils/isNullish');
var _jsutilsIsNullish2 = _interopRequireDefault(_jsutilsIsNullish);
var _jsutilsKeyMap = require('../jsutils/keyMap');
var _jsutilsKeyMap2 = _interopRequireDefault(_jsutilsKeyMap);
var _jsutilsKeyValMap = require('../jsutils/keyValMap');
var _jsutilsKeyValMap2 = _interopRequireDefault(_jsutilsKeyValMap);
var _valueFromAST = require('./valueFromAST');
var _languageKinds = require('../language/kinds');
var _type = require('../type');
function buildWrappedType(innerType, inputTypeAST) {
if (inputTypeAST.kind === _languageKinds.LIST_TYPE) {
return new _type.GraphQLList(buildWrappedType(innerType, inputTypeAST.type));
}
if (inputTypeAST.kind === _languageKinds.NON_NULL_TYPE) {
return new _type.GraphQLNonNull(buildWrappedType(innerType, inputTypeAST.type));
}
return innerType;
}
function getInnerTypeName(_x) {
var _again = true;
_function: while (_again) {
var typeAST = _x;
_again = false;
if (typeAST.kind === _languageKinds.LIST_TYPE || typeAST.kind === _languageKinds.NON_NULL_TYPE) {
_x = typeAST.type;
_again = true;
continue _function;
}
return typeAST.name.value;
}
}
/**
* This takes the ast of a schema document produced by parseSchema in
* src/language/schema/parser.js.
*
* Given that AST it constructs a GraphQLSchema. As constructed
* they are not particularly useful for non-introspection queries
* since they have no resolve methods.
*/
function buildASTSchema(ast, queryTypeName, mutationTypeName) {
if ((0, _jsutilsIsNullish2['default'])(ast)) {
throw new Error('must pass in ast');
}
if ((0, _jsutilsIsNullish2['default'])(queryTypeName)) {
throw new Error('must pass in query type');
}
var typeDefs = ast.definitions.filter(function (d) {
switch (d.kind) {
case _languageKinds.OBJECT_TYPE_DEFINITION:
case _languageKinds.INTERFACE_TYPE_DEFINITION:
case _languageKinds.ENUM_TYPE_DEFINITION:
case _languageKinds.UNION_TYPE_DEFINITION:
case _languageKinds.SCALAR_TYPE_DEFINITION:
case _languageKinds.INPUT_OBJECT_TYPE_DEFINITION:
return true;
}
});
var astMap = (0, _jsutilsKeyMap2['default'])(typeDefs, function (d) {
return d.name.value;
});
if ((0, _jsutilsIsNullish2['default'])(astMap[queryTypeName])) {
throw new Error('Specified query type ' + queryTypeName + ' not found in document.');
}
if (!(0, _jsutilsIsNullish2['default'])(mutationTypeName) && (0, _jsutilsIsNullish2['default'])(astMap[mutationTypeName])) {
throw new Error('Specified mutation type ' + mutationTypeName + ' not found in document.');
}
/**
* This generates a function that allows you to produce
* type definitions on demand. We produce the function
* in order to close over the memoization dictionaries
* that need to be retained over multiple functions calls.
**/
function getTypeDefProducer() {
var innerTypeMap = {
String: _type.GraphQLString,
Int: _type.GraphQLInt,
Float: _type.GraphQLFloat,
Boolean: _type.GraphQLBoolean,
ID: _type.GraphQLID
};
return function (typeAST) {
var typeName = getInnerTypeName(typeAST);
if (!(0, _jsutilsIsNullish2['default'])(innerTypeMap[typeName])) {
return buildWrappedType(innerTypeMap[typeName], typeAST);
}
if ((0, _jsutilsIsNullish2['default'])(astMap[typeName])) {
throw new Error('Type ' + typeName + ' not found in document');
}
var innerTypeDef = makeSchemaDef(astMap[typeName]);
if ((0, _jsutilsIsNullish2['default'])(innerTypeDef)) {
throw new Error('Nothing constructed for ' + typeName);
}
innerTypeMap[typeName] = innerTypeDef;
return buildWrappedType(innerTypeDef, typeAST);
};
}
var produceTypeDef = getTypeDefProducer(ast);
ast.definitions.forEach(produceTypeDef);
var queryType = produceTypeDef(astMap[queryTypeName]);
var schema;
if ((0, _jsutilsIsNullish2['default'])(mutationTypeName)) {
schema = new _type.GraphQLSchema({ query: queryType });
} else {
schema = new _type.GraphQLSchema({
query: queryType,
mutation: produceTypeDef(astMap[mutationTypeName])
});
}
return schema;
function makeSchemaDef(def) {
if ((0, _jsutilsIsNullish2['default'])(def)) {
throw new Error('def must be defined');
}
switch (def.kind) {
case _languageKinds.OBJECT_TYPE_DEFINITION:
return makeTypeDef(def);
case _languageKinds.INTERFACE_TYPE_DEFINITION:
return makeInterfaceDef(def);
case _languageKinds.ENUM_TYPE_DEFINITION:
return makeEnumDef(def);
case _languageKinds.UNION_TYPE_DEFINITION:
return makeUnionDef(def);
case _languageKinds.SCALAR_TYPE_DEFINITION:
return makeScalarDef(def);
case _languageKinds.INPUT_OBJECT_TYPE_DEFINITION:
return makeInputObjectDef(def);
default:
throw new Error(def.kind + ' not supported');
}
}
function makeTypeDef(def) {
var typeName = def.name.value;
var config = {
name: typeName,
fields: function fields() {
return makeFieldDefMap(def);
},
interfaces: function interfaces() {
return makeImplementedInterfaces(def);
}
};
return new _type.GraphQLObjectType(config);
}
function makeFieldDefMap(def) {
return (0, _jsutilsKeyValMap2['default'])(def.fields, function (field) {
return field.name.value;
}, function (field) {
return {
type: produceTypeDef(field.type),
args: makeInputValues(field.arguments)
};
});
}
function makeImplementedInterfaces(def) {
return def.interfaces.map(function (inter) {
return produceTypeDef(inter);
});
}
function makeInputValues(values) {
return (0, _jsutilsKeyValMap2['default'])(values, function (value) {
return value.name.value;
}, function (value) {
var type = produceTypeDef(value.type);
return { type: type, defaultValue: (0, _valueFromAST.valueFromAST)(value.defaultValue, type) };
});
}
function makeInterfaceDef(def) {
var typeName = def.name.value;
var config = {
name: typeName,
resolveType: function resolveType() {
return null;
},
fields: function fields() {
return makeFieldDefMap(def);
}
};
return new _type.GraphQLInterfaceType(config);
}
function makeEnumDef(def) {
var enumType = new _type.GraphQLEnumType({
name: def.name.value,
values: (0, _jsutilsKeyValMap2['default'])(def.values, function (v) {
return v.name.value;
}, function () {
return {};
})
});
return enumType;
}
function makeUnionDef(def) {
return new _type.GraphQLUnionType({
name: def.name.value,
resolveType: function resolveType() {
return null;
},
types: def.types.map(function (t) {
return produceTypeDef(t);
})
});
}
function makeScalarDef(def) {
return new _type.GraphQLScalarType({
name: def.name.value,
serialize: function serialize() {
return null;
},
// Note: validation calls the parse functions to determine if a
// literal value is correct. Returning null would cause use of custom
// scalars to always fail validation. Returning false causes them to
// always pass validation.
parseValue: function parseValue() {
return false;
},
parseLiteral: function parseLiteral() {
return false;
}
});
}
function makeInputObjectDef(def) {
return new _type.GraphQLInputObjectType({
name: def.name.value,
fields: function fields() {
return makeInputValues(def.fields);
}
});
}
}
},{"../jsutils/isNullish":34,"../jsutils/keyMap":35,"../jsutils/keyValMap":36,"../language/kinds":38,"../type":136,"./valueFromAST":151,"babel-runtime/helpers/interop-require-default":60}],143:[function(require,module,exports){
/**
* Copyright (c) 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.
*/
/**
* Build a GraphQLSchema for use by client tools.
*
* Given the result of a client running the introspection query, creates and
* returns a GraphQLSchema instance which can be then used with all graphql-js
* tools, but cannot be used to execute a query, as introspection does not
* represent the "resolver", "parse" or "serialize" functions or any other
* server-internal mechanisms.
*/
'use strict';
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.buildClientSchema = buildClientSchema;
var _jsutilsInvariant = require('../jsutils/invariant');
var _jsutilsInvariant2 = _interopRequireDefault(_jsutilsInvariant);
var _jsutilsKeyMap = require('../jsutils/keyMap');
var _jsutilsKeyMap2 = _interopRequireDefault(_jsutilsKeyMap);
var _jsutilsKeyValMap = require('../jsutils/keyValMap');
var _jsutilsKeyValMap2 = _interopRequireDefault(_jsutilsKeyValMap);
var _valueFromAST = require('./valueFromAST');
var _languageParser = require('../language/parser');
var _typeSchema = require('../type/schema');
var _typeDefinition = require('../type/definition');
var _typeScalars = require('../type/scalars');
var _typeIntrospection = require('../type/introspection');
function buildClientSchema(introspection) {
// Get the schema from the introspection result.
var schemaIntrospection = introspection.__schema;
// Converts the list of types into a keyMap based on the type names.
var typeIntrospectionMap = (0, _jsutilsKeyMap2['default'])(schemaIntrospection.types, function (type) {
return type.name;
});
// A cache to use to store the actual GraphQLType definition objects by name.
// Initialize to the GraphQL built in scalars. All functions below are inline
// so that this type def cache is within the scope of the closure.
var typeDefCache = {
String: _typeScalars.GraphQLString,
Int: _typeScalars.GraphQLInt,
Float: _typeScalars.GraphQLFloat,
Boolean: _typeScalars.GraphQLBoolean,
ID: _typeScalars.GraphQLID
};
// Given a type reference in introspection, return the GraphQLType instance.
// preferring cached instances before building new instances.
function getType(typeRef) {
if (typeRef.kind === _typeIntrospection.TypeKind.LIST) {
var itemRef = typeRef.ofType;
if (!itemRef) {
throw new Error('Decorated type deeper than introspection query.');
}
return new _typeDefinition.GraphQLList(getType(itemRef));
}
if (typeRef.kind === _typeIntrospection.TypeKind.NON_NULL) {
var nullableRef = typeRef.ofType;
if (!nullableRef) {
throw new Error('Decorated type deeper than introspection query.');
}
return new _typeDefinition.GraphQLNonNull(getType(nullableRef));
}
return getNamedType(typeRef.name);
}
function getNamedType(typeName) {
if (typeDefCache[typeName]) {
return typeDefCache[typeName];
}
var typeIntrospection = typeIntrospectionMap[typeName];
if (!typeIntrospection) {
throw new Error('Invalid or incomplete schema, unknown type: ' + typeName + '. Ensure ' + 'that a full introspection query is used in order to build a ' + 'client schema.');
}
var typeDef = buildType(typeIntrospection);
typeDefCache[typeName] = typeDef;
return typeDef;
}
function getInputType(typeRef) {
var type = getType(typeRef);
(0, _jsutilsInvariant2['default'])((0, _typeDefinition.isInputType)(type), 'Introspection must provide input type for arguments.');
return type;
}
function getOutputType(typeRef) {
var type = getType(typeRef);
(0, _jsutilsInvariant2['default'])((0, _typeDefinition.isOutputType)(type), 'Introspection must provide output type for fields.');
return type;
}
function getObjectType(typeRef) {
var type = getType(typeRef);
(0, _jsutilsInvariant2['default'])(type instanceof _typeDefinition.GraphQLObjectType, 'Introspection must provide object type for possibleTypes.');
return type;
}
function getInterfaceType(typeRef) {
var type = getType(typeRef);
(0, _jsutilsInvariant2['default'])(type instanceof _typeDefinition.GraphQLInterfaceType, 'Introspection must provide interface type for interfaces.');
return type;
}
// Given a type's introspection result, construct the correct
// GraphQLType instance.
function buildType(type) {
switch (type.kind) {
case _typeIntrospection.TypeKind.SCALAR:
return buildScalarDef(type);
case _typeIntrospection.TypeKind.OBJECT:
return buildObjectDef(type);
case _typeIntrospection.TypeKind.INTERFACE:
return buildInterfaceDef(type);
case _typeIntrospection.TypeKind.UNION:
return buildUnionDef(type);
case _typeIntrospection.TypeKind.ENUM:
return buildEnumDef(type);
case _typeIntrospection.TypeKind.INPUT_OBJECT:
return buildInputObjectDef(type);
default:
throw new Error('Invalid or incomplete schema, unknown kind: ' + type.kind + '. Ensure ' + 'that a full introspection query is used in order to build a ' + 'client schema.');
}
}
function buildScalarDef(scalarIntrospection) {
return new _typeDefinition.GraphQLScalarType({
name: scalarIntrospection.name,
description: scalarIntrospection.description,
serialize: function serialize() {
return null;
},
// Note: validation calls the parse functions to determine if a
// literal value is correct. Returning null would cause use of custom
// scalars to always fail validation. Returning false causes them to
// always pass validation.
parseValue: function parseValue() {
return false;
},
parseLiteral: function parseLiteral() {
return false;
}
});
}
function buildObjectDef(objectIntrospection) {
return new _typeDefinition.GraphQLObjectType({
name: objectIntrospection.name,
description: objectIntrospection.description,
interfaces: objectIntrospection.interfaces.map(getInterfaceType),
fields: function fields() {
return buildFieldDefMap(objectIntrospection);
}
});
}
function buildInterfaceDef(interfaceIntrospection) {
return new _typeDefinition.GraphQLInterfaceType({
name: interfaceIntrospection.name,
description: interfaceIntrospection.description,
fields: function fields() {
return buildFieldDefMap(interfaceIntrospection);
},
resolveType: function resolveType() {
throw new Error('Client Schema cannot be used for execution.');
}
});
}
function buildUnionDef(unionIntrospection) {
return new _typeDefinition.GraphQLUnionType({
name: unionIntrospection.name,
description: unionIntrospection.description,
types: unionIntrospection.possibleTypes.map(getObjectType),
resolveType: function resolveType() {
throw new Error('Client Schema cannot be used for execution.');
}
});
}
function buildEnumDef(enumIntrospection) {
return new _typeDefinition.GraphQLEnumType({
name: enumIntrospection.name,
description: enumIntrospection.description,
values: (0, _jsutilsKeyValMap2['default'])(enumIntrospection.enumValues, function (valueIntrospection) {
return valueIntrospection.name;
}, function (valueIntrospection) {
return {
description: valueIntrospection.description
};
})
});
}
function buildInputObjectDef(inputObjectIntrospection) {
return new _typeDefinition.GraphQLInputObjectType({
name: inputObjectIntrospection.name,
description: inputObjectIntrospection.description,
fields: function fields() {
return buildInputValueDefMap(inputObjectIntrospection.inputFields);
}
});
}
function buildFieldDefMap(typeIntrospection) {
return (0, _jsutilsKeyValMap2['default'])(typeIntrospection.fields, function (fieldIntrospection) {
return fieldIntrospection.name;
}, function (fieldIntrospection) {
return {
description: fieldIntrospection.description,
type: getOutputType(fieldIntrospection.type),
args: buildInputValueDefMap(fieldIntrospection.args),
resolve: function resolve() {
throw new Error('Client Schema cannot be used for execution.');
}
};
});
}
function buildInputValueDefMap(inputValueIntrospections) {
return (0, _jsutilsKeyValMap2['default'])(inputValueIntrospections, function (inputValue) {
return inputValue.name;
}, function (inputValue) {
var description = inputValue.description;
var type = getInputType(inputValue.type);
var defaultValue = inputValue.defaultValue ? (0, _valueFromAST.valueFromAST)((0, _languageParser.parseValue)(inputValue.defaultValue), type) : null;
return { description: description, type: type, defaultValue: defaultValue };
});
}
// TODO: deprecation
// TODO: directives
// Iterate through all types, getting the type definition for each, ensuring
// that any type not directly referenced by a field will get created.
schemaIntrospection.types.forEach(function (typeIntrospection) {
return getNamedType(typeIntrospection.name);
});
// Get the root Query and Mutation types.
var queryType = getType(schemaIntrospection.queryType);
var mutationType = schemaIntrospection.mutationType ? getType(schemaIntrospection.mutationType) : null;
// Then produce and return a Schema with these types.
var schema = new _typeSchema.GraphQLSchema({
query: queryType,
mutation: mutationType
});
return schema;
}
},{"../jsutils/invariant":33,"../jsutils/keyMap":35,"../jsutils/keyValMap":36,"../language/parser":41,"../type/definition":134,"../type/introspection":137,"../type/scalars":138,"../type/schema":139,"./valueFromAST":151,"babel-runtime/helpers/interop-require-default":60}],144:[function(require,module,exports){
/**
* Copyright (c) 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.
*/
/**
* Returns an operation AST given a document AST and optionally an operation
* name. If a name is not provided, an operation is only returned if only one is
* provided in the document.
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.getOperationAST = getOperationAST;
var _languageKinds = require('../language/kinds');
function getOperationAST(documentAST, operationName) {
var operation = null;
for (var i = 0; i < documentAST.definitions.length; i++) {
var definition = documentAST.definitions[i];
if (definition.kind === _languageKinds.OPERATION_DEFINITION) {
if (!operationName) {
// If no operation name was provided, only return an Operation if there
// is one defined in the document. Upon encountering the second, return
// null.
if (operation) {
return null;
}
operation = definition;
} else if (definition.name && definition.name.value === operationName) {
return definition;
}
}
}
return operation;
}
},{"../language/kinds":38}],145:[function(require,module,exports){
/**
* Copyright (c) 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.
*/
// The GraphQL query recommended for a full schema introspection.
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _introspectionQuery = require('./introspectionQuery');
Object.defineProperty(exports, 'introspectionQuery', {
enumerable: true,
get: function get() {
return _introspectionQuery.introspectionQuery;
}
});
// Gets the target Operation from a Document
var _getOperationAST = require('./getOperationAST');
Object.defineProperty(exports, 'getOperationAST', {
enumerable: true,
get: function get() {
return _getOperationAST.getOperationAST;
}
});
// Build a GraphQLSchema from an introspection result.
var _buildClientSchema = require('./buildClientSchema');
Object.defineProperty(exports, 'buildClientSchema', {
enumerable: true,
get: function get() {
return _buildClientSchema.buildClientSchema;
}
});
// Build a GraphQLSchema from a parsed GraphQL Schema language AST.
var _buildASTSchema = require('./buildASTSchema');
Object.defineProperty(exports, 'buildASTSchema', {
enumerable: true,
get: function get() {
return _buildASTSchema.buildASTSchema;
}
});
// Print a GraphQLSchema to GraphQL Schema language.
var _schemaPrinter = require('./schemaPrinter');
Object.defineProperty(exports, 'printSchema', {
enumerable: true,
get: function get() {
return _schemaPrinter.printSchema;
}
});
Object.defineProperty(exports, 'printIntrospectionSchema', {
enumerable: true,
get: function get() {
return _schemaPrinter.printIntrospectionSchema;
}
});
// Create a GraphQLType from a GraphQL language AST.
var _typeFromAST = require('./typeFromAST');
Object.defineProperty(exports, 'typeFromAST', {
enumerable: true,
get: function get() {
return _typeFromAST.typeFromAST;
}
});
// Create a JavaScript value from a GraphQL language AST.
var _valueFromAST = require('./valueFromAST');
Object.defineProperty(exports, 'valueFromAST', {
enumerable: true,
get: function get() {
return _valueFromAST.valueFromAST;
}
});
// Create a GraphQL language AST from a JavaScript value.
var _astFromValue = require('./astFromValue');
Object.defineProperty(exports, 'astFromValue', {
enumerable: true,
get: function get() {
return _astFromValue.astFromValue;
}
});
// A helper to use within recursive-descent visitors which need to be aware of
// the GraphQL type system.
var _TypeInfo = require('./TypeInfo');
Object.defineProperty(exports, 'TypeInfo', {
enumerable: true,
get: function get() {
return _TypeInfo.TypeInfo;
}
});
// Determine if JavaScript values adhere to a GraphQL type.
var _isValidJSValue = require('./isValidJSValue');
Object.defineProperty(exports, 'isValidJSValue', {
enumerable: true,
get: function get() {
return _isValidJSValue.isValidJSValue;
}
});
// Determine if AST values adhere to a GraphQL type.
var _isValidLiteralValue = require('./isValidLiteralValue');
Object.defineProperty(exports, 'isValidLiteralValue', {
enumerable: true,
get: function get() {
return _isValidLiteralValue.isValidLiteralValue;
}
});
},{"./TypeInfo":140,"./astFromValue":141,"./buildASTSchema":142,"./buildClientSchema":143,"./getOperationAST":144,"./introspectionQuery":146,"./isValidJSValue":147,"./isValidLiteralValue":148,"./schemaPrinter":149,"./typeFromAST":150,"./valueFromAST":151}],146:[function(require,module,exports){
/**
* Copyright (c) 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';
Object.defineProperty(exports, '__esModule', {
value: true
});
var introspectionQuery = '\n query IntrospectionQuery {\n __schema {\n queryType { name }\n mutationType { name }\n types {\n ...FullType\n }\n directives {\n name\n description\n args {\n ...InputValue\n }\n onOperation\n onFragment\n onField\n }\n }\n }\n\n fragment FullType on __Type {\n kind\n name\n description\n fields {\n name\n description\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues {\n name\n description\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n }\n\n fragment InputValue on __InputValue {\n name\n description\n type { ...TypeRef }\n defaultValue\n }\n\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n';
exports.introspectionQuery = introspectionQuery;
},{}],147:[function(require,module,exports){
/**
* Copyright (c) 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.
*/
/**
* Given a JavaScript value and a GraphQL type, determine if the value will be
* accepted for that type. This is primarily useful for validating the
* runtime values of query variables.
*/
'use strict';
var _Object$keys = require('babel-runtime/core-js/object/keys')['default'];
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.isValidJSValue = isValidJSValue;
var _jsutilsInvariant = require('../jsutils/invariant');
var _jsutilsInvariant2 = _interopRequireDefault(_jsutilsInvariant);
var _jsutilsIsNullish = require('../jsutils/isNullish');
var _jsutilsIsNullish2 = _interopRequireDefault(_jsutilsIsNullish);
var _typeDefinition = require('../type/definition');
function isValidJSValue(_x, _x2) {
var _again = true;
_function: while (_again) {
var value = _x,
type = _x2;
nullableType = itemType = fields = undefined;
_again = false;
// A value must be provided if the type is non-null.
if (type instanceof _typeDefinition.GraphQLNonNull) {
if ((0, _jsutilsIsNullish2['default'])(value)) {
return false;
}
var nullableType = type.ofType;
_x = value;
_x2 = nullableType;
_again = true;
continue _function;
}
if ((0, _jsutilsIsNullish2['default'])(value)) {
return true;
}
// Lists accept a non-list value as a list of one.
if (type instanceof _typeDefinition.GraphQLList) {
var itemType = type.ofType;
if (Array.isArray(value)) {
return value.every(function (item) {
return isValidJSValue(item, itemType);
});
}
_x = value;
_x2 = itemType;
_again = true;
continue _function;
}
// Input objects check each defined field.
if (type instanceof _typeDefinition.GraphQLInputObjectType) {
if (typeof value !== 'object') {
return false;
}
var fields = type.getFields();
// Ensure every provided field is defined.
if (_Object$keys(value).some(function (fieldName) {
return !fields[fieldName];
})) {
return false;
}
// Ensure every defined field is valid.
return _Object$keys(fields).every(function (fieldName) {
return isValidJSValue(value[fieldName], fields[fieldName].type);
});
}
(0, _jsutilsInvariant2['default'])(type instanceof _typeDefinition.GraphQLScalarType || type instanceof _typeDefinition.GraphQLEnumType, 'Must be input type');
// Scalar/Enum input checks to ensure the type can parse the value to
// a non-null value.
return !(0, _jsutilsIsNullish2['default'])(type.parseValue(value));
}
}
},{"../jsutils/invariant":33,"../jsutils/isNullish":34,"../type/definition":134,"babel-runtime/core-js/object/keys":52,"babel-runtime/helpers/interop-require-default":60}],148:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _Object$keys = require('babel-runtime/core-js/object/keys')['default'];
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.isValidLiteralValue = isValidLiteralValue;
var _languageKinds = require('../language/kinds');
var _typeDefinition = require('../type/definition');
var _jsutilsInvariant = require('../jsutils/invariant');
var _jsutilsInvariant2 = _interopRequireDefault(_jsutilsInvariant);
var _jsutilsKeyMap = require('../jsutils/keyMap');
var _jsutilsKeyMap2 = _interopRequireDefault(_jsutilsKeyMap);
var _jsutilsIsNullish = require('../jsutils/isNullish');
var _jsutilsIsNullish2 = _interopRequireDefault(_jsutilsIsNullish);
/**
* Utility for validators which determines if a value literal AST is valid given
* an input type.
*
* Note that this only validates literal values, variables are assumed to
* provide values of the correct type.
*/
function isValidLiteralValue(_x, _x2) {
var _again = true;
_function: while (_again) {
var type = _x,
valueAST = _x2;
ofType = itemType = fields = fieldASTs = fieldASTMap = undefined;
_again = false;
// A value must be provided if the type is non-null.
if (type instanceof _typeDefinition.GraphQLNonNull) {
if (!valueAST) {
return false;
}
var ofType = type.ofType;
_x = ofType;
_x2 = valueAST;
_again = true;
continue _function;
}
if (!valueAST) {
return true;
}
// This function only tests literals, and assumes variables will provide
// values of the correct type.
if (valueAST.kind === _languageKinds.VARIABLE) {
return true;
}
// Lists accept a non-list value as a list of one.
if (type instanceof _typeDefinition.GraphQLList) {
var itemType = type.ofType;
if (valueAST.kind === _languageKinds.LIST) {
return valueAST.values.every(function (itemAST) {
return isValidLiteralValue(itemType, itemAST);
});
}
_x = itemType;
_x2 = valueAST;
_again = true;
continue _function;
}
// Input objects check each defined field and look for undefined fields.
if (type instanceof _typeDefinition.GraphQLInputObjectType) {
if (valueAST.kind !== _languageKinds.OBJECT) {
return false;
}
var fields = type.getFields();
// Ensure every provided field is defined.
var fieldASTs = valueAST.fields;
if (fieldASTs.some(function (fieldAST) {
return !fields[fieldAST.name.value];
})) {
return false;
}
// Ensure every defined field is valid.
var fieldASTMap = (0, _jsutilsKeyMap2['default'])(fieldASTs, function (fieldAST) {
return fieldAST.name.value;
});
return _Object$keys(fields).every(function (fieldName) {
return isValidLiteralValue(fields[fieldName].type, fieldASTMap[fieldName] && fieldASTMap[fieldName].value);
});
}
(0, _jsutilsInvariant2['default'])(type instanceof _typeDefinition.GraphQLScalarType || type instanceof _typeDefinition.GraphQLEnumType, 'Must be input type');
// Scalar/Enum input checks to ensure the type can parse the value to
// a non-null value.
return !(0, _jsutilsIsNullish2['default'])(type.parseLiteral(valueAST));
}
}
},{"../jsutils/invariant":33,"../jsutils/isNullish":34,"../jsutils/keyMap":35,"../language/kinds":38,"../type/definition":134,"babel-runtime/core-js/object/keys":52,"babel-runtime/helpers/interop-require-default":60}],149:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _Object$keys = require('babel-runtime/core-js/object/keys')['default'];
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.printSchema = printSchema;
exports.printIntrospectionSchema = printIntrospectionSchema;
var _jsutilsInvariant = require('../jsutils/invariant');
var _jsutilsInvariant2 = _interopRequireDefault(_jsutilsInvariant);
var _jsutilsIsNullish = require('../jsutils/isNullish');
var _jsutilsIsNullish2 = _interopRequireDefault(_jsutilsIsNullish);
var _utilitiesAstFromValue = require('../utilities/astFromValue');
var _languagePrinter = require('../language/printer');
var _typeDefinition = require('../type/definition');
function printSchema(schema) {
return printFilteredSchema(schema, isDefinedType);
}
function printIntrospectionSchema(schema) {
return printFilteredSchema(schema, isIntrospectionType);
}
function isDefinedType(typename) {
return !isIntrospectionType(typename) && !isBuiltInScalar(typename);
}
function isIntrospectionType(typename) {
return typename.indexOf('__') === 0;
}
function isBuiltInScalar(typename) {
return typename === 'String' || typename === 'Boolean' || typename === 'Int' || typename === 'Float' || typename === 'ID';
}
function printFilteredSchema(schema, typeFilter) {
var typeMap = schema.getTypeMap();
var types = _Object$keys(typeMap).filter(typeFilter).sort(function (name1, name2) {
return name1.localeCompare(name2);
}).map(function (typeName) {
return typeMap[typeName];
});
return types.map(printType).join('\n\n') + '\n';
}
function printType(type) {
if (type instanceof _typeDefinition.GraphQLScalarType) {
return printScalar(type);
} else if (type instanceof _typeDefinition.GraphQLObjectType) {
return printObject(type);
} else if (type instanceof _typeDefinition.GraphQLInterfaceType) {
return printInterface(type);
} else if (type instanceof _typeDefinition.GraphQLUnionType) {
return printUnion(type);
} else if (type instanceof _typeDefinition.GraphQLEnumType) {
return printEnum(type);
}
(0, _jsutilsInvariant2['default'])(type instanceof _typeDefinition.GraphQLInputObjectType);
return printInputObject(type);
}
function printScalar(type) {
return 'scalar ' + type.name;
}
function printObject(type) {
var interfaces = type.getInterfaces();
var implementedInterfaces = interfaces.length ? ' implements ' + interfaces.map(function (i) {
return i.name;
}).join(', ') : '';
return 'type ' + type.name + implementedInterfaces + ' {\n' + printFields(type) + '\n' + '}';
}
function printInterface(type) {
return 'interface ' + type.name + ' {\n' + printFields(type) + '\n' + '}';
}
function printUnion(type) {
return 'union ' + type.name + ' = ' + type.getPossibleTypes().join(' | ');
}
function printEnum(type) {
var values = type.getValues();
return 'enum ' + type.name + ' {\n' + values.map(function (v) {
return ' ' + v.name;
}).join('\n') + '\n' + '}';
}
function printInputObject(type) {
var fieldMap = type.getFields();
var fields = _Object$keys(fieldMap).map(function (fieldName) {
return fieldMap[fieldName];
});
return 'input ' + type.name + ' {\n' + fields.map(function (f) {
return ' ' + printInputValue(f);
}).join('\n') + '\n' + '}';
}
function printFields(type) {
var fieldMap = type.getFields();
var fields = _Object$keys(fieldMap).map(function (fieldName) {
return fieldMap[fieldName];
});
return fields.map(function (f) {
return ' ' + f.name + printArgs(f) + ': ' + f.type;
}).join('\n');
}
function printArgs(field) {
if (field.args.length === 0) {
return '';
}
return '(' + field.args.map(printInputValue).join(', ') + ')';
}
function printInputValue(arg) {
var argDecl = arg.name + ': ' + arg.type;
if (!(0, _jsutilsIsNullish2['default'])(arg.defaultValue)) {
argDecl += ' = ' + (0, _languagePrinter.print)((0, _utilitiesAstFromValue.astFromValue)(arg.defaultValue, arg.type));
}
return argDecl;
}
},{"../jsutils/invariant":33,"../jsutils/isNullish":34,"../language/printer":42,"../type/definition":134,"../utilities/astFromValue":141,"babel-runtime/core-js/object/keys":52,"babel-runtime/helpers/interop-require-default":60}],150:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.typeFromAST = typeFromAST;
var _jsutilsInvariant = require('../jsutils/invariant');
var _jsutilsInvariant2 = _interopRequireDefault(_jsutilsInvariant);
var _languageKinds = require('../language/kinds');
var _typeDefinition = require('../type/definition');
function typeFromAST(schema, inputTypeAST) {
var innerType;
if (inputTypeAST.kind === _languageKinds.LIST_TYPE) {
innerType = typeFromAST(schema, inputTypeAST.type);
return innerType && new _typeDefinition.GraphQLList(innerType);
}
if (inputTypeAST.kind === _languageKinds.NON_NULL_TYPE) {
innerType = typeFromAST(schema, inputTypeAST.type);
return innerType && new _typeDefinition.GraphQLNonNull(innerType);
}
(0, _jsutilsInvariant2['default'])(inputTypeAST.kind === _languageKinds.NAMED_TYPE, 'Must be a named type.');
return schema.getType(inputTypeAST.name.value);
}
},{"../jsutils/invariant":33,"../language/kinds":38,"../type/definition":134,"babel-runtime/helpers/interop-require-default":60}],151:[function(require,module,exports){
/**
* Copyright (c) 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.
*/
/**
* Produces a JavaScript value given a GraphQL Value AST.
*
* A GraphQL type must be provided, which will be used to interpret different
* GraphQL Value literals.
*
* | GraphQL Value | JSON Value |
* | -------------------- | ------------- |
* | Input Object | Object |
* | List | Array |
* | Boolean | Boolean |
* | String / Enum Value | String |
* | Int / Float | Number |
*
*/
'use strict';
var _Object$keys = require('babel-runtime/core-js/object/keys')['default'];
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
var _interopRequireWildcard = require('babel-runtime/helpers/interop-require-wildcard')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.valueFromAST = valueFromAST;
var _jsutilsKeyMap = require('../jsutils/keyMap');
var _jsutilsKeyMap2 = _interopRequireDefault(_jsutilsKeyMap);
var _jsutilsInvariant = require('../jsutils/invariant');
var _jsutilsInvariant2 = _interopRequireDefault(_jsutilsInvariant);
var _jsutilsIsNullish = require('../jsutils/isNullish');
var _jsutilsIsNullish2 = _interopRequireDefault(_jsutilsIsNullish);
var _languageKinds = require('../language/kinds');
var Kind = _interopRequireWildcard(_languageKinds);
var _typeDefinition = require('../type/definition');
function valueFromAST(_x, _x2, _x3) {
var _again = true;
_function: while (_again) {
var valueAST = _x,
type = _x2,
variables = _x3;
nullableType = variableName = itemType = fields = fieldASTs = parsed = undefined;
_again = false;
if (type instanceof _typeDefinition.GraphQLNonNull) {
var nullableType = type.ofType;
// Note: we're not checking that the result of valueFromAST is non-null.
// We're assuming that this query has been validated and the value used
// here is of the correct type.
_x = valueAST;
_x2 = nullableType;
_x3 = variables;
_again = true;
continue _function;
}
if (!valueAST) {
return null;
}
if (valueAST.kind === Kind.VARIABLE) {
var variableName = valueAST.name.value;
if (!variables || !variables.hasOwnProperty(variableName)) {
return null;
}
// Note: we're not doing any checking that this variable is correct. We're
// assuming that this query has been validated and the variable usage here
// is of the correct type.
return variables[variableName];
}
if (type instanceof _typeDefinition.GraphQLList) {
var itemType = type.ofType;
if (valueAST.kind === Kind.LIST) {
return valueAST.values.map(function (itemAST) {
return valueFromAST(itemAST, itemType, variables);
});
}
return [valueFromAST(valueAST, itemType, variables)];
}
if (type instanceof _typeDefinition.GraphQLInputObjectType) {
var fields = type.getFields();
if (valueAST.kind !== Kind.OBJECT) {
return null;
}
var fieldASTs = (0, _jsutilsKeyMap2['default'])(valueAST.fields, function (field) {
return field.name.value;
});
return _Object$keys(fields).reduce(function (obj, fieldName) {
var field = fields[fieldName];
var fieldAST = fieldASTs[fieldName];
var fieldValue = valueFromAST(fieldAST && fieldAST.value, field.type, variables);
if ((0, _jsutilsIsNullish2['default'])(fieldValue)) {
fieldValue = field.defaultValue;
}
if (!(0, _jsutilsIsNullish2['default'])(fieldValue)) {
obj[fieldName] = fieldValue;
}
return obj;
}, {});
}
(0, _jsutilsInvariant2['default'])(type instanceof _typeDefinition.GraphQLScalarType || type instanceof _typeDefinition.GraphQLEnumType, 'Must be input type');
var parsed = type.parseLiteral(valueAST);
if (!(0, _jsutilsIsNullish2['default'])(parsed)) {
return parsed;
}
}
}
},{"../jsutils/invariant":33,"../jsutils/isNullish":34,"../jsutils/keyMap":35,"../language/kinds":38,"../type/definition":134,"babel-runtime/core-js/object/keys":52,"babel-runtime/helpers/interop-require-default":60,"babel-runtime/helpers/interop-require-wildcard":61}],152:[function(require,module,exports){
/**
* Copyright (c) 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';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _validate = require('./validate');
Object.defineProperty(exports, 'validate', {
enumerable: true,
get: function get() {
return _validate.validate;
}
});
var _specifiedRules = require('./specifiedRules');
Object.defineProperty(exports, 'specifiedRules', {
enumerable: true,
get: function get() {
return _specifiedRules.specifiedRules;
}
});
},{"./specifiedRules":176,"./validate":177}],153:[function(require,module,exports){
/**
* Copyright (c) 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';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.badValueMessage = badValueMessage;
exports.ArgumentsOfCorrectType = ArgumentsOfCorrectType;
var _error = require('../../error');
var _languagePrinter = require('../../language/printer');
var _utilitiesIsValidLiteralValue = require('../../utilities/isValidLiteralValue');
function badValueMessage(argName, type, value) {
return 'Argument "' + argName + '" expected type "' + type + '" but got: ' + value + '.';
}
/**
* Argument values of correct type
*
* A GraphQL document is only valid if all field argument literal values are
* of the type expected by their position.
*/
function ArgumentsOfCorrectType(context) {
return {
Argument: function Argument(argAST) {
var argDef = context.getArgument();
if (argDef && !(0, _utilitiesIsValidLiteralValue.isValidLiteralValue)(argDef.type, argAST.value)) {
return new _error.GraphQLError(badValueMessage(argAST.name.value, argDef.type, (0, _languagePrinter.print)(argAST.value)), [argAST.value]);
}
}
};
}
},{"../../error":29,"../../language/printer":42,"../../utilities/isValidLiteralValue":148}],154:[function(require,module,exports){
/**
* Copyright (c) 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';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.defaultForNonNullArgMessage = defaultForNonNullArgMessage;
exports.badValueForDefaultArgMessage = badValueForDefaultArgMessage;
exports.DefaultValuesOfCorrectType = DefaultValuesOfCorrectType;
var _error = require('../../error');
var _languagePrinter = require('../../language/printer');
var _typeDefinition = require('../../type/definition');
var _utilitiesIsValidLiteralValue = require('../../utilities/isValidLiteralValue');
function defaultForNonNullArgMessage(varName, type, guessType) {
return 'Variable "$' + varName + '" of type "' + type + '" is required and will not ' + ('use the default value. Perhaps you meant to use type "' + guessType + '".');
}
function badValueForDefaultArgMessage(varName, type, value) {
return 'Variable "$' + varName + '" of type "' + type + '" has invalid default ' + ('value: ' + value + '.');
}
/**
* Variable default values of correct type
*
* A GraphQL document is only valid if all variable default values are of the
* type expected by their definition.
*/
function DefaultValuesOfCorrectType(context) {
return {
VariableDefinition: function VariableDefinition(varDefAST) {
var name = varDefAST.variable.name.value;
var defaultValue = varDefAST.defaultValue;
var type = context.getInputType();
if (type instanceof _typeDefinition.GraphQLNonNull && defaultValue) {
return new _error.GraphQLError(defaultForNonNullArgMessage(name, type, type.ofType), [defaultValue]);
}
if (type && defaultValue && !(0, _utilitiesIsValidLiteralValue.isValidLiteralValue)(type, defaultValue)) {
return new _error.GraphQLError(badValueForDefaultArgMessage(name, type, (0, _languagePrinter.print)(defaultValue)), [defaultValue]);
}
}
};
}
},{"../../error":29,"../../language/printer":42,"../../type/definition":134,"../../utilities/isValidLiteralValue":148}],155:[function(require,module,exports){
/**
* Copyright (c) 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';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.undefinedFieldMessage = undefinedFieldMessage;
exports.FieldsOnCorrectType = FieldsOnCorrectType;
var _error = require('../../error');
function undefinedFieldMessage(fieldName, type) {
return 'Cannot query field "' + fieldName + '" on "' + type + '".';
}
/**
* Fields on correct type
*
* A GraphQL document is only valid if all fields selected are defined by the
* parent type, or are an allowed meta field such as __typenamme
*/
function FieldsOnCorrectType(context) {
return {
Field: function Field(node) {
var type = context.getParentType();
if (type) {
var fieldDef = context.getFieldDef();
if (!fieldDef) {
return new _error.GraphQLError(undefinedFieldMessage(node.name.value, type.name), [node]);
}
}
}
};
}
},{"../../error":29}],156:[function(require,module,exports){
/**
* Copyright (c) 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';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.inlineFragmentOnNonCompositeErrorMessage = inlineFragmentOnNonCompositeErrorMessage;
exports.fragmentOnNonCompositeErrorMessage = fragmentOnNonCompositeErrorMessage;
exports.FragmentsOnCompositeTypes = FragmentsOnCompositeTypes;
var _error = require('../../error');
var _languagePrinter = require('../../language/printer');
var _typeDefinition = require('../../type/definition');
function inlineFragmentOnNonCompositeErrorMessage(type) {
return 'Fragment cannot condition on non composite type "' + type + '".';
}
function fragmentOnNonCompositeErrorMessage(fragName, type) {
return 'Fragment "' + fragName + '" cannot condition on non composite ' + ('type "' + type + '".');
}
/**
* Fragments on composite type
*
* Fragments use a type condition to determine if they apply, since fragments
* can only be spread into a composite type (object, interface, or union), the
* type condition must also be a composite type.
*/
function FragmentsOnCompositeTypes(context) {
return {
InlineFragment: function InlineFragment(node) {
var type = context.getType();
if (node.typeCondition && type && !(0, _typeDefinition.isCompositeType)(type)) {
return new _error.GraphQLError(inlineFragmentOnNonCompositeErrorMessage((0, _languagePrinter.print)(node.typeCondition)), [node.typeCondition]);
}
},
FragmentDefinition: function FragmentDefinition(node) {
var type = context.getType();
if (type && !(0, _typeDefinition.isCompositeType)(type)) {
return new _error.GraphQLError(fragmentOnNonCompositeErrorMessage(node.name.value, (0, _languagePrinter.print)(node.typeCondition)), [node.typeCondition]);
}
}
};
}
},{"../../error":29,"../../language/printer":42,"../../type/definition":134}],157:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.unknownArgMessage = unknownArgMessage;
exports.unknownDirectiveArgMessage = unknownDirectiveArgMessage;
exports.KnownArgumentNames = KnownArgumentNames;
var _error = require('../../error');
var _jsutilsFind = require('../../jsutils/find');
var _jsutilsFind2 = _interopRequireDefault(_jsutilsFind);
var _jsutilsInvariant = require('../../jsutils/invariant');
var _jsutilsInvariant2 = _interopRequireDefault(_jsutilsInvariant);
var _languageKinds = require('../../language/kinds');
function unknownArgMessage(argName, fieldName, type) {
return 'Unknown argument "' + argName + '" on field "' + fieldName + '" of ' + ('type "' + type + '".');
}
function unknownDirectiveArgMessage(argName, directiveName) {
return 'Unknown argument "' + argName + '" on directive "@' + directiveName + '".';
}
/**
* Known argument names
*
* A GraphQL field is only valid if all supplied arguments are defined by
* that field.
*/
function KnownArgumentNames(context) {
return {
Argument: function Argument(node, key, parent, path, ancestors) {
var argumentOf = ancestors[ancestors.length - 1];
if (argumentOf.kind === _languageKinds.FIELD) {
var fieldDef = context.getFieldDef();
if (fieldDef) {
var fieldArgDef = (0, _jsutilsFind2['default'])(fieldDef.args, function (arg) {
return arg.name === node.name.value;
});
if (!fieldArgDef) {
var parentType = context.getParentType();
(0, _jsutilsInvariant2['default'])(parentType);
return new _error.GraphQLError(unknownArgMessage(node.name.value, fieldDef.name, parentType.name), [node]);
}
}
} else if (argumentOf.kind === _languageKinds.DIRECTIVE) {
var directive = context.getDirective();
if (directive) {
var directiveArgDef = (0, _jsutilsFind2['default'])(directive.args, function (arg) {
return arg.name === node.name.value;
});
if (!directiveArgDef) {
return new _error.GraphQLError(unknownDirectiveArgMessage(node.name.value, directive.name), [node]);
}
}
}
}
};
}
},{"../../error":29,"../../jsutils/find":32,"../../jsutils/invariant":33,"../../language/kinds":38,"babel-runtime/helpers/interop-require-default":60}],158:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.unknownDirectiveMessage = unknownDirectiveMessage;
exports.misplacedDirectiveMessage = misplacedDirectiveMessage;
exports.KnownDirectives = KnownDirectives;
var _error = require('../../error');
var _jsutilsFind = require('../../jsutils/find');
var _jsutilsFind2 = _interopRequireDefault(_jsutilsFind);
var _languageKinds = require('../../language/kinds');
function unknownDirectiveMessage(directiveName) {
return 'Unknown directive "' + directiveName + '".';
}
function misplacedDirectiveMessage(directiveName, placement) {
return 'Directive "' + directiveName + '" may not be used on "' + placement + '".';
}
/**
* Known directives
*
* A GraphQL document is only valid if all `@directives` are known by the
* schema and legally positioned.
*/
function KnownDirectives(context) {
return {
Directive: function Directive(node, key, parent, path, ancestors) {
var directiveDef = (0, _jsutilsFind2['default'])(context.getSchema().getDirectives(), function (def) {
return def.name === node.name.value;
});
if (!directiveDef) {
return new _error.GraphQLError(unknownDirectiveMessage(node.name.value), [node]);
}
var appliedTo = ancestors[ancestors.length - 1];
if (appliedTo.kind === _languageKinds.OPERATION_DEFINITION && !directiveDef.onOperation) {
return new _error.GraphQLError(misplacedDirectiveMessage(node.name.value, 'operation'), [node]);
}
if (appliedTo.kind === _languageKinds.FIELD && !directiveDef.onField) {
return new _error.GraphQLError(misplacedDirectiveMessage(node.name.value, 'field'), [node]);
}
if ((appliedTo.kind === _languageKinds.FRAGMENT_SPREAD || appliedTo.kind === _languageKinds.INLINE_FRAGMENT || appliedTo.kind === _languageKinds.FRAGMENT_DEFINITION) && !directiveDef.onFragment) {
return new _error.GraphQLError(misplacedDirectiveMessage(node.name.value, 'fragment'), [node]);
}
}
};
}
},{"../../error":29,"../../jsutils/find":32,"../../language/kinds":38,"babel-runtime/helpers/interop-require-default":60}],159:[function(require,module,exports){
/**
* Copyright (c) 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';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.unknownFragmentMessage = unknownFragmentMessage;
exports.KnownFragmentNames = KnownFragmentNames;
var _error = require('../../error');
function unknownFragmentMessage(fragName) {
return 'Unknown fragment "' + fragName + '".';
}
/**
* Known fragment names
*
* A GraphQL document is only valid if all `...Fragment` fragment spreads refer
* to fragments defined in the same document.
*/
function KnownFragmentNames(context) {
return {
FragmentSpread: function FragmentSpread(node) {
var fragmentName = node.name.value;
var fragment = context.getFragment(fragmentName);
if (!fragment) {
return new _error.GraphQLError(unknownFragmentMessage(fragmentName), [node.name]);
}
}
};
}
},{"../../error":29}],160:[function(require,module,exports){
/**
* Copyright (c) 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';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.unknownTypeMessage = unknownTypeMessage;
exports.KnownTypeNames = KnownTypeNames;
var _error = require('../../error');
function unknownTypeMessage(type) {
return 'Unknown type "' + type + '".';
}
/**
* Known type names
*
* A GraphQL document is only valid if referenced types (specifically
* variable definitions and fragment conditions) are defined by the type schema.
*/
function KnownTypeNames(context) {
return {
NamedType: function NamedType(node) {
var typeName = node.name.value;
var type = context.getSchema().getType(typeName);
if (!type) {
return new _error.GraphQLError(unknownTypeMessage(typeName), [node]);
}
}
};
}
},{"../../error":29}],161:[function(require,module,exports){
/**
* Copyright (c) 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';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.anonOperationNotAloneMessage = anonOperationNotAloneMessage;
exports.LoneAnonymousOperation = LoneAnonymousOperation;
var _error = require('../../error');
var _languageKinds = require('../../language/kinds');
function anonOperationNotAloneMessage() {
return 'This anonymous operation must be the only defined operation.';
}
/**
* Lone anonymous operation
*
* A GraphQL document is only valid if when it contains an anonymous operation
* (the query short-hand) that it contains only that one operation definition.
*/
function LoneAnonymousOperation() {
var operationCount = 0;
return {
Document: function Document(node) {
operationCount = node.definitions.filter(function (definition) {
return definition.kind === _languageKinds.OPERATION_DEFINITION;
}).length;
},
OperationDefinition: function OperationDefinition(node) {
if (!node.name && operationCount > 1) {
return new _error.GraphQLError(anonOperationNotAloneMessage(), [node]);
}
}
};
}
},{"../../error":29,"../../language/kinds":38}],162:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _Set = require('babel-runtime/core-js/set')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.cycleErrorMessage = cycleErrorMessage;
exports.NoFragmentCycles = NoFragmentCycles;
var _error = require('../../error');
var _languageKinds = require('../../language/kinds');
var _languageVisitor = require('../../language/visitor');
function cycleErrorMessage(fragName, spreadNames) {
var via = spreadNames.length ? ' via ' + spreadNames.join(', ') : '';
return 'Cannot spread fragment "' + fragName + '" within itself' + via + '.';
}
function NoFragmentCycles(context) {
// Gather all the fragment spreads ASTs for each fragment definition.
// Importantly this does not include inline fragments.
var definitions = context.getDocument().definitions;
var spreadsInFragment = definitions.reduce(function (map, node) {
if (node.kind === _languageKinds.FRAGMENT_DEFINITION) {
map[node.name.value] = gatherSpreads(node);
}
return map;
}, {});
// Tracks spreads known to lead to cycles to ensure that cycles are not
// redundantly reported.
var knownToLeadToCycle = new _Set();
return {
FragmentDefinition: function FragmentDefinition(node) {
var errors = [];
var initialName = node.name.value;
// Array of AST nodes used to produce meaningful errors
var spreadPath = [];
// This does a straight-forward DFS to find cycles.
// It does not terminate when a cycle was found but continues to explore
// the graph to find all possible cycles.
function detectCycleRecursive(fragmentName) {
var spreadNodes = spreadsInFragment[fragmentName];
for (var i = 0; i < spreadNodes.length; ++i) {
var spreadNode = spreadNodes[i];
if (knownToLeadToCycle.has(spreadNode)) {
continue;
}
if (spreadNode.name.value === initialName) {
var cyclePath = spreadPath.concat(spreadNode);
cyclePath.forEach(function (spread) {
return knownToLeadToCycle.add(spread);
});
errors.push(new _error.GraphQLError(cycleErrorMessage(initialName, spreadPath.map(function (s) {
return s.name.value;
})), cyclePath));
continue;
}
if (spreadPath.some(function (spread) {
return spread === spreadNode;
})) {
continue;
}
spreadPath.push(spreadNode);
detectCycleRecursive(spreadNode.name.value);
spreadPath.pop();
}
}
detectCycleRecursive(initialName);
if (errors.length > 0) {
return errors;
}
}
};
}
/**
* Given an operation or fragment AST node, gather all the
* named spreads defined within the scope of the fragment
* or operation
*/
function gatherSpreads(node) {
var spreadNodes = [];
(0, _languageVisitor.visit)(node, {
FragmentSpread: function FragmentSpread(spread) {
spreadNodes.push(spread);
}
});
return spreadNodes;
}
},{"../../error":29,"../../language/kinds":38,"../../language/visitor":44,"babel-runtime/core-js/set":54}],163:[function(require,module,exports){
/**
* Copyright (c) 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';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.undefinedVarMessage = undefinedVarMessage;
exports.undefinedVarByOpMessage = undefinedVarByOpMessage;
exports.NoUndefinedVariables = NoUndefinedVariables;
var _error = require('../../error');
var _languageKinds = require('../../language/kinds');
function undefinedVarMessage(varName) {
return 'Variable "$' + varName + '" is not defined.';
}
function undefinedVarByOpMessage(varName, opName) {
return 'Variable "$' + varName + '" is not defined by operation "' + opName + '".';
}
/**
* No undefined variables
*
* A GraphQL operation is only valid if all variables encountered, both directly
* and via fragment spreads, are defined by that operation.
*/
function NoUndefinedVariables() {
var operation;
var visitedFragmentNames = {};
var definedVariableNames = {};
return {
// Visit FragmentDefinition after visiting FragmentSpread
visitSpreadFragments: true,
OperationDefinition: function OperationDefinition(node) {
operation = node;
visitedFragmentNames = {};
definedVariableNames = {};
},
VariableDefinition: function VariableDefinition(def) {
definedVariableNames[def.variable.name.value] = true;
},
Variable: function Variable(variable, key, parent, path, ancestors) {
var varName = variable.name.value;
if (definedVariableNames[varName] !== true) {
var withinFragment = ancestors.some(function (node) {
return node.kind === _languageKinds.FRAGMENT_DEFINITION;
});
if (withinFragment && operation && operation.name) {
return new _error.GraphQLError(undefinedVarByOpMessage(varName, operation.name.value), [variable, operation]);
}
return new _error.GraphQLError(undefinedVarMessage(varName), [variable]);
}
},
FragmentSpread: function FragmentSpread(spreadAST) {
// Only visit fragments of a particular name once per operation
if (visitedFragmentNames[spreadAST.name.value] === true) {
return false;
}
visitedFragmentNames[spreadAST.name.value] = true;
}
};
}
},{"../../error":29,"../../language/kinds":38}],164:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _Object$keys = require('babel-runtime/core-js/object/keys')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.unusedFragMessage = unusedFragMessage;
exports.NoUnusedFragments = NoUnusedFragments;
var _error = require('../../error');
function unusedFragMessage(fragName) {
return 'Fragment "' + fragName + '" is never used.';
}
/**
* No unused fragments
*
* A GraphQL document is only valid if all fragment definitions are spread
* within operations, or spread within other fragments spread within operations.
*/
function NoUnusedFragments() {
var fragmentDefs = [];
var spreadsWithinOperation = [];
var fragAdjacencies = {};
var spreadNames = {};
return {
OperationDefinition: function OperationDefinition() {
spreadNames = {};
spreadsWithinOperation.push(spreadNames);
},
FragmentDefinition: function FragmentDefinition(def) {
fragmentDefs.push(def);
spreadNames = {};
fragAdjacencies[def.name.value] = spreadNames;
},
FragmentSpread: function FragmentSpread(spread) {
spreadNames[spread.name.value] = true;
},
Document: {
leave: function leave() {
var fragmentNameUsed = {};
var reduceSpreadFragments = function reduceSpreadFragments(spreads) {
var keys = _Object$keys(spreads);
keys.forEach(function (fragName) {
if (fragmentNameUsed[fragName] !== true) {
fragmentNameUsed[fragName] = true;
var adjacencies = fragAdjacencies[fragName];
if (adjacencies) {
reduceSpreadFragments(adjacencies);
}
}
});
};
spreadsWithinOperation.forEach(reduceSpreadFragments);
var errors = fragmentDefs.filter(function (def) {
return fragmentNameUsed[def.name.value] !== true;
}).map(function (def) {
return new _error.GraphQLError(unusedFragMessage(def.name.value), [def]);
});
if (errors.length > 0) {
return errors;
}
}
}
};
}
},{"../../error":29,"babel-runtime/core-js/object/keys":52}],165:[function(require,module,exports){
/**
* Copyright (c) 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';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.unusedVariableMessage = unusedVariableMessage;
exports.NoUnusedVariables = NoUnusedVariables;
var _error = require('../../error');
function unusedVariableMessage(varName) {
return 'Variable "$' + varName + '" is never used.';
}
/**
* No unused variables
*
* A GraphQL operation is only valid if all variables defined by an operation
* are used, either directly or within a spread fragment.
*/
function NoUnusedVariables() {
var visitedFragmentNames = {};
var variableDefs = [];
var variableNameUsed = {};
return {
// Visit FragmentDefinition after visiting FragmentSpread
visitSpreadFragments: true,
OperationDefinition: {
enter: function enter() {
visitedFragmentNames = {};
variableDefs = [];
variableNameUsed = {};
},
leave: function leave() {
var errors = variableDefs.filter(function (def) {
return variableNameUsed[def.variable.name.value] !== true;
}).map(function (def) {
return new _error.GraphQLError(unusedVariableMessage(def.variable.name.value), [def]);
});
if (errors.length > 0) {
return errors;
}
}
},
VariableDefinition: function VariableDefinition(def) {
variableDefs.push(def);
// Do not visit deeper, or else the defined variable name will be visited.
return false;
},
Variable: function Variable(variable) {
variableNameUsed[variable.name.value] = true;
},
FragmentSpread: function FragmentSpread(spreadAST) {
// Only visit fragments of a particular name once per operation
if (visitedFragmentNames[spreadAST.name.value] === true) {
return false;
}
visitedFragmentNames[spreadAST.name.value] = true;
}
};
}
},{"../../error":29}],166:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _createClass = require('babel-runtime/helpers/create-class')['default'];
var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default'];
var _slicedToArray = require('babel-runtime/helpers/sliced-to-array')['default'];
var _Object$keys = require('babel-runtime/core-js/object/keys')['default'];
var _Map = require('babel-runtime/core-js/map')['default'];
var _Set = require('babel-runtime/core-js/set')['default'];
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.fieldsConflictMessage = fieldsConflictMessage;
exports.OverlappingFieldsCanBeMerged = OverlappingFieldsCanBeMerged;
// Field name and reason.
// Reason is a string, or a nested list of conflicts.
var _error = require('../../error');
var _jsutilsFind = require('../../jsutils/find');
var _jsutilsFind2 = _interopRequireDefault(_jsutilsFind);
var _languageKinds = require('../../language/kinds');
var _languagePrinter = require('../../language/printer');
var _typeDefinition = require('../../type/definition');
var _utilitiesTypeFromAST = require('../../utilities/typeFromAST');
function fieldsConflictMessage(responseName, reason) {
return 'Fields "' + responseName + '" conflict because ' + reasonMessage(reason) + '.';
}
function reasonMessage(reason) {
if (Array.isArray(reason)) {
return reason.map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2);
var responseName = _ref2[0];
var subreason = _ref2[1];
return 'subfields "' + responseName + '" conflict because ' + reasonMessage(subreason);
}).join(' and ');
}
return reason;
}
/**
* Overlapping fields can be merged
*
* A selection set is only valid if all fields (including spreading any
* fragments) either correspond to distinct response names or can be merged
* without ambiguity.
*/
function OverlappingFieldsCanBeMerged(context) {
var comparedSet = new PairSet();
function findConflicts(fieldMap) {
var conflicts = [];
_Object$keys(fieldMap).forEach(function (responseName) {
var fields = fieldMap[responseName];
if (fields.length > 1) {
for (var i = 0; i < fields.length; i++) {
for (var j = i; j < fields.length; j++) {
var conflict = findConflict(responseName, fields[i], fields[j]);
if (conflict) {
conflicts.push(conflict);
}
}
}
}
});
return conflicts;
}
function findConflict(responseName, pair1, pair2) {
var _pair1 = _slicedToArray(pair1, 2);
var ast1 = _pair1[0];
var def1 = _pair1[1];
var _pair2 = _slicedToArray(pair2, 2);
var ast2 = _pair2[0];
var def2 = _pair2[1];
if (ast1 === ast2 || comparedSet.has(ast1, ast2)) {
return;
}
comparedSet.add(ast1, ast2);
var name1 = ast1.name.value;
var name2 = ast2.name.value;
if (name1 !== name2) {
return [[responseName, name1 + ' and ' + name2 + ' are different fields'], [ast1, ast2]];
}
var type1 = def1 && def1.type;
var type2 = def2 && def2.type;
if (type1 && type2 && !sameType(type1, type2)) {
return [[responseName, 'they return differing types ' + type1 + ' and ' + type2], [ast1, ast2]];
}
if (!sameArguments(ast1.arguments || [], ast2.arguments || [])) {
return [[responseName, 'they have differing arguments'], [ast1, ast2]];
}
if (!sameDirectives(ast1.directives || [], ast2.directives || [])) {
return [[responseName, 'they have differing directives'], [ast1, ast2]];
}
var selectionSet1 = ast1.selectionSet;
var selectionSet2 = ast2.selectionSet;
if (selectionSet1 && selectionSet2) {
var visitedFragmentNames = {};
var subfieldMap = collectFieldASTsAndDefs(context, (0, _typeDefinition.getNamedType)(type1), selectionSet1, visitedFragmentNames);
subfieldMap = collectFieldASTsAndDefs(context, (0, _typeDefinition.getNamedType)(type2), selectionSet2, visitedFragmentNames, subfieldMap);
var conflicts = findConflicts(subfieldMap);
if (conflicts.length > 0) {
return [[responseName, conflicts.map(function (_ref3) {
var _ref32 = _slicedToArray(_ref3, 1);
var reason = _ref32[0];
return reason;
})], conflicts.reduce(function (allFields, _ref4) {
var _ref42 = _slicedToArray(_ref4, 2);
var fields = _ref42[1];
return allFields.concat(fields);
}, [ast1, ast2])];
}
}
}
return {
SelectionSet: {
// Note: we validate on the reverse traversal so deeper conflicts will be
// caught first, for clearer error messages.
leave: function leave(selectionSet) {
var fieldMap = collectFieldASTsAndDefs(context, context.getParentType(), selectionSet);
var conflicts = findConflicts(fieldMap);
if (conflicts.length) {
return conflicts.map(function (_ref5) {
var _ref52 = _slicedToArray(_ref5, 2);
var _ref52$0 = _slicedToArray(_ref52[0], 2);
var responseName = _ref52$0[0];
var reason = _ref52$0[1];
var fields = _ref52[1];
return new _error.GraphQLError(fieldsConflictMessage(responseName, reason), fields);
});
}
}
}
};
}
function sameDirectives(directives1, directives2) {
if (directives1.length !== directives2.length) {
return false;
}
return directives1.every(function (directive1) {
var directive2 = (0, _jsutilsFind2['default'])(directives2, function (directive) {
return directive.name.value === directive1.name.value;
});
if (!directive2) {
return false;
}
return sameArguments(directive1.arguments || [], directive2.arguments || []);
});
}
function sameArguments(arguments1, arguments2) {
if (arguments1.length !== arguments2.length) {
return false;
}
return arguments1.every(function (argument1) {
var argument2 = (0, _jsutilsFind2['default'])(arguments2, function (argument) {
return argument.name.value === argument1.name.value;
});
if (!argument2) {
return false;
}
return sameValue(argument1.value, argument2.value);
});
}
function sameValue(value1, value2) {
return !value1 && !value2 || (0, _languagePrinter.print)(value1) === (0, _languagePrinter.print)(value2);
}
function sameType(type1, type2) {
return String(type1) === String(type2);
}
/**
* Given a selectionSet, adds all of the fields in that selection to
* the passed in map of fields, and returns it at the end.
*
* Note: This is not the same as execution's collectFields because at static
* time we do not know what object type will be used, so we unconditionally
* spread in all fragments.
*/
function collectFieldASTsAndDefs(context, parentType, selectionSet, visitedFragmentNames, astAndDefs) {
var _visitedFragmentNames = visitedFragmentNames || {};
var _astAndDefs = astAndDefs || {};
for (var i = 0; i < selectionSet.selections.length; i++) {
var selection = selectionSet.selections[i];
switch (selection.kind) {
case _languageKinds.FIELD:
var fieldName = selection.name.value;
var fieldDef;
if (parentType instanceof _typeDefinition.GraphQLObjectType || parentType instanceof _typeDefinition.GraphQLInterfaceType) {
fieldDef = parentType.getFields()[fieldName];
}
var responseName = selection.alias ? selection.alias.value : fieldName;
if (!_astAndDefs[responseName]) {
_astAndDefs[responseName] = [];
}
_astAndDefs[responseName].push([selection, fieldDef]);
break;
case _languageKinds.INLINE_FRAGMENT:
var typeCondition = selection.typeCondition;
var inlineFragmentType = typeCondition ? (0, _utilitiesTypeFromAST.typeFromAST)(context.getSchema(), selection.typeCondition) : parentType;
_astAndDefs = collectFieldASTsAndDefs(context, inlineFragmentType, selection.selectionSet, _visitedFragmentNames, _astAndDefs);
break;
case _languageKinds.FRAGMENT_SPREAD:
var fragName = selection.name.value;
if (_visitedFragmentNames[fragName]) {
continue;
}
_visitedFragmentNames[fragName] = true;
var fragment = context.getFragment(fragName);
if (!fragment) {
continue;
}
_astAndDefs = collectFieldASTsAndDefs(context, (0, _utilitiesTypeFromAST.typeFromAST)(context.getSchema(), fragment.typeCondition), fragment.selectionSet, _visitedFragmentNames, _astAndDefs);
break;
}
}
return _astAndDefs;
}
/**
* A way to keep track of pairs of things when the ordering of the pair does
* not matter. We do this by maintaining a sort of double adjacency sets.
*/
var PairSet = (function () {
function PairSet() {
_classCallCheck(this, PairSet);
this._data = new _Map();
}
_createClass(PairSet, [{
key: 'has',
value: function has(a, b) {
var first = this._data.get(a);
return first && first.has(b);
}
}, {
key: 'add',
value: function add(a, b) {
_pairSetAdd(this._data, a, b);
_pairSetAdd(this._data, b, a);
}
}]);
return PairSet;
})();
function _pairSetAdd(data, a, b) {
var set = data.get(a);
if (!set) {
set = new _Set();
data.set(a, set);
}
set.add(b);
}
},{"../../error":29,"../../jsutils/find":32,"../../language/kinds":38,"../../language/printer":42,"../../type/definition":134,"../../utilities/typeFromAST":150,"babel-runtime/core-js/map":47,"babel-runtime/core-js/object/keys":52,"babel-runtime/core-js/set":54,"babel-runtime/helpers/class-call-check":55,"babel-runtime/helpers/create-class":56,"babel-runtime/helpers/interop-require-default":60,"babel-runtime/helpers/sliced-to-array":62}],167:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.typeIncompatibleSpreadMessage = typeIncompatibleSpreadMessage;
exports.typeIncompatibleAnonSpreadMessage = typeIncompatibleAnonSpreadMessage;
exports.PossibleFragmentSpreads = PossibleFragmentSpreads;
var _error = require('../../error');
var _jsutilsKeyMap = require('../../jsutils/keyMap');
var _jsutilsKeyMap2 = _interopRequireDefault(_jsutilsKeyMap);
var _typeDefinition = require('../../type/definition');
var _utilitiesTypeFromAST = require('../../utilities/typeFromAST');
function typeIncompatibleSpreadMessage(fragName, parentType, fragType) {
return 'Fragment "' + fragName + '" cannot be spread here as objects of ' + ('type "' + parentType + '" can never be of type "' + fragType + '".');
}
function typeIncompatibleAnonSpreadMessage(parentType, fragType) {
return 'Fragment cannot be spread here as objects of ' + ('type "' + parentType + '" can never be of type "' + fragType + '".');
}
/**
* Possible fragment spread
*
* A fragment spread is only valid if the type condition could ever possibly
* be true: if there is a non-empty intersection of the possible parent types,
* and possible types which pass the type condition.
*/
function PossibleFragmentSpreads(context) {
return {
InlineFragment: function InlineFragment(node) {
var fragType = context.getType();
var parentType = context.getParentType();
if (fragType && parentType && !doTypesOverlap(fragType, parentType)) {
return new _error.GraphQLError(typeIncompatibleAnonSpreadMessage(parentType, fragType), [node]);
}
},
FragmentSpread: function FragmentSpread(node) {
var fragName = node.name.value;
var fragType = getFragmentType(context, fragName);
var parentType = context.getParentType();
if (fragType && parentType && !doTypesOverlap(fragType, parentType)) {
return new _error.GraphQLError(typeIncompatibleSpreadMessage(fragName, parentType, fragType), [node]);
}
}
};
}
function getFragmentType(context, name) {
var frag = context.getFragment(name);
return frag && (0, _utilitiesTypeFromAST.typeFromAST)(context.getSchema(), frag.typeCondition);
}
function doTypesOverlap(t1, t2) {
if (t1 === t2) {
return true;
}
if (t1 instanceof _typeDefinition.GraphQLObjectType) {
if (t2 instanceof _typeDefinition.GraphQLObjectType) {
return false;
}
return t2.getPossibleTypes().indexOf(t1) !== -1;
}
if (t1 instanceof _typeDefinition.GraphQLInterfaceType || t1 instanceof _typeDefinition.GraphQLUnionType) {
if (t2 instanceof _typeDefinition.GraphQLObjectType) {
return t1.getPossibleTypes().indexOf(t2) !== -1;
}
var t1TypeNames = (0, _jsutilsKeyMap2['default'])(t1.getPossibleTypes(), function (type) {
return type.name;
});
return t2.getPossibleTypes().some(function (type) {
return t1TypeNames[type.name];
});
}
}
},{"../../error":29,"../../jsutils/keyMap":35,"../../type/definition":134,"../../utilities/typeFromAST":150,"babel-runtime/helpers/interop-require-default":60}],168:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.missingFieldArgMessage = missingFieldArgMessage;
exports.missingDirectiveArgMessage = missingDirectiveArgMessage;
exports.ProvidedNonNullArguments = ProvidedNonNullArguments;
var _error = require('../../error');
var _jsutilsKeyMap = require('../../jsutils/keyMap');
var _jsutilsKeyMap2 = _interopRequireDefault(_jsutilsKeyMap);
var _typeDefinition = require('../../type/definition');
function missingFieldArgMessage(fieldName, argName, type) {
return 'Field "' + fieldName + '" argument "' + argName + '" of type "' + type + '" ' + 'is required but not provided.';
}
function missingDirectiveArgMessage(directiveName, argName, type) {
return 'Directive "@' + directiveName + '" argument "' + argName + '" of type ' + ('"' + type + '" is required but not provided.');
}
/**
* Provided required arguments
*
* A field or directive is only valid if all required (non-null) field arguments
* have been provided.
*/
function ProvidedNonNullArguments(context) {
return {
Field: {
// Validate on leave to allow for deeper errors to appear first.
leave: function leave(fieldAST) {
var fieldDef = context.getFieldDef();
if (!fieldDef) {
return false;
}
var errors = [];
var argASTs = fieldAST.arguments || [];
var argASTMap = (0, _jsutilsKeyMap2['default'])(argASTs, function (arg) {
return arg.name.value;
});
fieldDef.args.forEach(function (argDef) {
var argAST = argASTMap[argDef.name];
if (!argAST && argDef.type instanceof _typeDefinition.GraphQLNonNull) {
errors.push(new _error.GraphQLError(missingFieldArgMessage(fieldAST.name.value, argDef.name, argDef.type), [fieldAST]));
}
});
if (errors.length > 0) {
return errors;
}
}
},
Directive: {
// Validate on leave to allow for deeper errors to appear first.
leave: function leave(directiveAST) {
var directiveDef = context.getDirective();
if (!directiveDef) {
return false;
}
var errors = [];
var argASTs = directiveAST.arguments || [];
var argASTMap = (0, _jsutilsKeyMap2['default'])(argASTs, function (arg) {
return arg.name.value;
});
directiveDef.args.forEach(function (argDef) {
var argAST = argASTMap[argDef.name];
if (!argAST && argDef.type instanceof _typeDefinition.GraphQLNonNull) {
errors.push(new _error.GraphQLError(missingDirectiveArgMessage(directiveAST.name.value, argDef.name, argDef.type), [directiveAST]));
}
});
if (errors.length > 0) {
return errors;
}
}
}
};
}
},{"../../error":29,"../../jsutils/keyMap":35,"../../type/definition":134,"babel-runtime/helpers/interop-require-default":60}],169:[function(require,module,exports){
/**
* Copyright (c) 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';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.noSubselectionAllowedMessage = noSubselectionAllowedMessage;
exports.requiredSubselectionMessage = requiredSubselectionMessage;
exports.ScalarLeafs = ScalarLeafs;
var _error = require('../../error');
var _typeDefinition = require('../../type/definition');
function noSubselectionAllowedMessage(field, type) {
return 'Field "' + field + '" of type "' + type + '" must not have a sub selection.';
}
function requiredSubselectionMessage(field, type) {
return 'Field "' + field + '" of type "' + type + '" must have a sub selection.';
}
/**
* Scalar leafs
*
* A GraphQL document is valid only if all leaf fields (fields without
* sub selections) are of scalar or enum types.
*/
function ScalarLeafs(context) {
return {
Field: function Field(node) {
var type = context.getType();
if (type) {
if ((0, _typeDefinition.isLeafType)(type)) {
if (node.selectionSet) {
return new _error.GraphQLError(noSubselectionAllowedMessage(node.name.value, type), [node.selectionSet]);
}
} else if (!node.selectionSet) {
return new _error.GraphQLError(requiredSubselectionMessage(node.name.value, type), [node]);
}
}
}
};
}
},{"../../error":29,"../../type/definition":134}],170:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _Object$create = require('babel-runtime/core-js/object/create')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.duplicateArgMessage = duplicateArgMessage;
exports.UniqueArgumentNames = UniqueArgumentNames;
var _error = require('../../error');
function duplicateArgMessage(argName) {
return 'There can be only one argument named "' + argName + '".';
}
/**
* Unique argument names
*
* A GraphQL field or directive is only valid if all supplied arguments are
* uniquely named.
*/
function UniqueArgumentNames() {
var knownArgNames = _Object$create(null);
return {
Field: function Field() {
knownArgNames = _Object$create(null);
},
Directive: function Directive() {
knownArgNames = _Object$create(null);
},
Argument: function Argument(node) {
var argName = node.name.value;
if (knownArgNames[argName]) {
return new _error.GraphQLError(duplicateArgMessage(argName), [knownArgNames[argName], node.name]);
}
knownArgNames[argName] = node.name;
}
};
}
},{"../../error":29,"babel-runtime/core-js/object/create":49}],171:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _Object$create = require('babel-runtime/core-js/object/create')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.duplicateFragmentNameMessage = duplicateFragmentNameMessage;
exports.UniqueFragmentNames = UniqueFragmentNames;
var _error = require('../../error');
function duplicateFragmentNameMessage(fragName) {
return 'There can only be one fragment named "' + fragName + '".';
}
/**
* Unique fragment names
*
* A GraphQL document is only valid if all defined fragments have unique names.
*/
function UniqueFragmentNames() {
var knownFragmentNames = _Object$create(null);
return {
FragmentDefinition: function FragmentDefinition(node) {
var fragmentName = node.name.value;
if (knownFragmentNames[fragmentName]) {
return new _error.GraphQLError(duplicateFragmentNameMessage(fragmentName), [knownFragmentNames[fragmentName], node.name]);
}
knownFragmentNames[fragmentName] = node.name;
}
};
}
},{"../../error":29,"babel-runtime/core-js/object/create":49}],172:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _Object$create = require('babel-runtime/core-js/object/create')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.duplicateInputFieldMessage = duplicateInputFieldMessage;
exports.UniqueInputFieldNames = UniqueInputFieldNames;
var _error = require('../../error');
function duplicateInputFieldMessage(fieldName) {
return 'There can be only one input field named "' + fieldName + '".';
}
/**
* Unique input field names
*
* A GraphQL input object value is only valid if all supplied fields are
* uniquely named.
*/
function UniqueInputFieldNames() {
var knownNames = _Object$create(null);
return {
ObjectValue: function ObjectValue() {
knownNames = _Object$create(null);
},
ObjectField: function ObjectField(node) {
var fieldName = node.name.value;
if (knownNames[fieldName]) {
return new _error.GraphQLError(duplicateInputFieldMessage(fieldName), [knownNames[fieldName], node.name]);
}
knownNames[fieldName] = node.name;
}
};
}
},{"../../error":29,"babel-runtime/core-js/object/create":49}],173:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _Object$create = require('babel-runtime/core-js/object/create')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.duplicateOperationNameMessage = duplicateOperationNameMessage;
exports.UniqueOperationNames = UniqueOperationNames;
var _error = require('../../error');
function duplicateOperationNameMessage(operationName) {
return 'There can only be one operation named "' + operationName + '".';
}
/**
* Unique operation names
*
* A GraphQL document is only valid if all defined operations have unique names.
*/
function UniqueOperationNames() {
var knownOperationNames = _Object$create(null);
return {
OperationDefinition: function OperationDefinition(node) {
var operationName = node.name;
if (operationName) {
if (knownOperationNames[operationName.value]) {
return new _error.GraphQLError(duplicateOperationNameMessage(operationName.value), [knownOperationNames[operationName.value], operationName]);
}
knownOperationNames[operationName.value] = operationName;
}
}
};
}
},{"../../error":29,"babel-runtime/core-js/object/create":49}],174:[function(require,module,exports){
/**
* Copyright (c) 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';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.nonInputTypeOnVarMessage = nonInputTypeOnVarMessage;
exports.VariablesAreInputTypes = VariablesAreInputTypes;
var _error = require('../../error');
var _languagePrinter = require('../../language/printer');
var _typeDefinition = require('../../type/definition');
var _utilitiesTypeFromAST = require('../../utilities/typeFromAST');
function nonInputTypeOnVarMessage(variableName, typeName) {
return 'Variable "$' + variableName + '" cannot be non-input type "' + typeName + '".';
}
/**
* Variables are input types
*
* A GraphQL operation is only valid if all the variables it defines are of
* input types (scalar, enum, or input object).
*/
function VariablesAreInputTypes(context) {
return {
VariableDefinition: function VariableDefinition(node) {
var type = (0, _utilitiesTypeFromAST.typeFromAST)(context.getSchema(), node.type);
// If the variable type is not an input type, return an error.
if (type && !(0, _typeDefinition.isInputType)(type)) {
var variableName = node.variable.name.value;
return new _error.GraphQLError(nonInputTypeOnVarMessage(variableName, (0, _languagePrinter.print)(node.type)), [node.type]);
}
}
};
}
},{"../../error":29,"../../language/printer":42,"../../type/definition":134,"../../utilities/typeFromAST":150}],175:[function(require,module,exports){
/**
* Copyright (c) 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';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.badVarPosMessage = badVarPosMessage;
exports.VariablesInAllowedPosition = VariablesInAllowedPosition;
var _error = require('../../error');
var _typeDefinition = require('../../type/definition');
var _utilitiesTypeFromAST = require('../../utilities/typeFromAST');
function badVarPosMessage(varName, varType, expectedType) {
return 'Variable "$' + varName + '" of type "' + varType + '" used in position ' + ('expecting type "' + expectedType + '".');
}
/**
* Variables passed to field arguments conform to type
*/
function VariablesInAllowedPosition(context) {
var varDefMap = {};
var visitedFragmentNames = {};
return {
// Visit FragmentDefinition after visiting FragmentSpread
visitSpreadFragments: true,
OperationDefinition: function OperationDefinition() {
varDefMap = {};
visitedFragmentNames = {};
},
VariableDefinition: function VariableDefinition(varDefAST) {
varDefMap[varDefAST.variable.name.value] = varDefAST;
},
FragmentSpread: function FragmentSpread(spreadAST) {
// Only visit fragments of a particular name once per operation
if (visitedFragmentNames[spreadAST.name.value]) {
return false;
}
visitedFragmentNames[spreadAST.name.value] = true;
},
Variable: function Variable(variableAST) {
var varName = variableAST.name.value;
var varDef = varDefMap[varName];
var varType = varDef && (0, _utilitiesTypeFromAST.typeFromAST)(context.getSchema(), varDef.type);
var inputType = context.getInputType();
if (varType && inputType && !varTypeAllowedForType(effectiveType(varType, varDef), inputType)) {
return new _error.GraphQLError(badVarPosMessage(varName, varType, inputType), [variableAST]);
}
}
};
}
// If a variable definition has a default value, it's effectively non-null.
function effectiveType(varType, varDef) {
return !varDef.defaultValue || varType instanceof _typeDefinition.GraphQLNonNull ? varType : new _typeDefinition.GraphQLNonNull(varType);
}
// A var type is allowed if it is the same or more strict than the expected
// type. It can be more strict if the variable type is non-null when the
// expected type is nullable. If both are list types, the variable item type can
// be more strict than the expected item type.
function varTypeAllowedForType(_x, _x2) {
var _again = true;
_function: while (_again) {
var varType = _x,
expectedType = _x2;
_again = false;
if (expectedType instanceof _typeDefinition.GraphQLNonNull) {
if (varType instanceof _typeDefinition.GraphQLNonNull) {
_x = varType.ofType;
_x2 = expectedType.ofType;
_again = true;
continue _function;
}
return false;
}
if (varType instanceof _typeDefinition.GraphQLNonNull) {
_x = varType.ofType;
_x2 = expectedType;
_again = true;
continue _function;
}
if (varType instanceof _typeDefinition.GraphQLList && expectedType instanceof _typeDefinition.GraphQLList) {
_x = varType.ofType;
_x2 = expectedType.ofType;
_again = true;
continue _function;
}
return varType === expectedType;
}
}
},{"../../error":29,"../../type/definition":134,"../../utilities/typeFromAST":150}],176:[function(require,module,exports){
/**
* Copyright (c) 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.
*/
// Spec Section: "Operation Name Uniqueness"
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _rulesUniqueOperationNames = require('./rules/UniqueOperationNames');
// Spec Section: "Lone Anonymous Operation"
var _rulesLoneAnonymousOperation = require('./rules/LoneAnonymousOperation');
// Spec Section: "Fragment Spread Type Existence"
var _rulesKnownTypeNames = require('./rules/KnownTypeNames');
// Spec Section: "Fragments on Composite Types"
var _rulesFragmentsOnCompositeTypes = require('./rules/FragmentsOnCompositeTypes');
// Spec Section: "Variables are Input Types"
var _rulesVariablesAreInputTypes = require('./rules/VariablesAreInputTypes');
// Spec Section: "Leaf Field Selections"
var _rulesScalarLeafs = require('./rules/ScalarLeafs');
// Spec Section: "Field Selections on Objects, Interfaces, and Unions Types"
var _rulesFieldsOnCorrectType = require('./rules/FieldsOnCorrectType');
// Spec Section: "Fragment Name Uniqueness"
var _rulesUniqueFragmentNames = require('./rules/UniqueFragmentNames');
// Spec Section: "Fragment spread target defined"
var _rulesKnownFragmentNames = require('./rules/KnownFragmentNames');
// Spec Section: "Fragments must be used"
var _rulesNoUnusedFragments = require('./rules/NoUnusedFragments');
// Spec Section: "Fragment spread is possible"
var _rulesPossibleFragmentSpreads = require('./rules/PossibleFragmentSpreads');
// Spec Section: "Fragments must not form cycles"
var _rulesNoFragmentCycles = require('./rules/NoFragmentCycles');
// Spec Section: "All Variable Used Defined"
var _rulesNoUndefinedVariables = require('./rules/NoUndefinedVariables');
// Spec Section: "All Variables Used"
var _rulesNoUnusedVariables = require('./rules/NoUnusedVariables');
// Spec Section: "Directives Are Defined"
var _rulesKnownDirectives = require('./rules/KnownDirectives');
// Spec Section: "Argument Names"
var _rulesKnownArgumentNames = require('./rules/KnownArgumentNames');
// Spec Section: "Argument Uniqueness"
var _rulesUniqueArgumentNames = require('./rules/UniqueArgumentNames');
// Spec Section: "Argument Values Type Correctness"
var _rulesArgumentsOfCorrectType = require('./rules/ArgumentsOfCorrectType');
// Spec Section: "Argument Optionality"
var _rulesProvidedNonNullArguments = require('./rules/ProvidedNonNullArguments');
// Spec Section: "Variable Default Values Are Correctly Typed"
var _rulesDefaultValuesOfCorrectType = require('./rules/DefaultValuesOfCorrectType');
// Spec Section: "All Variable Usages Are Allowed"
var _rulesVariablesInAllowedPosition = require('./rules/VariablesInAllowedPosition');
// Spec Section: "Field Selection Merging"
var _rulesOverlappingFieldsCanBeMerged = require('./rules/OverlappingFieldsCanBeMerged');
// Spec Section: "Input Object Field Uniqueness"
var _rulesUniqueInputFieldNames = require('./rules/UniqueInputFieldNames');
/**
* This set includes all validation rules defined by the GraphQL spec.
*/
var specifiedRules = [_rulesUniqueOperationNames.UniqueOperationNames, _rulesLoneAnonymousOperation.LoneAnonymousOperation, _rulesKnownTypeNames.KnownTypeNames, _rulesFragmentsOnCompositeTypes.FragmentsOnCompositeTypes, _rulesVariablesAreInputTypes.VariablesAreInputTypes, _rulesScalarLeafs.ScalarLeafs, _rulesFieldsOnCorrectType.FieldsOnCorrectType, _rulesUniqueFragmentNames.UniqueFragmentNames, _rulesKnownFragmentNames.KnownFragmentNames, _rulesNoUnusedFragments.NoUnusedFragments, _rulesPossibleFragmentSpreads.PossibleFragmentSpreads, _rulesNoFragmentCycles.NoFragmentCycles, _rulesNoUndefinedVariables.NoUndefinedVariables, _rulesNoUnusedVariables.NoUnusedVariables, _rulesKnownDirectives.KnownDirectives, _rulesKnownArgumentNames.KnownArgumentNames, _rulesUniqueArgumentNames.UniqueArgumentNames, _rulesArgumentsOfCorrectType.ArgumentsOfCorrectType, _rulesProvidedNonNullArguments.ProvidedNonNullArguments, _rulesDefaultValuesOfCorrectType.DefaultValuesOfCorrectType, _rulesVariablesInAllowedPosition.VariablesInAllowedPosition, _rulesOverlappingFieldsCanBeMerged.OverlappingFieldsCanBeMerged, _rulesUniqueInputFieldNames.UniqueInputFieldNames];
exports.specifiedRules = specifiedRules;
},{"./rules/ArgumentsOfCorrectType":153,"./rules/DefaultValuesOfCorrectType":154,"./rules/FieldsOnCorrectType":155,"./rules/FragmentsOnCompositeTypes":156,"./rules/KnownArgumentNames":157,"./rules/KnownDirectives":158,"./rules/KnownFragmentNames":159,"./rules/KnownTypeNames":160,"./rules/LoneAnonymousOperation":161,"./rules/NoFragmentCycles":162,"./rules/NoUndefinedVariables":163,"./rules/NoUnusedFragments":164,"./rules/NoUnusedVariables":165,"./rules/OverlappingFieldsCanBeMerged":166,"./rules/PossibleFragmentSpreads":167,"./rules/ProvidedNonNullArguments":168,"./rules/ScalarLeafs":169,"./rules/UniqueArgumentNames":170,"./rules/UniqueFragmentNames":171,"./rules/UniqueInputFieldNames":172,"./rules/UniqueOperationNames":173,"./rules/VariablesAreInputTypes":174,"./rules/VariablesInAllowedPosition":175}],177:[function(require,module,exports){
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var _createClass = require('babel-runtime/helpers/create-class')['default'];
var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default'];
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
var _interopRequireWildcard = require('babel-runtime/helpers/interop-require-wildcard')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.validate = validate;
var _jsutilsInvariant = require('../jsutils/invariant');
var _jsutilsInvariant2 = _interopRequireDefault(_jsutilsInvariant);
var _error = require('../error');
var _languageVisitor = require('../language/visitor');
var _languageKinds = require('../language/kinds');
var Kind = _interopRequireWildcard(_languageKinds);
var _typeSchema = require('../type/schema');
var _utilitiesTypeInfo = require('../utilities/TypeInfo');
var _specifiedRules = require('./specifiedRules');
/**
* Implements the "Validation" section of the spec.
*
* Validation runs synchronously, returning an array of encountered errors, or
* an empty array if no errors were encountered and the document is valid.
*
* A list of specific validation rules may be provided. If not provided, the
* default list of rules defined by the GraphQL specification will be used.
*
* Each validation rules is a function which returns a visitor
* (see the language/visitor API). Visitor methods are expected to return
* GraphQLErrors, or Arrays of GraphQLErrors when invalid.
*
* Visitors can also supply `visitSpreadFragments: true` which will alter the
* behavior of the visitor to skip over top level defined fragments, and instead
* visit those fragments at every point a spread is encountered.
*/
function validate(schema, ast, rules) {
(0, _jsutilsInvariant2['default'])(schema, 'Must provide schema');
(0, _jsutilsInvariant2['default'])(ast, 'Must provide document');
(0, _jsutilsInvariant2['default'])(schema instanceof _typeSchema.GraphQLSchema, 'Schema must be an instance of GraphQLSchema. Also ensure that there are ' + 'not multiple versions of GraphQL installed in your node_modules directory.');
return visitUsingRules(schema, ast, rules || _specifiedRules.specifiedRules);
}
/**
* This uses a specialized visitor which runs multiple visitors in parallel,
* while maintaining the visitor skip and break API.
*/
function visitUsingRules(schema, documentAST, rules) {
var typeInfo = new _utilitiesTypeInfo.TypeInfo(schema);
var context = new ValidationContext(schema, documentAST, typeInfo);
var errors = [];
function visitInstance(ast, instance) {
(0, _languageVisitor.visit)(ast, {
enter: function enter(node, key) {
// Collect type information about the current position in the AST.
typeInfo.enter(node);
// Do not visit top level fragment definitions if this instance will
// visit those fragments inline because it
// provided `visitSpreadFragments`.
var result;
if (node.kind === Kind.FRAGMENT_DEFINITION && key !== undefined && instance.visitSpreadFragments) {
return false;
}
// Get the visitor function from the validation instance, and if it
// exists, call it with the visitor arguments.
var enter = (0, _languageVisitor.getVisitFn)(instance, false, node.kind);
result = enter ? enter.apply(instance, arguments) : undefined;
// If the visitor returned an error, log it and do not visit any
// deeper nodes.
if (result && isError(result)) {
append(errors, result);
result = false;
}
// If any validation instances provide the flag `visitSpreadFragments`
// and this node is a fragment spread, visit the fragment definition
// from this point.
if (result === undefined && instance.visitSpreadFragments && node.kind === Kind.FRAGMENT_SPREAD) {
var fragment = context.getFragment(node.name.value);
if (fragment) {
visitInstance(fragment, instance);
}
}
// If the result is "false", we're not visiting any descendent nodes,
// but need to update typeInfo.
if (result === false) {
typeInfo.leave(node);
}
return result;
},
leave: function leave(node) {
// Get the visitor function from the validation instance, and if it
// exists, call it with the visitor arguments.
var leave = (0, _languageVisitor.getVisitFn)(instance, true, node.kind);
var result = leave ? leave.apply(instance, arguments) : undefined;
// If the visitor returned an error, log it and do not visit any
// deeper nodes.
if (result && isError(result)) {
append(errors, result);
result = false;
}
// Update typeInfo.
typeInfo.leave(node);
return result;
}
});
}
// Visit the whole document with each instance of all provided rules.
var instances = rules.map(function (rule) {
return rule(context);
});
instances.forEach(function (instance) {
visitInstance(documentAST, instance);
});
return errors;
}
function isError(value) {
return Array.isArray(value) ? value.every(function (item) {
return item instanceof _error.GraphQLError;
}) : value instanceof _error.GraphQLError;
}
function append(arr, items) {
if (Array.isArray(items)) {
arr.push.apply(arr, items);
} else {
arr.push(items);
}
}
/**
* An instance of this class is passed as the "this" context to all validators,
* allowing access to commonly useful contextual information from within a
* validation rule.
*/
var ValidationContext = (function () {
function ValidationContext(schema, ast, typeInfo) {
_classCallCheck(this, ValidationContext);
this._schema = schema;
this._ast = ast;
this._typeInfo = typeInfo;
}
_createClass(ValidationContext, [{
key: 'getSchema',
value: function getSchema() {
return this._schema;
}
}, {
key: 'getDocument',
value: function getDocument() {
return this._ast;
}
}, {
key: 'getFragment',
value: function getFragment(name) {
var fragments = this._fragments;
if (!fragments) {
this._fragments = fragments = this.getDocument().definitions.reduce(function (frags, statement) {
if (statement.kind === Kind.FRAGMENT_DEFINITION) {
frags[statement.name.value] = statement;
}
return frags;
}, {});
}
return fragments[name];
}
}, {
key: 'getType',
value: function getType() {
return this._typeInfo.getType();
}
}, {
key: 'getParentType',
value: function getParentType() {
return this._typeInfo.getParentType();
}
}, {
key: 'getInputType',
value: function getInputType() {
return this._typeInfo.getInputType();
}
}, {
key: 'getFieldDef',
value: function getFieldDef() {
return this._typeInfo.getFieldDef();
}
}, {
key: 'getDirective',
value: function getDirective() {
return this._typeInfo.getDirective();
}
}, {
key: 'getArgument',
value: function getArgument() {
return this._typeInfo.getArgument();
}
}]);
return ValidationContext;
})();
exports.ValidationContext = ValidationContext;
},{"../error":29,"../jsutils/invariant":33,"../language/kinds":38,"../language/visitor":44,"../type/schema":139,"../utilities/TypeInfo":140,"./specifiedRules":176,"babel-runtime/helpers/class-call-check":55,"babel-runtime/helpers/create-class":56,"babel-runtime/helpers/interop-require-default":60,"babel-runtime/helpers/interop-require-wildcard":61}],178:[function(require,module,exports){
(function (global){
/**
* marked - a markdown parser
* Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
* https://github.com/chjj/marked
*/
;(function() {
/**
* Block-Level Grammar
*/
var block = {
newline: /^\n+/,
code: /^( {4}[^\n]+\n*)+/,
fences: noop,
hr: /^( *[-*_]){3,} *(?:\n+|$)/,
heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
nptable: noop,
lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
table: noop,
paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
text: /^[^\n]+/
};
block.bullet = /(?:[*+-]|\d+\.)/;
block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
block.item = replace(block.item, 'gm')
(/bull/g, block.bullet)
();
block.list = replace(block.list)
(/bull/g, block.bullet)
('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
('def', '\\n+(?=' + block.def.source + ')')
();
block.blockquote = replace(block.blockquote)
('def', block.def)
();
block._tag = '(?!(?:'
+ 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
+ '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
+ '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
block.html = replace(block.html)
('comment', /<!--[\s\S]*?-->/)
('closed', /<(tag)[\s\S]+?<\/\1>/)
('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
(/tag/g, block._tag)
();
block.paragraph = replace(block.paragraph)
('hr', block.hr)
('heading', block.heading)
('lheading', block.lheading)
('blockquote', block.blockquote)
('tag', '<' + block._tag)
('def', block.def)
();
/**
* Normal Block Grammar
*/
block.normal = merge({}, block);
/**
* GFM Block Grammar
*/
block.gfm = merge({}, block.normal, {
fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,
paragraph: /^/,
heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
});
block.gfm.paragraph = replace(block.paragraph)
('(?!', '(?!'
+ block.gfm.fences.source.replace('\\1', '\\2') + '|'
+ block.list.source.replace('\\1', '\\3') + '|')
();
/**
* GFM + Tables Block Grammar
*/
block.tables = merge({}, block.gfm, {
nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
});
/**
* Block Lexer
*/
function Lexer(options) {
this.tokens = [];
this.tokens.links = {};
this.options = options || marked.defaults;
this.rules = block.normal;
if (this.options.gfm) {
if (this.options.tables) {
this.rules = block.tables;
} else {
this.rules = block.gfm;
}
}
}
/**
* Expose Block Rules
*/
Lexer.rules = block;
/**
* Static Lex Method
*/
Lexer.lex = function(src, options) {
var lexer = new Lexer(options);
return lexer.lex(src);
};
/**
* Preprocessing
*/
Lexer.prototype.lex = function(src) {
src = src
.replace(/\r\n|\r/g, '\n')
.replace(/\t/g, ' ')
.replace(/\u00a0/g, ' ')
.replace(/\u2424/g, '\n');
return this.token(src, true);
};
/**
* Lexing
*/
Lexer.prototype.token = function(src, top, bq) {
var src = src.replace(/^ +$/gm, '')
, next
, loose
, cap
, bull
, b
, item
, space
, i
, l;
while (src) {
// newline
if (cap = this.rules.newline.exec(src)) {
src = src.substring(cap[0].length);
if (cap[0].length > 1) {
this.tokens.push({
type: 'space'
});
}
}
// code
if (cap = this.rules.code.exec(src)) {
src = src.substring(cap[0].length);
cap = cap[0].replace(/^ {4}/gm, '');
this.tokens.push({
type: 'code',
text: !this.options.pedantic
? cap.replace(/\n+$/, '')
: cap
});
continue;
}
// fences (gfm)
if (cap = this.rules.fences.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'code',
lang: cap[2],
text: cap[3] || ''
});
continue;
}
// heading
if (cap = this.rules.heading.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'heading',
depth: cap[1].length,
text: cap[2]
});
continue;
}
// table no leading pipe (gfm)
if (top && (cap = this.rules.nptable.exec(src))) {
src = src.substring(cap[0].length);
item = {
type: 'table',
header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3].replace(/\n$/, '').split('\n')
};
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = item.cells[i].split(/ *\| */);
}
this.tokens.push(item);
continue;
}
// lheading
if (cap = this.rules.lheading.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'heading',
depth: cap[2] === '=' ? 1 : 2,
text: cap[1]
});
continue;
}
// hr
if (cap = this.rules.hr.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'hr'
});
continue;
}
// blockquote
if (cap = this.rules.blockquote.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'blockquote_start'
});
cap = cap[0].replace(/^ *> ?/gm, '');
// Pass `top` to keep the current
// "toplevel" state. This is exactly
// how markdown.pl works.
this.token(cap, top, true);
this.tokens.push({
type: 'blockquote_end'
});
continue;
}
// list
if (cap = this.rules.list.exec(src)) {
src = src.substring(cap[0].length);
bull = cap[2];
this.tokens.push({
type: 'list_start',
ordered: bull.length > 1
});
// Get each top-level item.
cap = cap[0].match(this.rules.item);
next = false;
l = cap.length;
i = 0;
for (; i < l; i++) {
item = cap[i];
// Remove the list item's bullet
// so it is seen as the next token.
space = item.length;
item = item.replace(/^ *([*+-]|\d+\.) +/, '');
// Outdent whatever the
// list item contains. Hacky.
if (~item.indexOf('\n ')) {
space -= item.length;
item = !this.options.pedantic
? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
: item.replace(/^ {1,4}/gm, '');
}
// Determine whether the next list item belongs here.
// Backpedal if it does not belong in this list.
if (this.options.smartLists && i !== l - 1) {
b = block.bullet.exec(cap[i + 1])[0];
if (bull !== b && !(bull.length > 1 && b.length > 1)) {
src = cap.slice(i + 1).join('\n') + src;
i = l - 1;
}
}
// Determine whether item is loose or not.
// Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
// for discount behavior.
loose = next || /\n\n(?!\s*$)/.test(item);
if (i !== l - 1) {
next = item.charAt(item.length - 1) === '\n';
if (!loose) loose = next;
}
this.tokens.push({
type: loose
? 'loose_item_start'
: 'list_item_start'
});
// Recurse.
this.token(item, false, bq);
this.tokens.push({
type: 'list_item_end'
});
}
this.tokens.push({
type: 'list_end'
});
continue;
}
// html
if (cap = this.rules.html.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: this.options.sanitize
? 'paragraph'
: 'html',
pre: !this.options.sanitizer
&& (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
text: cap[0]
});
continue;
}
// def
if ((!bq && top) && (cap = this.rules.def.exec(src))) {
src = src.substring(cap[0].length);
this.tokens.links[cap[1].toLowerCase()] = {
href: cap[2],
title: cap[3]
};
continue;
}
// table (gfm)
if (top && (cap = this.rules.table.exec(src))) {
src = src.substring(cap[0].length);
item = {
type: 'table',
header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
};
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = item.cells[i]
.replace(/^ *\| *| *\| *$/g, '')
.split(/ *\| */);
}
this.tokens.push(item);
continue;
}
// top-level paragraph
if (top && (cap = this.rules.paragraph.exec(src))) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'paragraph',
text: cap[1].charAt(cap[1].length - 1) === '\n'
? cap[1].slice(0, -1)
: cap[1]
});
continue;
}
// text
if (cap = this.rules.text.exec(src)) {
// Top-level should never reach here.
src = src.substring(cap[0].length);
this.tokens.push({
type: 'text',
text: cap[0]
});
continue;
}
if (src) {
throw new
Error('Infinite loop on byte: ' + src.charCodeAt(0));
}
}
return this.tokens;
};
/**
* Inline-Level Grammar
*/
var inline = {
escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
url: noop,
tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
link: /^!?\[(inside)\]\(href\)/,
reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
br: /^ {2,}\n(?!\s*$)/,
del: noop,
text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
};
inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
inline.link = replace(inline.link)
('inside', inline._inside)
('href', inline._href)
();
inline.reflink = replace(inline.reflink)
('inside', inline._inside)
();
/**
* Normal Inline Grammar
*/
inline.normal = merge({}, inline);
/**
* Pedantic Inline Grammar
*/
inline.pedantic = merge({}, inline.normal, {
strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
});
/**
* GFM Inline Grammar
*/
inline.gfm = merge({}, inline.normal, {
escape: replace(inline.escape)('])', '~|])')(),
url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
del: /^~~(?=\S)([\s\S]*?\S)~~/,
text: replace(inline.text)
(']|', '~]|')
('|', '|https?://|')
()
});
/**
* GFM + Line Breaks Inline Grammar
*/
inline.breaks = merge({}, inline.gfm, {
br: replace(inline.br)('{2,}', '*')(),
text: replace(inline.gfm.text)('{2,}', '*')()
});
/**
* Inline Lexer & Compiler
*/
function InlineLexer(links, options) {
this.options = options || marked.defaults;
this.links = links;
this.rules = inline.normal;
this.renderer = this.options.renderer || new Renderer;
this.renderer.options = this.options;
if (!this.links) {
throw new
Error('Tokens array requires a `links` property.');
}
if (this.options.gfm) {
if (this.options.breaks) {
this.rules = inline.breaks;
} else {
this.rules = inline.gfm;
}
} else if (this.options.pedantic) {
this.rules = inline.pedantic;
}
}
/**
* Expose Inline Rules
*/
InlineLexer.rules = inline;
/**
* Static Lexing/Compiling Method
*/
InlineLexer.output = function(src, links, options) {
var inline = new InlineLexer(links, options);
return inline.output(src);
};
/**
* Lexing/Compiling
*/
InlineLexer.prototype.output = function(src) {
var out = ''
, link
, text
, href
, cap;
while (src) {
// escape
if (cap = this.rules.escape.exec(src)) {
src = src.substring(cap[0].length);
out += cap[1];
continue;
}
// autolink
if (cap = this.rules.autolink.exec(src)) {
src = src.substring(cap[0].length);
if (cap[2] === '@') {
text = cap[1].charAt(6) === ':'
? this.mangle(cap[1].substring(7))
: this.mangle(cap[1]);
href = this.mangle('mailto:') + text;
} else {
text = escape(cap[1]);
href = text;
}
out += this.renderer.link(href, null, text);
continue;
}
// url (gfm)
if (!this.inLink && (cap = this.rules.url.exec(src))) {
src = src.substring(cap[0].length);
text = escape(cap[1]);
href = text;
out += this.renderer.link(href, null, text);
continue;
}
// tag
if (cap = this.rules.tag.exec(src)) {
if (!this.inLink && /^<a /i.test(cap[0])) {
this.inLink = true;
} else if (this.inLink && /^<\/a>/i.test(cap[0])) {
this.inLink = false;
}
src = src.substring(cap[0].length);
out += this.options.sanitize
? this.options.sanitizer
? this.options.sanitizer(cap[0])
: escape(cap[0])
: cap[0]
continue;
}
// link
if (cap = this.rules.link.exec(src)) {
src = src.substring(cap[0].length);
this.inLink = true;
out += this.outputLink(cap, {
href: cap[2],
title: cap[3]
});
this.inLink = false;
continue;
}
// reflink, nolink
if ((cap = this.rules.reflink.exec(src))
|| (cap = this.rules.nolink.exec(src))) {
src = src.substring(cap[0].length);
link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
link = this.links[link.toLowerCase()];
if (!link || !link.href) {
out += cap[0].charAt(0);
src = cap[0].substring(1) + src;
continue;
}
this.inLink = true;
out += this.outputLink(cap, link);
this.inLink = false;
continue;
}
// strong
if (cap = this.rules.strong.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.strong(this.output(cap[2] || cap[1]));
continue;
}
// em
if (cap = this.rules.em.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.em(this.output(cap[2] || cap[1]));
continue;
}
// code
if (cap = this.rules.code.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.codespan(escape(cap[2], true));
continue;
}
// br
if (cap = this.rules.br.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.br();
continue;
}
// del (gfm)
if (cap = this.rules.del.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.del(this.output(cap[1]));
continue;
}
// text
if (cap = this.rules.text.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.text(escape(this.smartypants(cap[0])));
continue;
}
if (src) {
throw new
Error('Infinite loop on byte: ' + src.charCodeAt(0));
}
}
return out;
};
/**
* Compile Link
*/
InlineLexer.prototype.outputLink = function(cap, link) {
var href = escape(link.href)
, title = link.title ? escape(link.title) : null;
return cap[0].charAt(0) !== '!'
? this.renderer.link(href, title, this.output(cap[1]))
: this.renderer.image(href, title, escape(cap[1]));
};
/**
* Smartypants Transformations
*/
InlineLexer.prototype.smartypants = function(text) {
if (!this.options.smartypants) return text;
return text
// em-dashes
.replace(/---/g, '\u2014')
// en-dashes
.replace(/--/g, '\u2013')
// opening singles
.replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
// closing singles & apostrophes
.replace(/'/g, '\u2019')
// opening doubles
.replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
// closing doubles
.replace(/"/g, '\u201d')
// ellipses
.replace(/\.{3}/g, '\u2026');
};
/**
* Mangle Links
*/
InlineLexer.prototype.mangle = function(text) {
if (!this.options.mangle) return text;
var out = ''
, l = text.length
, i = 0
, ch;
for (; i < l; i++) {
ch = text.charCodeAt(i);
if (Math.random() > 0.5) {
ch = 'x' + ch.toString(16);
}
out += '&#' + ch + ';';
}
return out;
};
/**
* Renderer
*/
function Renderer(options) {
this.options = options || {};
}
Renderer.prototype.code = function(code, lang, escaped) {
if (this.options.highlight) {
var out = this.options.highlight(code, lang);
if (out != null && out !== code) {
escaped = true;
code = out;
}
}
if (!lang) {
return '<pre><code>'
+ (escaped ? code : escape(code, true))
+ '\n</code></pre>';
}
return '<pre><code class="'
+ this.options.langPrefix
+ escape(lang, true)
+ '">'
+ (escaped ? code : escape(code, true))
+ '\n</code></pre>\n';
};
Renderer.prototype.blockquote = function(quote) {
return '<blockquote>\n' + quote + '</blockquote>\n';
};
Renderer.prototype.html = function(html) {
return html;
};
Renderer.prototype.heading = function(text, level, raw) {
return '<h'
+ level
+ ' id="'
+ this.options.headerPrefix
+ raw.toLowerCase().replace(/[^\w]+/g, '-')
+ '">'
+ text
+ '</h'
+ level
+ '>\n';
};
Renderer.prototype.hr = function() {
return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
};
Renderer.prototype.list = function(body, ordered) {
var type = ordered ? 'ol' : 'ul';
return '<' + type + '>\n' + body + '</' + type + '>\n';
};
Renderer.prototype.listitem = function(text) {
return '<li>' + text + '</li>\n';
};
Renderer.prototype.paragraph = function(text) {
return '<p>' + text + '</p>\n';
};
Renderer.prototype.table = function(header, body) {
return '<table>\n'
+ '<thead>\n'
+ header
+ '</thead>\n'
+ '<tbody>\n'
+ body
+ '</tbody>\n'
+ '</table>\n';
};
Renderer.prototype.tablerow = function(content) {
return '<tr>\n' + content + '</tr>\n';
};
Renderer.prototype.tablecell = function(content, flags) {
var type = flags.header ? 'th' : 'td';
var tag = flags.align
? '<' + type + ' style="text-align:' + flags.align + '">'
: '<' + type + '>';
return tag + content + '</' + type + '>\n';
};
// span level renderer
Renderer.prototype.strong = function(text) {
return '<strong>' + text + '</strong>';
};
Renderer.prototype.em = function(text) {
return '<em>' + text + '</em>';
};
Renderer.prototype.codespan = function(text) {
return '<code>' + text + '</code>';
};
Renderer.prototype.br = function() {
return this.options.xhtml ? '<br/>' : '<br>';
};
Renderer.prototype.del = function(text) {
return '<del>' + text + '</del>';
};
Renderer.prototype.link = function(href, title, text) {
if (this.options.sanitize) {
try {
var prot = decodeURIComponent(unescape(href))
.replace(/[^\w:]/g, '')
.toLowerCase();
} catch (e) {
return '';
}
if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0) {
return '';
}
}
var out = '<a href="' + href + '"';
if (title) {
out += ' title="' + title + '"';
}
out += '>' + text + '</a>';
return out;
};
Renderer.prototype.image = function(href, title, text) {
var out = '<img src="' + href + '" alt="' + text + '"';
if (title) {
out += ' title="' + title + '"';
}
out += this.options.xhtml ? '/>' : '>';
return out;
};
Renderer.prototype.text = function(text) {
return text;
};
/**
* Parsing & Compiling
*/
function Parser(options) {
this.tokens = [];
this.token = null;
this.options = options || marked.defaults;
this.options.renderer = this.options.renderer || new Renderer;
this.renderer = this.options.renderer;
this.renderer.options = this.options;
}
/**
* Static Parse Method
*/
Parser.parse = function(src, options, renderer) {
var parser = new Parser(options, renderer);
return parser.parse(src);
};
/**
* Parse Loop
*/
Parser.prototype.parse = function(src) {
this.inline = new InlineLexer(src.links, this.options, this.renderer);
this.tokens = src.reverse();
var out = '';
while (this.next()) {
out += this.tok();
}
return out;
};
/**
* Next Token
*/
Parser.prototype.next = function() {
return this.token = this.tokens.pop();
};
/**
* Preview Next Token
*/
Parser.prototype.peek = function() {
return this.tokens[this.tokens.length - 1] || 0;
};
/**
* Parse Text Tokens
*/
Parser.prototype.parseText = function() {
var body = this.token.text;
while (this.peek().type === 'text') {
body += '\n' + this.next().text;
}
return this.inline.output(body);
};
/**
* Parse Current Token
*/
Parser.prototype.tok = function() {
switch (this.token.type) {
case 'space': {
return '';
}
case 'hr': {
return this.renderer.hr();
}
case 'heading': {
return this.renderer.heading(
this.inline.output(this.token.text),
this.token.depth,
this.token.text);
}
case 'code': {
return this.renderer.code(this.token.text,
this.token.lang,
this.token.escaped);
}
case 'table': {
var header = ''
, body = ''
, i
, row
, cell
, flags
, j;
// header
cell = '';
for (i = 0; i < this.token.header.length; i++) {
flags = { header: true, align: this.token.align[i] };
cell += this.renderer.tablecell(
this.inline.output(this.token.header[i]),
{ header: true, align: this.token.align[i] }
);
}
header += this.renderer.tablerow(cell);
for (i = 0; i < this.token.cells.length; i++) {
row = this.token.cells[i];
cell = '';
for (j = 0; j < row.length; j++) {
cell += this.renderer.tablecell(
this.inline.output(row[j]),
{ header: false, align: this.token.align[j] }
);
}
body += this.renderer.tablerow(cell);
}
return this.renderer.table(header, body);
}
case 'blockquote_start': {
var body = '';
while (this.next().type !== 'blockquote_end') {
body += this.tok();
}
return this.renderer.blockquote(body);
}
case 'list_start': {
var body = ''
, ordered = this.token.ordered;
while (this.next().type !== 'list_end') {
body += this.tok();
}
return this.renderer.list(body, ordered);
}
case 'list_item_start': {
var body = '';
while (this.next().type !== 'list_item_end') {
body += this.token.type === 'text'
? this.parseText()
: this.tok();
}
return this.renderer.listitem(body);
}
case 'loose_item_start': {
var body = '';
while (this.next().type !== 'list_item_end') {
body += this.tok();
}
return this.renderer.listitem(body);
}
case 'html': {
var html = !this.token.pre && !this.options.pedantic
? this.inline.output(this.token.text)
: this.token.text;
return this.renderer.html(html);
}
case 'paragraph': {
return this.renderer.paragraph(this.inline.output(this.token.text));
}
case 'text': {
return this.renderer.paragraph(this.parseText());
}
}
};
/**
* Helpers
*/
function escape(html, encode) {
return html
.replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function unescape(html) {
return html.replace(/&([#\w]+);/g, function(_, n) {
n = n.toLowerCase();
if (n === 'colon') return ':';
if (n.charAt(0) === '#') {
return n.charAt(1) === 'x'
? String.fromCharCode(parseInt(n.substring(2), 16))
: String.fromCharCode(+n.substring(1));
}
return '';
});
}
function replace(regex, opt) {
regex = regex.source;
opt = opt || '';
return function self(name, val) {
if (!name) return new RegExp(regex, opt);
val = val.source || val;
val = val.replace(/(^|[^\[])\^/g, '$1');
regex = regex.replace(name, val);
return self;
};
}
function noop() {}
noop.exec = noop;
function merge(obj) {
var i = 1
, target
, key;
for (; i < arguments.length; i++) {
target = arguments[i];
for (key in target) {
if (Object.prototype.hasOwnProperty.call(target, key)) {
obj[key] = target[key];
}
}
}
return obj;
}
/**
* Marked
*/
function marked(src, opt, callback) {
if (callback || typeof opt === 'function') {
if (!callback) {
callback = opt;
opt = null;
}
opt = merge({}, marked.defaults, opt || {});
var highlight = opt.highlight
, tokens
, pending
, i = 0;
try {
tokens = Lexer.lex(src, opt)
} catch (e) {
return callback(e);
}
pending = tokens.length;
var done = function(err) {
if (err) {
opt.highlight = highlight;
return callback(err);
}
var out;
try {
out = Parser.parse(tokens, opt);
} catch (e) {
err = e;
}
opt.highlight = highlight;
return err
? callback(err)
: callback(null, out);
};
if (!highlight || highlight.length < 3) {
return done();
}
delete opt.highlight;
if (!pending) return done();
for (; i < tokens.length; i++) {
(function(token) {
if (token.type !== 'code') {
return --pending || done();
}
return highlight(token.text, token.lang, function(err, code) {
if (err) return done(err);
if (code == null || code === token.text) {
return --pending || done();
}
token.text = code;
token.escaped = true;
--pending || done();
});
})(tokens[i]);
}
return;
}
try {
if (opt) opt = merge({}, marked.defaults, opt);
return Parser.parse(Lexer.lex(src, opt), opt);
} catch (e) {
e.message += '\nPlease report this to https://github.com/chjj/marked.';
if ((opt || marked.defaults).silent) {
return '<p>An error occured:</p><pre>'
+ escape(e.message + '', true)
+ '</pre>';
}
throw e;
}
}
/**
* Options
*/
marked.options =
marked.setOptions = function(opt) {
merge(marked.defaults, opt);
return marked;
};
marked.defaults = {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
sanitizer: null,
mangle: true,
smartLists: false,
silent: false,
highlight: null,
langPrefix: 'lang-',
smartypants: false,
headerPrefix: '',
renderer: new Renderer,
xhtml: false
};
/**
* Expose
*/
marked.Parser = Parser;
marked.parser = Parser.parse;
marked.Renderer = Renderer;
marked.Lexer = Lexer;
marked.lexer = Lexer.lex;
marked.InlineLexer = InlineLexer;
marked.inlineLexer = InlineLexer.output;
marked.parse = marked;
if (typeof module !== 'undefined' && typeof exports === 'object') {
module.exports = marked;
} else if (typeof define === 'function' && define.amd) {
define(function() { return marked; });
} else {
this.marked = marked;
}
}).call(function() {
return this || (typeof window !== 'undefined' ? window : global);
}());
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[9])(9)
}); |
ajax/libs/yui/3.1.2/event-custom/event-custom-debug.js | legomushroom/cdnjs | YUI.add('event-custom-base', function(Y) {
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
*/
Y.Env.evt = {
handles: {},
plugins: {}
};
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
* @submodule event-custom-base
*/
(function() {
/**
* Allows for the insertion of methods that are executed before or after
* a specified method
* @class Do
* @static
*/
var BEFORE = 0,
AFTER = 1;
Y.Do = {
/**
* Cache of objects touched by the utility
* @property objs
* @static
*/
objs: {},
/**
* Execute the supplied method before the specified function
* @method before
* @param fn {Function} the function to execute
* @param obj the object hosting the method to displace
* @param sFn {string} the name of the method to displace
* @param c The execution context for fn
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* when the event fires.
* @return {string} handle for the subscription
* @static
*/
before: function(fn, obj, sFn, c) {
// Y.log('Do before: ' + sFn, 'info', 'event');
var f = fn, a;
if (c) {
a = [fn, c].concat(Y.Array(arguments, 4, true));
f = Y.rbind.apply(Y, a);
}
return this._inject(BEFORE, f, obj, sFn);
},
/**
* Execute the supplied method after the specified function
* @method after
* @param fn {Function} the function to execute
* @param obj the object hosting the method to displace
* @param sFn {string} the name of the method to displace
* @param c The execution context for fn
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* @return {string} handle for the subscription
* @static
*/
after: function(fn, obj, sFn, c) {
var f = fn, a;
if (c) {
a = [fn, c].concat(Y.Array(arguments, 4, true));
f = Y.rbind.apply(Y, a);
}
return this._inject(AFTER, f, obj, sFn);
},
/**
* Execute the supplied method after the specified function
* @method _inject
* @param when {string} before or after
* @param fn {Function} the function to execute
* @param obj the object hosting the method to displace
* @param sFn {string} the name of the method to displace
* @param c The execution context for fn
* @return {string} handle for the subscription
* @private
* @static
*/
_inject: function(when, fn, obj, sFn) {
// object id
var id = Y.stamp(obj), o, sid;
if (! this.objs[id]) {
// create a map entry for the obj if it doesn't exist
this.objs[id] = {};
}
o = this.objs[id];
if (! o[sFn]) {
// create a map entry for the method if it doesn't exist
o[sFn] = new Y.Do.Method(obj, sFn);
// re-route the method to our wrapper
obj[sFn] =
function() {
return o[sFn].exec.apply(o[sFn], arguments);
};
}
// subscriber id
sid = id + Y.stamp(fn) + sFn;
// register the callback
o[sFn].register(sid, fn, when);
return new Y.EventHandle(o[sFn], sid);
},
/**
* Detach a before or after subscription
* @method detach
* @param handle {string} the subscription handle
*/
detach: function(handle) {
if (handle.detach) {
handle.detach();
}
},
_unload: function(e, me) {
}
};
//////////////////////////////////////////////////////////////////////////
/**
* Wrapper for a displaced method with aop enabled
* @class Do.Method
* @constructor
* @param obj The object to operate on
* @param sFn The name of the method to displace
*/
Y.Do.Method = function(obj, sFn) {
this.obj = obj;
this.methodName = sFn;
this.method = obj[sFn];
this.before = {};
this.after = {};
};
/**
* Register a aop subscriber
* @method register
* @param sid {string} the subscriber id
* @param fn {Function} the function to execute
* @param when {string} when to execute the function
*/
Y.Do.Method.prototype.register = function (sid, fn, when) {
if (when) {
this.after[sid] = fn;
} else {
this.before[sid] = fn;
}
};
/**
* Unregister a aop subscriber
* @method delete
* @param sid {string} the subscriber id
* @param fn {Function} the function to execute
* @param when {string} when to execute the function
*/
Y.Do.Method.prototype._delete = function (sid) {
// Y.log('Y.Do._delete: ' + sid, 'info', 'Event');
delete this.before[sid];
delete this.after[sid];
};
/**
* Execute the wrapped method
* @method exec
*/
Y.Do.Method.prototype.exec = function () {
var args = Y.Array(arguments, 0, true),
i, ret, newRet,
bf = this.before,
af = this.after,
prevented = false;
// execute before
for (i in bf) {
if (bf.hasOwnProperty(i)) {
ret = bf[i].apply(this.obj, args);
if (ret) {
switch (ret.constructor) {
case Y.Do.Halt:
return ret.retVal;
case Y.Do.AlterArgs:
args = ret.newArgs;
break;
case Y.Do.Prevent:
prevented = true;
break;
default:
}
}
}
}
// execute method
if (!prevented) {
ret = this.method.apply(this.obj, args);
}
// execute after methods.
for (i in af) {
if (af.hasOwnProperty(i)) {
newRet = af[i].apply(this.obj, args);
// Stop processing if a Halt object is returned
if (newRet && newRet.constructor == Y.Do.Halt) {
return newRet.retVal;
// Check for a new return value
} else if (newRet && newRet.constructor == Y.Do.AlterReturn) {
ret = newRet.newRetVal;
}
}
}
return ret;
};
//////////////////////////////////////////////////////////////////////////
/**
* Return an AlterArgs object when you want to change the arguments that
* were passed into the function. An example would be a service that scrubs
* out illegal characters prior to executing the core business logic.
* @class Do.AlterArgs
*/
Y.Do.AlterArgs = function(msg, newArgs) {
this.msg = msg;
this.newArgs = newArgs;
};
/**
* Return an AlterReturn object when you want to change the result returned
* from the core method to the caller
* @class Do.AlterReturn
*/
Y.Do.AlterReturn = function(msg, newRetVal) {
this.msg = msg;
this.newRetVal = newRetVal;
};
/**
* Return a Halt object when you want to terminate the execution
* of all subsequent subscribers as well as the wrapped method
* if it has not exectued yet.
* @class Do.Halt
*/
Y.Do.Halt = function(msg, retVal) {
this.msg = msg;
this.retVal = retVal;
};
/**
* Return a Prevent object when you want to prevent the wrapped function
* from executing, but want the remaining listeners to execute
* @class Do.Prevent
*/
Y.Do.Prevent = function(msg) {
this.msg = msg;
};
/**
* Return an Error object when you want to terminate the execution
* of all subsequent method calls.
* @class Do.Error
* @deprecated use Y.Do.Halt or Y.Do.Prevent
*/
Y.Do.Error = Y.Do.Halt;
//////////////////////////////////////////////////////////////////////////
// Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do);
})();
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
* @submodule event-custom-base
*/
/**
* Return value from all subscribe operations
* @class EventHandle
* @constructor
* @param evt {CustomEvent} the custom event
* @param sub {Subscriber} the subscriber
*/
// var onsubscribeType = "_event:onsub",
var AFTER = 'after',
CONFIGS = [
'broadcast',
'monitored',
'bubbles',
'context',
'contextFn',
'currentTarget',
'defaultFn',
'defaultTargetOnly',
'details',
'emitFacade',
'fireOnce',
'async',
'host',
'preventable',
'preventedFn',
'queuable',
'silent',
'stoppedFn',
'target',
'type'
],
YUI3_SIGNATURE = 9,
YUI_LOG = 'yui:log';
Y.EventHandle = function(evt, sub) {
/**
* The custom event
* @type CustomEvent
*/
this.evt = evt;
/**
* The subscriber object
* @type Subscriber
*/
this.sub = sub;
};
Y.EventHandle.prototype = {
/**
* Detaches this subscriber
* @method detach
*/
detach: function() {
var evt = this.evt, detached = 0, i;
if (evt) {
// Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event');
if (Y.Lang.isArray(evt)) {
for (i=0; i<evt.length; i++) {
detached += evt[i].detach();
}
} else {
evt._delete(this.sub);
detached = 1;
}
}
return detached;
},
/**
* Monitor the event state for the subscribed event. The first parameter
* is what should be monitored, the rest are the normal parameters when
* subscribing to an event.
* @method monitor
* @param what {string} what to monitor ('attach', 'detach', 'publish')
* @return {EventHandle} return value from the monitor event subscription
*/
monitor: function(what) {
return this.evt.monitor.apply(this.evt, arguments);
}
};
/**
* The CustomEvent class lets you define events for your application
* that can be subscribed to by one or more independent component.
*
* @param {String} type The type of event, which is passed to the callback
* when the event fires
* @param o configuration object
* @class CustomEvent
* @constructor
*/
Y.CustomEvent = function(type, o) {
// if (arguments.length > 2) {
// this.log('CustomEvent context and silent are now in the config', 'warn', 'Event');
// }
o = o || {};
this.id = Y.stamp(this);
/**
* The type of event, returned to subscribers when the event fires
* @property type
* @type string
*/
this.type = type;
/**
* The context the the event will fire from by default. Defaults to the YUI
* instance.
* @property context
* @type object
*/
this.context = Y;
/**
* Monitor when an event is attached or detached.
*
* @property monitored
* @type boolean
*/
// this.monitored = false;
this.logSystem = (type == YUI_LOG);
/**
* If 0, this event does not broadcast. If 1, the YUI instance is notified
* every time this event fires. If 2, the YUI instance and the YUI global
* (if event is enabled on the global) are notified every time this event
* fires.
* @property broadcast
* @type int
*/
// this.broadcast = 0;
/**
* By default all custom events are logged in the debug build, set silent
* to true to disable debug outpu for this event.
* @property silent
* @type boolean
*/
this.silent = this.logSystem;
/**
* Specifies whether this event should be queued when the host is actively
* processing an event. This will effect exectution order of the callbacks
* for the various events.
* @property queuable
* @type boolean
* @default false
*/
// this.queuable = false;
/**
* The subscribers to this event
* @property subscribers
* @type Subscriber{}
*/
this.subscribers = {};
/**
* 'After' subscribers
* @property afters
* @type Subscriber{}
*/
this.afters = {};
/**
* This event has fired if true
*
* @property fired
* @type boolean
* @default false;
*/
// this.fired = false;
/**
* An array containing the arguments the custom event
* was last fired with.
* @property firedWith
* @type Array
*/
// this.firedWith;
/**
* This event should only fire one time if true, and if
* it has fired, any new subscribers should be notified
* immediately.
*
* @property fireOnce
* @type boolean
* @default false;
*/
// this.fireOnce = false;
/**
* fireOnce listeners will fire syncronously unless async
* is set to true
* @property async
* @type boolean
* @default false
*/
//this.async = false;
/**
* Flag for stopPropagation that is modified during fire()
* 1 means to stop propagation to bubble targets. 2 means
* to also stop additional subscribers on this target.
* @property stopped
* @type int
*/
// this.stopped = 0;
/**
* Flag for preventDefault that is modified during fire().
* if it is not 0, the default behavior for this event
* @property prevented
* @type int
*/
// this.prevented = 0;
/**
* Specifies the host for this custom event. This is used
* to enable event bubbling
* @property host
* @type EventTarget
*/
// this.host = null;
/**
* The default function to execute after event listeners
* have fire, but only if the default action was not
* prevented.
* @property defaultFn
* @type Function
*/
// this.defaultFn = null;
/**
* The function to execute if a subscriber calls
* stopPropagation or stopImmediatePropagation
* @property stoppedFn
* @type Function
*/
// this.stoppedFn = null;
/**
* The function to execute if a subscriber calls
* preventDefault
* @property preventedFn
* @type Function
*/
// this.preventedFn = null;
/**
* Specifies whether or not this event's default function
* can be cancelled by a subscriber by executing preventDefault()
* on the event facade
* @property preventable
* @type boolean
* @default true
*/
this.preventable = true;
/**
* Specifies whether or not a subscriber can stop the event propagation
* via stopPropagation(), stopImmediatePropagation(), or halt()
*
* Events can only bubble if emitFacade is true.
*
* @property bubbles
* @type boolean
* @default true
*/
this.bubbles = true;
/**
* Supports multiple options for listener signatures in order to
* port YUI 2 apps.
* @property signature
* @type int
* @default 9
*/
this.signature = YUI3_SIGNATURE;
this.subCount = 0;
this.afterCount = 0;
// this.hasSubscribers = false;
// this.hasAfters = false;
/**
* If set to true, the custom event will deliver an EventFacade object
* that is similar to a DOM event object.
* @property emitFacade
* @type boolean
* @default false
*/
// this.emitFacade = false;
this.applyConfig(o, true);
// this.log("Creating " + this.type);
};
Y.CustomEvent.prototype = {
hasSubs: function(when) {
var s = this.subCount, a = this.afterCount, sib = this.sibling;
if (sib) {
s += sib.subCount;
a += sib.afterCount;
}
if (when) {
return (when == 'after') ? a : s;
}
return (s + a);
},
/**
* Monitor the event state for the subscribed event. The first parameter
* is what should be monitored, the rest are the normal parameters when
* subscribing to an event.
* @method monitor
* @param what {string} what to monitor ('detach', 'attach', 'publish')
* @return {EventHandle} return value from the monitor event subscription
*/
monitor: function(what) {
this.monitored = true;
var type = this.id + '|' + this.type + '_' + what,
args = Y.Array(arguments, 0, true);
args[0] = type;
return this.host.on.apply(this.host, args);
},
/**
* Get all of the subscribers to this event and any sibling event
* @return {Array} first item is the on subscribers, second the after
*/
getSubs: function() {
var s = Y.merge(this.subscribers), a = Y.merge(this.afters), sib = this.sibling;
if (sib) {
Y.mix(s, sib.subscribers);
Y.mix(a, sib.afters);
}
return [s, a];
},
/**
* Apply configuration properties. Only applies the CONFIG whitelist
* @method applyConfig
* @param o hash of properties to apply
* @param force {boolean} if true, properties that exist on the event
* will be overwritten.
*/
applyConfig: function(o, force) {
if (o) {
Y.mix(this, o, force, CONFIGS);
}
},
_on: function(fn, context, args, when) {
if (!fn) {
this.log("Invalid callback for CE: " + this.type);
}
var s = new Y.Subscriber(fn, context, args, when);
if (this.fireOnce && this.fired) {
if (this.async) {
setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0);
} else {
this._notify(s, this.firedWith);
}
}
if (when == AFTER) {
this.afters[s.id] = s;
this.afterCount++;
} else {
this.subscribers[s.id] = s;
this.subCount++;
}
return new Y.EventHandle(this, s);
},
/**
* Listen for this event
* @method subscribe
* @param {Function} fn The function to execute
* @return {EventHandle} Unsubscribe handle
* @deprecated use on
*/
subscribe: function(fn, context) {
Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated');
var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null;
return this._on(fn, context, a, true);
},
/**
* Listen for this event
* @method on
* @param {Function} fn The function to execute
* @param context {object} optional execution context.
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* when the event fires.
* @return {EventHandle} An object with a detach method to detch the handler(s)
*/
on: function(fn, context) {
var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null;
this.host._monitor('attach', this.type, {
args: arguments
});
return this._on(fn, context, a, true);
},
/**
* Listen for this event after the normal subscribers have been notified and
* the default behavior has been applied. If a normal subscriber prevents the
* default behavior, it also prevents after listeners from firing.
* @method after
* @param {Function} fn The function to execute
* @param context {object} optional execution context.
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* when the event fires.
* @return {EventHandle} handle Unsubscribe handle
*/
after: function(fn, context) {
var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null;
return this._on(fn, context, a, AFTER);
},
/**
* Detach listeners.
* @method detach
* @param {Function} fn The subscribed function to remove, if not supplied
* all will be removed
* @param {Object} context The context object passed to subscribe.
* @return {int} returns the number of subscribers unsubscribed
*/
detach: function(fn, context) {
// unsubscribe handle
if (fn && fn.detach) {
return fn.detach();
}
var found = 0, subs = this.subscribers, i, s;
for (i in subs) {
if (subs.hasOwnProperty(i)) {
s = subs[i];
if (s && (!fn || fn === s.fn)) {
this._delete(s);
found++;
}
}
}
return found;
},
/**
* Detach listeners.
* @method unsubscribe
* @param {Function} fn The subscribed function to remove, if not supplied
* all will be removed
* @param {Object} context The context object passed to subscribe.
* @return {int|undefined} returns the number of subscribers unsubscribed
* @deprecated use detach
*/
unsubscribe: function() {
return this.detach.apply(this, arguments);
},
/**
* Notify a single subscriber
* @method _notify
* @param s {Subscriber} the subscriber
* @param args {Array} the arguments array to apply to the listener
* @private
*/
_notify: function(s, args, ef) {
this.log(this.type + "->" + "sub: " + s.id);
var ret;
ret = s.notify(args, this);
if (false === ret || this.stopped > 1) {
this.log(this.type + " cancelled by subscriber");
return false;
}
return true;
},
/**
* Logger abstraction to centralize the application of the silent flag
* @method log
* @param msg {string} message to log
* @param cat {string} log category
*/
log: function(msg, cat) {
if (!this.silent) {
Y.log(this.id + ': ' + msg, cat || "info", "event");
}
},
/**
* Notifies the subscribers. The callback functions will be executed
* from the context specified when the event was created, and with the
* following parameters:
* <ul>
* <li>The type of event</li>
* <li>All of the arguments fire() was executed with as an array</li>
* <li>The custom object (if any) that was passed into the subscribe()
* method</li>
* </ul>
* @method fire
* @param {Object*} arguments an arbitrary set of parameters to pass to
* the handler.
* @return {boolean} false if one of the subscribers returned false,
* true otherwise
*
*/
fire: function() {
if (this.fireOnce && this.fired) {
this.log('fireOnce event: ' + this.type + ' already fired');
return true;
} else {
var args = Y.Array(arguments, 0, true);
// this doesn't happen if the event isn't published
// this.host._monitor('fire', this.type, args);
this.fired = true;
this.firedWith = args;
if (this.emitFacade) {
return this.fireComplex(args);
} else {
return this.fireSimple(args);
}
}
},
fireSimple: function(args) {
this.stopped = 0;
this.prevented = 0;
if (this.hasSubs()) {
// this._procSubs(Y.merge(this.subscribers, this.afters), args);
var subs = this.getSubs();
this._procSubs(subs[0], args);
this._procSubs(subs[1], args);
}
this._broadcast(args);
return this.stopped ? false : true;
},
// Requires the event-custom-complex module for full funcitonality.
fireComplex: function(args) {
Y.log('Missing event-custom-complex needed to emit a facade for: ' + this.type);
args[0] = args[0] || {};
return this.fireSimple(args);
},
_procSubs: function(subs, args, ef) {
var s, i;
for (i in subs) {
if (subs.hasOwnProperty(i)) {
s = subs[i];
if (s && s.fn) {
if (false === this._notify(s, args, ef)) {
this.stopped = 2;
}
if (this.stopped == 2) {
return false;
}
}
}
}
return true;
},
_broadcast: function(args) {
if (!this.stopped && this.broadcast) {
var a = Y.Array(args);
a.unshift(this.type);
if (this.host !== Y) {
Y.fire.apply(Y, a);
}
if (this.broadcast == 2) {
Y.Global.fire.apply(Y.Global, a);
}
}
},
/**
* Removes all listeners
* @method unsubscribeAll
* @return {int} The number of listeners unsubscribed
* @deprecated use detachAll
*/
unsubscribeAll: function() {
return this.detachAll.apply(this, arguments);
},
/**
* Removes all listeners
* @method detachAll
* @return {int} The number of listeners unsubscribed
*/
detachAll: function() {
return this.detach();
},
/**
* @method _delete
* @param subscriber object
* @private
*/
_delete: function(s) {
if (s) {
delete s.fn;
delete s.context;
delete this.subscribers[s.id];
delete this.afters[s.id];
}
this.host._monitor('detach', this.type, {
ce: this,
sub: s
});
}
};
/////////////////////////////////////////////////////////////////////
/**
* Stores the subscriber information to be used when the event fires.
* @param {Function} fn The wrapped function to execute
* @param {Object} context The value of the keyword 'this' in the listener
* @param {Array} args* 0..n additional arguments to supply the listener
*
* @class Subscriber
* @constructor
*/
Y.Subscriber = function(fn, context, args) {
/**
* The callback that will be execute when the event fires
* This is wrapped by Y.rbind if obj was supplied.
* @property fn
* @type Function
*/
this.fn = fn;
/**
* Optional 'this' keyword for the listener
* @property context
* @type Object
*/
this.context = context;
/**
* Unique subscriber id
* @property id
* @type String
*/
this.id = Y.stamp(this);
/**
* Additional arguments to propagate to the subscriber
* @property args
* @type Array
*/
this.args = args;
/**
* Custom events for a given fire transaction.
* @property events
* @type {EventTarget}
*/
// this.events = null;
/**
* This listener only reacts to the event once
* @property once
*/
// this.once = false;
};
Y.Subscriber.prototype = {
_notify: function(c, args, ce) {
var a = this.args, ret;
switch (ce.signature) {
case 0:
ret = this.fn.call(c, ce.type, args, c);
break;
case 1:
ret = this.fn.call(c, args[0] || null, c);
break;
default:
if (a || args) {
args = args || [];
a = (a) ? args.concat(a) : args;
ret = this.fn.apply(c, a);
} else {
ret = this.fn.call(c);
}
}
if (this.once) {
ce._delete(this);
}
return ret;
},
/**
* Executes the subscriber.
* @method notify
* @param args {Array} Arguments array for the subscriber
* @param ce {CustomEvent} The custom event that sent the notification
*/
notify: function(args, ce) {
var c = this.context,
ret = true;
if (!c) {
c = (ce.contextFn) ? ce.contextFn() : ce.context;
}
// only catch errors if we will not re-throw them.
if (Y.config.throwFail) {
ret = this._notify(c, args, ce);
} else {
try {
ret = this._notify(c, args, ce);
} catch(e) {
Y.error(this + ' failed: ' + e.message, e);
}
}
return ret;
},
/**
* Returns true if the fn and obj match this objects properties.
* Used by the unsubscribe method to match the right subscriber.
*
* @method contains
* @param {Function} fn the function to execute
* @param {Object} context optional 'this' keyword for the listener
* @return {boolean} true if the supplied arguments match this
* subscriber's signature.
*/
contains: function(fn, context) {
if (context) {
return ((this.fn == fn) && this.context == context);
} else {
return (this.fn == fn);
}
}
};
/**
* Custom event engine, DOM event listener abstraction layer, synthetic DOM
* events.
* @module event-custom
* @submodule event-custom-base
*/
(function() {
/**
* EventTarget provides the implementation for any object to
* publish, subscribe and fire to custom events, and also
* alows other EventTargets to target the object with events
* sourced from the other object.
* EventTarget is designed to be used with Y.augment to wrap
* EventCustom in an interface that allows events to be listened to
* and fired by name. This makes it possible for implementing code to
* subscribe to an event that either has not been created yet, or will
* not be created at all.
* @class EventTarget
* @param opts a configuration object
* @config emitFacade {boolean} if true, all events will emit event
* facade payloads by default (default false)
* @config prefix {string} the prefix to apply to non-prefixed event names
* @config chain {boolean} if true, on/after/detach return the host to allow
* chaining, otherwise they return an EventHandle (default false)
*/
var L = Y.Lang,
PREFIX_DELIMITER = ':',
CATEGORY_DELIMITER = '|',
AFTER_PREFIX = '~AFTER~',
_wildType = Y.cached(function(type) {
return type.replace(/(.*)(:)(.*)/, "*$2$3");
}),
/**
* If the instance has a prefix attribute and the
* event type is not prefixed, the instance prefix is
* applied to the supplied type.
* @method _getType
* @private
*/
_getType = Y.cached(function(type, pre) {
if (!pre || !L.isString(type) || type.indexOf(PREFIX_DELIMITER) > -1) {
return type;
}
return pre + PREFIX_DELIMITER + type;
}),
/**
* Returns an array with the detach key (if provided),
* and the prefixed event name from _getType
* Y.on('detachcategory| menu:click', fn)
* @method _parseType
* @private
*/
_parseType = Y.cached(function(type, pre) {
var t = type, detachcategory, after, i;
if (!L.isString(t)) {
return t;
}
i = t.indexOf(AFTER_PREFIX);
if (i > -1) {
after = true;
t = t.substr(AFTER_PREFIX.length);
// Y.log(t);
}
i = t.indexOf(CATEGORY_DELIMITER);
if (i > -1) {
detachcategory = t.substr(0, (i));
t = t.substr(i+1);
if (t == '*') {
t = null;
}
}
// detach category, full type with instance prefix, is this an after listener, short type
return [detachcategory, (pre) ? _getType(t, pre) : t, after, t];
}),
ET = function(opts) {
// Y.log('EventTarget constructor executed: ' + this._yuid);
var o = (L.isObject(opts)) ? opts : {};
this._yuievt = this._yuievt || {
id: Y.guid(),
events: {},
targets: {},
config: o,
chain: ('chain' in o) ? o.chain : Y.config.chain,
bubbling: false,
defaults: {
context: o.context || this,
host: this,
emitFacade: o.emitFacade,
fireOnce: o.fireOnce,
queuable: o.queuable,
monitored: o.monitored,
broadcast: o.broadcast,
defaultTargetOnly: o.defaulTargetOnly,
bubbles: ('bubbles' in o) ? o.bubbles : true
}
};
};
ET.prototype = {
/**
* Listen to a custom event hosted by this object one time.
* This is the equivalent to <code>on</code> except the
* listener is immediatelly detached when it is executed.
* @method once
* @param type {string} The type of the event
* @param fn {Function} The callback
* @param context {object} optional execution context.
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* @return the event target or a detach handle per 'chain' config
*/
once: function() {
var handle = this.on.apply(this, arguments);
handle.sub.once = true;
return handle;
},
/**
* Subscribe to a custom event hosted by this object
* @method on
* @param type {string} The type of the event
* @param fn {Function} The callback
* @param context {object} optional execution context.
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* @return the event target or a detach handle per 'chain' config
*/
on: function(type, fn, context) {
var parts = _parseType(type, this._yuievt.config.prefix), f, c, args, ret, ce,
detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype,
Node = Y.Node, n, domevent, isArr;
// full name, args, detachcategory, after
this._monitor('attach', parts[1], {
args: arguments,
category: parts[0],
after: parts[2]
});
if (L.isObject(type)) {
if (L.isFunction(type)) {
return Y.Do.before.apply(Y.Do, arguments);
}
f = fn;
c = context;
args = Y.Array(arguments, 0, true);
ret = {};
if (L.isArray(type)) {
isArr = true;
} else {
after = type._after;
delete type._after;
}
Y.each(type, function(v, k) {
if (L.isObject(v)) {
f = v.fn || ((L.isFunction(v)) ? v : f);
c = v.context || c;
}
args[0] = (isArr) ? v : ((after) ? AFTER_PREFIX + k : k);
args[1] = f;
args[2] = c;
ret[k] = this.on.apply(this, args);
}, this);
return (this._yuievt.chain) ? this : new Y.EventHandle(ret);
}
detachcategory = parts[0];
after = parts[2];
shorttype = parts[3];
// extra redirection so we catch adaptor events too. take a look at this.
if (Node && (this instanceof Node) && (shorttype in Node.DOM_EVENTS)) {
args = Y.Array(arguments, 0, true);
args.splice(2, 0, Node.getDOMNode(this));
// Y.log("Node detected, redirecting with these args: " + args);
return Y.on.apply(Y, args);
}
type = parts[1];
if (this instanceof YUI) {
adapt = Y.Env.evt.plugins[type];
args = Y.Array(arguments, 0, true);
args[0] = shorttype;
if (Node) {
n = args[2];
if (n instanceof Y.NodeList) {
n = Y.NodeList.getDOMNodes(n);
} else if (n instanceof Node) {
n = Node.getDOMNode(n);
}
domevent = (shorttype in Node.DOM_EVENTS);
// Captures both DOM events and event plugins.
if (domevent) {
args[2] = n;
}
}
// check for the existance of an event adaptor
if (adapt) {
Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event');
handle = adapt.on.apply(Y, args);
} else if ((!type) || domevent) {
handle = Y.Event._attach(args);
}
}
if (!handle) {
ce = this._yuievt.events[type] || this.publish(type);
handle = ce._on(fn, context, (arguments.length > 3) ? Y.Array(arguments, 3, true) : null, (after) ? 'after' : true);
}
if (detachcategory) {
store[detachcategory] = store[detachcategory] || {};
store[detachcategory][type] = store[detachcategory][type] || [];
store[detachcategory][type].push(handle);
}
return (this._yuievt.chain) ? this : handle;
},
/**
* subscribe to an event
* @method subscribe
* @deprecated use on
*/
subscribe: function() {
Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated');
return this.on.apply(this, arguments);
},
/**
* Detach one or more listeners the from the specified event
* @method detach
* @param type {string|Object} Either the handle to the subscriber or the
* type of event. If the type
* is not specified, it will attempt to remove
* the listener from all hosted events.
* @param fn {Function} The subscribed function to unsubscribe, if not
* supplied, all subscribers will be removed.
* @param context {Object} The custom object passed to subscribe. This is
* optional, but if supplied will be used to
* disambiguate multiple listeners that are the same
* (e.g., you subscribe many object using a function
* that lives on the prototype)
* @return {EventTarget} the host
*/
detach: function(type, fn, context) {
var evts = this._yuievt.events, i,
Node = Y.Node, isNode = Node && (this instanceof Node);
// detachAll disabled on the Y instance.
if (!type && (this !== Y)) {
for (i in evts) {
if (evts.hasOwnProperty(i)) {
evts[i].detach(fn, context);
}
}
if (isNode) {
Y.Event.purgeElement(Node.getDOMNode(this));
}
return this;
}
var parts = _parseType(type, this._yuievt.config.prefix),
detachcategory = L.isArray(parts) ? parts[0] : null,
shorttype = (parts) ? parts[3] : null,
handle, adapt, store = Y.Env.evt.handles, cat, args,
ce,
keyDetacher = function(lcat, ltype) {
var handles = lcat[ltype];
if (handles) {
while (handles.length) {
handle = handles.pop();
handle.detach();
}
}
};
if (detachcategory) {
cat = store[detachcategory];
type = parts[1];
if (cat) {
if (type) {
keyDetacher(cat, type);
} else {
for (i in cat) {
if (cat.hasOwnProperty(i)) {
keyDetacher(cat, i);
}
}
}
return this;
}
// If this is an event handle, use it to detach
} else if (L.isObject(type) && type.detach) {
type.detach();
return this;
// extra redirection so we catch adaptor events too. take a look at this.
} else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) {
args = Y.Array(arguments, 0, true);
args[2] = Node.getDOMNode(this);
Y.detach.apply(Y, args);
return this;
}
adapt = Y.Env.evt.plugins[shorttype];
// The YUI instance handles DOM events and adaptors
if (this instanceof YUI) {
args = Y.Array(arguments, 0, true);
// use the adaptor specific detach code if
if (adapt && adapt.detach) {
adapt.detach.apply(Y, args);
return this;
// DOM event fork
} else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) {
args[0] = type;
Y.Event.detach.apply(Y.Event, args);
return this;
}
}
// ce = evts[type];
ce = evts[parts[1]];
if (ce) {
ce.detach(fn, context);
}
return this;
},
/**
* detach a listener
* @method unsubscribe
* @deprecated use detach
*/
unsubscribe: function() {
Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated');
return this.detach.apply(this, arguments);
},
/**
* Removes all listeners from the specified event. If the event type
* is not specified, all listeners from all hosted custom events will
* be removed.
* @method detachAll
* @param type {string} The type, or name of the event
*/
detachAll: function(type) {
return this.detach(type);
},
/**
* Removes all listeners from the specified event. If the event type
* is not specified, all listeners from all hosted custom events will
* be removed.
* @method unsubscribeAll
* @param type {string} The type, or name of the event
* @deprecated use detachAll
*/
unsubscribeAll: function() {
Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated');
return this.detachAll.apply(this, arguments);
},
/**
* Creates a new custom event of the specified type. If a custom event
* by that name already exists, it will not be re-created. In either
* case the custom event is returned.
*
* @method publish
*
* @param type {string} the type, or name of the event
* @param opts {object} optional config params. Valid properties are:
*
* <ul>
* <li>
* 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false)
* </li>
* <li>
* 'bubbles': whether or not this event bubbles (true)
* Events can only bubble if emitFacade is true.
* </li>
* <li>
* 'context': the default execution context for the listeners (this)
* </li>
* <li>
* 'defaultFn': the default function to execute when this event fires if preventDefault was not called
* </li>
* <li>
* 'emitFacade': whether or not this event emits a facade (false)
* </li>
* <li>
* 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click'
* </li>
* <li>
* 'fireOnce': if an event is configured to fire once, new subscribers after
* the fire will be notified immediately.
* </li>
* <li>
* 'preventable': whether or not preventDefault() has an effect (true)
* </li>
* <li>
* 'preventedFn': a function that is executed when preventDefault is called
* </li>
* <li>
* 'queuable': whether or not this event can be queued during bubbling (false)
* </li>
* <li>
* 'silent': if silent is true, debug messages are not provided for this event.
* </li>
* <li>
* 'stoppedFn': a function that is executed when stopPropagation is called
* </li>
*
* <li>
* 'monitored': specifies whether or not this event should send notifications about
* when the event has been attached, detached, or published.
* </li>
* <li>
* 'type': the event type (valid option if not provided as the first parameter to publish)
* </li>
* </ul>
*
* @return {CustomEvent} the custom event
*
*/
publish: function(type, opts) {
var events, ce, ret, pre = this._yuievt.config.prefix;
type = (pre) ? _getType(type, pre) : type;
this._monitor('publish', type, {
args: arguments
});
if (L.isObject(type)) {
ret = {};
Y.each(type, function(v, k) {
ret[k] = this.publish(k, v || opts);
}, this);
return ret;
}
events = this._yuievt.events;
ce = events[type];
if (ce) {
// ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event');
if (opts) {
ce.applyConfig(opts, true);
}
} else {
// apply defaults
ce = new Y.CustomEvent(type, (opts) ? Y.mix(opts, this._yuievt.defaults) : this._yuievt.defaults);
events[type] = ce;
}
// make sure we turn the broadcast flag off if this
// event was published as a result of bubbling
// if (opts instanceof Y.CustomEvent) {
// events[type].broadcast = false;
// }
return events[type];
},
/**
* This is the entry point for the event monitoring system.
* You can monitor 'attach', 'detach', 'fire', and 'publish'.
* When configured, these events generate an event. click ->
* click_attach, click_detach, click_publish -- these can
* be subscribed to like other events to monitor the event
* system. Inividual published events can have monitoring
* turned on or off (publish can't be turned off before it
* it published) by setting the events 'monitor' config.
*
* @private
*/
_monitor: function(what, type, o) {
var monitorevt, ce = this.getEvent(type);
if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) {
monitorevt = type + '_' + what;
// Y.log('monitoring: ' + monitorevt);
o.monitored = what;
this.fire.call(this, monitorevt, o);
}
},
/**
* Fire a custom event by name. The callback functions will be executed
* from the context specified when the event was created, and with the
* following parameters.
*
* If the custom event object hasn't been created, then the event hasn't
* been published and it has no subscribers. For performance sake, we
* immediate exit in this case. This means the event won't bubble, so
* if the intention is that a bubble target be notified, the event must
* be published on this object first.
*
* The first argument is the event type, and any additional arguments are
* passed to the listeners as parameters. If the first of these is an
* object literal, and the event is configured to emit an event facade,
* that object is mixed into the event facade and the facade is provided
* in place of the original object.
*
* @method fire
* @param type {String|Object} The type of the event, or an object that contains
* a 'type' property.
* @param arguments {Object*} an arbitrary set of parameters to pass to
* the handler. If the first of these is an object literal and the event is
* configured to emit an event facade, the event facade will replace that
* parameter after the properties the object literal contains are copied to
* the event facade.
* @return {EventTarget} the event host
*
*/
fire: function(type) {
var typeIncluded = L.isString(type),
t = (typeIncluded) ? type : (type && type.type),
ce, ret, pre = this._yuievt.config.prefix, ce2,
args = (typeIncluded) ? Y.Array(arguments, 1, true) : arguments;
t = (pre) ? _getType(t, pre) : t;
this._monitor('fire', t, {
args: args
});
ce = this.getEvent(t, true);
ce2 = this.getSibling(t, ce);
if (ce2 && !ce) {
ce = this.publish(t);
}
// this event has not been published or subscribed to
if (!ce) {
if (this._yuievt.hasTargets) {
return this.bubble({ type: t }, args, this);
}
// otherwise there is nothing to be done
ret = true;
} else {
ce.sibling = ce2;
ret = ce.fire.apply(ce, args);
}
return (this._yuievt.chain) ? this : ret;
},
getSibling: function(type, ce) {
var ce2;
// delegate to *:type events if there are subscribers
if (type.indexOf(PREFIX_DELIMITER) > -1) {
type = _wildType(type);
// console.log(type);
ce2 = this.getEvent(type, true);
if (ce2) {
// console.log("GOT ONE: " + type);
ce2.applyConfig(ce);
ce2.bubbles = false;
ce2.broadcast = 0;
// ret = ce2.fire.apply(ce2, a);
}
}
return ce2;
},
/**
* Returns the custom event of the provided type has been created, a
* falsy value otherwise
* @method getEvent
* @param type {string} the type, or name of the event
* @param prefixed {string} if true, the type is prefixed already
* @return {CustomEvent} the custom event or null
*/
getEvent: function(type, prefixed) {
var pre, e;
if (!prefixed) {
pre = this._yuievt.config.prefix;
type = (pre) ? _getType(type, pre) : type;
}
e = this._yuievt.events;
return e[type] || null;
},
/**
* Subscribe to a custom event hosted by this object. The
* supplied callback will execute after any listeners add
* via the subscribe method, and after the default function,
* if configured for the event, has executed.
* @method after
* @param type {string} The type of the event
* @param fn {Function} The callback
* @param context {object} optional execution context.
* @param arg* {mixed} 0..n additional arguments to supply to the subscriber
* @return the event target or a detach handle per 'chain' config
*/
after: function(type, fn) {
var a = Y.Array(arguments, 0, true);
switch (L.type(type)) {
case 'function':
return Y.Do.after.apply(Y.Do, arguments);
case 'object':
a[0]._after = true;
break;
default:
a[0] = AFTER_PREFIX + type;
}
return this.on.apply(this, a);
},
/**
* Executes the callback before a DOM event, custom event
* or method. If the first argument is a function, it
* is assumed the target is a method. For DOM and custom
* events, this is an alias for Y.on.
*
* For DOM and custom events:
* type, callback, context, 0-n arguments
*
* For methods:
* callback, object (method host), methodName, context, 0-n arguments
*
* @method before
* @return detach handle
*/
before: function() {
return this.on.apply(this, arguments);
}
};
Y.EventTarget = ET;
// make Y an event target
Y.mix(Y, ET.prototype, false, false, {
bubbles: false
});
ET.call(Y);
YUI.Env.globalEvents = YUI.Env.globalEvents || new ET();
/**
* Hosts YUI page level events. This is where events bubble to
* when the broadcast config is set to 2. This property is
* only available if the custom event module is loaded.
* @property Global
* @type EventTarget
* @for YUI
*/
Y.Global = YUI.Env.globalEvents;
// @TODO implement a global namespace function on Y.Global?
})();
/**
* <code>YUI</code>'s <code>on</code> method is a unified interface for subscribing to
* most events exposed by YUI. This includes custom events, DOM events, and
* function events. <code>detach</code> is also provided to remove listeners
* serviced by this function.
*
* The signature that <code>on</code> accepts varies depending on the type
* of event being consumed. Refer to the specific methods that will
* service a specific request for additional information about subscribing
* to that type of event.
*
* <ul>
* <li>Custom events. These events are defined by various
* modules in the library. This type of event is delegated to
* <code>EventTarget</code>'s <code>on</code> method.
* <ul>
* <li>The type of the event</li>
* <li>The callback to execute</li>
* <li>An optional context object</li>
* <li>0..n additional arguments to supply the callback.</li>
* </ul>
* Example:
* <code>Y.on('domready', function() { // start work });</code>
* </li>
* <li>DOM events. These are moments reported by the browser related
* to browser functionality and user interaction.
* This type of event is delegated to <code>Event</code>'s
* <code>attach</code> method.
* <ul>
* <li>The type of the event</li>
* <li>The callback to execute</li>
* <li>The specification for the Node(s) to attach the listener
* to. This can be a selector, collections, or Node/Element
* refereces.</li>
* <li>An optional context object</li>
* <li>0..n additional arguments to supply the callback.</li>
* </ul>
* Example:
* <code>Y.on('click', function(e) { // something was clicked }, '#someelement');</code>
* </li>
* <li>Function events. These events can be used to react before or after a
* function is executed. This type of event is delegated to <code>Event.Do</code>'s
* <code>before</code> method.
* <ul>
* <li>The callback to execute</li>
* <li>The object that has the function that will be listened for.</li>
* <li>The name of the function to listen for.</li>
* <li>An optional context object</li>
* <li>0..n additional arguments to supply the callback.</li>
* </ul>
* Example <code>Y.on(function(arg1, arg2, etc) { // obj.methodname was executed }, obj 'methodname');</code>
* </li>
* </ul>
*
* <code>on</code> corresponds to the moment before any default behavior of
* the event. <code>after</code> works the same way, but these listeners
* execute after the event's default behavior. <code>before</code> is an
* alias for <code>on</code>.
*
* @method on
* @param type** event type (this parameter does not apply for function events)
* @param fn the callback
* @param target** a descriptor for the target (applies to custom events only).
* For function events, this is the object that contains the function to
* execute.
* @param extra** 0..n Extra information a particular event may need. These
* will be documented with the event. In the case of function events, this
* is the name of the function to execute on the host. In the case of
* delegate listeners, this is the event delegation specification.
* @param context optionally change the value of 'this' in the callback
* @param args* 0..n additional arguments to pass to the callback.
* @return the event target or a detach handle per 'chain' config
* @for YUI
*/
/**
* Listen for an event one time. Equivalent to <code>on</code>, except that
* the listener is immediately detached when executed.
* @see on
* @method once
* @param type** event type (this parameter does not apply for function events)
* @param fn the callback
* @param target** a descriptor for the target (applies to custom events only).
* For function events, this is the object that contains the function to
* execute.
* @param extra** 0..n Extra information a particular event may need. These
* will be documented with the event. In the case of function events, this
* is the name of the function to execute on the host. In the case of
* delegate listeners, this is the event delegation specification.
* @param context optionally change the value of 'this' in the callback
* @param args* 0..n additional arguments to pass to the callback.
* @return the event target or a detach handle per 'chain' config
* @for YUI
*/
/**
* after() is a unified interface for subscribing to
* most events exposed by YUI. This includes custom events,
* DOM events, and AOP events. This works the same way as
* the on() function, only it operates after any default
* behavior for the event has executed. @see <code>on</code> for more
* information.
* @method after
* @param type event type (this parameter does not apply for function events)
* @param fn the callback
* @param target a descriptor for the target (applies to custom events only).
* For function events, this is the object that contains the function to
* execute.
* @param extra 0..n Extra information a particular event may need. These
* will be documented with the event. In the case of function events, this
* is the name of the function to execute on the host. In the case of
* delegate listeners, this is the event delegation specification.
* @param context optionally change the value of 'this' in the callback
* @param args* 0..n additional arguments to pass to the callback.
* @return the event target or a detach handle per 'chain' config
* @for YUI
*/
}, '@VERSION@' ,{requires:['oop']});
YUI.add('event-custom-complex', function(Y) {
/**
* Adds event facades, preventable default behavior, and bubbling.
* events.
* @module event-custom
* @submodule event-custom-complex
*/
(function() {
var FACADE, FACADE_KEYS, CEProto = Y.CustomEvent.prototype,
ETProto = Y.EventTarget.prototype;
/**
* Wraps and protects a custom event for use when emitFacade is set to true.
* Requires the event-custom-complex module
* @class EventFacade
* @param e {Event} the custom event
* @param currentTarget {HTMLElement} the element the listener was attached to
*/
Y.EventFacade = function(e, currentTarget) {
e = e || {};
/**
* The arguments passed to fire
* @property details
* @type Array
*/
this.details = e.details;
/**
* The event type, this can be overridden by the fire() payload
* @property type
* @type string
*/
this.type = e.type;
/**
* The real event type
* @property type
* @type string
*/
this._type = e.type;
//////////////////////////////////////////////////////
/**
* Node reference for the targeted eventtarget
* @propery target
* @type Node
*/
this.target = e.target;
/**
* Node reference for the element that the listener was attached to.
* @propery currentTarget
* @type Node
*/
this.currentTarget = currentTarget;
/**
* Node reference to the relatedTarget
* @propery relatedTarget
* @type Node
*/
this.relatedTarget = e.relatedTarget;
/**
* Stops the propagation to the next bubble target
* @method stopPropagation
*/
this.stopPropagation = function() {
e.stopPropagation();
};
/**
* Stops the propagation to the next bubble target and
* prevents any additional listeners from being exectued
* on the current target.
* @method stopImmediatePropagation
*/
this.stopImmediatePropagation = function() {
e.stopImmediatePropagation();
};
/**
* Prevents the event's default behavior
* @method preventDefault
*/
this.preventDefault = function() {
e.preventDefault();
};
/**
* Stops the event propagation and prevents the default
* event behavior.
* @method halt
* @param immediate {boolean} if true additional listeners
* on the current target will not be executed
*/
this.halt = function(immediate) {
e.halt(immediate);
};
};
CEProto.fireComplex = function(args) {
var es = Y.Env._eventstack, ef, q, queue, ce, ret, events, subs,
self = this, host = self.host || self, next, oldbubble;
if (es) {
// queue this event if the current item in the queue bubbles
if (self.queuable && self.type != es.next.type) {
self.log('queue ' + self.type);
es.queue.push([self, args]);
return true;
}
} else {
Y.Env._eventstack = {
// id of the first event in the stack
id: self.id,
next: self,
silent: self.silent,
stopped: 0,
prevented: 0,
bubbling: null,
type: self.type,
// defaultFnQueue: new Y.Queue(),
afterQueue: new Y.Queue(),
defaultTargetOnly: self.defaultTargetOnly,
queue: []
};
es = Y.Env._eventstack;
}
subs = self.getSubs();
self.stopped = (self.type !== es.type) ? 0 : es.stopped;
self.prevented = (self.type !== es.type) ? 0 : es.prevented;
self.target = self.target || host;
events = new Y.EventTarget({
fireOnce: true,
context: host
});
self.events = events;
if (self.preventedFn) {
events.on('prevented', self.preventedFn);
}
if (self.stoppedFn) {
events.on('stopped', self.stoppedFn);
}
self.currentTarget = host;
self.details = args.slice(); // original arguments in the details
// self.log("Firing " + self + ", " + "args: " + args);
self.log("Firing " + self.type);
self._facade = null; // kill facade to eliminate stale properties
ef = self._getFacade(args);
if (Y.Lang.isObject(args[0])) {
args[0] = ef;
} else {
args.unshift(ef);
}
// if (subCount) {
if (subs[0]) {
// self._procSubs(Y.merge(self.subscribers), args, ef);
self._procSubs(subs[0], args, ef);
}
// bubble if this is hosted in an event target and propagation has not been stopped
if (self.bubbles && host.bubble && !self.stopped) {
oldbubble = es.bubbling;
// self.bubbling = true;
es.bubbling = self.type;
// if (host !== ef.target || es.type != self.type) {
if (es.type != self.type) {
es.stopped = 0;
es.prevented = 0;
}
ret = host.bubble(self);
self.stopped = Math.max(self.stopped, es.stopped);
self.prevented = Math.max(self.prevented, es.prevented);
// self.bubbling = false;
es.bubbling = oldbubble;
}
// execute the default behavior if not prevented
// console.log('defaultTargetOnly: ' + self.defaultTargetOnly);
// console.log('host === target: ' + (host === ef.target));
// if (self.defaultFn && !self.prevented && ((!self.defaultTargetOnly) || host === es.id === self.id)) {
if (self.defaultFn && !self.prevented && ((!self.defaultTargetOnly && !es.defaultTargetOnly) || host === ef.target)) {
// if (es.id === self.id) {
// self.defaultFn.apply(host, args);
// while ((next = es.defaultFnQueue.last())) {
// next();
// }
// } else {
// es.defaultFnQueue.add(function() {
// self.defaultFn.apply(host, args);
// });
// }
self.defaultFn.apply(host, args);
}
// broadcast listeners are fired as discreet events on the
// YUI instance and potentially the YUI global.
self._broadcast(args);
// process after listeners. If the default behavior was
// prevented, the after events don't fire.
// if (self.afterCount && !self.prevented && self.stopped < 2) {
// if (subs[1] && !self.prevented && self.stopped < 2) {
// // self._procSubs(Y.merge(self.afters), args, ef);
// self._procSubs(subs[1], args, ef);
// }
// Queue the after
if (subs[1] && !self.prevented && self.stopped < 2) {
if (es.id === self.id || self.type != host._yuievt.bubbling) {
self._procSubs(subs[1], args, ef);
while ((next = es.afterQueue.last())) {
next();
}
} else {
es.afterQueue.add(function() {
self._procSubs(subs[1], args, ef);
});
}
}
self.target = null;
// es.stopped = 0;
// es.prevented = 0;
if (es.id === self.id) {
queue = es.queue;
while (queue.length) {
q = queue.pop();
ce = q[0];
// set up stack to allow the next item to be processed
es.next = ce;
ce.fire.apply(ce, q[1]);
// es.stopped = 0;
// es.prevented = 0;
}
Y.Env._eventstack = null;
}
ret = !(self.stopped);
if (self.type != host._yuievt.bubbling) {
es.stopped = 0;
es.prevented = 0;
self.stopped = 0;
self.prevented = 0;
}
return ret;
};
CEProto._getFacade = function() {
var ef = this._facade, o, o2,
args = this.details;
if (!ef) {
ef = new Y.EventFacade(this, this.currentTarget);
}
// if the first argument is an object literal, apply the
// properties to the event facade
o = args && args[0];
if (Y.Lang.isObject(o, true)) {
o2 = {};
// protect the event facade properties
Y.mix(o2, ef, true, FACADE_KEYS);
// mix the data
Y.mix(ef, o, true);
// restore ef
Y.mix(ef, o2, true, FACADE_KEYS);
// Allow the event type to be faked
// http://yuilibrary.com/projects/yui3/ticket/2528376
ef.type = o.type || ef.type;
}
// update the details field with the arguments
// ef.type = this.type;
ef.details = this.details;
// use the original target when the event bubbled to this target
ef.target = this.originalTarget || this.target;
ef.currentTarget = this.currentTarget;
ef.stopped = 0;
ef.prevented = 0;
this._facade = ef;
return this._facade;
};
/**
* Stop propagation to bubble targets
* @for CustomEvent
* @method stopPropagation
*/
CEProto.stopPropagation = function() {
this.stopped = 1;
Y.Env._eventstack.stopped = 1;
this.events.fire('stopped', this);
};
/**
* Stops propagation to bubble targets, and prevents any remaining
* subscribers on the current target from executing.
* @method stopImmediatePropagation
*/
CEProto.stopImmediatePropagation = function() {
this.stopped = 2;
Y.Env._eventstack.stopped = 2;
this.events.fire('stopped', this);
};
/**
* Prevents the execution of this event's defaultFn
* @method preventDefault
*/
CEProto.preventDefault = function() {
if (this.preventable) {
this.prevented = 1;
Y.Env._eventstack.prevented = 1;
this.events.fire('prevented', this);
}
};
/**
* Stops the event propagation and prevents the default
* event behavior.
* @method halt
* @param immediate {boolean} if true additional listeners
* on the current target will not be executed
*/
CEProto.halt = function(immediate) {
if (immediate) {
this.stopImmediatePropagation();
} else {
this.stopPropagation();
}
this.preventDefault();
};
/**
* Registers another EventTarget as a bubble target. Bubble order
* is determined by the order registered. Multiple targets can
* be specified.
*
* Events can only bubble if emitFacade is true.
*
* Included in the event-custom-complex submodule.
*
* @method addTarget
* @param o {EventTarget} the target to add
* @for EventTarget
*/
ETProto.addTarget = function(o) {
this._yuievt.targets[Y.stamp(o)] = o;
this._yuievt.hasTargets = true;
};
/**
* Returns an array of bubble targets for this object.
* @method getTargets
* @return EventTarget[]
*/
ETProto.getTargets = function() {
return Y.Object.values(this._yuievt.targets);
};
/**
* Removes a bubble target
* @method removeTarget
* @param o {EventTarget} the target to remove
* @for EventTarget
*/
ETProto.removeTarget = function(o) {
delete this._yuievt.targets[Y.stamp(o)];
};
/**
* Propagate an event. Requires the event-custom-complex module.
* @method bubble
* @param evt {Event.Custom} the custom event to propagate
* @return {boolean} the aggregated return value from Event.Custom.fire
* @for EventTarget
*/
ETProto.bubble = function(evt, args, target) {
var targs = this._yuievt.targets, ret = true,
t, type = evt && evt.type, ce, i, bc, ce2,
originalTarget = target || (evt && evt.target) || this,
es = Y.Env._eventstack, oldbubble;
if (!evt || ((!evt.stopped) && targs)) {
// Y.log('Bubbling ' + evt.type);
for (i in targs) {
if (targs.hasOwnProperty(i)) {
t = targs[i];
ce = t.getEvent(type, true);
ce2 = t.getSibling(type, ce);
if (ce2 && !ce) {
ce = t.publish(type);
}
oldbubble = t._yuievt.bubbling;
t._yuievt.bubbling = type;
// if this event was not published on the bubble target,
// continue propagating the event.
if (!ce) {
if (t._yuievt.hasTargets) {
t.bubble(evt, args, originalTarget);
}
} else {
ce.sibling = ce2;
// set the original target to that the target payload on the
// facade is correct.
ce.target = originalTarget;
ce.originalTarget = originalTarget;
ce.currentTarget = t;
bc = ce.broadcast;
ce.broadcast = false;
ret = ret && ce.fire.apply(ce, args || evt.details || []);
ce.broadcast = bc;
ce.originalTarget = null;
// stopPropagation() was called
if (ce.stopped) {
break;
}
}
t._yuievt.bubbling = oldbubble;
}
}
}
return ret;
};
FACADE = new Y.EventFacade();
FACADE_KEYS = Y.Object.keys(FACADE);
})();
}, '@VERSION@' ,{requires:['event-custom-base']});
YUI.add('event-custom', function(Y){}, '@VERSION@' ,{use:['event-custom-base', 'event-custom-complex']});
|
src/components/SegmentedControl.js | bs1180/elemental | import classnames from 'classnames';
import React from 'react';
module.exports = React.createClass({
displayName: 'SegmentedControl',
propTypes: {
className: React.PropTypes.string,
equalWidthSegments: React.PropTypes.bool,
onChange: React.PropTypes.func.isRequired,
options: React.PropTypes.array.isRequired,
type: React.PropTypes.oneOf('default', 'muted', 'danger', 'info', 'primary', 'success', 'warning'),
value: React.PropTypes.string
},
getDefaultProps () {
return {
type: 'default'
};
},
onChange (value) {
this.props.onChange(value);
},
render () {
let componentClassName = classnames('SegmentedControl', ('SegmentedControl--' + this.props.type), {
'SegmentedControl--equal-widths': this.props.equalWidthSegments
}, this.props.className);
let options = this.props.options.map((op) => {
let buttonClassName = classnames('SegmentedControl__button', {
'is-selected': op.value === this.props.value
});
return (
<span key={'option-' + op.value} className="SegmentedControl__item">
<button type="button" onClick={this.onChange.bind(this, op.value)} className={buttonClassName}>
{op.label}
</button>
</span>
);
});
return <div className={componentClassName}>{options}</div>;
}
});
|
src/charts/series-chart.js | WaldoJeffers/react-dc | import React from 'react'
import dc from 'dc'
import CompositeChart from './composite-chart'
import seriesMixin from '../mixins/series-mixin'
@seriesMixin
export default class SeriesChart extends CompositeChart{
static displayName = 'SeriesChart'
componentDidMount(){
this.chart = dc.seriesChart(this.chart)
this.configure()
this.chart.render()
}
}
|
client/menu/main-menu.js | sekainogenkai/faito | import {Menu, MenuPage, ButtonMenuItem} from './menu';
import CharacterSelectMenuPage from './character-select';
import React from 'react';
export default function (props) {
return (
<MenuPage {...props}>
<ButtonMenuItem action={menu => menu.pushMenuPage(
<CharacterSelectMenuPage game={props.game}/>
)}>Play Game</ButtonMenuItem>
<ButtonMenuItem action={menu => menu.pushMenuPage(
<MenuPage>
<ButtonMenuItem action={menu => menu.popMenuPage()}>Return</ButtonMenuItem>
</MenuPage>)}>Settings</ButtonMenuItem>
</MenuPage>
);
}
|
node_modules/node_modules/babel-plugin-jest-hoist/src/__tests__/integration-test.js | SerendpityZOEY/Fixr-RelevantCodeSearch | /**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails oncall+jsinfra
*/
/* eslint-disable no-useless-concat */
'use strict';
import React from 'react';
import Unmocked from '../__test_modules__/Unmocked';
import Mocked from '../__test_modules__/Mocked';
import a from '../__test_modules__/a';
import b from '../__test_modules__/b';
import c from '../__test_modules__/c';
import d from '../__test_modules__/d';
import e from '../__test_modules__/e';
// These will all be hoisted above imports
jest.unmock('react');
jest.unmock('../__test_modules__/Unmocked');
jest
.unmock('../__test_modules__/c')
.unmock('../__test_modules__/d');
jest.mock('../__test_modules__/e', () => {
if (!global.CALLS) {
global.CALLS = 0;
}
global.CALLS++;
return {
_isMock: true,
fn: () => {
// The `jest.mock` transform will allow require, built-ins and globals.
const path = require('path');
const array = new Array(3);
array[0] = path.sep;
return jest.fn(() => array);
},
};
});
// These will not be hoisted
jest.unmock('../__test_modules__/a').dontMock('../__test_modules__/b');
jest.unmock('../__test_modules__/' + 'c');
jest.dontMock('../__test_modules__/Mocked');
describe('babel-plugin-jest-hoist', () => {
it('does not throw during transform', () => {
const object = {};
object.__defineGetter__('foo', () => 'bar');
expect(object.foo).toEqual('bar');
});
it('hoists react unmock call before imports', () => {
expect(typeof React).toEqual('object');
expect(React.isValidElement.mock).toBe(undefined);
});
it('hoists unmocked modules before imports', () => {
expect(Unmocked._isMockFunction).toBe(undefined);
expect((new Unmocked()).isUnmocked).toEqual(true);
expect(c._isMockFunction).toBe(undefined);
expect(c()).toEqual('unmocked');
expect(d._isMockFunction).toBe(undefined);
expect(d()).toEqual('unmocked');
});
it('hoists mock call with 2 arguments', () => {
const path = require('path');
expect(e._isMock).toBe(true);
const mockFn = e.fn();
expect(mockFn()).toEqual([path.sep, undefined, undefined]);
});
it('only executes the module factories once', () => {
global.CALLS = 0;
require('../__test_modules__/e');
expect(global.CALLS).toEqual(1);
require('../__test_modules__/e');
expect(global.CALLS).toEqual(1);
delete global.CALLS;
});
it('does not hoist dontMock calls before imports', () => {
expect(Mocked._isMockFunction).toBe(true);
expect((new Mocked()).isMocked).toEqual(undefined);
expect(a._isMockFunction).toBe(true);
expect(a()).toEqual(undefined);
expect(b._isMockFunction).toBe(true);
expect(b()).toEqual(undefined);
});
});
|
src/views/components/user-card/index.spec.js | zerubeus/sawt | import React from 'react';
import { shallow } from 'enzyme';
import { User } from '../../../core/users';
import UserCard from './index';
describe('views', () => {
describe('UserCard', () => {
let props;
let user;
beforeEach(() => {
user = new User({
id: 123,
followingsCount: 20,
followersCount: 40,
likesCount: 60,
trackCount: 80,
username: 'username'
});
props = {user};
});
function getWrapper() {
return shallow(
<UserCard {...props} />
);
}
it('should display username', () => {
expect(getWrapper().find('h1').text()).toBe(user.username);
});
it('should display trackCount label linked to user-tracks route', () => {
let label = getWrapper().find('.user-stats__label').at(0);
expect(label.prop('to')).toBe(`/users/${user.id}/tracks`);
});
it('should display FormattedInteger for trackCount', () => {
let formattedInteger = getWrapper().find('FormattedInteger').at(0);
expect(formattedInteger.prop('value')).toBe(user.trackCount);
});
it('should display likesCount label linked to user-likes route', () => {
let label = getWrapper().find('.user-stats__label').at(1);
expect(label.prop('to')).toBe(`/users/${user.id}/likes`);
});
it('should display FormattedInteger for likesCount', () => {
let formattedInteger = getWrapper().find('FormattedInteger').at(1);
expect(formattedInteger.prop('value')).toBe(user.likesCount);
});
it('should display followersCount label', () => {
let label = getWrapper().find('.user-stats__label').at(2);
expect(label.length).toBe(1);
});
it('should display FormattedInteger for followersCount', () => {
let formattedInteger = getWrapper().find('FormattedInteger').at(2);
expect(formattedInteger.prop('value')).toBe(user.followersCount);
});
it('should display followingsCount label', () => {
let label = getWrapper().find('.user-stats__label').at(3);
expect(label.length).toBe(1);
});
it('should display FormattedInteger for followingsCount', () => {
let formattedInteger = getWrapper().find('FormattedInteger').at(3);
expect(formattedInteger.prop('value')).toBe(user.followingsCount);
});
});
});
|
ajax/libs/js-data/2.9.0/js-data-debug.min.js | dada0423/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 if(typeof exports==="object")exports["JSData"]=factory();else root["JSData"]=factory()})(this,function(){return function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module=installedModules[moduleId]={exports:{},id:moduleId,loaded:false};modules[moduleId].call(module.exports,module,module.exports,__webpack_require__);module.loaded=true;return module.exports}__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.p="";return __webpack_require__(0)}([function(module,exports,__webpack_require__){"use strict";var _index=__webpack_require__(1);var _index2=_interopRequireDefault(_index);var _utils=__webpack_require__(2);var _utils2=_interopRequireDefault(_utils);var _errors=__webpack_require__(3);var _errors2=_interopRequireDefault(_errors);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}module.exports={DS:_index2.default,DSUtils:_utils2.default,DSErrors:_errors2.default,createStore:function createStore(options){return new _index2.default(options)},version:{full:"2.9.0",major:parseInt("2",10),minor:parseInt("9",10),patch:parseInt("0",10),alpha:true?"false":false,beta:true?"false":false}}},function(module,exports,__webpack_require__){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol?"symbol":typeof obj};var _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 _utils=__webpack_require__(2);var _utils2=_interopRequireDefault(_utils);var _errors=__webpack_require__(3);var _errors2=_interopRequireDefault(_errors);var _index=__webpack_require__(41);var _index2=_interopRequireDefault(_index);var _index3=__webpack_require__(47);var _index4=_interopRequireDefault(_index3);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 lifecycleNoopCb(resource,attrs,cb){cb(null,attrs)}function lifecycleNoop(resource,attrs){return attrs}function compare(orderBy,index,a,b){var def=orderBy[index];var cA=_utils2.default.get(a,def[0]);var cB=_utils2.default.get(b,def[0]);if(_utils2.default._s(cA)){cA=_utils2.default.upperCase(cA)}if(_utils2.default._s(cB)){cB=_utils2.default.upperCase(cB)}if(def[1]==="DESC"){if(cB<cA){return-1}else if(cB>cA){return 1}else{if(index<orderBy.length-1){return compare(orderBy,index+1,a,b)}else{return 0}}}else{if(cA<cB){return-1}else if(cA>cB){return 1}else{if(index<orderBy.length-1){return compare(orderBy,index+1,a,b)}else{return 0}}}}var Defaults=function(){function Defaults(){_classCallCheck(this,Defaults)}_createClass(Defaults,[{key:"errorFn",value:function errorFn(a,b){if(this.error&&typeof this.error==="function"){try{if(typeof a==="string"){throw new Error(a)}else{throw a}}catch(err){a=err}this.error(this.name||null,a||null,b||null)}}}]);return Defaults}();var defaultsPrototype=Defaults.prototype;defaultsPrototype.actions={};defaultsPrototype.afterCreate=lifecycleNoopCb;defaultsPrototype.afterCreateCollection=lifecycleNoop;defaultsPrototype.afterCreateInstance=lifecycleNoop;defaultsPrototype.afterDestroy=lifecycleNoopCb;defaultsPrototype.afterEject=lifecycleNoop;defaultsPrototype.afterFind=lifecycleNoopCb;defaultsPrototype.afterFindAll=lifecycleNoopCb;defaultsPrototype.afterInject=lifecycleNoop;defaultsPrototype.afterLoadRelations=lifecycleNoopCb;defaultsPrototype.afterReap=lifecycleNoop;defaultsPrototype.afterUpdate=lifecycleNoopCb;defaultsPrototype.afterValidate=lifecycleNoopCb;defaultsPrototype.allowSimpleWhere=true;defaultsPrototype.basePath="";defaultsPrototype.beforeCreate=lifecycleNoopCb;defaultsPrototype.beforeCreateCollection=lifecycleNoop;defaultsPrototype.beforeCreateInstance=lifecycleNoop;defaultsPrototype.beforeDestroy=lifecycleNoopCb;defaultsPrototype.beforeEject=lifecycleNoop;defaultsPrototype.beforeInject=lifecycleNoop;defaultsPrototype.beforeReap=lifecycleNoop;defaultsPrototype.beforeUpdate=lifecycleNoopCb;defaultsPrototype.beforeValidate=lifecycleNoopCb;defaultsPrototype.bypassCache=false;defaultsPrototype.cacheResponse=!!_utils2.default.w;defaultsPrototype.csp=false;defaultsPrototype.clearEmptyQueries=true;defaultsPrototype.computed={};defaultsPrototype.defaultAdapter="http";defaultsPrototype.debug=false;defaultsPrototype.defaultValues={};defaultsPrototype.eagerEject=false;defaultsPrototype.eagerInject=false;defaultsPrototype.endpoint="";defaultsPrototype.error=console?function(a,b,c){return console[typeof console.error==="function"?"error":"log"](a,b,c)}:false;defaultsPrototype.errorHandler=function(){return _utils2.default.Promise.reject(arguments.length<=0?undefined:arguments[0])};defaultsPrototype.fallbackAdapters=["http"];defaultsPrototype.findStrictCache=false;defaultsPrototype.idAttribute="id";defaultsPrototype.ignoredChanges=[/\$/];defaultsPrototype.instanceEvents=!!_utils2.default.w;defaultsPrototype.keepChangeHistory=false;defaultsPrototype.linkRelations=!!_utils2.default.w;defaultsPrototype.log=console?function(a,b,c,d,e){return console[typeof console.info==="function"?"info":"log"](a,b,c,d,e)}:false;defaultsPrototype.logFn=function(a,b,c,d){var _this=this;if(_this.debug&&_this.log&&typeof _this.log==="function"){_this.log(_this.name||null,a||null,b||null,c||null,d||null)}};defaultsPrototype.maxAge=false;defaultsPrototype.methods={};defaultsPrototype.notify=!!_utils2.default.w;defaultsPrototype.omit=[];defaultsPrototype.onConflict="merge";defaultsPrototype.reapAction=_utils2.default.w?"inject":"none";defaultsPrototype.reapInterval=_utils2.default.w?3e4:false;defaultsPrototype.relationsEnumerable=false;defaultsPrototype.resetHistoryOnInject=true;defaultsPrototype.returnMeta=false;defaultsPrototype.scopes={};defaultsPrototype.strategy="single";defaultsPrototype.upsert=!!_utils2.default.w;defaultsPrototype.useClass=true;defaultsPrototype.useFilter=false;defaultsPrototype.validate=lifecycleNoopCb;defaultsPrototype.watchChanges=!!_utils2.default.w;var escapeRegExp=/([.*+?^=!:${}()|[\]\/\\])/g;var percentRegExp=/%/g;var underscoreRegExp=/_/g;function escape(pattern){return pattern.replace(escapeRegExp,"\\$1")}function like(pattern,flags){return new RegExp("^"+escape(pattern).replace(percentRegExp,".*").replace(underscoreRegExp,".")+"$",flags)}defaultsPrototype.defaultFilter=function(collection,resourceName,params,options){var definition=this.definitions[resourceName];var idA="id";var resource=undefined;if(definition){idA=definition.idAttribute;resource=this.store[resourceName]}var filtered=collection;var where=null;var reserved={skip:"",offset:"",where:"",limit:"",orderBy:"",sort:""};params=params||{};options=options||{};if(_utils2.default._o(params.where)){where=params.where}else{where={}}if(options.allowSimpleWhere){_utils2.default.forOwn(params,function(value,key){if(!(key in reserved)&&!(key in where)){where[key]={"==":value}}})}if(_utils2.default.isEmpty(where)){where=null}if(where){filtered=_utils2.default.filter(filtered,function(attrs){var first=true;var keep=true;if(options.excludeTemporary&&resource&&resource.temporaryItems[attrs[idA]]){return false}_utils2.default.forOwn(where,function(clause,field){if(!_utils2.default._o(clause)){clause={"==":clause}}_utils2.default.forOwn(clause,function(term,op){var expr=undefined;var isOr=op[0]==="|";var val=_utils2.default.get(attrs,field);op=isOr?op.substr(1):op;if(op==="=="){expr=val==term}else if(op==="==="){expr=val===term}else if(op==="!="){expr=val!=term}else if(op==="!=="){expr=val!==term}else if(op===">"){expr=val>term}else if(op===">="){expr=val>=term}else if(op==="<"){expr=val<term}else if(op==="<="){expr=val<=term}else if(op==="isectEmpty"){expr=!_utils2.default.intersection(val||[],term||[]).length}else if(op==="isectNotEmpty"){expr=_utils2.default.intersection(val||[],term||[]).length}else if(op==="in"){if(_utils2.default._s(term)){expr=term.indexOf(val)!==-1}else{expr=_utils2.default.contains(term,val)}}else if(op==="notIn"){if(_utils2.default._s(term)){expr=term.indexOf(val)===-1}else{expr=!_utils2.default.contains(term,val)}}else if(op.indexOf("like")===0){expr=like(term,op.substr(4)).exec(val)!==null}else if(op.indexOf("notLike")===0){expr=like(term,op.substr(7)).exec(val)===null}else if(op==="contains"){if(_utils2.default._s(val)){expr=val.indexOf(term)!==-1}else{expr=_utils2.default.contains(val,term)}}else if(op==="notContains"){if(_utils2.default._s(val)){expr=val.indexOf(term)===-1}else{expr=!_utils2.default.contains(val,term)}}if(expr!==undefined){keep=first?expr:isOr?keep||expr:keep&&expr}first=false})});return keep})}else if(options.excludeTemporary&&resource){filtered=_utils2.default.filter(filtered,function(attrs){return resource.temporaryItems[attrs[idA]]})}var orderBy=null;if(_utils2.default._s(params.orderBy)){orderBy=[[params.orderBy,"ASC"]]}else if(_utils2.default._a(params.orderBy)){orderBy=params.orderBy}if(!orderBy&&_utils2.default._s(params.sort)){orderBy=[[params.sort,"ASC"]]}else if(!orderBy&&_utils2.default._a(params.sort)){orderBy=params.sort}if(orderBy){(function(){var index=0;_utils2.default.forEach(orderBy,function(def,i){if(_utils2.default._s(def)){orderBy[i]=[def,"ASC"]}else if(!_utils2.default._a(def)){throw new _errors2.default.IA('DS.filter("'+resourceName+'"[, params][, options]): '+_utils2.default.toJson(def)+": Must be a string or an array!",{params:{"orderBy[i]":{actual:typeof def==="undefined"?"undefined":_typeof(def),expected:"string|array"}}})}});filtered=_utils2.default.sort(filtered,function(a,b){return compare(orderBy,index,a,b)})})()}var limit=_utils2.default._n(params.limit)?params.limit:null;var skip=null;if(_utils2.default._n(params.skip)){skip=params.skip}else if(_utils2.default._n(params.offset)){skip=params.offset}if(limit&&skip){filtered=_utils2.default.slice(filtered,skip,Math.min(filtered.length,skip+limit))}else if(_utils2.default._n(limit)){filtered=_utils2.default.slice(filtered,0,Math.min(filtered.length,limit))}else if(_utils2.default._n(skip)){if(skip<filtered.length){filtered=_utils2.default.slice(filtered,skip)}else{filtered=[]}}return filtered===collection?filtered.slice():filtered};var DS=function(){function DS(options){_classCallCheck(this,DS);var _this=this;options=options||{};_this.store={};_this.definitions={};_this.adapters={};_this.defaults=new Defaults;_this.observe=_utils2.default.observe;_utils2.default.forOwn(options,function(v,k){if(k==="omit"){_this.defaults.omit=v.concat(Defaults.prototype.omit)}else{_this.defaults[k]=v}});_this.defaults.logFn("new data store created",_this.defaults);var P=_utils2.default.Promise;if(P&&!P.prototype.spread){P.prototype.spread=function(cb){return this.then(function(arr){return cb.apply(this,arr)})}}_utils2.default.Events(_this)}_createClass(DS,[{key:"getAdapterName",value:function getAdapterName(options){var errorIfNotExist=false;options=options||{};this.defaults.logFn("getAdapterName",options);if(_utils2.default._s(options)){errorIfNotExist=true;options={adapter:options}}if(this.adapters[options.adapter]){return options.adapter}else if(errorIfNotExist){throw new Error(options.adapter+" is not a registered adapter!")}else{return options.defaultAdapter}}},{key:"getAdapter",value:function getAdapter(options){options=options||{};this.defaults.logFn("getAdapter",options);return this.adapters[this.getAdapterName(options)]}},{key:"registerAdapter",value:function registerAdapter(name,Adapter,options){var _this=this;options=options||{};_this.defaults.logFn("registerAdapter",name,Adapter,options);if(_utils2.default.isFunction(Adapter)){_this.adapters[name]=new Adapter(options)}else{_this.adapters[name]=Adapter}if(options.default){_this.defaults.defaultAdapter=name}_this.defaults.logFn("default adapter is "+_this.defaults.defaultAdapter)}},{key:"is",value:function is(resourceName,instance){var definition=this.definitions[resourceName];if(!definition){throw new _errors2.default.NER(resourceName)}return instance instanceof definition[definition.class]}},{key:"clear",value:function clear(){var _this2=this;var ejected={};_utils2.default.forOwn(this.definitions,function(definition){var name=definition.name;ejected[name]=definition.ejectAll();_this2.store[name].completedQueries={};_this2.store[name].queryData={}});return ejected}},{key:"errorFn",value:function errorFn(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}var options=args[args.length-1];var defaultHandler=this.defaults.errorHandler;var errorHandler=options?options.errorHandler:defaultHandler;errorHandler=errorHandler||defaultHandler;return function(err){return errorHandler.apply(undefined,[err].concat(args))}}}]);return DS}();var dsPrototype=DS.prototype;dsPrototype.getAdapterName.shorthand=false;dsPrototype.getAdapter.shorthand=false;dsPrototype.registerAdapter.shorthand=false;dsPrototype.errors=_errors2.default;dsPrototype.utils=_utils2.default;function addMethods(target,obj){_utils2.default.forOwn(obj,function(v,k){target[k]=v;target[k].before=function(fn){var orig=target[k];target[k]=function(){for(var _len2=arguments.length,args=Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2]}return orig.apply(this,fn.apply(this,args)||args)}}})}addMethods(dsPrototype,_index2.default);addMethods(dsPrototype,_index4.default);exports.default=DS},function(module,exports,__webpack_require__){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol?"symbol":typeof obj};var _errors=__webpack_require__(3);var _errors2=_interopRequireDefault(_errors);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}var BinaryHeap=__webpack_require__(4);var forEach=__webpack_require__(5);var slice=__webpack_require__(6);var forOwn=__webpack_require__(7);var contains=__webpack_require__(10);var deepMixIn=__webpack_require__(12);var pascalCase=__webpack_require__(14);var remove=__webpack_require__(21);var pick=__webpack_require__(22);var _keys=__webpack_require__(23);var sort=__webpack_require__(24);var upperCase=__webpack_require__(19);var get=__webpack_require__(25);var set=__webpack_require__(27);var observe=__webpack_require__(29);var guid=__webpack_require__(30);var w=undefined,P=undefined,File=undefined;var objectProto=Object.prototype;var toString=objectProto.toString;try{P=Promise}catch(e){console.error("js-data requires a global Promise constructor!")}try{File=window.File}catch(e){File=function File(){}}function _isArray(value){return toString.call(value)==="[object Array]"||false}var isArray=Array.isArray||_isArray;function isRegExp(value){return toString.call(value)==="[object RegExp]"||false}function isString(value){return typeof value==="string"||value&&(typeof value==="undefined"?"undefined":_typeof(value))==="object"&&toString.call(value)==="[object String]"||false}function isObject(value){return toString.call(value)==="[object Object]"||false}function isDate(value){return value&&(typeof value==="undefined"?"undefined":_typeof(value))==="object"&&toString.call(value)==="[object Date]"||false}function isNumber(value){var type=typeof value==="undefined"?"undefined":_typeof(value);return type==="number"||value&&type==="object"&&toString.call(value)==="[object Number]"||false}function isFunction(value){return typeof value==="function"||value&&toString.call(value)==="[object Function]"||false}function isStringOrNumber(value){return isString(value)||isNumber(value)}function isStringOrNumberErr(field){return new _errors2.default.IA('"'+field+'" must be a string or a number!')}function isObjectErr(field){return new _errors2.default.IA('"'+field+'" must be an object!')}function isArrayErr(field){return new _errors2.default.IA('"'+field+'" must be an array!')}function isEmpty(val){if(val==null){return true}else if(typeof val==="string"||isArray(val)){return!val.length}else if((typeof val==="undefined"?"undefined":_typeof(val))==="object"){var result=true;forOwn(val,function(){result=false;return false});return result}else{return true}}function intersection(array1,array2){if(!array1||!array2){return[]}var result=[];var item=undefined;for(var i=0,length=array1.length;i<length;i++){item=array1[i];if(contains(result,item)){continue}if(contains(array2,item)){result.push(item)}}return result}function filter(array,cb,thisObj){var results=[];forEach(array,function(value,key,arr){if(cb(value,key,arr)){results.push(value)}},thisObj);return results}try{w=window;w={}}catch(e){w=null}function Events(target){var events={};target=target||this;Object.defineProperties(target,{on:{value:function value(type,func,ctx){events[type]=events[type]||[];events[type].push({f:func,c:ctx})}},off:{value:function value(type,func){var listeners=events[type];if(!listeners){events={}}else if(func){for(var i=0;i<listeners.length;i++){if(listeners[i].f===func){listeners.splice(i,1);break}}}else{listeners.splice(0,listeners.length)}}},emit:{value:function value(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}var listeners=events[args.shift()]||[];if(listeners){for(var i=0;i<listeners.length;i++){listeners[i].f.apply(listeners[i].c,args)}}}}})}var toPromisify=["beforeValidate","validate","afterValidate","beforeCreate","afterCreate","beforeUpdate","afterUpdate","beforeDestroy","afterDestroy"];var isBlacklisted=observe.isBlacklisted;function copy(source,destination,stackSource,stackDest,blacklist){if(!destination){destination=source;if(source){if(isArray(source)){destination=copy(source,[],stackSource,stackDest,blacklist)}else if(isDate(source)){destination=new Date(source.getTime())}else if(isRegExp(source)){destination=new RegExp(source.source,source.toString().match(/[^\/]*$/)[0]);destination.lastIndex=source.lastIndex}else if(isObject(source)){destination=copy(source,Object.create(Object.getPrototypeOf(source)),stackSource,stackDest,blacklist)}}}else{if(source===destination){throw new Error("Cannot copy! Source and destination are identical.")}stackSource=stackSource||[];stackDest=stackDest||[];if(isObject(source)){var index=stackSource.indexOf(source);if(index!==-1){return stackDest[index]}stackSource.push(source);stackDest.push(destination)}var result=undefined;if(isArray(source)){var i=undefined;destination.length=0;for(i=0;i<source.length;i++){result=copy(source[i],null,stackSource,stackDest,blacklist);if(isObject(source[i])){stackSource.push(source[i]);stackDest.push(result)}destination.push(result)}}else{if(isArray(destination)){destination.length=0}else{forEach(destination,function(value,key){delete destination[key]})}for(var key in source){if(source.hasOwnProperty(key)){if(isBlacklisted(key,blacklist)){continue}result=copy(source[key],null,stackSource,stackDest,blacklist);if(isObject(source[key])){stackSource.push(source[key]);stackDest.push(result)}destination[key]=result}}}}return destination}function equals(o1,o2){if(o1===o2){return true}if(o1===null||o2===null){return false}if(o1!==o1&&o2!==o2){return true}var t1=typeof o1==="undefined"?"undefined":_typeof(o1);var t2=typeof o2==="undefined"?"undefined":_typeof(o2);var length,key,keySet;if(t1==t2){if(t1=="object"){if(isArray(o1)){if(!isArray(o2)){return false}if((length=o1.length)===o2.length){for(key=0;key<length;key++){if(!equals(o1[key],o2[key])){return false}}return true}}else if(isDate(o1)){if(!isDate(o2)){return false}return equals(o1.getTime(),o2.getTime())}else if(isRegExp(o1)&&isRegExp(o2)){return o1.toString()==o2.toString()}else{if(isArray(o2)){return false}keySet={};for(key in o1){if(key.charAt(0)==="$"||isFunction(o1[key])){continue}if(!equals(o1[key],o2[key])){return false}keySet[key]=true}for(key in o2){if(!keySet.hasOwnProperty(key)&&key.charAt(0)!=="$"&&o2[key]!==undefined&&!isFunction(o2[key])){return false}}return true}}}return false}function resolveId(definition,idOrInstance){if(isString(idOrInstance)||isNumber(idOrInstance)){return idOrInstance}else if(idOrInstance&&definition){return idOrInstance[definition.idAttribute]||idOrInstance}else{return idOrInstance}}function resolveItem(resource,idOrInstance){if(resource&&(isString(idOrInstance)||isNumber(idOrInstance))){return resource.index[idOrInstance]||idOrInstance}else{return idOrInstance}}function isValidString(val){return val!=null&&val!==""}function join(items,separator){separator=separator||"";return filter(items,isValidString).join(separator)}function makePath(){for(var _len2=arguments.length,args=Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2]}var result=join(args,"/");return result.replace(/([^:\/]|^)\/{2,}/g,"$1/")}exports.default={Promise:P,_:function _(parent,options){var _this=this;parent=parent||{};options=options||{};if(options&&options.constructor===parent.constructor){return options}else if(!isObject(options)){throw new _errors2.default.IA('"options" must be an object!')}forEach(toPromisify,function(name){if(typeof options[name]==="function"&&options[name].toString().indexOf("for (var _len = arg")===-1){options[name]=_this.promisify(options[name])}});var O=function Options(attrs){var self=this;forOwn(attrs,function(value,key){self[key]=value})};O.prototype=parent;O.prototype.orig=function(){var orig={};forOwn(this,function(value,key){orig[key]=value});return orig};return new O(options)},_n:isNumber,_s:isString,_sn:isStringOrNumber,_snErr:isStringOrNumberErr,_o:isObject,_oErr:isObjectErr,_a:isArray,_aErr:isArrayErr,applyScope:function applyScope(definition,params,options){var scope=options.scope;var _params=copy(params);if(scope){if(isString(scope)){scope=[scope]}}else{scope=[]}scope.unshift("defaultScope");forEach(scope,function(_scope){var scopeDef=options.scopes[_scope];if(typeof scopeDef==="function"){deepMixIn(params,scopeDef(definition))}else if(scopeDef){deepMixIn(params,scopeDef)}});deepMixIn(params,_params)},compute:function compute(fn,field){var _this=this;var args=[];if(!isObject(fn)){forEach(fn.deps,function(dep){args.push(get(_this,dep))});set(_this,field,fn[fn.length-1].apply(_this,args))}},contains:contains,copy:copy,deepMixIn:deepMixIn,diffObjectFromOldObject:observe.diffObjectFromOldObject,BinaryHeap:BinaryHeap,equals:equals,Events:Events,filter:filter,fillIn:function fillIn(target,obj){forOwn(obj,function(v,k){if(!(k in target)){target[k]=v}});return target},forEach:forEach,forOwn:forOwn,fromJson:function fromJson(json){return isString(json)?JSON.parse(json):json},get:get,guid:guid,intersection:intersection,isArray:isArray,isBlacklisted:isBlacklisted,isEmpty:isEmpty,isFunction:isFunction,isObject:isObject,isNumber:isNumber,isString:isString,keys:_keys,makePath:makePath,observe:observe,omit:function omit(obj,bl){var toRemove=[];forOwn(obj,function(v,k){if(isBlacklisted(k,bl)){toRemove.push(k)}});forEach(toRemove,function(k){delete obj[k]});return obj},pascalCase:pascalCase,pick:pick,promisify:function promisify(fn,target){var _this=this;if(!fn){return}else if(typeof fn!=="function"){throw new Error("Can only promisify functions!")}return function(){for(var _len3=arguments.length,args=Array(_len3),_key3=0;_key3<_len3;_key3++){args[_key3]=arguments[_key3]}return new _this.Promise(function(resolve,reject){args.push(function(err,result){if(err){reject(err)}else{resolve(result)}});try{var promise=fn.apply(target||this,args);if(promise&&promise.then){promise.then(resolve,reject)}}catch(err){reject(err)}})}},remove:remove,set:set,slice:slice,sort:sort,toJson:JSON.stringify,updateTimestamp:function updateTimestamp(timestamp){var newTimestamp=typeof Date.now==="function"?Date.now():(new Date).getTime();if(timestamp&&newTimestamp<=timestamp){return timestamp+1}else{return newTimestamp}},upperCase:upperCase,removeCircular:function removeCircular(object){return function rmCirc(value,ctx){var i=undefined;var nu=undefined;if((typeof value==="undefined"?"undefined":_typeof(value))==="object"&&value!==null&&!(value instanceof Boolean)&&!(value instanceof Date)&&!(value instanceof Number)&&!(value instanceof RegExp)&&!(value instanceof String)&&(!File||!(value instanceof File))){var cur=ctx.cur;var parent=ctx.ctx;while(parent){if(parent.cur===cur){return undefined}parent=parent.ctx}if(isArray(value)){nu=[];for(i=0;i<value.length;i+=1){nu[i]=rmCirc(value[i],{ctx:ctx,cur:value[i]})}}else{nu={};forOwn(value,function(v,k){nu[k]=rmCirc(value[k],{ctx:ctx,cur:value[k]})})}return nu}return value}(object,{ctx:null,cur:object})},resolveItem:resolveItem,resolveId:resolveId,respond:function respond(response,meta,options){if(options.returnMeta==="array"){return[response,meta]}else if(options.returnMeta==="object"){return{response:response,meta:meta}}else{return response}},w:w,applyRelationGettersToTarget:function applyRelationGettersToTarget(store,definition,target){this.forEach(definition.relationList,function(def){var relationName=def.relation;var localField=def.localField;var localKey=def.localKey;var foreignKey=def.foreignKey;var localKeys=def.localKeys;var foreignKeys=def.foreignKeys;var enumerable=typeof def.enumerable==="boolean"?def.enumerable:!!definition.relationsEnumerable;if(typeof def.link==="boolean"?def.link:!!definition.linkRelations){delete target[localField];var prop={enumerable:enumerable};if(def.type==="belongsTo"){prop.get=function(){var key=get(this,localKey);var hasKey=!!(key||key===0);return hasKey?definition.getResource(relationName).get(key):undefined};prop.set=function(parent){if(parent){set(this,localKey,get(parent,definition.getResource(relationName).idAttribute))}return get(this,localField)}}else if(def.type==="hasMany"){prop.get=function(){var params={};if(foreignKey){params[foreignKey]=this[definition.idAttribute];return definition.getResource(relationName).defaultFilter.call(store,store.store[relationName].collection,relationName,params,{allowSimpleWhere:true})}else if(localKeys){var keys=get(this,localKeys)||[];return definition.getResource(relationName).getAll(isArray(keys)?keys:_keys(keys))}else if(foreignKeys){set(params,"where."+foreignKeys+".contains",this[definition.idAttribute]);return definition.getResource(relationName).defaultFilter.call(store,store.store[relationName].collection,relationName,params)}return undefined};prop.set=function(children){var _this2=this;if(children&&children.length){(function(){var id=get(_this2,definition.idAttribute);if(foreignKey){forEach(children,function(child){set(child,foreignKey,id)})}else if(localKeys){(function(){var keys=[];forEach(children,function(child){keys.push(get(child,definition.getResource(relationName).idAttribute))});set(_this2,localKeys,keys)})()}else if(foreignKeys){forEach(children,function(child){var keys=get(child,foreignKeys);if(keys){if(!contains(keys,id)){keys.push(id)}}else{set(child,foreignKeys,[id])}})}})()}return get(this,localField)}}else if(def.type==="hasOne"){if(localKey){prop.get=function(){var key=get(this,localKey);var hasKey=!!(key||key===0);return hasKey?definition.getResource(relationName).get(key):undefined};prop.set=function(sibling){if(sibling){set(this,localKey,get(sibling,definition.getResource(relationName).idAttribute))}return get(this,localField)}}else{prop.get=function(){var params={};params[foreignKey]=this[definition.idAttribute];var items=params[foreignKey]?definition.getResource(relationName).defaultFilter.call(store,store.store[relationName].collection,relationName,params,{allowSimpleWhere:true}):[];if(items.length){return items[0]}return undefined};prop.set=function(sibling){if(sibling){set(sibling,foreignKey,get(this,definition.idAttribute))}return get(this,localField)}}}if(def.get){(function(){var orig=prop.get;prop.get=function(){var _this3=this;return def.get(definition,def,this,function(){for(var _len4=arguments.length,args=Array(_len4),_key4=0;_key4<_len4;_key4++){args[_key4]=arguments[_key4]}return orig.apply(_this3,args)})}})()}Object.defineProperty(target,localField,prop)}})}}},function(module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});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 IllegalArgumentError=function(_Error){_inherits(IllegalArgumentError,_Error);function IllegalArgumentError(message){_classCallCheck(this,IllegalArgumentError);var _this=_possibleConstructorReturn(this,Object.getPrototypeOf(IllegalArgumentError).call(this));if(typeof Error.captureStackTrace==="function"){Error.captureStackTrace(_this,_this.constructor)}_this.type=_this.constructor.name;_this.message=message;return _this}return IllegalArgumentError}(Error);var RuntimeError=function(_Error2){_inherits(RuntimeError,_Error2);function RuntimeError(message){_classCallCheck(this,RuntimeError);var _this2=_possibleConstructorReturn(this,Object.getPrototypeOf(RuntimeError).call(this));if(typeof Error.captureStackTrace==="function"){Error.captureStackTrace(_this2,_this2.constructor)}_this2.type=_this2.constructor.name;_this2.message=message;return _this2}return RuntimeError}(Error);var NonexistentResourceError=function(_Error3){_inherits(NonexistentResourceError,_Error3);function NonexistentResourceError(resourceName){_classCallCheck(this,NonexistentResourceError);var _this3=_possibleConstructorReturn(this,Object.getPrototypeOf(NonexistentResourceError).call(this));if(typeof Error.captureStackTrace==="function"){Error.captureStackTrace(_this3,_this3.constructor)}_this3.type=_this3.constructor.name;_this3.message=resourceName+" is not a registered resource!";return _this3}return NonexistentResourceError}(Error);exports.default={IllegalArgumentError:IllegalArgumentError,IA:IllegalArgumentError,RuntimeError:RuntimeError,R:RuntimeError,NonexistentResourceError:NonexistentResourceError,NER:NonexistentResourceError}},function(module,exports,__webpack_require__){(function webpackUniversalModuleDefinition(root,factory){if(true)module.exports=factory();else if(typeof define==="function"&&define.amd)define("yabh",factory);else if(typeof exports==="object")exports["BinaryHeap"]=factory();else root["BinaryHeap"]=factory()})(this,function(){return function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module=installedModules[moduleId]={exports:{},id:moduleId,loaded:false};modules[moduleId].call(module.exports,module,module.exports,__webpack_require__);
module.loaded=true;return module.exports}__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.p="";return __webpack_require__(0)}([function(module,exports,__webpack_require__){function bubbleUp(heap,weightFunc,n){var element=heap[n];var weight=weightFunc(element);while(n>0){var parentN=Math.floor((n+1)/2)-1;var _parent=heap[parentN];if(weight>=weightFunc(_parent)){break}else{heap[parentN]=element;heap[n]=_parent;n=parentN}}}var bubbleDown=function bubbleDown(heap,weightFunc,n){var length=heap.length;var node=heap[n];var nodeWeight=weightFunc(node);while(true){var child2N=(n+1)*2,child1N=child2N-1;var swap=null;if(child1N<length){var child1=heap[child1N],child1Weight=weightFunc(child1);if(child1Weight<nodeWeight){swap=child1N}}if(child2N<length){var child2=heap[child2N],child2Weight=weightFunc(child2);if(child2Weight<(swap===null?nodeWeight:weightFunc(heap[child1N]))){swap=child2N}}if(swap===null){break}else{heap[n]=heap[swap];heap[swap]=node;n=swap}}};function BinaryHeap(weightFunc,compareFunc){if(!weightFunc){weightFunc=function(x){return x}}if(!compareFunc){compareFunc=function(x,y){return x===y}}if(typeof weightFunc!=="function"){throw new Error('BinaryHeap([weightFunc][, compareFunc]): "weightFunc" must be a function!')}if(typeof compareFunc!=="function"){throw new Error('BinaryHeap([weightFunc][, compareFunc]): "compareFunc" must be a function!')}this.weightFunc=weightFunc;this.compareFunc=compareFunc;this.heap=[]}var BHProto=BinaryHeap.prototype;BHProto.push=function(node){this.heap.push(node);bubbleUp(this.heap,this.weightFunc,this.heap.length-1)};BHProto.peek=function(){return this.heap[0]};BHProto.pop=function(){var front=this.heap[0];var end=this.heap.pop();if(this.heap.length>0){this.heap[0]=end;bubbleDown(this.heap,this.weightFunc,0)}return front};BHProto.remove=function(node){var length=this.heap.length;for(var i=0;i<length;i++){if(this.compareFunc(this.heap[i],node)){var removed=this.heap[i];var end=this.heap.pop();if(i!==length-1){this.heap[i]=end;bubbleUp(this.heap,this.weightFunc,i);bubbleDown(this.heap,this.weightFunc,i)}return removed}}return null};BHProto.removeAll=function(){this.heap=[]};BHProto.size=function(){return this.heap.length};module.exports=BinaryHeap}])})},function(module,exports){function forEach(arr,callback,thisObj){if(arr==null){return}var i=-1,len=arr.length;while(++i<len){if(callback.call(thisObj,arr[i],i,arr)===false){break}}}module.exports=forEach},function(module,exports){function slice(arr,start,end){var len=arr.length;if(start==null){start=0}else if(start<0){start=Math.max(len+start,0)}else{start=Math.min(start,len)}if(end==null){end=len}else if(end<0){end=Math.max(len+end,0)}else{end=Math.min(end,len)}var result=[];while(start<end){result.push(arr[start++])}return result}module.exports=slice},function(module,exports,__webpack_require__){var hasOwn=__webpack_require__(8);var forIn=__webpack_require__(9);function forOwn(obj,fn,thisObj){forIn(obj,function(val,key){if(hasOwn(obj,key)){return fn.call(thisObj,obj[key],key,obj)}})}module.exports=forOwn},function(module,exports){function hasOwn(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}module.exports=hasOwn},function(module,exports,__webpack_require__){var hasOwn=__webpack_require__(8);var _hasDontEnumBug,_dontEnums;function checkDontEnum(){_dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"];_hasDontEnumBug=true;for(var key in{toString:null}){_hasDontEnumBug=false}}function forIn(obj,fn,thisObj){var key,i=0;if(_hasDontEnumBug==null)checkDontEnum();for(key in obj){if(exec(fn,obj,key,thisObj)===false){break}}if(_hasDontEnumBug){var ctor=obj.constructor,isProto=!!ctor&&obj===ctor.prototype;while(key=_dontEnums[i++]){if((key!=="constructor"||!isProto&&hasOwn(obj,key))&&obj[key]!==Object.prototype[key]){if(exec(fn,obj,key,thisObj)===false){break}}}}}function exec(fn,obj,key,thisObj){return fn.call(thisObj,obj[key],key,obj)}module.exports=forIn},function(module,exports,__webpack_require__){var indexOf=__webpack_require__(11);function contains(arr,val){return indexOf(arr,val)!==-1}module.exports=contains},function(module,exports){function indexOf(arr,item,fromIndex){fromIndex=fromIndex||0;if(arr==null){return-1}var len=arr.length,i=fromIndex<0?len+fromIndex:fromIndex;while(i<len){if(arr[i]===item){return i}i++}return-1}module.exports=indexOf},function(module,exports,__webpack_require__){var forOwn=__webpack_require__(7);var isPlainObject=__webpack_require__(13);function deepMixIn(target,objects){var i=0,n=arguments.length,obj;while(++i<n){obj=arguments[i];if(obj){forOwn(obj,copyProp,target)}}return target}function copyProp(val,key){var existing=this[key];if(isPlainObject(val)&&isPlainObject(existing)){deepMixIn(existing,val)}else{this[key]=val}}module.exports=deepMixIn},function(module,exports){function isPlainObject(value){return!!value&&typeof value==="object"&&value.constructor===Object}module.exports=isPlainObject},function(module,exports,__webpack_require__){var toString=__webpack_require__(15);var camelCase=__webpack_require__(16);var upperCase=__webpack_require__(19);function pascalCase(str){str=toString(str);return camelCase(str).replace(/^[a-z]/,upperCase)}module.exports=pascalCase},function(module,exports){function toString(val){return val==null?"":val.toString()}module.exports=toString},function(module,exports,__webpack_require__){var toString=__webpack_require__(15);var replaceAccents=__webpack_require__(17);var removeNonWord=__webpack_require__(18);var upperCase=__webpack_require__(19);var lowerCase=__webpack_require__(20);function camelCase(str){str=toString(str);str=replaceAccents(str);str=removeNonWord(str).replace(/[\-_]/g," ").replace(/\s[a-z]/g,upperCase).replace(/\s+/g,"").replace(/^[A-Z]/g,lowerCase);return str}module.exports=camelCase},function(module,exports,__webpack_require__){var toString=__webpack_require__(15);function replaceAccents(str){str=toString(str);if(str.search(/[\xC0-\xFF]/g)>-1){str=str.replace(/[\xC0-\xC5]/g,"A").replace(/[\xC6]/g,"AE").replace(/[\xC7]/g,"C").replace(/[\xC8-\xCB]/g,"E").replace(/[\xCC-\xCF]/g,"I").replace(/[\xD0]/g,"D").replace(/[\xD1]/g,"N").replace(/[\xD2-\xD6\xD8]/g,"O").replace(/[\xD9-\xDC]/g,"U").replace(/[\xDD]/g,"Y").replace(/[\xDE]/g,"P").replace(/[\xE0-\xE5]/g,"a").replace(/[\xE6]/g,"ae").replace(/[\xE7]/g,"c").replace(/[\xE8-\xEB]/g,"e").replace(/[\xEC-\xEF]/g,"i").replace(/[\xF1]/g,"n").replace(/[\xF2-\xF6\xF8]/g,"o").replace(/[\xF9-\xFC]/g,"u").replace(/[\xFE]/g,"p").replace(/[\xFD\xFF]/g,"y")}return str}module.exports=replaceAccents},function(module,exports,__webpack_require__){var toString=__webpack_require__(15);var PATTERN=/[^\x20\x2D0-9A-Z\x5Fa-z\xC0-\xD6\xD8-\xF6\xF8-\xFF]/g;function removeNonWord(str){str=toString(str);return str.replace(PATTERN,"")}module.exports=removeNonWord},function(module,exports,__webpack_require__){var toString=__webpack_require__(15);function upperCase(str){str=toString(str);return str.toUpperCase()}module.exports=upperCase},function(module,exports,__webpack_require__){var toString=__webpack_require__(15);function lowerCase(str){str=toString(str);return str.toLowerCase()}module.exports=lowerCase},function(module,exports,__webpack_require__){var indexOf=__webpack_require__(11);function remove(arr,item){var idx=indexOf(arr,item);if(idx!==-1)arr.splice(idx,1)}module.exports=remove},function(module,exports,__webpack_require__){var slice=__webpack_require__(6);function pick(obj,var_keys){var keys=typeof arguments[1]!=="string"?arguments[1]:slice(arguments,1),out={},i=0,key;while(key=keys[i++]){out[key]=obj[key]}return out}module.exports=pick},function(module,exports,__webpack_require__){var forOwn=__webpack_require__(7);var keys=Object.keys||function(obj){var keys=[];forOwn(obj,function(val,key){keys.push(key)});return keys};module.exports=keys},function(module,exports){function mergeSort(arr,compareFn){if(arr==null){return[]}else if(arr.length<2){return arr}if(compareFn==null){compareFn=defaultCompare}var mid,left,right;mid=~~(arr.length/2);left=mergeSort(arr.slice(0,mid),compareFn);right=mergeSort(arr.slice(mid,arr.length),compareFn);return merge(left,right,compareFn)}function defaultCompare(a,b){return a<b?-1:a>b?1:0}function merge(left,right,compareFn){var result=[];while(left.length&&right.length){if(compareFn(left[0],right[0])<=0){result.push(left.shift())}else{result.push(right.shift())}}if(left.length){result.push.apply(result,left)}if(right.length){result.push.apply(result,right)}return result}module.exports=mergeSort},function(module,exports,__webpack_require__){var isPrimitive=__webpack_require__(26);function get(obj,prop){var parts=prop.split("."),last=parts.pop();while(prop=parts.shift()){obj=obj[prop];if(obj==null)return}return obj[last]}module.exports=get},function(module,exports){function isPrimitive(value){switch(typeof value){case"string":case"number":case"boolean":return true}return value==null}module.exports=isPrimitive},function(module,exports,__webpack_require__){var namespace=__webpack_require__(28);function set(obj,prop,val){var parts=/^(.+)\.(.+)$/.exec(prop);if(parts){namespace(obj,parts[1])[parts[2]]=val}else{obj[prop]=val}}module.exports=set},function(module,exports,__webpack_require__){var forEach=__webpack_require__(5);function namespace(obj,path){if(!path)return obj;forEach(path.split("."),function(key){if(!obj[key]){obj[key]={}}obj=obj[key]});return obj}module.exports=namespace},function(module,exports){(function(global){var testingExposeCycleCount=global.testingExposeCycleCount;function detectObjectObserve(){if(typeof Object.observe!=="function"||typeof Array.observe!=="function"){return false}var records=[];function callback(recs){records=recs}var test={};var arr=[];Object.observe(test,callback);Array.observe(arr,callback);test.id=1;test.id=2;delete test.id;arr.push(1,2);arr.length=0;Object.deliverChangeRecords(callback);if(records.length!==5)return false;if(records[0].type!="add"||records[1].type!="update"||records[2].type!="delete"||records[3].type!="splice"||records[4].type!="splice"){return false}Object.unobserve(test,callback);Array.unobserve(arr,callback);return true}var hasObserve=detectObjectObserve();var createObject="__proto__"in{}?function(obj){return obj}:function(obj){var proto=obj.__proto__;if(!proto)return obj;var newObject=Object.create(proto);Object.getOwnPropertyNames(obj).forEach(function(name){Object.defineProperty(newObject,name,Object.getOwnPropertyDescriptor(obj,name))});return newObject};var MAX_DIRTY_CHECK_CYCLES=1e3;function dirtyCheck(observer){var cycles=0;while(cycles<MAX_DIRTY_CHECK_CYCLES&&observer.check_()){cycles++}if(testingExposeCycleCount)global.dirtyCheckCycleCount=cycles;return cycles>0}function objectIsEmpty(object){for(var prop in object)return false;return true}function diffIsEmpty(diff){return objectIsEmpty(diff.added)&&objectIsEmpty(diff.removed)&&objectIsEmpty(diff.changed)}function isBlacklisted(prop,bl){if(!bl||!bl.length){return false}var matches;for(var i=0;i<bl.length;i++){if(Object.prototype.toString.call(bl[i])==="[object RegExp]"&&bl[i].test(prop)||bl[i]===prop){return matches=prop}}return!!matches}function diffObjectFromOldObject(object,oldObject,equals,bl){var added={};var removed={};var changed={};for(var prop in oldObject){var newValue=object[prop];if(isBlacklisted(prop,bl))continue;if(newValue!==undefined&&(equals?equals(newValue,oldObject[prop]):newValue===oldObject[prop]))continue;if(!(prop in object)){removed[prop]=undefined;continue}if(equals?!equals(newValue,oldObject[prop]):newValue!==oldObject[prop])changed[prop]=newValue}for(var prop in object){if(prop in oldObject)continue;if(isBlacklisted(prop,bl))continue;added[prop]=object[prop]}if(Array.isArray(object)&&object.length!==oldObject.length)changed.length=object.length;return{added:added,removed:removed,changed:changed}}var eomTasks=[];function runEOMTasks(){if(!eomTasks.length)return false;for(var i=0;i<eomTasks.length;i++){eomTasks[i]()}eomTasks.length=0;return true}var runEOM=hasObserve?function(){return function(fn){return Promise.resolve().then(fn)}}():function(){return function(fn){eomTasks.push(fn)}}();var observedObjectCache=[];function newObservedObject(){var observer;var object;var discardRecords=false;var first=true;function callback(records){if(observer&&observer.state_===OPENED&&!discardRecords)observer.check_(records)}return{open:function(obs){if(observer)throw Error("ObservedObject in use");if(!first)Object.deliverChangeRecords(callback);observer=obs;first=false},observe:function(obj,arrayObserve){object=obj;if(arrayObserve)Array.observe(object,callback);else Object.observe(object,callback)},deliver:function(discard){discardRecords=discard;Object.deliverChangeRecords(callback);discardRecords=false},close:function(){observer=undefined;Object.unobserve(object,callback);observedObjectCache.push(this)}}}function getObservedObject(observer,object,arrayObserve){var dir=observedObjectCache.pop()||newObservedObject();dir.open(observer);dir.observe(object,arrayObserve);return dir}var UNOPENED=0;var OPENED=1;var CLOSED=2;var nextObserverId=1;function Observer(){this.state_=UNOPENED;this.callback_=undefined;this.target_=undefined;this.directObserver_=undefined;this.value_=undefined;this.id_=nextObserverId++}Observer.prototype={open:function(callback,target){if(this.state_!=UNOPENED)throw Error("Observer has already been opened.");addToAll(this);this.callback_=callback;this.target_=target;this.connect_();this.state_=OPENED;return this.value_},close:function(){if(this.state_!=OPENED)return;removeFromAll(this);this.disconnect_();this.value_=undefined;this.callback_=undefined;this.target_=undefined;this.state_=CLOSED},deliver:function(){if(this.state_!=OPENED)return;dirtyCheck(this)},report_:function(changes){try{this.callback_.apply(this.target_,changes)}catch(ex){Observer._errorThrownDuringCallback=true;console.error("Exception caught during observer callback: "+(ex.stack||ex))}},discardChanges:function(){this.check_(undefined,true);return this.value_}};var collectObservers=!hasObserve;var allObservers;Observer._allObserversCount=0;if(collectObservers){allObservers=[]}function addToAll(observer){Observer._allObserversCount++;if(!collectObservers)return;allObservers.push(observer)}function removeFromAll(observer){Observer._allObserversCount--}var runningMicrotaskCheckpoint=false;global.Platform=global.Platform||{};global.Platform.performMicrotaskCheckpoint=function(){if(runningMicrotaskCheckpoint)return;if(!collectObservers)return;runningMicrotaskCheckpoint=true;var cycles=0;var anyChanged,toCheck;do{cycles++;toCheck=allObservers;allObservers=[];anyChanged=false;for(var i=0;i<toCheck.length;i++){var observer=toCheck[i];if(observer.state_!=OPENED)continue;if(observer.check_())anyChanged=true;allObservers.push(observer)}if(runEOMTasks())anyChanged=true}while(cycles<MAX_DIRTY_CHECK_CYCLES&&anyChanged);if(testingExposeCycleCount)global.dirtyCheckCycleCount=cycles;runningMicrotaskCheckpoint=false};if(collectObservers){global.Platform.clearObservers=function(){allObservers=[]}}function ObjectObserver(object){Observer.call(this);this.value_=object;this.oldObject_=undefined}ObjectObserver.prototype=createObject({__proto__:Observer.prototype,arrayObserve:false,connect_:function(callback,target){if(hasObserve){this.directObserver_=getObservedObject(this,this.value_,this.arrayObserve)}else{this.oldObject_=this.copyObject(this.value_)}},copyObject:function(object){var copy=Array.isArray(object)?[]:{};for(var prop in object){copy[prop]=object[prop]}if(Array.isArray(object))copy.length=object.length;return copy},check_:function(changeRecords,skipChanges){var diff;var oldValues;if(hasObserve){if(!changeRecords)return false;oldValues={};diff=diffObjectFromChangeRecords(this.value_,changeRecords,oldValues)}else{oldValues=this.oldObject_;diff=diffObjectFromOldObject(this.value_,this.oldObject_)}if(diffIsEmpty(diff))return false;if(!hasObserve)this.oldObject_=this.copyObject(this.value_);this.report_([diff.added||{},diff.removed||{},diff.changed||{},function(property){return oldValues[property]}]);return true},disconnect_:function(){if(hasObserve){this.directObserver_.close();this.directObserver_=undefined}else{this.oldObject_=undefined}},deliver:function(){if(this.state_!=OPENED)return;if(hasObserve)this.directObserver_.deliver(false);else dirtyCheck(this)},discardChanges:function(){if(this.directObserver_)this.directObserver_.deliver(true);else this.oldObject_=this.copyObject(this.value_);return this.value_}});var observerSentinel={};var expectedRecordTypes={add:true,update:true,"delete":true};function diffObjectFromChangeRecords(object,changeRecords,oldValues){var added={};var removed={};for(var i=0;i<changeRecords.length;i++){var record=changeRecords[i];if(!expectedRecordTypes[record.type]){console.error("Unknown changeRecord type: "+record.type);console.error(record);continue}if(!(record.name in oldValues))oldValues[record.name]=record.oldValue;if(record.type=="update")continue;if(record.type=="add"){if(record.name in removed)delete removed[record.name];else added[record.name]=true;continue}if(record.name in added){delete added[record.name];delete oldValues[record.name]}else{removed[record.name]=true}}for(var prop in added)added[prop]=object[prop];for(var prop in removed)removed[prop]=undefined;var changed={};for(var prop in oldValues){if(prop in added||prop in removed)continue;var newValue=object[prop];if(oldValues[prop]!==newValue)changed[prop]=newValue}return{added:added,removed:removed,changed:changed}}global.Observer=Observer;global.isBlacklisted=isBlacklisted;global.Observer.runEOM_=runEOM;global.Observer.observerSentinel_=observerSentinel;global.Observer.hasObjectObserve=hasObserve;global.diffObjectFromOldObject=diffObjectFromOldObject;global.ObjectObserver=ObjectObserver})(exports)},function(module,exports,__webpack_require__){var randHex=__webpack_require__(31);var choice=__webpack_require__(32);function guid(){return randHex(8)+"-"+randHex(4)+"-"+"4"+randHex(3)+"-"+choice(8,9,"a","b")+randHex(3)+"-"+randHex(12)}module.exports=guid},function(module,exports,__webpack_require__){var choice=__webpack_require__(32);var _chars="0123456789abcdef".split("");function randHex(size){size=size&&size>0?size:6;var str="";while(size--){str+=choice(_chars)}return str}module.exports=randHex},function(module,exports,__webpack_require__){var randInt=__webpack_require__(33);var isArray=__webpack_require__(38);function choice(items){var target=arguments.length===1&&isArray(items)?items:arguments;return target[randInt(0,target.length-1)]}module.exports=choice},function(module,exports,__webpack_require__){var MIN_INT=__webpack_require__(34);var MAX_INT=__webpack_require__(35);var rand=__webpack_require__(36);function randInt(min,max){min=min==null?MIN_INT:~~min;max=max==null?MAX_INT:~~max;return Math.round(rand(min-.5,max+.499999999999))}module.exports=randInt},function(module,exports){module.exports=-2147483648},function(module,exports){module.exports=2147483647},function(module,exports,__webpack_require__){var random=__webpack_require__(37);var MIN_INT=__webpack_require__(34);var MAX_INT=__webpack_require__(35);function rand(min,max){min=min==null?MIN_INT:min;max=max==null?MAX_INT:max;return min+(max-min)*random()}module.exports=rand},function(module,exports){function random(){return random.get()}random.get=Math.random;module.exports=random},function(module,exports,__webpack_require__){var isKind=__webpack_require__(39);var isArray=Array.isArray||function(val){return isKind(val,"Array")};module.exports=isArray},function(module,exports,__webpack_require__){var kindOf=__webpack_require__(40);function isKind(val,kind){return kindOf(val)===kind}module.exports=isKind},function(module,exports){var _rKind=/^\[object (.*)\]$/,_toString=Object.prototype.toString,UNDEF;function kindOf(val){if(val===null){return"Null"}else if(val===UNDEF){return"Undefined"}else{return _rKind.exec(_toString.call(val))[1]}}module.exports=kindOf},function(module,exports,__webpack_require__){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol?"symbol":typeof obj};var _utils=__webpack_require__(2);var _utils2=_interopRequireDefault(_utils);var _errors=__webpack_require__(3);var _errors2=_interopRequireDefault(_errors);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}var NER=_errors2.default.NER;var IA=_errors2.default.IA;var R=_errors2.default.R;var fakeId="DS_"+(new Date).getTime();function diffIsEmpty(diff){return!(_utils2.default.isEmpty(diff.added)&&_utils2.default.isEmpty(diff.removed)&&_utils2.default.isEmpty(diff.changed))}function check(fnName,resourceName,id,options){var _this=this;var definition=_this.definitions[resourceName];options=options||{};id=_utils2.default.resolveId(definition,id);if(!definition){throw new NER(resourceName)}else if(!_utils2.default._sn(id)){throw _utils2.default._snErr("id")}id=id===fakeId?undefined:id;options=_utils2.default._(definition,options);options.logFn(fnName,id,options);return{_this:_this,definition:definition,_resourceName:resourceName,_id:id,_options:options}}exports.default={changes:function changes(resourceName,id,options){var _check$call=check.call(this,"changes",resourceName,id,options);var _this=_check$call._this;var definition=_check$call.definition;var _resourceName=_check$call._resourceName;var _id=_check$call._id;var _options=_check$call._options;var item=definition.get(_id);if(item){var _ret=function(){var observer=_this.store[_resourceName].observers[_id];if(observer&&typeof observer==="function"){observer.deliver()}var ignoredChanges=_options.ignoredChanges||[];_utils2.default.forEach(definition.relationFields,function(field){if(!_utils2.default.contains(ignoredChanges,field)){ignoredChanges.push(field)}});var diff=_utils2.default.diffObjectFromOldObject(item,_this.store[_resourceName].previousAttributes[_id],_utils2.default.equals,ignoredChanges);_utils2.default.forOwn(diff,function(changeset,name){var toKeep=[];_utils2.default.forOwn(changeset,function(value,field){if(!_utils2.default.isFunction(value)){toKeep.push(field)}});diff[name]=_utils2.default.pick(diff[name],toKeep)});_utils2.default.forEach(definition.relationFields,function(field){delete diff.added[field];delete diff.removed[field];delete diff.changed[field]});return{v:diff}}();if((typeof _ret==="undefined"?"undefined":_typeof(_ret))==="object")return _ret.v}},changeHistory:function changeHistory(resourceName,id){var _check$call2=check.call(this,"changeHistory",resourceName,id||fakeId);var _this=_check$call2._this;var definition=_check$call2.definition;var _resourceName=_check$call2._resourceName;var _id=_check$call2._id;var resource=_this.store[_resourceName];if(!definition.keepChangeHistory){definition.errorFn("changeHistory is disabled for this resource!")}else{if(_resourceName){var item=definition.get(_id);if(item){return resource.changeHistories[_id]}}else{return resource.changeHistory}}},commit:function commit(resourceName,id){var _check$call3=check.call(this,"commit",resourceName,id);var _this=_check$call3._this;var definition=_check$call3.definition;var _resourceName=_check$call3._resourceName;var _id=_check$call3._id;var resource=_this.store[_resourceName];var item=_this.store[_resourceName].index[_id];if(item){resource.previousAttributes[_id]=_utils2.default.copy(item,null,null,null,definition.relationFields)}if(resource.changeHistories[_id].length){_utils2.default.forEach(resource.changeHistories[_id],function(changeRecord){_utils2.default.remove(resource.changeHistory,changeRecord)});resource.changeHistories[_id].splice(0,resource.changeHistories[_id].length)}return item},compute:function compute(resourceName,instance){var _this=this;var definition=_this.definitions[resourceName];instance=_utils2.default.resolveItem(_this.store[resourceName],instance);if(!definition){throw new NER(resourceName)}else if(!instance){throw new R("Item not in the store!")}else if(!_utils2.default._o(instance)&&!_utils2.default._sn(instance)){throw new IA('"instance" must be an object, string or number!')}definition.logFn("compute",instance);_utils2.default.forOwn(definition.computed,function(fn,field){_utils2.default.compute.call(instance,fn,field)});return instance},createInstance:function createInstance(resourceName,attrs,options){var definition=this.definitions[resourceName];var item=undefined;attrs=attrs||{};if(!definition){throw new NER(resourceName)}else if(attrs&&!_utils2.default.isObject(attrs)){throw new IA('"attrs" must be an object!')}options=_utils2.default._(definition,options);var relationList=definition.relationList||[];if(relationList.length){_utils2.default.forEach(relationList,function(def){var relationData=_utils2.default.get(attrs,def.localField);if(relationData){if(_utils2.default.isArray(relationData)){(function(){var array=[];var Resource=definition.getResource(def.relation);var _options=options.orig();_utils2.default.forEach(relationData,function(relationDataItem){array.push(Resource.createInstance(relationDataItem,_options))});_utils2.default.set(attrs,def.localField,array)})()}else if(_utils2.default.isObject(relationData)){_utils2.default.set(attrs,def.localField,definition.getResource(def.relation).createInstance(relationData,options.orig()))}}})}options.logFn("createInstance",attrs,options);options.beforeCreateInstance(options,attrs);var Constructor=definition[definition.class];item=new Constructor;if(definition.instanceEvents){_utils2.default.Events(item)}if(options.defaultValues){_utils2.default.deepMixIn(item,_utils2.default.copy(options.defaultValues))}_utils2.default.deepMixIn(item,attrs);if(definition.computed){definition.compute(item)}options.afterCreateInstance(options,item);return item},createCollection:function createCollection(resourceName,arr,params,options){var _this=this;var definition=_this.definitions[resourceName];arr=arr||[];params=params||{};if(!definition){throw new NER(resourceName)}else if(arr&&!_utils2.default.isArray(arr)){throw new IA('"arr" must be an array!')}options=_utils2.default._(definition,options);options.logFn("createCollection",arr,options);options.beforeCreateCollection(options,arr);Object.defineProperties(arr,{fetch:{value:function value(params,options){var __this=this;__this.params=params||__this.params;return definition.findAll(__this.params,options).then(function(data){if(data===__this){return __this}data.unshift(__this.length);data.unshift(0);__this.splice.apply(__this,data);data.shift();data.shift();if(data.$$injected){_this.store[resourceName].queryData[_utils2.default.toJson(__this.params)]=__this;__this.$$injected=true}return __this})}},params:{value:params,writable:true},resourceName:{value:resourceName}});options.afterCreateCollection(options,arr);return arr},defineResource:__webpack_require__(42),digest:function digest(){this.observe.Platform.performMicrotaskCheckpoint()},eject:__webpack_require__(43),ejectAll:__webpack_require__(44),filter:__webpack_require__(45),get:function get(resourceName,id){var _check$call4=check.call(this,"get",resourceName,id);var _this=_check$call4._this;var _resourceName=_check$call4._resourceName;var _id=_check$call4._id;return _this.store[_resourceName].index[_id]},getAll:function getAll(resourceName,ids){var _this=this;var definition=_this.definitions[resourceName];var resource=_this.store[resourceName];var collection=[];if(!definition){throw new NER(resourceName)}else if(ids&&!_utils2.default._a(ids)){throw _utils2.default._aErr("ids")}definition.logFn("getAll",ids);if(_utils2.default._a(ids)){var length=ids.length;for(var i=0;i<length;i++){if(resource.index[ids[i]]){collection.push(resource.index[ids[i]])}}}else{collection=resource.collection.slice()}return collection},hasChanges:function hasChanges(resourceName,id){var _check$call5=check.call(this,"hasChanges",resourceName,id);var definition=_check$call5.definition;var _id=_check$call5._id;return definition.get(_id)?diffIsEmpty(definition.changes(_id)):false},inject:__webpack_require__(46),isNew:function isNew(resourceName,id){var _check$call6=check.call(this,"isNew",resourceName,id||fakeId);var _this=_check$call6._this;var _resourceName=_check$call6._resourceName;var _id=_check$call6._id;var resource=_this.store[_resourceName];return!!resource.temporaryItems[_id]},lastModified:function lastModified(resourceName,id){var _check$call7=check.call(this,"lastModified",resourceName,id||fakeId);var _this=_check$call7._this;var _resourceName=_check$call7._resourceName;var _id=_check$call7._id;var resource=_this.store[_resourceName];if(_id){if(!(_id in resource.modified)){resource.modified[_id]=0}return resource.modified[_id]}return resource.collectionModified},lastSaved:function lastSaved(resourceName,id){var _check$call8=check.call(this,"lastSaved",resourceName,id||fakeId);var _this=_check$call8._this;var _resourceName=_check$call8._resourceName;var _id=_check$call8._id;var resource=_this.store[_resourceName];if(!(_id in resource.saved)){resource.saved[_id]=0}return resource.saved[_id]},previous:function previous(resourceName,id){var _check$call9=check.call(this,"previous",resourceName,id);var _this=_check$call9._this;var _resourceName=_check$call9._resourceName;var _id=_check$call9._id;var resource=_this.store[_resourceName];return resource.previousAttributes[_id]?_utils2.default.copy(resource.previousAttributes[_id]):undefined},revert:function revert(resourceName,id,options){var _check$call10=check.call(this,"revert",resourceName,id,options);var _this=_check$call10._this;var definition=_check$call10.definition;var _resourceName=_check$call10._resourceName;var _id=_check$call10._id;var _options=_check$call10._options;var preserve=_options.preserve||[];var injectObj={};if(preserve.length===0){injectObj=_this.previous(_resourceName,_id)}else{var _ret3=function(){var instance=definition.get(id);var previousInstance=_this.previous(_resourceName,_id);if(!instance){return{v:undefined}}_utils2.default.forOwn(instance,function(value,key){if(_utils2.default.contains(preserve,key)){injectObj[key]=instance[key]}else{injectObj[key]=previousInstance[key]}})}();if((typeof _ret3==="undefined"?"undefined":_typeof(_ret3))==="object")return _ret3.v}return definition.inject(injectObj,{onConflict:"replace"})}}},function(module,exports,__webpack_require__){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol?"symbol":typeof obj};var _utils=__webpack_require__(2);var _utils2=_interopRequireDefault(_utils);var _errors=__webpack_require__(3);var _errors2=_interopRequireDefault(_errors);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}var instanceMethods=["compute","eject","refresh","save","update","destroy","loadRelations","changeHistory","changes","commit","hasChanges","isNew","lastModified","lastSaved","previous","revert"];module.exports=function defineResource(definition){var _this=this;var definitions=_this.definitions;if(_utils2.default._s(definition)){definition={name:definition.replace(/\s/gi,"")}}if(!_utils2.default._o(definition)){throw _utils2.default._oErr("definition")}else if(!_utils2.default._s(definition.name)){throw new _errors2.default.IA('"name" must be a string!')}else if(definitions[definition.name]){throw new _errors2.default.R(definition.name+" is already registered!")}function Resource(options){this.defaultValues={};this.methods={};this.computed={};this.scopes={};this.actions={};_utils2.default.deepMixIn(this,options);var parent=_this.defaults;if(definition.extends&&definitions[definition.extends]){parent=definitions[definition.extends]}_utils2.default.fillIn(this.defaultValues,parent.defaultValues);_utils2.default.fillIn(this.methods,parent.methods);
_utils2.default.fillIn(this.computed,parent.computed);_utils2.default.fillIn(this.scopes,parent.scopes);_utils2.default.fillIn(this.actions,parent.actions);this.endpoint="endpoint"in options?options.endpoint:this.name}try{var def;var _class;var _ret=function(){if(definition.extends&&definitions[definition.extends]){Resource.prototype=definitions[definition.extends]}else{Resource.prototype=_this.defaults}definitions[definition.name]=new Resource(definition);def=definitions[definition.name];def.getResource=function(resourceName){return _this.definitions[resourceName]};def.logFn("Preparing resource.");if(!_utils2.default._s(def.idAttribute)){throw new _errors2.default.IA('"idAttribute" must be a string!')}if(def.relations){def.relationList=[];def.relationFields=[];_utils2.default.forOwn(def.relations,function(relatedModels,type){_utils2.default.forOwn(relatedModels,function(defs,relationName){if(!_utils2.default._a(defs)){relatedModels[relationName]=[defs]}_utils2.default.forEach(relatedModels[relationName],function(d){d.type=type;d.relation=relationName;d.name=def.name;def.relationList.push(d);if(d.localField){def.relationFields.push(d.localField)}})})});if(def.relations.belongsTo){def.parents={};_utils2.default.forOwn(def.relations.belongsTo,function(relatedModel,modelName){_utils2.default.forEach(relatedModel,function(relation){if(relation.parent){def.parent=modelName;def.parentKey=relation.localKey;def.parentField=relation.localField;def.parents[modelName]={key:def.parentKey,field:def.parentField}}})})}if(typeof Object.freeze==="function"){Object.freeze(def.relations);Object.freeze(def.relationList)}}_class=def["class"]=_utils2.default.pascalCase(def.name);try{if(typeof def.useClass==="function"){if(def.csp){def[_class]=function(){def.useClass.call(this)}}else{def[_class]=new Function("def","return function "+_class+"() { def.useClass.call(this); }")(def)}def[_class].prototype=function(proto){function Ctor(){}Ctor.prototype=proto;return new Ctor}(def.useClass.prototype)}else if(def.csp){def[_class]=function(){}}else{def[_class]=new Function("return function "+_class+"() {}")()}}catch(e){def[_class]=function(){}}_utils2.default.forOwn(def.methods,function(fn,m){def[_class].prototype[m]=fn});def[_class].prototype.set=function(key,value){var _this2=this;_utils2.default.set(this,key,value);def.compute(this);if(def.instanceEvents){setTimeout(function(){_this2.emit("DS.change",def,_this2)},0)}def.handleChange(this);return this};def[_class].prototype.get=function(key){return _utils2.default.get(this,key)};_utils2.default.applyRelationGettersToTarget(_this,def,def[_class].prototype);var parentOmit=null;if(!def.hasOwnProperty("omit")){parentOmit=def.omit;def.omit=[]}else{parentOmit=_this.defaults.omit}def.omit=def.omit.concat(parentOmit||[]);_utils2.default.forOwn(def.computed,function(fn,field){if(_utils2.default.isFunction(fn)){def.computed[field]=[fn];fn=def.computed[field]}if(def.methods&&field in def.methods){def.errorFn('Computed property "'+field+'" conflicts with previously defined prototype method!')}def.omit.push(field);if(_utils2.default.isArray(fn)){var deps;if(fn.length===1){var match=fn[0].toString().match(/function.*?\(([\s\S]*?)\)/);deps=match[1].split(",");deps=_utils2.default.filter(deps,function(x){return x});def.computed[field]=deps.concat(fn);fn=def.computed[field];if(deps.length){def.errorFn("Use the computed property array syntax for compatibility with minified code!")}}deps=fn.slice(0,fn.length-1);_utils2.default.forEach(deps,function(val,index){deps[index]=val.trim()});fn.deps=_utils2.default.filter(deps,function(dep){return!!dep})}else if(_utils2.default.isObject(fn)){Object.defineProperty(def[_class].prototype,field,fn)}});_utils2.default.forEach(instanceMethods,function(name){def[_class].prototype["DS"+_utils2.default.pascalCase(name)]=function(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}args.unshift(this[def.idAttribute]||this);args.unshift(def.name);return _this[name].apply(_this,args)}});def[_class].prototype.DSCreate=function(){for(var _len2=arguments.length,args=Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2]}args.unshift(this);args.unshift(def.name);return _this.create.apply(_this,args)};_this.store[def.name]={collection:[],expiresHeap:new _utils2.default.BinaryHeap(function(x){return x.expires},function(x,y){return x.item===y}),completedQueries:{},queryData:{},pendingQueries:{},index:{},modified:{},saved:{},previousAttributes:{},observers:{},changeHistories:{},changeHistory:[],collectionModified:0,temporaryItems:{}};var resource=_this.store[def.name];if(def.reapInterval){setInterval(function(){return def.reap()},def.reapInterval)}var fns=["registerAdapter","getAdapterName","getAdapter","is","!clear"];for(var key in _this){if(typeof _this[key]==="function"){fns.push(key)}}_utils2.default.forEach(fns,function(key){var k=key;if(k[0]==="!"){return}if(_this[k].shorthand!==false){def[k]=function(){for(var _len3=arguments.length,args=Array(_len3),_key3=0;_key3<_len3;_key3++){args[_key3]=arguments[_key3]}args.unshift(def.name);return _this[k].apply(_this,args)};def[k].before=function(fn){var orig=def[k];def[k]=function(){for(var _len4=arguments.length,args=Array(_len4),_key4=0;_key4<_len4;_key4++){args[_key4]=arguments[_key4]}return orig.apply(def,fn.apply(def,args)||args)}}}else{def[k]=function(){for(var _len5=arguments.length,args=Array(_len5),_key5=0;_key5<_len5;_key5++){args[_key5]=arguments[_key5]}return _this[k].apply(_this,args)}}});def.beforeValidate=_utils2.default.promisify(def.beforeValidate);def.validate=_utils2.default.promisify(def.validate);def.afterValidate=_utils2.default.promisify(def.afterValidate);def.beforeCreate=_utils2.default.promisify(def.beforeCreate);def.afterCreate=_utils2.default.promisify(def.afterCreate);def.afterFind=_utils2.default.promisify(def.afterFind);def.afterFindAll=_utils2.default.promisify(def.afterFindAll);def.afterLoadRelations=_utils2.default.promisify(def.afterLoadRelations);def.beforeUpdate=_utils2.default.promisify(def.beforeUpdate);def.afterUpdate=_utils2.default.promisify(def.afterUpdate);def.beforeDestroy=_utils2.default.promisify(def.beforeDestroy);def.afterDestroy=_utils2.default.promisify(def.afterDestroy);var defaultAdapter=undefined;if(def.hasOwnProperty("defaultAdapter")){defaultAdapter=def.defaultAdapter}_utils2.default.forOwn(def.actions,function(action,name){if(def[name]&&!def.actions[name]){throw new Error('Cannot override existing method "'+name+'"!')}action.request=action.request||function(config){return config};action.response=action.response||function(response){return response};action.responseError=action.responseError||function(err){return _utils2.default.Promise.reject(err)};def[name]=function(id,options){if(_utils2.default._o(id)){options=id}options=options||{};var adapter=def.getAdapter(action.adapter||defaultAdapter||"http");var config=_utils2.default.deepMixIn({},action);if(!options.hasOwnProperty("endpoint")&&config.endpoint){options.endpoint=config.endpoint}if(typeof options.getEndpoint==="function"){config.url=options.getEndpoint(def,options)}else{var _args=[options.basePath||def.basePath||adapter.defaults.basePath,adapter.getEndpoint(def,_utils2.default._sn(id)?id:null,options)];if(_utils2.default._sn(id)){_args.push(id)}_args.push(action.pathname||name);config.url=_utils2.default.makePath.apply(null,_args)}config.method=config.method||"GET";config.resourceName=def.name;_utils2.default.deepMixIn(config,options);return new _utils2.default.Promise(function(resolve){return resolve(config)}).then(options.request||action.request).then(function(config){return adapter.HTTP(config)}).then(function(data){if(data&&data.config){data.config.resourceName=def.name}return data}).then(options.response||action.response,options.responseError||action.responseError)}});_utils2.default.Events(def);def.handleChange=function(data){resource.collectionModified=_utils2.default.updateTimestamp(resource.collectionModified);if(def.notify){setTimeout(function(){def.emit("DS.change",def,data)},0)}};def.logFn("Done preparing resource.");return{v:def}}();if((typeof _ret==="undefined"?"undefined":_typeof(_ret))==="object")return _ret.v}catch(err){_this.defaults.errorFn(err);delete definitions[definition.name];delete _this.store[definition.name];throw err}}},function(module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol?"symbol":typeof obj};module.exports=function eject(resourceName,id,options){var _this=this;var DSUtils=_this.utils;var definition=_this.definitions[resourceName];var resource=_this.store[resourceName];var item=undefined;var found=false;id=DSUtils.resolveId(definition,id);if(!definition){throw new _this.errors.NER(resourceName)}else if(!DSUtils._sn(id)){throw DSUtils._snErr("id")}options=DSUtils._(definition,options);options.logFn("eject",id,options);for(var i=0;i<resource.collection.length;i++){if(resource.collection[i][definition.idAttribute]==id){item=resource.collection[i];resource.expiresHeap.remove(item);found=true;break}}if(found){var _ret=function(){definition.beforeEject(options,item);if(options.notify){definition.emit("DS.beforeEject",definition,item)}var toRemove=[];DSUtils.forOwn(resource.queryData,function(items,queryHash){if(items.$$injected){DSUtils.remove(items,item)}if(!items.length&&options.clearEmptyQueries){toRemove.push(queryHash)}});DSUtils.forEach(resource.changeHistories[id],function(changeRecord){DSUtils.remove(resource.changeHistory,changeRecord)});DSUtils.forEach(toRemove,function(queryHash){delete resource.completedQueries[queryHash];delete resource.queryData[queryHash]});if(resource.observers[id]&&typeof resource.observers[id].close==="function"){resource.observers[id].close()}delete resource.observers[id];delete resource.index[id];delete resource.previousAttributes[id];delete resource.completedQueries[id];delete resource.pendingQueries[id];delete resource.changeHistories[id];delete resource.modified[id];delete resource.saved[id];if(definition.instanceEvents&&item.off){item.off()}resource.collection.splice(i,1);definition.handleChange(item);definition.afterEject(options,item);if(options.notify){definition.emit("DS.afterEject",definition,item)}return{v:item}}();if((typeof _ret==="undefined"?"undefined":_typeof(_ret))==="object")return _ret.v}}},function(module,exports){"use strict";module.exports=function ejectAll(resourceName,params,options){var _this=this;var DSUtils=_this.utils;var definition=_this.definitions[resourceName];params=params||{};if(!definition){throw new _this.errors.NER(resourceName)}else if(!DSUtils._o(params)){throw DSUtils._oErr("params")}options=DSUtils._(definition,options);definition.logFn("ejectAll",params,options);DSUtils.applyScope(definition,params,options);var resource=_this.store[resourceName];var queryHash=DSUtils.toJson(params);var items=definition.filter(params);if(DSUtils.isEmpty(params)){resource.completedQueries={}}else{delete resource.completedQueries[queryHash]}DSUtils.forEach(items,function(item){if(item&&item[definition.idAttribute]){definition.eject(item[definition.idAttribute],options)}});definition.handleChange(items);return items}},function(module,exports){"use strict";module.exports=function filter(resourceName,params,options){var _this=this;var DSUtils=_this.utils;var definition=_this.definitions[resourceName];if(!definition){throw new _this.errors.NER(resourceName)}else if(params&&!DSUtils._o(params)){throw DSUtils._oErr("params")}params=params||{};options=DSUtils._(definition,options);options.logFn("filter",params,options);DSUtils.applyScope(definition,params,options);return definition.defaultFilter.call(_this,_this.store[resourceName].collection,resourceName,params,options)}},function(module,exports,__webpack_require__){"use strict";var _utils=__webpack_require__(2);var _utils2=_interopRequireDefault(_utils);var _errors=__webpack_require__(3);var _errors2=_interopRequireDefault(_errors);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{"default":obj}}function makeObserverHandler(definition,resource){var DS=this;var name=definition.name;return function _react(added,removed,changed,oldValueFn,firstTime){var target=this;var item=undefined;var innerId=oldValueFn&&oldValueFn(definition.idAttribute)?oldValueFn(definition.idAttribute):target[definition.idAttribute];_utils2.default.forEach(definition.relationFields,function(field){delete added[field];delete removed[field];delete changed[field]});if(!_utils2.default.isEmpty(added)||!_utils2.default.isEmpty(removed)||!_utils2.default.isEmpty(changed)||firstTime){item=DS.get(name,innerId);resource.modified[innerId]=_utils2.default.updateTimestamp(resource.modified[innerId]);if(item&&definition.instanceEvents){setTimeout(function(){item.emit("DS.change",definition,item)},0)}definition.handleChange(item);if(definition.keepChangeHistory){var changeRecord={resourceName:name,target:item,added:added,removed:removed,changed:changed,timestamp:resource.modified[innerId]};resource.changeHistories[innerId].push(changeRecord);resource.changeHistory.push(changeRecord)}}if(definition.computed){item=item||DS.get(name,innerId);_utils2.default.forOwn(definition.computed,function(fn,field){if(_utils2.default._o(fn)){return}var compute=false;_utils2.default.forEach(fn.deps,function(dep){if(dep in added||dep in removed||dep in changed||!(field in item)){compute=true}});compute=compute||!fn.deps.length;if(compute){_utils2.default.compute.call(item,fn,field)}})}if(definition.idAttribute in changed){definition.errorFn('Doh! You just changed the primary key of an object! Your data for the "'+name+'" resource is now in an undefined (probably broken) state.')}}}function _inject(definition,resource,attrs,options){var _this=this;var injected=undefined;if(_utils2.default._a(attrs)){injected=[];for(var i=0;i<attrs.length;i++){injected.push(_inject.call(_this,definition,resource,attrs[i],options))}}else{var c=definition.computed;var idA=definition.idAttribute;if(c&&c[idA]){(function(){var args=[];_utils2.default.forEach(c[idA].deps,function(dep){args.push(attrs[dep])});attrs[idA]=c[idA][c[idA].length-1].apply(attrs,args)})()}else if(options.temporary){attrs[idA]=_utils2.default.guid()}if(!(idA in attrs)){var error=new _errors2.default.R(definition.name+'.inject: "attrs" must contain the property specified by "idAttribute"!');options.errorFn(error);throw error}else{try{(function(){_utils2.default.forEach(definition.relationList,function(def){var relationName=def.relation;var relationDef=_this.definitions[relationName];var toInject=attrs[def.localField];if(typeof def.inject==="function"){def.inject(definition,def,attrs)}else if(toInject&&def.inject!==false){if(!relationDef){throw new _errors2.default.R(definition.name+" relation is defined but the resource is not!")}if(_utils2.default._a(toInject)){(function(){var items=[];_utils2.default.forEach(toInject,function(toInjectItem){if(toInjectItem!==_this.store[relationName].index[toInjectItem[relationDef.idAttribute]]){try{var injectedItem=relationDef.inject(toInjectItem,options.orig());if(def.foreignKey){_utils2.default.set(injectedItem,def.foreignKey,attrs[definition.idAttribute])}items.push(injectedItem)}catch(err){options.errorFn(err,"Failed to inject "+def.type+' relation: "'+relationName+'"!')}}})})()}else{if(toInject!==_this.store[relationName].index[toInject[relationDef.idAttribute]]){try{var _injected=relationDef.inject(attrs[def.localField],options.orig());if(def.foreignKey){_utils2.default.set(_injected,def.foreignKey,attrs[definition.idAttribute])}if(def.localKey){_utils2.default.set(attrs,def.localKey,_utils2.default.get(_injected,relationDef.idAttribute))}}catch(err){options.errorFn(err,"Failed to inject "+def.type+' relation: "'+relationName+'"!')}}}}});var id=attrs[idA];var item=definition.get(id);var initialLastModified=item?resource.modified[id]:0;if(!item){if(attrs instanceof definition[definition["class"]]){item=attrs}else{item=new definition[definition["class"]]}if(definition.instanceEvents&&typeof item.emit!=="function"){_utils2.default.Events(item)}_utils2.default.forEach(definition.relationList,function(def){if(typeof def.link==="boolean"?def.link:!!definition.linkRelations){delete attrs[def.localField]}});_utils2.default.deepMixIn(item,attrs);resource.collection.push(item);resource.changeHistories[id]=[];var _react=makeObserverHandler.call(_this,definition,resource);if(definition.watchChanges){resource.observers[id]=new _this.observe.ObjectObserver(item);resource.observers[id].open(_react,item)}resource.index[id]=item;_react.call(item,{},{},{},null,true);resource.previousAttributes[id]=_utils2.default.copy(item,null,null,null,definition.relationFields);if(options.temporary){resource.temporaryItems[id]=true}}else{if(options.onConflict==="merge"){_utils2.default.deepMixIn(item,attrs)}else if(options.onConflict==="replace"){_utils2.default.forOwn(item,function(v,k){if(k!==definition.idAttribute){if(!attrs.hasOwnProperty(k)){delete item[k]}}});_utils2.default.forOwn(attrs,function(v,k){if(k!==definition.idAttribute){item[k]=v}})}if(definition.resetHistoryOnInject){_this.commit(definition.name,id)}if(resource.observers[id]&&typeof resource.observers[id]==="function"){resource.observers[id].deliver()}}resource.modified[id]=initialLastModified&&resource.modified[id]===initialLastModified?_utils2.default.updateTimestamp(resource.modified[id]):resource.modified[id];resource.expiresHeap.remove(item);var timestamp=(new Date).getTime();resource.expiresHeap.push({item:item,timestamp:timestamp,expires:definition.maxAge?timestamp+definition.maxAge:Number.MAX_VALUE});injected=item})()}catch(err){options.errorFn(err,attrs)}}}return injected}module.exports=function inject(resourceName,attrs,options){var _this=this;var definition=_this.definitions[resourceName];var resource=_this.store[resourceName];var injected=undefined;if(!definition){throw new _errors2.default.NER(resourceName)}else if(!_utils2.default._o(attrs)&&!_utils2.default._a(attrs)){throw new _errors2.default.IA(resourceName+'.inject: "attrs" must be an object or an array!')}options=_utils2.default._(definition,options);options.logFn("inject",attrs,options);options.beforeInject(options,attrs);if(options.notify){definition.emit("DS.beforeInject",definition,attrs)}injected=_inject.call(_this,definition,resource,attrs,options);definition.handleChange(injected);options.afterInject(options,injected);if(options.notify){definition.emit("DS.afterInject",definition,injected)}return injected}},function(module,exports,__webpack_require__){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default={create:__webpack_require__(48),destroy:__webpack_require__(49),destroyAll:__webpack_require__(50),find:__webpack_require__(51),findAll:__webpack_require__(52),loadRelations:__webpack_require__(53),reap:__webpack_require__(54),refresh:function refresh(resourceName,id,options){var _this=this;var DSUtils=_this.utils;return new DSUtils.Promise(function(resolve,reject){var definition=_this.definitions[resourceName];id=DSUtils.resolveId(_this.definitions[resourceName],id);if(!definition){reject(new _this.errors.NER(resourceName))}else if(!DSUtils._sn(id)){reject(DSUtils._snErr("id"))}else{options=DSUtils._(definition,options);options.bypassCache=true;options.logFn("refresh",id,options);resolve(_this.get(resourceName,id))}}).then(function(item){return item?_this.find(resourceName,id,options):item}).catch(_this.errorFn("refresh",resourceName,id,options))},refreshAll:function refreshAll(resourceName,params,options){var _this=this;var DSUtils=_this.utils;var definition=_this.definitions[resourceName];params=params||{};return new DSUtils.Promise(function(resolve,reject){if(!definition){reject(new _this.errors.NER(resourceName))}else if(!DSUtils._o(params)){reject(DSUtils._oErr("params"))}else{options=DSUtils._(definition,options);options.bypassCache=true;options.logFn("refreshAll",params,options);resolve(_this.filter(resourceName,params,options))}}).then(function(existing){options.bypassCache=true;return _this.findAll(resourceName,params,options).then(function(found){DSUtils.forEach(existing,function(item){if(found.indexOf(item)===-1){definition.eject(item)}});return found})}).catch(_this.errorFn("refreshAll",resourceName,params,options))},save:__webpack_require__(55),update:__webpack_require__(56),updateAll:__webpack_require__(57)}},function(module,exports){"use strict";module.exports=function create(resourceName,attrs,options){var _this=this;var DSUtils=_this.utils;var definition=_this.definitions[resourceName];var resource=_this.store[resourceName];var adapter=undefined;options=options||{};attrs=attrs||{};var rejectionError=undefined;if(!definition){rejectionError=new _this.errors.NER(resourceName)}else if(!DSUtils._o(attrs)){rejectionError=DSUtils._oErr("attrs")}else{options=DSUtils._(definition,options);if(options.upsert&&DSUtils._sn(attrs[definition.idAttribute])&&!resource.temporaryItems[attrs[definition.idAttribute]]){return _this.update(resourceName,attrs[definition.idAttribute],attrs,options)}options.logFn("create",attrs,options)}return new DSUtils.Promise(function(resolve,reject){if(rejectionError){reject(rejectionError)}else{resolve(attrs)}}).then(function(attrs){return options.beforeValidate.call(attrs,options,attrs)}).then(function(attrs){return options.validate.call(attrs,options,attrs)}).then(function(attrs){return options.afterValidate.call(attrs,options,attrs)}).then(function(attrs){return options.beforeCreate.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.beforeCreate",definition,attrs)}adapter=_this.getAdapterName(options);return _this.adapters[adapter].create(definition,DSUtils.omit(attrs,options.omit),options)}).then(function(attrs){return options.afterCreate.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.afterCreate",definition,attrs)}if(options.cacheResponse){var created=_this.inject(definition.name,attrs,options.orig());var id=created[definition.idAttribute];var _resource=_this.store[resourceName];_resource.completedQueries[id]=(new Date).getTime();_resource.saved[id]=DSUtils.updateTimestamp(_resource.saved[id]);return created}else{return _this.createInstance(resourceName,attrs,options)}}).then(function(item){return DSUtils.respond(item,{adapter:adapter},options)})["catch"](_this.errorFn("create",resourceName,attrs,options))}},function(module,exports){"use strict";module.exports=function destroy(resourceName,id,options){var _this=this;var DSUtils=_this.utils;var definition=_this.definitions[resourceName];var item=undefined,adapter=undefined;return new DSUtils.Promise(function(resolve,reject){id=DSUtils.resolveId(definition,id);if(!definition){reject(new _this.errors.NER(resourceName))}else if(!DSUtils._sn(id)){reject(DSUtils._snErr("id"))}else{item=definition.get(id)||{id:id};options=DSUtils._(definition,options);options.logFn("destroy",id,options);resolve(item)}}).then(function(attrs){return options.beforeDestroy.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.beforeDestroy",definition,attrs)}if(options.eagerEject){definition.eject(id)}adapter=definition.getAdapter(options);return adapter.destroy(definition,id,options)}).then(function(){return options.afterDestroy.call(item,options,item)}).then(function(item){if(options.notify){definition.emit("DS.afterDestroy",definition,item)}definition.eject(id);return DSUtils.respond(id,{adapter:adapter},options)})["catch"](function(err){if(options&&options.eagerEject&&item){definition.inject(item,{notify:false})}return _this.errorFn("destroy",resourceName,id,options)(err)})}},function(module,exports){"use strict";module.exports=function destroyAll(resourceName,params,options){var _this=this;var DSUtils=_this.utils;var definition=_this.definitions[resourceName];var ejected=undefined,toEject=undefined,adapter=undefined;params=params||{};return new DSUtils.Promise(function(resolve,reject){if(!definition){reject(new _this.errors.NER(resourceName))}else if(!DSUtils._o(params)){reject(DSUtils._oErr("attrs"))}else{options=DSUtils._(definition,options);options.logFn("destroyAll",params,options);DSUtils.applyScope(definition,params,options);resolve()}}).then(function(){toEject=definition.defaultFilter.call(_this,resourceName,params);return options.beforeDestroy(options,toEject)}).then(function(){if(options.notify){definition.emit("DS.beforeDestroy",definition,toEject)}if(options.eagerEject){ejected=definition.ejectAll(params)}adapter=definition.getAdapterName(options);return _this.adapters[adapter].destroyAll(definition,params,options)}).then(function(){return options.afterDestroy(options,toEject)}).then(function(){if(options.notify){definition.emit("DS.afterDestroy",definition,toEject)}return ejected||definition.ejectAll(params)}).then(function(items){return DSUtils.respond(items,{adapter:adapter},options)})["catch"](function(err){if(options&&options.eagerEject&&ejected){definition.inject(ejected,{notify:false})}return _this.errorFn("destroyAll",resourceName,params,options)(err)})}},function(module,exports){"use strict";module.exports=function find(resourceName,id,options){var _this=this;var DSUtils=_this.utils;var definition=_this.definitions[resourceName];var resource=_this.store[resourceName];var adapter=undefined;return new DSUtils.Promise(function(resolve,reject){if(!definition){reject(new _this.errors.NER(resourceName))}else if(!DSUtils._sn(id)){reject(DSUtils._snErr("id"))}else{options=DSUtils._(definition,options);options.logFn("find",id,options);if(options.params){options.params=DSUtils.copy(options.params)}if(options.bypassCache||!options.cacheResponse){delete resource.completedQueries[id]}var expired=options.maxAge&&id in resource.completedQueries&&resource.completedQueries[id]+options.maxAge<(new Date).getTime();if((!options.findStrictCache||id in resource.completedQueries)&&definition.get(id)&&!options.bypassCache&&!expired){resolve(definition.get(id))}else{delete resource.completedQueries[id];resolve()}}}).then(function(item){if(!item){if(!(id in resource.pendingQueries)){var promise=undefined;var strategy=options.findStrategy||options.strategy;if(strategy==="fallback"){var makeFallbackCall=function makeFallbackCall(index){adapter=definition.getAdapterName((options.findFallbackAdapters||options.fallbackAdapters)[index]);return _this.adapters[adapter].find(definition,id,options)["catch"](function(err){index++;if(index<options.fallbackAdapters.length){return makeFallbackCall(index)}else{return DSUtils.Promise.reject(err)}})};promise=makeFallbackCall(0)}else{adapter=definition.getAdapterName(options);promise=_this.adapters[adapter].find(definition,id,options)}resource.pendingQueries[id]=promise.then(function(data){return options.afterFind.call(data,options,data)}).then(function(data){delete resource.pendingQueries[id];if(options.cacheResponse){var injected=definition.inject(data,options.orig());resource.completedQueries[id]=(new Date).getTime();resource.saved[id]=DSUtils.updateTimestamp(resource.saved[id]);return injected}else{return definition.createInstance(data,options.orig())}})}return resource.pendingQueries[id]}else{return item}}).then(function(item){return DSUtils.respond(item,{adapter:adapter},options)})["catch"](function(err){if(resource){delete resource.pendingQueries[id]}return _this.errorFn("find",resourceName,id,options)(err)})}},function(module,exports){"use strict";function processResults(data,resourceName,queryHash,options){var _this=this;var DSUtils=_this.utils;var definition=_this.definitions[resourceName];var resource=_this.store[resourceName];var idAttribute=definition.idAttribute;var date=(new Date).getTime();data=data||[];delete resource.pendingQueries[queryHash];resource.completedQueries[queryHash]=date;var injected=definition.inject(data,options.orig());if(DSUtils._a(injected)){DSUtils.forEach(injected,function(item){if(item){var id=item[idAttribute];if(id){resource.completedQueries[id]=date;resource.saved[id]=DSUtils.updateTimestamp(resource.saved[id])}}})}else{options.errorFn("response is expected to be an array!");resource.completedQueries[injected[idAttribute]]=date}return injected}module.exports=function findAll(resourceName,params,options){var _this=this;var DSUtils=_this.utils;var definition=_this.definitions[resourceName];var resource=_this.store[resourceName];var queryHash=undefined,adapter=undefined;return new DSUtils.Promise(function(resolve,reject){params=params||{};if(!_this.definitions[resourceName]){reject(new _this.errors.NER(resourceName))}else if(!DSUtils._o(params)){reject(DSUtils._oErr("params"))}else{options=DSUtils._(definition,options);queryHash=DSUtils.toJson(params);options.logFn("findAll",params,options);if(options.params){options.params=DSUtils.copy(options.params)}DSUtils.applyScope(definition,params,options);if(options.bypassCache||!options.cacheResponse){delete resource.completedQueries[queryHash];delete resource.queryData[queryHash]}var expired=options.maxAge&&queryHash in resource.completedQueries&&resource.completedQueries[queryHash]+options.maxAge<(new Date).getTime();if(queryHash in resource.completedQueries&&!expired){if(options.useFilter){if(options.localKeys){resolve(definition.getAll(options.localKeys,options.orig()))}else{resolve(definition.filter(params,options.orig()))}}else{resolve(resource.queryData[queryHash])}}else{resolve()}}}).then(function(items){if(!items){if(!(queryHash in resource.pendingQueries)){var promise=undefined;var strategy=options.findAllStrategy||options.strategy;if(strategy==="fallback"){var makeFallbackCall=function makeFallbackCall(index){adapter=definition.getAdapterName((options.findAllFallbackAdapters||options.fallbackAdapters)[index]);return _this.adapters[adapter].findAll(definition,params,options)["catch"](function(err){index++;if(index<options.fallbackAdapters.length){return makeFallbackCall(index)}else{return DSUtils.Promise.reject(err)}})};promise=makeFallbackCall(0)}else{adapter=definition.getAdapterName(options);promise=_this.adapters[adapter].findAll(definition,params,options)}resource.pendingQueries[queryHash]=promise.then(function(data){return options.afterFindAll.call(data,options,data)}).then(function(data){delete resource.pendingQueries[queryHash];if(options.cacheResponse){resource.queryData[queryHash]=processResults.call(_this,data,resourceName,queryHash,options);resource.queryData[queryHash].$$injected=true;return resource.queryData[queryHash]}else{DSUtils.forEach(data,function(item,i){data[i]=definition.createInstance(item,options.orig())});return data}})}return resource.pendingQueries[queryHash]}else{return items}}).then(function(items){return DSUtils.respond(items,{adapter:adapter},options)})["catch"](function(err){if(resource){delete resource.pendingQueries[queryHash]}return _this.errorFn("findAll",resourceName,params,options)(err)})}},function(module,exports){"use strict";function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}module.exports=function loadRelations(resourceName,instance,relations,options){var _this=this;var DSUtils=_this.utils;var DSErrors=_this.errors;var definition=_this.definitions[resourceName];var _options=undefined;return new DSUtils.Promise(function(resolve,reject){if(DSUtils._sn(instance)){instance=definition.get(instance)}if(DSUtils._s(relations)){relations=[relations]}relations=relations||[];if(!definition){reject(new DSErrors.NER(resourceName))}else if(!DSUtils._o(instance)){reject(new DSErrors.IA('"instance(id)" must be a string, number or object!'))}else if(!DSUtils._a(relations)){reject(new DSErrors.IA('"relations" must be a string or an array!'))}else{(function(){_options=DSUtils._(definition,options);_options.logFn("loadRelations",instance,relations,_options);
var tasks=[];DSUtils.forEach(definition.relationList,function(def){var relationName=def.relation;var relationDef=definition.getResource(relationName);var __options=DSUtils._(relationDef,options);if(!relations.length||DSUtils.contains(relations,relationName)||DSUtils.contains(relations,def.localField)){var task=undefined;var params={};if(__options.allowSimpleWhere){params[def.foreignKey]=instance[definition.idAttribute]}else{params.where={};params.where[def.foreignKey]={"==":instance[definition.idAttribute]}}var orig=__options.orig();var defKey=def.localKey?DSUtils.get(instance,def.localKey):null;var hasDefKey=!!(defKey||defKey===0);if(typeof def.load==="function"){task=def.load(definition,def,instance,orig)}else{if(def.type==="hasMany"){if(def.localKeys){delete params[def.foreignKey];var keys=DSUtils.get(instance,def.localKeys)||[];keys=DSUtils._a(keys)?keys:DSUtils.keys(keys);params.where=_defineProperty({},relationDef.idAttribute,{"in":keys});orig.localKeys=keys}else if(def.foreignKeys){delete params[def.foreignKey];params.where=_defineProperty({},def.foreignKeys,{contains:instance[definition.idAttribute]})}task=relationDef.findAll(params,orig)}else if(def.type==="hasOne"){if(def.localKey&&hasDefKey){task=relationDef.find(defKey,orig)}else if(def.foreignKey){task=relationDef.findAll(params,orig).then(function(hasOnes){return hasOnes.length?hasOnes[0]:null})}}else if(hasDefKey){task=relationDef.find(defKey,orig)}}if(task){if(!_options.linkRelations){task=task.then(function(data){instance[def.localField]=data})}tasks.push(task)}}});resolve(tasks)})()}}).then(function(tasks){return DSUtils.Promise.all(tasks)}).then(function(){return _options.afterLoadRelations.call(instance,_options,instance)}).catch(_this.errorFn("loadRelations",resourceName,instance,relations,options))}},function(module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol?"symbol":typeof obj};module.exports=function reap(resourceName,options){var _this=this;var DSUtils=_this.utils;var definition=_this.definitions[resourceName];var resource=_this.store[resourceName];return new DSUtils.Promise(function(resolve,reject){if(!definition){reject(new _this.errors.NER(resourceName))}else{options=DSUtils._(definition,options);if(!options.hasOwnProperty("notify")){options.notify=false}options.logFn("reap",options);var items=[];var now=(new Date).getTime();var expiredItem=undefined;while((expiredItem=resource.expiresHeap.peek())&&expiredItem.expires<now){items.push(expiredItem.item);delete expiredItem.item;resource.expiresHeap.pop()}resolve(items)}}).then(function(items){if(items.length){definition.beforeReap(options,items);if(options.notify){definition.emit("DS.beforeReap",definition,items)}}if(options.reapAction==="inject"){(function(){var timestamp=(new Date).getTime();DSUtils.forEach(items,function(item){resource.expiresHeap.push({item:item,timestamp:timestamp,expires:definition.maxAge?timestamp+definition.maxAge:Number.MAX_VALUE})})})()}else if(options.reapAction==="eject"){DSUtils.forEach(items,function(item){definition.eject(item[definition.idAttribute])})}else if(options.reapAction==="refresh"){var _ret2=function(){var tasks=[];DSUtils.forEach(items,function(item){tasks.push(definition.refresh(item[definition.idAttribute]))});return{v:DSUtils.Promise.all(tasks)}}();if((typeof _ret2==="undefined"?"undefined":_typeof(_ret2))==="object")return _ret2.v}return items}).then(function(items){if(items.length){definition.afterReap(options,items);if(options.notify){definition.emit("DS.afterReap",definition,items)}}return items}).catch(_this.errorFn("reap",resourceName,options))}},function(module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol?"symbol":typeof obj};module.exports=function save(resourceName,id,options){var _this=this;var DSUtils=_this.utils;var DSErrors=_this.errors;var definition=_this.definitions[resourceName];var resource=_this.store[resourceName];var item=undefined,noChanges=undefined,adapter=undefined;return new DSUtils.Promise(function(resolve,reject){id=DSUtils.resolveId(definition,id);if(!definition){reject(new DSErrors.NER(resourceName))}else if(!DSUtils._sn(id)){reject(DSUtils._snErr("id"))}else if(!definition.get(id)){reject(new DSErrors.R('id "'+id+'" not found in cache!'))}else{item=definition.get(id);options=DSUtils._(definition,options);options.logFn("save",id,options);resolve(item)}}).then(function(attrs){return options.beforeValidate.call(attrs,options,attrs)}).then(function(attrs){return options.validate.call(attrs,options,attrs)}).then(function(attrs){return options.afterValidate.call(attrs,options,attrs)}).then(function(attrs){return options.beforeUpdate.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.beforeUpdate",definition,attrs)}if(options.changesOnly){var key;var _ret=function(){if(resource.observers[id]&&typeof resource.observers[id]==="function"){resource.observers[id].deliver()}var toKeep=[];var changes=definition.changes(id);for(key in changes.added){toKeep.push(key)}for(key in changes.changed){toKeep.push(key)}DSUtils.forEach(options.always,function(property){toKeep.push(property)});changes=DSUtils.pick(attrs,toKeep);if(DSUtils.isEmpty(changes)){options.logFn("save - no changes",id,options);noChanges=true;return{v:attrs}}else{attrs=changes}}();if((typeof _ret==="undefined"?"undefined":_typeof(_ret))==="object")return _ret.v}adapter=definition.getAdapterName(options);return _this.adapters[adapter].update(definition,id,DSUtils.omit(attrs,options.omit),options)}).then(function(data){return options.afterUpdate.call(data,options,data)}).then(function(attrs){if(options.notify){definition.emit("DS.afterUpdate",definition,attrs)}if(noChanges){return attrs}else if(options.cacheResponse){var injected=definition.inject(attrs,options.orig());resource.saved[id]=DSUtils.updateTimestamp(resource.saved[id]);if(!definition.resetHistoryOnInject){resource.previousAttributes[id]=DSUtils.copy(injected,null,null,null,definition.relationFields)}return injected}else{return definition.createInstance(attrs,options.orig())}}).then(function(item){return DSUtils.respond(item,{adapter:adapter},options)}).catch(_this.errorFn("save",resourceName,id,options))}},function(module,exports){"use strict";module.exports=function update(resourceName,id,attrs,options){var _this=this;var DSUtils=_this.utils;var DSErrors=_this.errors;var definition=_this.definitions[resourceName];var adapter=undefined;return new DSUtils.Promise(function(resolve,reject){id=DSUtils.resolveId(definition,id);if(!definition){reject(new DSErrors.NER(resourceName))}else if(!DSUtils._sn(id)){reject(DSUtils._snErr("id"))}else{options=DSUtils._(definition,options);options.logFn("update",id,attrs,options);resolve(attrs)}}).then(function(attrs){return options.beforeValidate.call(attrs,options,attrs)}).then(function(attrs){return options.validate.call(attrs,options,attrs)}).then(function(attrs){return options.afterValidate.call(attrs,options,attrs)}).then(function(attrs){return options.beforeUpdate.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.beforeUpdate",definition,attrs)}adapter=definition.getAdapterName(options);return _this.adapters[adapter].update(definition,id,DSUtils.omit(attrs,options.omit),options)}).then(function(data){return options.afterUpdate.call(data,options,data)}).then(function(attrs){if(options.notify){definition.emit("DS.afterUpdate",definition,attrs)}if(options.cacheResponse){var injected=definition.inject(attrs,options.orig());var resource=_this.store[resourceName];var _id=injected[definition.idAttribute];resource.saved[_id]=DSUtils.updateTimestamp(resource.saved[_id]);if(!definition.resetHistoryOnInject){resource.previousAttributes[_id]=DSUtils.copy(injected,null,null,null,definition.relationFields)}return injected}else{return definition.createInstance(attrs,options.orig())}}).then(function(item){return DSUtils.respond(item,{adapter:adapter},options)}).catch(_this.errorFn("update",resourceName,id,attrs,options))}},function(module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol?"symbol":typeof obj};module.exports=function updateAll(resourceName,attrs,params,options){var _this=this;var DSUtils=_this.utils;var DSErrors=_this.errors;var definition=_this.definitions[resourceName];var adapter=undefined;return new DSUtils.Promise(function(resolve,reject){if(!definition){reject(new DSErrors.NER(resourceName))}else{options=DSUtils._(definition,options);options.logFn("updateAll",attrs,params,options);DSUtils.applyScope(definition,params,options);resolve(attrs)}}).then(function(attrs){return options.beforeValidate.call(attrs,options,attrs)}).then(function(attrs){return options.validate.call(attrs,options,attrs)}).then(function(attrs){return options.afterValidate.call(attrs,options,attrs)}).then(function(attrs){return options.beforeUpdate.call(attrs,options,attrs)}).then(function(attrs){if(options.notify){definition.emit("DS.beforeUpdate",definition,attrs)}adapter=definition.getAdapterName(options);return _this.adapters[adapter].updateAll(definition,DSUtils.omit(attrs,options.omit),params,options)}).then(function(data){return options.afterUpdate.call(data,options,data)}).then(function(data){if(options.notify){definition.emit("DS.afterUpdate",definition,attrs)}var origOptions=options.orig();if(options.cacheResponse){var _ret=function(){var injected=definition.inject(data,origOptions);var resource=_this.store[resourceName];DSUtils.forEach(injected,function(i){var id=i[definition.idAttribute];resource.saved[id]=DSUtils.updateTimestamp(resource.saved[id]);if(!definition.resetHistoryOnInject){resource.previousAttributes[id]=DSUtils.copy(i,null,null,null,definition.relationFields)}});return{v:injected}}();if((typeof _ret==="undefined"?"undefined":_typeof(_ret))==="object")return _ret.v}else{var _ret2=function(){var instances=[];DSUtils.forEach(data,function(item){instances.push(definition.createInstance(item,origOptions))});return{v:instances}}();if((typeof _ret2==="undefined"?"undefined":_typeof(_ret2))==="object")return _ret2.v}}).then(function(items){return DSUtils.respond(items,{adapter:adapter},options)}).catch(_this.errorFn("updateAll",resourceName,attrs,params,options))}}])}); |
src/components/event.js | Peterrkang/Locals | import React, { Component } from 'react';
import { Link } from 'react-router';
class Event extends Component {
render() {
const values = Object.values(this.props.activeEvent)[0];
const id = Object.keys(this.props.activeEvent)[0];
if(!id) {
return <div className="event"> Select an event to get started. </div>;
}else{
return (
<div className="event">
<h3>{values.title}</h3>
{values.description}
<br />
{values.address}
<br />
<Link to={`/events/${id}`} params={{id: id}}>
Chat With Locals
</Link>
</div>
);
}
}
}
export default Event;
|
node_modules/react-solr-connector/demo/demo.js | SerendpityZOEY/Solr-Search-React-UI | import React from 'react';
class SolrConnectorDemo extends React.Component {
constructor(props) {
super(props);
this.state = {
solrSearchUrl: "http://localhost:8983/solr/techproducts/select",
query: "memory",
filter: "",
fetchFields: ""
}
}
onSubmit(event) {
event.preventDefault();
let searchParams = {
solrSearchUrl: this.state.solrSearchUrl,
query: this.state.query,
filter: [this.state.filter],
fetchFields: this.state.fetchFields.split(" "),
offset: 0,
limit: 10,
facet: {
manufacturer: {
type: "terms",
field: "manu_id_s",
limit: 20
},
price_range_0_100: {
query: "price:[0 TO 100]"
}
},
highlightParams: {
"hl": "true",
"hl.fl": "name manu",
"hl.snippets": 1,
"hl.fragsize": 500
}
};
this.props.doSearch(searchParams);
}
render() {
return <div>
<form className="inputForm" onSubmit={this.onSubmit.bind(this)}>
<h4>searchParams:</h4>
<p>
solrSearchUrl: {" "}
<input type="text" value={this.state.solrSearchUrl}
onChange={e => {this.setState({ solrSearchUrl: e.target.value })}} />
</p>
<p>
query: {" "}
<input type="text" value={this.state.query}
onChange={e => {this.setState({ query: e.target.value })}} />
{" "}
filter: {" "}
<input type="text" value={this.state.filter}
onChange={e => {this.setState({ filter: e.target.value })}} />
</p>
<p>
fetchFields: {" "}
<input type="text" value={this.state.fetchFields}
onChange={e => {this.setState({ fetchFields: e.target.value })}} />
</p>
<p>
<button type="submit">Search</button>
</p>
</form>
<div className="jsonOutput">
<pre>
this.props.solrConnector: {"\n\n"}
{ JSON.stringify(this.props.solrConnector, null, 2) }
</pre>
</div>
</div>;
}
}
export default SolrConnectorDemo;
|
scripts/generateFixtures.js | apiaryio/attributes-kit | import React from 'react';
import async from 'async';
import ReactDomServer from 'react-dom/server';
import msonZoo from 'mson-zoo';
import jsBeautify from 'js-beautify';
import fs from 'fs';
import path from 'path';
import { Namespace } from 'api-elements';
import parseMson from '../playground/parseMson';
import AttributesKit from '../dist/attributes-kit-server';
const fixtureLocation = path.join(__dirname, '../', 'fixtures');
if (!fs.existsSync(fixtureLocation)) {
fs.mkdirSync(fixtureLocation);
}
async.forEachOfLimit(msonZoo.samples, 10, (sample, sampleIndex, next) => {
const header = '# Data Structures';
parseMson(`${header}\n\n${sample.fileContent}`, (err, dataStructureElements) => {
if (err) {
console.error('An error occured during parsing one of the samples from MSON Zoo.');
console.error(`Name of the file is ‘${sample.fileName}.’`);
return next(err);
}
if (!dataStructureElements || dataStructureElements.length === 0) {
console.error('An error occured during, no data structure elements were returned.');
console.error(`Name of the file is ‘${sample.fileName}.’`);
return next(new Error('No data structure elements were returned.'));
}
const minimNamespace = new Namespace();
dataStructureElements = minimNamespace.fromRefract(dataStructureElements);
const renderedElement = React.createElement(AttributesKit.Attributes, {
element: dataStructureElements.first,
collapseByDefault: false,
includedProperties: 'show',
inheritedProperties: 'show',
});
const htmlString = jsBeautify.html(ReactDomServer.renderToStaticMarkup(renderedElement));
fs.writeFileSync(path.join(fixtureLocation, sample.fileName), htmlString);
next();
});
}, (err) => {
if (err) {
process.exit(1);
}
console.log('All good!');
});
|
app/javascript/mastodon/features/lists/components/new_list_form.js | maa123/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { changeListEditorTitle, submitListEditor } from '../../../actions/lists';
import IconButton from '../../../components/icon_button';
import { defineMessages, injectIntl } from 'react-intl';
const messages = defineMessages({
label: { id: 'lists.new.title_placeholder', defaultMessage: 'New list title' },
title: { id: 'lists.new.create', defaultMessage: 'Add list' },
});
const mapStateToProps = state => ({
value: state.getIn(['listEditor', 'title']),
disabled: state.getIn(['listEditor', 'isSubmitting']),
});
const mapDispatchToProps = dispatch => ({
onChange: value => dispatch(changeListEditorTitle(value)),
onSubmit: () => dispatch(submitListEditor(true)),
});
export default @connect(mapStateToProps, mapDispatchToProps)
@injectIntl
class NewListForm extends React.PureComponent {
static propTypes = {
value: PropTypes.string.isRequired,
disabled: PropTypes.bool,
intl: PropTypes.object.isRequired,
onChange: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
};
handleChange = e => {
this.props.onChange(e.target.value);
}
handleSubmit = e => {
e.preventDefault();
this.props.onSubmit();
}
handleClick = () => {
this.props.onSubmit();
}
render () {
const { value, disabled, intl } = this.props;
const label = intl.formatMessage(messages.label);
const title = intl.formatMessage(messages.title);
return (
<form className='column-inline-form' onSubmit={this.handleSubmit}>
<label>
<span style={{ display: 'none' }}>{label}</span>
<input
className='setting-text'
value={value}
disabled={disabled}
onChange={this.handleChange}
placeholder={label}
/>
</label>
<IconButton
disabled={disabled || !value}
icon='plus'
title={title}
onClick={this.handleClick}
/>
</form>
);
}
}
|
ajax/libs/rxjs/2.3.17/rx.js | SaravananRajaraman/cdnjs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise // Detect if promise exists
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = Date.now,
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; },
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 };
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 deprecate = Rx.helpers.deprecate = function (name, alternative) {
if (typeof console !== "undefined" && typeof console.warn === "function") {
console.warn(name + ' is deprecated, use ' + alternative + ' instead.', new Error('').stack);
}
}
/** `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;
}
// Collections
function IndexedItem(id, value) {
this.id = id;
this.value = value;
}
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
c === 0 && (c = this.id - other.id);
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) { return; }
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) { return; }
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
+index || (index = 0);
if (index >= this.length || index < 0) { return; }
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
delete this.items[this.length];
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
this.disposables = argsOrArray(arguments, 0);
this.isDisposed = false;
this.length = this.disposables.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Converts the existing CompositeDisposable to an array of disposables
* @returns {Array} An array of disposable objects.
*/
CompositeDisposablePrototype.toArray = function () {
return this.disposables.slice(0);
};
/**
* Provides a set of static methods for creating Disposables.
*
* @constructor
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () {
function BooleanDisposable () {
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed, old;
if (!shouldDispose) {
old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
var old;
if (!this.isDisposed) {
this.isDisposed = true;
old = this.current;
this.current = null;
}
old && old.dispose();
};
return BooleanDisposable;
}());
var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable;
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed) {
if (!this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
if (!this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler;
this.disposable = disposable;
this.isDisposed = false;
}
ScheduledDisposable.prototype.dispose = function () {
var parent = this;
this.scheduler.schedule(function () {
if (!parent.isDisposed) {
parent.isDisposed = true;
parent.disposable.dispose();
}
});
};
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
timeSpan < 0 && (timeSpan = 0);
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
(function (schedulerProto) {
function invokeRecImmediate(scheduler, pair) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function scheduleInnerRecursive(action, self) {
action(function(dt) { self(action, dt); });
}
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () { self(_action); }); });
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, action);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) {
if (typeof root.setInterval === 'undefined') { throw new Error('Periodic scheduling not supported.'); }
var s = state;
var id = root.setInterval(function () {
s = action(s);
}, period);
return disposableCreate(function () {
root.clearInterval(id);
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
* @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
* @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
*/
schedulerProto.catchError = schedulerProto['catch'] = function (handler) {
return new CatchScheduler(this, handler);
};
}(Scheduler.prototype));
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
/**
* Gets a scheduler that schedules work immediately on the current thread.
*/
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) { return action(this, state); }
function scheduleRelative(state, dueTime, action) {
var dt = normalizeTime(dt);
while (dt - this.now() > 0) { }
return action(this, state);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function runTrampoline (q) {
var item;
while (q.length > 0) {
item = q.dequeue();
if (!item.isCancelled()) {
// Note, do not schedule blocking work!
while (item.dueTime - Scheduler.now() > 0) {
}
if (!item.isCancelled()) {
item.invoke();
}
}
}
}
function scheduleNow(state, action) {
return this.scheduleWithRelativeAndState(state, 0, action);
}
function scheduleRelative(state, dueTime, action) {
var dt = this.now() + Scheduler.normalize(dueTime),
si = new ScheduledItem(this, state, action, dt);
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
try {
runTrampoline(queue);
} catch (e) {
throw e;
} finally {
queue = null;
}
} else {
queue.enqueue(si);
}
return si.disposable;
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
currentScheduler.scheduleRequired = function () { return !queue; };
currentScheduler.ensureTrampoline = function (action) {
if (!queue) { this.schedule(action); } else { action(); }
};
return currentScheduler;
}());
var scheduleMethod, clearMethod = noop;
var localTimer = (function () {
var localSetTimeout, localClearTimeout = noop;
if ('WScript' in this) {
localSetTimeout = function (fn, time) {
WScript.Sleep(time);
fn();
};
} else if (!!root.setTimeout) {
localSetTimeout = root.setTimeout;
localClearTimeout = root.clearTimeout;
} else {
throw new Error('No concurrency detected!');
}
return {
setTimeout: localSetTimeout,
clearTimeout: localClearTimeout
};
}());
var localSetTimeout = localTimer.setTimeout,
localClearTimeout = localTimer.clearTimeout;
(function () {
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate,
clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' &&
!reNative.test(clearImmediate) && clearImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false,
oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('', '*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout
if (typeof setImmediate === 'function') {
scheduleMethod = setImmediate;
clearMethod = clearImmediate;
} else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = process.nextTick;
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),
tasks = {},
taskId = 0;
function onGlobalPostMessage(event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
var handleId = event.data.substring(MSG_PREFIX.length),
action = tasks[handleId];
action();
delete tasks[handleId];
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var currentId = taskId++;
tasks[currentId] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel(),
channelTasks = {},
channelTaskId = 0;
channel.port1.onmessage = function (event) {
var id = event.data,
action = channelTasks[id];
action();
delete channelTasks[id];
};
scheduleMethod = function (action) {
var id = channelTaskId++;
channelTasks[id] = action;
channel.port2.postMessage(id);
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
scriptElement.onreadystatechange = function () {
action();
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
};
} else {
scheduleMethod = function (action) { return localSetTimeout(action, 0); };
clearMethod = localClearTimeout;
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable();
var id = localSetTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
localClearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
var CatchScheduler = (function (__super__) {
function scheduleNow(state, action) {
return this._scheduler.scheduleWithState(state, this._wrap(action));
}
function scheduleRelative(state, dueTime, action) {
return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action));
}
function scheduleAbsolute(state, dueTime, action) {
return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action));
}
inherits(CatchScheduler, __super__);
function CatchScheduler(scheduler, handler) {
this._scheduler = scheduler;
this._handler = handler;
this._recursiveOriginal = null;
this._recursiveWrapper = null;
__super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute);
}
CatchScheduler.prototype._clone = function (scheduler) {
return new CatchScheduler(scheduler, this._handler);
};
CatchScheduler.prototype._wrap = function (action) {
var parent = this;
return function (self, state) {
try {
return action(parent._getRecursiveWrapper(self), state);
} catch (e) {
if (!parent._handler(e)) { throw e; }
return disposableEmpty;
}
};
};
CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
if (this._recursiveOriginal !== scheduler) {
this._recursiveOriginal = scheduler;
var wrapper = this._clone(scheduler);
wrapper._recursiveOriginal = scheduler;
wrapper._recursiveWrapper = wrapper;
this._recursiveWrapper = wrapper;
}
return this._recursiveWrapper;
};
CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
var self = this, failed = false, d = new SingleAssignmentDisposable();
d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) {
if (failed) { return null; }
try {
return action(state1);
} catch (e) {
failed = true;
if (!self._handler(e)) { throw e; }
d.dispose();
return null;
}
}));
return d;
};
return CatchScheduler;
}(Scheduler));
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, hasValue) {
this.hasValue = hasValue == null ? false : hasValue;
this.kind = kind;
}
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObservable(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
Notification.prototype.toObservable = function (scheduler) {
var notification = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
notification._acceptObservable(observer);
notification.kind === 'N' && observer.onCompleted();
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept (onNext) { return onNext(this.value); }
function _acceptObservable(observer) { return observer.onNext(this.value); }
function toString () { return 'OnNext(' + this.value + ')'; }
return function (value) {
var notification = new Notification('N', true);
notification.value = value;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) { return onError(this.exception); }
function _acceptObservable(observer) { return observer.onError(this.exception); }
function toString () { return 'OnError(' + this.exception + ')'; }
return function (e) {
var notification = new Notification('E');
notification.exception = e;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) { return onCompleted(); }
function _acceptObservable(observer) { return observer.onCompleted(); }
function toString () { return 'OnCompleted()'; }
return function () {
var notification = new Notification('C');
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch (err) {
observer.onError();
return;
}
var isDisposed,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var currentItem;
if (isDisposed) { return; }
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
observer.onCompleted();
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () { self(); })
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchError = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch (err) {
observer.onError();
return;
}
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
var currentItem;
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
if (lastException) {
observer.onError(lastException);
} else {
observer.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
function (exn) {
lastException = exn;
self();
},
observer.onCompleted.bind(observer)));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount == null) { repeatCount = -1; }
return new Enumerable(function () {
var left = repeatCount;
return new Enumerator(function () {
if (left === 0) { return doneEnumerator; }
if (left > 0) { left--; }
return { done: false, value: value };
});
});
};
var enumerableOf = Enumerable.of = function (source, selector, thisArg) {
selector || (selector = identity);
return new Enumerable(function () {
var index = -1;
return new Enumerator(
function () {
return ++index < source.length ?
{ done: false, value: selector.call(thisArg, source[index], index, source) } :
doneEnumerator;
});
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) { return n.accept(observer); };
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
* If a violation is detected, an Error is thrown from the offending observer method call.
* @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
*/
Observer.prototype.checked = function () { return new CheckedObserver(this); };
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler, thisArg) {
return new AnonymousObserver(function (x) {
return handler.call(thisArg, notificationCreateOnNext(x));
}, function (e) {
return handler.call(thisArg, notificationCreateOnError(e));
}, function () {
return handler.call(thisArg, notificationCreateOnCompleted());
});
};
/**
* Schedules the invocation of observer methods on the given scheduler.
* @param {Scheduler} scheduler Scheduler to schedule observer messages on.
* @returns {Observer} Observer whose messages are scheduled on the given scheduler.
*/
Observer.notifyOn = function (scheduler) {
return new ObserveOnObserver(scheduler, this);
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) {
inherits(AbstractObserver, __super__);
/**
* Creates a new observer in a non-stopped state.
*/
function AbstractObserver() {
this.isStopped = false;
__super__.call(this);
}
/**
* Notifies the observer of a new element in the sequence.
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) { this.next(value); }
};
/**
* Notifies the observer that an exception has occurred.
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) {
inherits(AnonymousObserver, __super__);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
__super__.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (error) {
this._onError(error);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var CheckedObserver = (function (_super) {
inherits(CheckedObserver, _super);
function CheckedObserver(observer) {
_super.call(this);
this._observer = observer;
this._state = 0; // 0 - idle, 1 - busy, 2 - done
}
var CheckedObserverPrototype = CheckedObserver.prototype;
CheckedObserverPrototype.onNext = function (value) {
this.checkAccess();
try {
this._observer.onNext(value);
} catch (e) {
throw e;
} finally {
this._state = 0;
}
};
CheckedObserverPrototype.onError = function (err) {
this.checkAccess();
try {
this._observer.onError(err);
} catch (e) {
throw e;
} finally {
this._state = 2;
}
};
CheckedObserverPrototype.onCompleted = function () {
this.checkAccess();
try {
this._observer.onCompleted();
} catch (e) {
throw e;
} finally {
this._state = 2;
}
};
CheckedObserverPrototype.checkAccess = function () {
if (this._state === 1) { throw new Error('Re-entrancy detected'); }
if (this._state === 2) { throw new Error('Observer completed'); }
if (this._state === 0) { this._state = 1; }
};
return CheckedObserver;
}(Observer));
var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) {
inherits(ScheduledObserver, __super__);
function ScheduledObserver(scheduler, observer) {
__super__.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () {
self.observer.onNext(value);
});
};
ScheduledObserver.prototype.error = function (err) {
var self = this;
this.queue.push(function () {
self.observer.onError(err);
});
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () {
self.observer.onCompleted();
});
};
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
ScheduledObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
var ObserveOnObserver = (function (__super__) {
inherits(ObserveOnObserver, __super__);
function ObserveOnObserver() {
__super__.apply(this, arguments);
}
ObserveOnObserver.prototype.next = function (value) {
__super__.prototype.next.call(this, value);
this.ensureActive();
};
ObserveOnObserver.prototype.error = function (e) {
__super__.prototype.error.call(this, e);
this.ensureActive();
};
ObserveOnObserver.prototype.completed = function () {
__super__.prototype.completed.call(this);
this.ensureActive();
};
return ObserveOnObserver;
})(ScheduledObserver);
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
this._subscribe = subscribe;
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
return this._subscribe(typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onNext The function to invoke on each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnNext = function (onNext, thisArg) {
return this._subscribe(observerCreate(arguments.length === 2 ? function(x) { onNext.call(thisArg, x); } : onNext));
};
/**
* Subscribes to an exceptional condition in the sequence with an optional "this" argument.
* @param {Function} onError The function to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnError = function (onError, thisArg) {
return this._subscribe(observerCreate(null, arguments.length === 2 ? function(e) { onError.call(thisArg, e); } : onError));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnCompleted = function (onCompleted, thisArg) {
return this._subscribe(observerCreate(null, null, arguments.length === 2 ? function() { onCompleted.call(thisArg); } : onCompleted));
};
return Observable;
})();
/**
* Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
*
* This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
* that require to be run on a scheduler, use subscribeOn.
*
* @param {Scheduler} scheduler Scheduler to notify observers on.
* @returns {Observable} The source sequence whose observations happen on the specified scheduler.
*/
observableProto.observeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(new ObserveOnObserver(scheduler, observer));
});
};
/**
* Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
* see the remarks section for more information on the distinction between subscribeOn and observeOn.
* This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
* callbacks on a scheduler, use observeOn.
* @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
* @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
d.setDisposable(m);
m.setDisposable(scheduler.schedule(function () {
d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer)));
}));
return d;
});
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return observableDefer(function () {
var subject = new Rx.AsyncSubject();
promise.then(
function (value) {
if (!subject.isDisposed) {
subject.onNext(value);
subject.onCompleted();
}
},
subject.onError.bind(subject));
return subject;
});
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) { throw new TypeError('Promise type not provided nor in Rx.config.Promise'); }
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, reject, function () {
hasValue && resolve(value);
});
});
};
/**
* Creates an array from an observable sequence.
* @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
var 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 StringIterable(str) {
this._s = s;
}
StringIterable.prototype[$iterator$] = function () {
return new StringIterator(this._s);
};
function StringIterator(str) {
this._s = s;
this._l = s.length;
this._i = 0;
}
StringIterator.prototype[$iterator$] = function () {
return this;
};
StringIterator.prototype.next = function () {
if (this._i < this._l) {
var val = this._s.charAt(this._i++);
return { done: false, value: val };
} else {
return doneEnumerator;
}
};
function ArrayIterable(a) {
this._a = a;
}
ArrayIterable.prototype[$iterator$] = function () {
return new ArrayIterator(this._a);
};
function ArrayIterator(a) {
this._a = a;
this._l = toLength(a);
this._i = 0;
}
ArrayIterator.prototype[$iterator$] = function () {
return this;
};
ArrayIterator.prototype.next = function () {
if (this._i < this._l) {
var val = this._a[this._i++];
return { done: false, value: val };
} else {
return doneEnumerator;
}
};
function numberIsFinite(value) {
return typeof value === 'number' && root.isFinite(value);
}
function isNan(n) {
return n !== n;
}
function getIterable(o) {
var i = o[$iterator$], it;
if (!i && typeof o === 'string') {
it = new StringIterable(o);
return it[$iterator$]();
}
if (!i && o.length !== undefined) {
it = new ArrayIterable(o);
return it[$iterator$]();
}
if (!i) { throw new TypeError('Object is not iterable'); }
return o[$iterator$]();
}
function sign(value) {
var number = +value;
if (number === 0) { return number; }
if (isNaN(number)) { return number; }
return number < 0 ? -1 : 1;
}
function toLength(o) {
var len = +o.length;
if (isNaN(len)) { return 0; }
if (len === 0 || !numberIsFinite(len)) { return len; }
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) { return 0; }
if (len > maxSafeInteger) { return maxSafeInteger; }
return len;
}
/**
* This method creates a new Observable sequence from an array-like or iterable object.
* @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
* @param {Function} [mapFn] Map function to call on every element of the array.
* @param {Any} [thisArg] The context to use calling the mapFn if provided.
* @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
*/
var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) {
if (iterable == null) {
throw new Error('iterable cannot be null.')
}
if (mapFn && !isFunction(mapFn)) {
throw new Error('mapFn when provided must be a function');
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
var list = Object(iterable), it = getIterable(list);
return new AnonymousObservable(function (observer) {
var i = 0;
return scheduler.scheduleRecursive(function (self) {
var next;
try {
next = it.next();
} catch (e) {
observer.onError(e);
return;
}
if (next.done) {
observer.onCompleted();
return;
}
var result = next.value;
if (mapFn && isFunction(mapFn)) {
try {
result = mapFn.call(thisArg, result, i);
} catch (e) {
observer.onError(e);
return;
}
}
observer.onNext(result);
i++;
self();
});
});
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
* @deprecated use Observable.from or Observable.of
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
//deprecate('fromArray', 'from');
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0, len = array.length;
return scheduler.scheduleRecursive(function (self) {
if (count < len) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var first = true, state = initialState;
return scheduler.scheduleRecursive(function (self) {
var hasResult, result;
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
}
} catch (exception) {
observer.onError(exception);
return;
}
if (hasResult) {
observer.onNext(result);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
function observableOf (scheduler, array) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0, len = array.length;
return scheduler.scheduleRecursive(function (self) {
if (count < len) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
}
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
return observableOf(null, arguments);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.ofWithScheduler = function (scheduler) {
return observableOf(scheduler, slice.call(arguments, 1));
};
/**
* 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.just = function (value, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onNext(value);
observer.onCompleted();
});
});
};
/** @deprecated use return or just */
Observable.returnValue = function () {
deprecate('returnValue', 'return or just');
return observableReturn.apply(null, arguments);
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwError' for browsers <IE9.
* @param {Mixed} exception An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwException = Observable.throwError = function (exception, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(exception);
});
});
};
/**
* Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
* @param {Function} resourceFactory Factory function to obtain a resource object.
* @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
* @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
Observable.using = function (resourceFactory, observableFactory) {
return new AnonymousObservable(function (observer) {
var disposable = disposableEmpty, resource, source;
try {
resource = resourceFactory();
resource && (disposable = resource);
source = observableFactory(resource);
} catch (exception) {
return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable);
}
return new CompositeDisposable(source.subscribe(observer), disposable);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
observableProto.amb = function (rightSource) {
var leftSource = this;
return new AnonymousObservable(function (observer) {
var choice,
leftChoice = 'L', rightChoice = 'R',
leftSubscription = new SingleAssignmentDisposable(),
rightSubscription = new SingleAssignmentDisposable();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
function choiceL() {
if (!choice) {
choice = leftChoice;
rightSubscription.dispose();
}
}
function choiceR() {
if (!choice) {
choice = rightChoice;
leftSubscription.dispose();
}
}
leftSubscription.setDisposable(leftSource.subscribe(function (left) {
choiceL();
if (choice === leftChoice) {
observer.onNext(left);
}
}, function (err) {
choiceL();
if (choice === leftChoice) {
observer.onError(err);
}
}, function () {
choiceL();
if (choice === leftChoice) {
observer.onCompleted();
}
}));
rightSubscription.setDisposable(rightSource.subscribe(function (right) {
choiceR();
if (choice === rightChoice) {
observer.onNext(right);
}
}, function (err) {
choiceR();
if (choice === rightChoice) {
observer.onError(err);
}
}, function () {
choiceR();
if (choice === rightChoice) {
observer.onCompleted();
}
}));
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
*
* @example
* var = Rx.Observable.amb(xs, ys, zs);
* @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
Observable.amb = function () {
var acc = observableNever(),
items = argsOrArray(arguments, 0);
function func(previous, current) {
return previous.amb(current);
}
for (var i = 0, len = items.length; i < len; i++) {
acc = func(acc, items[i]);
}
return acc;
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (observer) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) {
var d, result;
try {
result = handler(exception);
} catch (ex) {
observer.onError(ex);
return;
}
isPromise(result) && (result = observableFromPromise(result));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(observer));
}, observer.onCompleted.bind(observer)));
return subscription;
});
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchError = function (handlerOrSecond) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
observableCatch([this, handlerOrSecond]);
};
/**
* @deprecated use #catch or #catchError instead.
*/
observableProto.catchException = function (handlerOrSecond) {
deprecate('catchException', 'catch or catchError');
return this.catchError(handlerOrSecond);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs.
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchError = Observable['catch'] = function () {
return enumerableOf(argsOrArray(arguments, 0)).catchError();
};
/**
* @deprecated use #catch or #catchError instead.
*/
Observable.catchException = function () {
deprecate('catchException', 'catch or catchError');
return observableCatch.apply(null, arguments);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var args = slice.call(arguments);
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var args = slice.call(arguments), resultSelector = args.pop();
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
}
function done (i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
}, 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.concatAll = function () {
return this.merge(1);
};
/** @deprecated Use `concatAll` instead. */
observableProto.concatObservable = function () {
deprecate('concatObservable', 'concatAll');
return this.merge(1);
};
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); }
var sources = this;
return new AnonymousObservable(function (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 observableOf(scheduler, sources).mergeAll();
};
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeAll = function () {
var sources = this;
return new AnonymousObservable(function (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;
});
};
/**
* @deprecated use #mergeAll instead.
*/
observableProto.mergeObservable = function () {
deprecate('mergeObservable', 'mergeAll');
return this.mergeAll.apply(this, arguments);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
* @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
* @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
*/
observableProto.onErrorResumeNext = function (second) {
if (!second) { throw new Error('Second observable is required'); }
return onErrorResumeNext([this, second]);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs);
* 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]);
* @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
*/
var onErrorResumeNext = Observable.onErrorResumeNext = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var pos = 0, subscription = new SerialDisposable(),
cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, d;
if (pos < sources.length) {
current = sources[pos++];
isPromise(current) && (current = observableFromPromise(current));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self));
} else {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && observer.onNext(left);
}, observer.onError.bind(observer), function () {
isOpen && observer.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, observer.onError.bind(observer), function () {
rightSubscription.dispose();
}));
return disposables;
});
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(
function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
// Check if Promise or Observable
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
d.setDisposable(innerSource.subscribe(
function (x) { latest === id && observer.onNext(x); },
function (e) { latest === id && observer.onError(e); },
function () {
if (latest === id) {
hasLatest = false;
isStopped && observer.onCompleted();
}
}));
},
observer.onError.bind(observer),
function () {
isStopped = true;
!hasLatest && observer.onCompleted();
});
return new CompositeDisposable(subscription, innerSubscription);
});
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
isPromise(other) && (other = observableFromPromise(other));
return new CompositeDisposable(
source.subscribe(observer),
other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop)
);
});
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
}
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) {
return zipArray.apply(this, arguments);
}
var parent = this, sources = slice.call(arguments), resultSelector = sources.pop();
sources.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = sources[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var args = slice.call(arguments, 0), first = args.shift();
return first.zip.apply(first, args);
};
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
var compositeDisposable = new CompositeDisposable(subscriptions);
compositeDisposable.add(disposableCreate(function () {
for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; }
}));
return compositeDisposable;
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
return new AnonymousObservable(this.subscribe.bind(this));
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
*
* @example
* var res = xs.bufferWithCount(10);
* var res = xs.bufferWithCount(10, 1);
* @param {Number} count Length of each buffer.
* @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithCount = function (count, skip) {
if (typeof skip !== 'number') {
skip = count;
}
return this.windowWithCount(count, skip).selectMany(function (x) {
return x.toArray();
}).where(function (x) {
return x.length > 0;
});
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
return x.accept(observer);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
keySelector || (keySelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var comparerEquals = false, key;
try {
key = keySelector(value);
} catch (exception) {
observer.onError(exception);
return;
}
if (hasCurrentKey) {
try {
comparerEquals = comparer(currentKey, key);
} catch (exception) {
observer.onError(exception);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.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();
});
});
};
/** @deprecated use #do or #tap instead. */
observableProto.doAction = function () {
deprecate('doAction', 'do or tap');
return this.tap.apply(this, arguments);
};
/**
* Invokes an action for each element in the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onNext Action to invoke for each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) {
return this.tap(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.
* @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();
}
});
});
};
/**
* @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 (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.
* @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();
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @example
* var res = source.scan(function (acc, x) { return acc + x; });
* var res = source.scan(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (observer) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(accumulation);
},
observer.onError.bind(observer),
function () {
!hasValue && hasSeed && observer.onNext(seed);
observer.onCompleted();
}
);
});
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && observer.onNext(q.shift());
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
* @example
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
* @param {Arguments} args The specified values to prepend to the observable sequence
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && isScheduler(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
values = slice.call(arguments, start);
return enumerableOf([observableFromArray(values, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence.
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, observer.onError.bind(observer), function () {
while (q.length > 0) { observer.onNext(q.shift()); }
observer.onCompleted();
});
});
};
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, observer.onError.bind(observer), function () {
observer.onNext(q);
observer.onCompleted();
});
});
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
*
* var res = xs.windowWithCount(10);
* var res = xs.windowWithCount(10, 1);
* @param {Number} count Length of each window.
* @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithCount = function (count, skip) {
var source = this;
+count || (count = 0);
Math.abs(count) === Infinity && (count = 0);
if (count <= 0) { throw new Error(argumentOutOfRange); }
skip == null && (skip = count);
+skip || (skip = 0);
Math.abs(skip) === Infinity && (skip = 0);
if (skip <= 0) { throw new Error(argumentOutOfRange); }
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(),
refCountDisposable = new RefCountDisposable(m),
n = 0,
q = [];
function createWindow () {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
createWindow();
m.setDisposable(source.subscribe(
function (x) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
var c = n - count + 1;
c >= 0 && c % skip === 0 && q.shift().onCompleted();
++n % skip === 0 && createWindow();
},
function (e) {
while (q.length > 0) { q.shift().onError(e); }
observer.onError(e);
},
function () {
while (q.length > 0) { q.shift().onCompleted(); }
observer.onCompleted();
}
));
return refCountDisposable;
});
};
function concatMap(source, selector, thisArg) {
return source.map(function (x, i) {
var result = selector.call(thisArg, x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(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;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNext.call(thisArg, x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onError.call(thisArg, err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompleted.call(thisArg);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}).concatAll();
};
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* var res = obs = xs.defaultIfEmpty();
* 2 - obs = xs.defaultIfEmpty(false);
*
* @memberOf Observable#
* @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
* @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
*/
observableProto.defaultIfEmpty = function (defaultValue) {
var source = this;
if (defaultValue === undefined) {
defaultValue = null;
}
return new AnonymousObservable(function (observer) {
var found = false;
return source.subscribe(function (x) {
found = true;
observer.onNext(x);
}, observer.onError.bind(observer), function () {
if (!found) {
observer.onNext(defaultValue);
}
observer.onCompleted();
});
});
};
// Swap out for Array.findIndex
function arrayIndexOfComparer(array, item, comparer) {
for (var i = 0, len = array.length; i < len; i++) {
if (comparer(array[i], item)) { return i; }
}
return -1;
}
function HashSet(comparer) {
this.comparer = comparer;
this.set = [];
}
HashSet.prototype.push = function(value) {
var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
retValue && this.set.push(value);
return retValue;
};
/**
* Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
* Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
*
* @example
* var res = obs = xs.distinct();
* 2 - obs = xs.distinct(function (x) { return x.id; });
* 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [comparer] Used to compare items in the collection.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hashSet = new HashSet(comparer);
return source.subscribe(function (x) {
var key = x;
if (keySelector) {
try {
key = keySelector(x);
} catch (e) {
observer.onError(e);
return;
}
}
hashSet.push(key) && observer.onNext(x);
},
observer.onError.bind(observer),
observer.onCompleted.bind(observer));
});
};
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.select = observableProto.map = function (selector, thisArg) {
var selectorFn = isFunction(selector) ? selector : function () { return selector; },
source = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return source.subscribe(function (value) {
var result;
try {
result = selectorFn.call(thisArg, value, count++, source);
} 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]; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNext.call(thisArg, x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onError.call(thisArg, err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompleted.call(thisArg);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}).mergeAll();
};
function flatMap(source, selector, thisArg) {
return source.map(function (x, i) {
var result = selector.call(thisArg, x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).mergeAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.flatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
}, thisArg);
}
return isFunction(selector) ?
flatMap(this, selector, thisArg) :
flatMap(this, function () { return selector; });
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) { throw new Error(argumentOutOfRange); }
var source = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining <= 0) {
observer.onNext(x);
} else {
remaining--;
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !predicate.call(thisArg, x, i++, source);
} catch (e) {
observer.onError(e);
return;
}
}
running && observer.onNext(x);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) { throw new RangeError(argumentOutOfRange); }
if (count === 0) { return observableEmpty(scheduler); }
var observable = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return observable.subscribe(function (x) {
if (remaining-- > 0) {
observer.onNext(x);
remaining === 0 && observer.onCompleted();
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var observable = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = true;
return observable.subscribe(function (x) {
if (running) {
try {
running = predicate.call(thisArg, x, i++, observable);
} catch (e) {
observer.onError(e);
return;
}
if (running) {
observer.onNext(x);
} else {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
*
* @example
* var res = source.where(function (value) { return value < 10; });
* var res = source.where(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.where = observableProto.filter = function (predicate, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, value, count++, parent);
} catch (e) {
observer.onError(e);
return;
}
shouldRun && observer.onNext(value);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Executes a transducer to transform the observable sequence
* @param {Transducer} transducer A transducer to execute
* @returns {Observable} An Observable sequence containing the results from the transducer.
*/
observableProto.transduce = function(transducer) {
var source = this;
function transformForObserver(observer) {
return {
init: function() {
return observer;
},
step: function(obs, input) {
return obs.onNext(input);
},
result: function(obs) {
return obs.onCompleted();
}
};
}
return new AnonymousObservable(function(observer) {
var xform = transducer(transformForObserver(observer));
return source.subscribe(
function(v) {
try {
xform.step(observer, v);
} catch (e) {
observer.onError(e);
}
},
observer.onError.bind(observer),
function() { xform.result(observer); }
);
});
};
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; }
return typeof subscriber === 'function' ?
disposableCreate(subscriber) :
disposableEmpty;
}
function AnonymousObservable(subscribe) {
if (!(this instanceof AnonymousObservable)) {
return new AnonymousObservable(subscribe);
}
function s(observer) {
var setDisposable = function () {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
};
var autoDetachObserver = new AutoDetachObserver(observer);
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.schedule(setDisposable);
} else {
setDisposable();
}
return autoDetachObserver;
}
__super__.call(this, s);
}
return AnonymousObservable;
}(Observable));
/** @private */
var AutoDetachObserver = (function (_super) {
inherits(AutoDetachObserver, _super);
function AutoDetachObserver(observer) {
_super.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var noError = false;
try {
this.observer.onNext(value);
noError = true;
} catch (e) {
throw e;
} finally {
if (!noError) {
this.dispose();
}
}
};
AutoDetachObserverPrototype.error = function (exn) {
try {
this.observer.onError(exn);
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.completed = function () {
try {
this.observer.onCompleted();
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); };
/* @private */
AutoDetachObserverPrototype.disposable = function (value) {
return arguments.length ? this.getDisposable() : setDisposable(value);
};
AutoDetachObserverPrototype.dispose = function () {
_super.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
/** @private */
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
/**
* @private
* @memberOf InnerSubscription
*/
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.exception) {
observer.onError(this.exception);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, _super);
/**
* Creates a subject.
* @constructor
*/
function Subject() {
_super.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
}
addProperties(Subject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
var ex = this.exception,
hv = this.hasValue,
v = this.value;
if (ex) {
observer.onError(ex);
} else if (hv) {
observer.onNext(v);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, __super__);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
__super__.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.value = null;
this.hasValue = false;
this.observers = [];
this.exception = null;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed.call(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var o, i, len;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
var os = this.observers.slice(0),
v = this.value,
hv = this.hasValue;
if (hv) {
for (i = 0, len = os.length; i < len; i++) {
o = os[i];
o.onNext(v);
o.onCompleted();
}
} else {
for (i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the error.
* @param {Mixed} error The Error to send to all observers.
*/
onError: function (error) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = error;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers = [];
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed.call(this);
if (this.isStopped) { return; }
this.value = value;
this.hasValue = true;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
inherits(AnonymousSubject, __super__);
function AnonymousSubject(observer, observable) {
this.observer = observer;
this.observable = observable;
__super__.call(this, this.observable.subscribe.bind(this.observable));
}
addProperties(AnonymousSubject.prototype, Observer, {
onCompleted: function () {
this.observer.onCompleted();
},
onError: function (exception) {
this.observer.onError(exception);
},
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
}.call(this));
|
ajax/libs/react/0.10.0/react.js | agraebe/cdnjs | /**
* React v0.10.0
*/
!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.React=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 AutoFocusMixin
* @typechecks static-only
*/
"use strict";
var focusNode = _dereq_("./focusNode");
var AutoFocusMixin = {
componentDidMount: function() {
if (this.props.autoFocus) {
focusNode(this.getDOMNode());
}
}
};
module.exports = AutoFocusMixin;
},{"./focusNode":100}],2:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 CSSProperty
*/
"use strict";
/**
* CSS properties which accept numbers but are not in units of "px".
*/
var isUnitlessNumber = {
columnCount: true,
fillOpacity: true,
flex: true,
flexGrow: true,
flexShrink: true,
fontWeight: true,
lineClamp: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
widows: true,
zIndex: true,
zoom: 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: {
backgroundImage: true,
backgroundPosition: true,
backgroundRepeat: true,
backgroundColor: 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
}
};
var CSSProperty = {
isUnitlessNumber: isUnitlessNumber,
shorthandPropertyExpansions: shorthandPropertyExpansions
};
module.exports = CSSProperty;
},{}],3:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 CSSPropertyOperations
* @typechecks static-only
*/
"use strict";
var CSSProperty = _dereq_("./CSSProperty");
var dangerousStyleValue = _dereq_("./dangerousStyleValue");
var escapeTextForBrowser = _dereq_("./escapeTextForBrowser");
var hyphenate = _dereq_("./hyphenate");
var memoizeStringOnly = _dereq_("./memoizeStringOnly");
var processStyleName = memoizeStringOnly(function(styleName) {
return escapeTextForBrowser(hyphenate(styleName));
});
/**
* 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.
*
* @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 (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;
}
var styleValue = dangerousStyleValue(styleName, styles[styleName]);
if (styleValue) {
style[styleName] = styleValue;
} else {
var expansion = 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] = '';
}
}
}
}
};
module.exports = CSSPropertyOperations;
},{"./CSSProperty":2,"./dangerousStyleValue":95,"./escapeTextForBrowser":98,"./hyphenate":110,"./memoizeStringOnly":120}],4:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ChangeEventPlugin
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPluginHub = _dereq_("./EventPluginHub");
var EventPropagators = _dereq_("./EventPropagators");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var ReactUpdates = _dereq_("./ReactUpdates");
var SyntheticEvent = _dereq_("./SyntheticEvent");
var isEventSupported = _dereq_("./isEventSupported");
var isTextInputElement = _dereq_("./isTextInputElement");
var keyOf = _dereq_("./keyOf");
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) {
return (
elem.nodeName === 'SELECT' ||
(elem.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
);
EventPropagators.accumulateTwoPhaseDispatches(event);
// If change and propertychange bubbled, we'd just bind to it like all the
// other events and have it go through ReactEventTopLevelCallback. 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();
}
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'
);
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 === '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) {
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
);
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
}
if (handleEventFunc) {
handleEventFunc(
topLevelType,
topLevelTarget,
topLevelTargetID
);
}
}
};
module.exports = ChangeEventPlugin;
},{"./EventConstants":14,"./EventPluginHub":16,"./EventPropagators":19,"./ExecutionEnvironment":20,"./ReactUpdates":71,"./SyntheticEvent":78,"./isEventSupported":113,"./isTextInputElement":115,"./keyOf":119}],5:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ClientReactRootIndex
* @typechecks
*/
"use strict";
var nextReactRootIndex = 0;
var ClientReactRootIndex = {
createReactRootIndex: function() {
return nextReactRootIndex++;
}
};
module.exports = ClientReactRootIndex;
},{}],6:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 CompositionEventPlugin
* @typechecks static-only
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPropagators = _dereq_("./EventPropagators");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var ReactInputSelection = _dereq_("./ReactInputSelection");
var SyntheticCompositionEvent = _dereq_("./SyntheticCompositionEvent");
var getTextContentAccessor = _dereq_("./getTextContentAccessor");
var keyOf = _dereq_("./keyOf");
var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
var START_KEYCODE = 229;
var useCompositionEvent = (
ExecutionEnvironment.canUseDOM &&
'CompositionEvent' in window
);
// In IE9+, we have access to composition events, but the data supplied
// by the native compositionend event may be incorrect. In Korean, for example,
// the compositionend event contains only one character regardless of
// how many characters have been composed since compositionstart.
// We therefore use the fallback data while still using the native
// events as triggers.
var useFallbackData = (
!useCompositionEvent ||
'documentMode' in document && document.documentMode > 8
);
var topLevelTypes = EventConstants.topLevelTypes;
var currentComposition = null;
// Events and their corresponding property names.
var eventTypes = {
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
]
}
};
/**
* 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 isFallbackStart(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 isFallbackEnd(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;
}
}
/**
* Helper class stores information about selection and document state
* so we can figure out what changed at a later date.
*
* @param {DOMEventTarget} root
*/
function FallbackCompositionState(root) {
this.root = root;
this.startSelection = ReactInputSelection.getSelection(root);
this.startValue = this.getText();
}
/**
* Get current text of input.
*
* @return {string}
*/
FallbackCompositionState.prototype.getText = function() {
return this.root.value || this.root[getTextContentAccessor()];
};
/**
* Text that has changed since the start of composition.
*
* @return {string}
*/
FallbackCompositionState.prototype.getData = function() {
var endValue = this.getText();
var prefixLength = this.startSelection.start;
var suffixLength = this.startValue.length - this.startSelection.end;
return endValue.substr(
prefixLength,
endValue.length - suffixLength - prefixLength
);
};
/**
* This plugin creates `onCompositionStart`, `onCompositionUpdate` and
* `onCompositionEnd` events on inputs, textareas and contentEditable
* nodes.
*/
var CompositionEventPlugin = {
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) {
var eventType;
var data;
if (useCompositionEvent) {
eventType = getCompositionEventType(topLevelType);
} else if (!currentComposition) {
if (isFallbackStart(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionStart;
}
} else if (isFallbackEnd(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionEnd;
}
if (useFallbackData) {
// The current composition is stored statically and must not be
// overwritten while composition continues.
if (!currentComposition && eventType === eventTypes.compositionStart) {
currentComposition = new FallbackCompositionState(topLevelTarget);
} else if (eventType === eventTypes.compositionEnd) {
if (currentComposition) {
data = currentComposition.getData();
currentComposition = null;
}
}
}
if (eventType) {
var event = SyntheticCompositionEvent.getPooled(
eventType,
topLevelTargetID,
nativeEvent
);
if (data) {
// Inject data generated from fallback path into the synthetic event.
// This matches the property of native CompositionEventInterface.
event.data = data;
}
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
}
};
module.exports = CompositionEventPlugin;
},{"./EventConstants":14,"./EventPropagators":19,"./ExecutionEnvironment":20,"./ReactInputSelection":52,"./SyntheticCompositionEvent":76,"./getTextContentAccessor":108,"./keyOf":119}],7:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 DOMChildrenOperations
* @typechecks static-only
*/
"use strict";
var Danger = _dereq_("./Danger");
var ReactMultiChildUpdateTypes = _dereq_("./ReactMultiChildUpdateTypes");
var getTextContentAccessor = _dereq_("./getTextContentAccessor");
/**
* The DOM property to use when setting text content.
*
* @type {string}
* @private
*/
var textContentAccessor = getTextContentAccessor();
/**
* 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) {
var childNodes = parentNode.childNodes;
if (childNodes[index] === childNode) {
return;
}
// If `childNode` is already a child of `parentNode`, remove it so that
// computing `childNodes[index]` takes into account the removal.
if (childNode.parentNode === parentNode) {
parentNode.removeChild(childNode);
}
if (index >= childNodes.length) {
parentNode.appendChild(childNode);
} else {
parentNode.insertBefore(childNode, childNodes[index]);
}
}
var updateTextContent;
if (textContentAccessor === 'textContent') {
/**
* Sets the text content of `node` to `text`.
*
* @param {DOMElement} node Node to change
* @param {string} text New text content
*/
updateTextContent = function(node, text) {
node.textContent = text;
};
} else {
/**
* Sets the text content of `node` to `text`.
*
* @param {DOMElement} node Node to change
* @param {string} text New text content
*/
updateTextContent = function(node, text) {
// In order to preserve newlines correctly, we can't use .innerText to set
// the contents (see #1080), so we empty the element then append a text node
while (node.firstChild) {
node.removeChild(node.firstChild);
}
if (text) {
var doc = node.ownerDocument || document;
node.appendChild(doc.createTextNode(text));
}
};
}
/**
* Operations for updating with DOM children.
*/
var DOMChildrenOperations = {
dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup,
updateTextContent: updateTextContent,
/**
* 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; update = updates[i]; 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;
initialChildren = initialChildren || {};
initialChildren[parentID] = initialChildren[parentID] || [];
initialChildren[parentID][updatedIndex] = updatedChild;
updatedChildren = updatedChildren || [];
updatedChildren.push(updatedChild);
}
}
var renderedMarkup = Danger.dangerouslyRenderMarkup(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; update = updates[k]; 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.TEXT_CONTENT:
updateTextContent(
update.parentNode,
update.textContent
);
break;
case ReactMultiChildUpdateTypes.REMOVE_NODE:
// Already removed by the for-loop above.
break;
}
}
}
};
module.exports = DOMChildrenOperations;
},{"./Danger":10,"./ReactMultiChildUpdateTypes":58,"./getTextContentAccessor":108}],8:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 DOMProperty
* @typechecks static-only
*/
/*jslint bitwise: true */
"use strict";
var invariant = _dereq_("./invariant");
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_POSITIVE_NUMERIC_VALUE: 0x10,
/**
* 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.
*
* 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 Properties = domPropertyConfig.Properties || {};
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) {
("production" !== "development" ? invariant(
!DOMProperty.isStandardName[propName],
'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(!DOMProperty.isStandardName[propName]));
DOMProperty.isStandardName[propName] = true;
var lowerCased = propName.toLowerCase();
DOMProperty.getPossibleStandardName[lowerCased] = propName;
var attributeName = DOMAttributeNames[propName];
if (attributeName) {
DOMProperty.getPossibleStandardName[attributeName] = propName;
}
DOMProperty.getAttributeName[propName] = attributeName || lowerCased;
DOMProperty.getPropertyName[propName] =
DOMPropertyNames[propName] || propName;
var mutationMethod = DOMMutationMethods[propName];
if (mutationMethod) {
DOMProperty.getMutationMethod[propName] = mutationMethod;
}
var propConfig = Properties[propName];
DOMProperty.mustUseAttribute[propName] =
propConfig & DOMPropertyInjection.MUST_USE_ATTRIBUTE;
DOMProperty.mustUseProperty[propName] =
propConfig & DOMPropertyInjection.MUST_USE_PROPERTY;
DOMProperty.hasSideEffects[propName] =
propConfig & DOMPropertyInjection.HAS_SIDE_EFFECTS;
DOMProperty.hasBooleanValue[propName] =
propConfig & DOMPropertyInjection.HAS_BOOLEAN_VALUE;
DOMProperty.hasPositiveNumericValue[propName] =
propConfig & DOMPropertyInjection.HAS_POSITIVE_NUMERIC_VALUE;
("production" !== "development" ? invariant(
!DOMProperty.mustUseAttribute[propName] ||
!DOMProperty.mustUseProperty[propName],
'DOMProperty: Cannot require using both attribute and property: %s',
propName
) : invariant(!DOMProperty.mustUseAttribute[propName] ||
!DOMProperty.mustUseProperty[propName]));
("production" !== "development" ? invariant(
DOMProperty.mustUseProperty[propName] ||
!DOMProperty.hasSideEffects[propName],
'DOMProperty: Properties that have side effects must use property: %s',
propName
) : invariant(DOMProperty.mustUseProperty[propName] ||
!DOMProperty.hasSideEffects[propName]));
("production" !== "development" ? invariant(
!DOMProperty.hasBooleanValue[propName] ||
!DOMProperty.hasPositiveNumericValue[propName],
'DOMProperty: Cannot have both boolean and positive numeric value: %s',
propName
) : invariant(!DOMProperty.hasBooleanValue[propName] ||
!DOMProperty.hasPositiveNumericValue[propName]));
}
}
};
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',
/**
* Checks whether a property name is a standard property.
* @type {Object}
*/
isStandardName: {},
/**
* Mapping from lowercase property names to the properly cased version, used
* to warn in the case of missing properties.
* @type {Object}
*/
getPossibleStandardName: {},
/**
* Mapping from normalized names to attribute names that differ. Attribute
* names are used when rendering markup or with `*Attribute()`.
* @type {Object}
*/
getAttributeName: {},
/**
* Mapping from normalized names to properties on DOM node instances.
* (This includes properties that mutate due to external factors.)
* @type {Object}
*/
getPropertyName: {},
/**
* Mapping from normalized names to mutation methods. This will only exist if
* mutation cannot be set simply by the property or `setAttribute()`.
* @type {Object}
*/
getMutationMethod: {},
/**
* Whether the property must be accessed and mutated as an object property.
* @type {Object}
*/
mustUseAttribute: {},
/**
* Whether the property must be accessed and mutated using `*Attribute()`.
* (This includes anything that fails `<propName> in <element>`.)
* @type {Object}
*/
mustUseProperty: {},
/**
* Whether or not setting a value causes side effects such as triggering
* resources to be loaded or text selection changes. We must ensure that
* the value is only set if it has changed.
* @type {Object}
*/
hasSideEffects: {},
/**
* Whether the property should be removed when set to a falsey value.
* @type {Object}
*/
hasBooleanValue: {},
/**
* Whether the property must be positive numeric or parse as a positive
* numeric and should be removed when set to a falsey value.
* @type {Object}
*/
hasPositiveNumericValue: {},
/**
* 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;
},{"./invariant":112}],9:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 DOMPropertyOperations
* @typechecks static-only
*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
var escapeTextForBrowser = _dereq_("./escapeTextForBrowser");
var memoizeStringOnly = _dereq_("./memoizeStringOnly");
var warning = _dereq_("./warning");
function shouldIgnoreValue(name, value) {
return value == null ||
DOMProperty.hasBooleanValue[name] && !value ||
DOMProperty.hasPositiveNumericValue[name] && (isNaN(value) || value < 1);
}
var processAttributeNameAndPrefix = memoizeStringOnly(function(name) {
return escapeTextForBrowser(name) + '="';
});
if ("production" !== "development") {
var reactProps = {
children: true,
dangerouslySetInnerHTML: true,
key: true,
ref: true
};
var warnedProperties = {};
var warnUnknownProperty = function(name) {
if (reactProps[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[lowerCasedName];
// For now, only warn when we have a suggested correction. This prevents
// logging too much when using transferPropsTo.
("production" !== "development" ? warning(
standardName == null,
'Unknown DOM property ' + name + '. Did you mean ' + standardName + '?'
) : null);
};
}
/**
* 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 processAttributeNameAndPrefix(DOMProperty.ID_ATTRIBUTE_NAME) +
escapeTextForBrowser(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) {
if (DOMProperty.isStandardName[name]) {
if (shouldIgnoreValue(name, value)) {
return '';
}
var attributeName = DOMProperty.getAttributeName[name];
if (DOMProperty.hasBooleanValue[name]) {
return escapeTextForBrowser(attributeName);
}
return processAttributeNameAndPrefix(attributeName) +
escapeTextForBrowser(value) + '"';
} else if (DOMProperty.isCustomAttribute(name)) {
if (value == null) {
return '';
}
return processAttributeNameAndPrefix(name) +
escapeTextForBrowser(value) + '"';
} else if ("production" !== "development") {
warnUnknownProperty(name);
}
return null;
},
/**
* Sets the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
* @param {*} value
*/
setValueForProperty: function(node, name, value) {
if (DOMProperty.isStandardName[name]) {
var mutationMethod = DOMProperty.getMutationMethod[name];
if (mutationMethod) {
mutationMethod(node, value);
} else if (shouldIgnoreValue(name, value)) {
this.deleteValueForProperty(node, name);
} else if (DOMProperty.mustUseAttribute[name]) {
node.setAttribute(DOMProperty.getAttributeName[name], '' + value);
} else {
var propName = DOMProperty.getPropertyName[name];
if (!DOMProperty.hasSideEffects[name] || node[propName] !== value) {
node[propName] = value;
}
}
} else if (DOMProperty.isCustomAttribute(name)) {
if (value == null) {
node.removeAttribute(DOMProperty.getAttributeName[name]);
} else {
node.setAttribute(name, '' + value);
}
} else if ("production" !== "development") {
warnUnknownProperty(name);
}
},
/**
* Deletes the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
*/
deleteValueForProperty: function(node, name) {
if (DOMProperty.isStandardName[name]) {
var mutationMethod = DOMProperty.getMutationMethod[name];
if (mutationMethod) {
mutationMethod(node, undefined);
} else if (DOMProperty.mustUseAttribute[name]) {
node.removeAttribute(DOMProperty.getAttributeName[name]);
} else {
var propName = DOMProperty.getPropertyName[name];
var defaultValue = DOMProperty.getDefaultValueForProperty(
node.nodeName,
propName
);
if (!DOMProperty.hasSideEffects[name] ||
node[propName] !== defaultValue) {
node[propName] = defaultValue;
}
}
} else if (DOMProperty.isCustomAttribute(name)) {
node.removeAttribute(name);
} else if ("production" !== "development") {
warnUnknownProperty(name);
}
}
};
module.exports = DOMPropertyOperations;
},{"./DOMProperty":8,"./escapeTextForBrowser":98,"./memoizeStringOnly":120,"./warning":134}],10:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 Danger
* @typechecks static-only
*/
/*jslint evil: true, sub: true */
"use strict";
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var createNodesFromMarkup = _dereq_("./createNodesFromMarkup");
var emptyFunction = _dereq_("./emptyFunction");
var getMarkupWrap = _dereq_("./getMarkupWrap");
var invariant = _dereq_("./invariant");
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) {
("production" !== "development" ? invariant(
ExecutionEnvironment.canUseDOM,
'dangerouslyRenderMarkup(...): Cannot render markup in a Worker ' +
'thread. This is likely a bug in the framework. Please report ' +
'immediately.'
) : invariant(ExecutionEnvironment.canUseDOM));
var nodeName;
var markupByNodeName = {};
// Group markup by `nodeName` if a wrap is necessary, else by '*'.
for (var i = 0; i < markupList.length; i++) {
("production" !== "development" ? invariant(
markupList[i],
'dangerouslyRenderMarkup(...): Missing markup.'
) : invariant(markupList[i]));
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.
for (var 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 (i = 0; i < renderNodes.length; ++i) {
var renderNode = renderNodes[i];
if (renderNode.hasAttribute &&
renderNode.hasAttribute(RESULT_INDEX_ATTR)) {
resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR);
renderNode.removeAttribute(RESULT_INDEX_ATTR);
("production" !== "development" ? invariant(
!resultList.hasOwnProperty(resultIndex),
'Danger: Assigning to an already-occupied result index.'
) : invariant(!resultList.hasOwnProperty(resultIndex)));
resultList[resultIndex] = renderNode;
// This should match resultList.length and markupList.length when
// we're done.
resultListAssignmentCount += 1;
} else if ("production" !== "development") {
console.error(
"Danger: Discarding unexpected node:",
renderNode
);
}
}
}
// Although resultList was populated out of order, it should now be a dense
// array.
("production" !== "development" ? invariant(
resultListAssignmentCount === resultList.length,
'Danger: Did not assign to every index of resultList.'
) : invariant(resultListAssignmentCount === resultList.length));
("production" !== "development" ? invariant(
resultList.length === markupList.length,
'Danger: Expected markup to render %s nodes, but rendered %s.',
markupList.length,
resultList.length
) : invariant(resultList.length === markupList.length));
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) {
("production" !== "development" ? invariant(
ExecutionEnvironment.canUseDOM,
'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a ' +
'worker thread. This is likely a bug in the framework. Please report ' +
'immediately.'
) : invariant(ExecutionEnvironment.canUseDOM));
("production" !== "development" ? invariant(markup, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : invariant(markup));
("production" !== "development" ? invariant(
oldChild.tagName.toLowerCase() !== 'html',
'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 renderComponentToString().'
) : invariant(oldChild.tagName.toLowerCase() !== 'html'));
var newChild = createNodesFromMarkup(markup, emptyFunction)[0];
oldChild.parentNode.replaceChild(newChild, oldChild);
}
};
module.exports = Danger;
},{"./ExecutionEnvironment":20,"./createNodesFromMarkup":93,"./emptyFunction":96,"./getMarkupWrap":105,"./invariant":112}],11:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 DefaultDOMPropertyConfig
*/
/*jslint bitwise: true*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
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_POSITIVE_NUMERIC_VALUE =
DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE;
var DefaultDOMPropertyConfig = {
isCustomAttribute: RegExp.prototype.test.bind(
/^(data|aria)-[a-z_][a-z\d_.\-]*$/
),
Properties: {
/**
* Standard Properties
*/
accept: 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 AutoFocusMixin
// autoFocus: HAS_BOOLEAN_VALUE,
autoPlay: HAS_BOOLEAN_VALUE,
cellPadding: null,
cellSpacing: null,
charSet: MUST_USE_ATTRIBUTE,
checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
className: 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,
crossOrigin: null,
data: null, // For `<object />` acts as `src`.
dateTime: MUST_USE_ATTRIBUTE,
defer: HAS_BOOLEAN_VALUE,
dir: null,
disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
download: null,
draggable: null,
encType: null,
form: MUST_USE_ATTRIBUTE,
formNoValidate: HAS_BOOLEAN_VALUE,
frameBorder: MUST_USE_ATTRIBUTE,
height: MUST_USE_ATTRIBUTE,
hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
href: null,
hrefLang: null,
htmlFor: null,
httpEquiv: null,
icon: null,
id: MUST_USE_PROPERTY,
label: null,
lang: null,
list: null,
loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
max: null,
maxLength: MUST_USE_ATTRIBUTE,
mediaGroup: null,
method: null,
min: null,
multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
name: null,
noValidate: HAS_BOOLEAN_VALUE,
pattern: null,
placeholder: null,
poster: null,
preload: null,
radioGroup: null,
readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
rel: null,
required: HAS_BOOLEAN_VALUE,
role: MUST_USE_ATTRIBUTE,
rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
rowSpan: null,
sandbox: null,
scope: null,
scrollLeft: MUST_USE_PROPERTY,
scrollTop: MUST_USE_PROPERTY,
seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
span: HAS_POSITIVE_NUMERIC_VALUE,
spellCheck: null,
src: null,
srcDoc: MUST_USE_PROPERTY,
srcSet: null,
step: null,
style: null,
tabIndex: null,
target: null,
title: null,
type: null,
value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS,
width: MUST_USE_ATTRIBUTE,
wmode: MUST_USE_ATTRIBUTE,
/**
* Non-standard Properties
*/
autoCapitalize: null, // Supported in Mobile Safari for keyboard hints
autoCorrect: null, // Supported in Mobile Safari for keyboard hints
property: null, // Supports OG in meta tags
/**
* SVG Properties
*/
cx: MUST_USE_ATTRIBUTE,
cy: MUST_USE_ATTRIBUTE,
d: MUST_USE_ATTRIBUTE,
fill: MUST_USE_ATTRIBUTE,
fx: MUST_USE_ATTRIBUTE,
fy: MUST_USE_ATTRIBUTE,
gradientTransform: MUST_USE_ATTRIBUTE,
gradientUnits: MUST_USE_ATTRIBUTE,
offset: MUST_USE_ATTRIBUTE,
points: 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,
strokeLinecap: 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,
y1: MUST_USE_ATTRIBUTE,
y2: MUST_USE_ATTRIBUTE,
y: MUST_USE_ATTRIBUTE
},
DOMAttributeNames: {
className: 'class',
gradientTransform: 'gradientTransform',
gradientUnits: 'gradientUnits',
htmlFor: 'for',
spreadMethod: 'spreadMethod',
stopColor: 'stop-color',
stopOpacity: 'stop-opacity',
strokeLinecap: 'stroke-linecap',
strokeWidth: 'stroke-width',
textAnchor: 'text-anchor',
viewBox: 'viewBox'
},
DOMPropertyNames: {
autoCapitalize: 'autocapitalize',
autoComplete: 'autocomplete',
autoCorrect: 'autocorrect',
autoFocus: 'autofocus',
autoPlay: 'autoplay',
encType: 'enctype',
hrefLang: 'hreflang',
radioGroup: 'radiogroup',
spellCheck: 'spellcheck',
srcDoc: 'srcdoc',
srcSet: 'srcset'
}
};
module.exports = DefaultDOMPropertyConfig;
},{"./DOMProperty":8}],12:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 DefaultEventPluginOrder
*/
"use strict";
var keyOf = _dereq_("./keyOf");
/**
* 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({CompositionEventPlugin: null}),
keyOf({AnalyticsEventPlugin: null}),
keyOf({MobileSafariClickEventPlugin: null})
];
module.exports = DefaultEventPluginOrder;
},{"./keyOf":119}],13:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 EnterLeaveEventPlugin
* @typechecks static-only
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPropagators = _dereq_("./EventPropagators");
var SyntheticMouseEvent = _dereq_("./SyntheticMouseEvent");
var ReactMount = _dereq_("./ReactMount");
var keyOf = _dereq_("./keyOf");
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) {
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, to;
if (topLevelType === topLevelTypes.topMouseOut) {
from = topLevelTarget;
to =
getFirstReactDOM(nativeEvent.relatedTarget || nativeEvent.toElement) ||
win;
} else {
from = win;
to = topLevelTarget;
}
if (from === to) {
// Nothing pertains to our managed components.
return null;
}
var fromID = from ? ReactMount.getID(from) : '';
var toID = to ? ReactMount.getID(to) : '';
var leave = SyntheticMouseEvent.getPooled(
eventTypes.mouseLeave,
fromID,
nativeEvent
);
leave.type = 'mouseleave';
leave.target = from;
leave.relatedTarget = to;
var enter = SyntheticMouseEvent.getPooled(
eventTypes.mouseEnter,
toID,
nativeEvent
);
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;
},{"./EventConstants":14,"./EventPropagators":19,"./ReactMount":55,"./SyntheticMouseEvent":81,"./keyOf":119}],14:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 EventConstants
*/
"use strict";
var keyMirror = _dereq_("./keyMirror");
var PropagationPhases = keyMirror({bubbled: null, captured: null});
/**
* Types of raw signals from the browser caught at the top level.
*/
var topLevelTypes = keyMirror({
topBlur: null,
topChange: null,
topClick: null,
topCompositionEnd: null,
topCompositionStart: null,
topCompositionUpdate: null,
topContextMenu: null,
topCopy: null,
topCut: null,
topDoubleClick: null,
topDrag: null,
topDragEnd: null,
topDragEnter: null,
topDragExit: null,
topDragLeave: null,
topDragOver: null,
topDragStart: null,
topDrop: null,
topError: null,
topFocus: null,
topInput: null,
topKeyDown: null,
topKeyPress: null,
topKeyUp: null,
topLoad: null,
topMouseDown: null,
topMouseMove: null,
topMouseOut: null,
topMouseOver: null,
topMouseUp: null,
topPaste: null,
topReset: null,
topScroll: null,
topSelectionChange: null,
topSubmit: null,
topTouchCancel: null,
topTouchEnd: null,
topTouchMove: null,
topTouchStart: null,
topWheel: null
});
var EventConstants = {
topLevelTypes: topLevelTypes,
PropagationPhases: PropagationPhases
};
module.exports = EventConstants;
},{"./keyMirror":118}],15:[function(_dereq_,module,exports){
/**
* @providesModule EventListener
*/
var emptyFunction = _dereq_("./emptyFunction");
/**
* 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(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) {
if ("production" !== "development") {
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
};
} else {
target.addEventListener(eventType, callback, true);
return {
remove: function() {
target.removeEventListener(eventType, callback, true);
}
};
}
}
};
module.exports = EventListener;
},{"./emptyFunction":96}],16:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 EventPluginHub
*/
"use strict";
var EventPluginRegistry = _dereq_("./EventPluginRegistry");
var EventPluginUtils = _dereq_("./EventPluginUtils");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var accumulate = _dereq_("./accumulate");
var forEachAccumulated = _dereq_("./forEachAccumulated");
var invariant = _dereq_("./invariant");
var isEventSupported = _dereq_("./isEventSupported");
var monitorCodeUse = _dereq_("./monitorCodeUse");
/**
* 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.
* @private
*/
var executeDispatchesAndRelease = function(event) {
if (event) {
var executeDispatch = EventPluginUtils.executeDispatch;
// Plugins can provide custom behavior when dispatching events.
var PluginModule = EventPluginRegistry.getPluginModuleForEvent(event);
if (PluginModule && PluginModule.executeDispatch) {
executeDispatch = PluginModule.executeDispatch;
}
EventPluginUtils.executeDispatchesInOrder(event, executeDispatch);
if (!event.isPersistent()) {
event.constructor.release(event);
}
}
};
/**
* - `InstanceHandle`: [required] Module that performs logical traversals of DOM
* hierarchy given ids of the logical DOM elements involved.
*/
var InstanceHandle = null;
function validateInstanceHandle() {
var invalid = !InstanceHandle||
!InstanceHandle.traverseTwoPhase ||
!InstanceHandle.traverseEnterLeave;
if (invalid) {
throw new Error('InstanceHandle not injected before use!');
}
}
/**
* 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 ("production" !== "development") {
validateInstanceHandle();
}
},
getInstanceHandle: function() {
if ("production" !== "development") {
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) {
("production" !== "development" ? invariant(
ExecutionEnvironment.canUseDOM,
'Cannot call putListener() in a non-DOM environment.'
) : invariant(ExecutionEnvironment.canUseDOM));
("production" !== "development" ? invariant(
!listener || typeof listener === 'function',
'Expected %s listener to be a function, instead got type %s',
registrationName, typeof listener
) : invariant(!listener || typeof listener === 'function'));
if ("production" !== "development") {
// IE8 has no API for event capturing and the `onScroll` event doesn't
// bubble.
if (registrationName === 'onScroll' &&
!isEventSupported('scroll', true)) {
monitorCodeUse('react_no_scroll_event');
console.warn('This browser doesn\'t support the `onScroll` event');
}
}
var bankForRegistrationName =
listenerBank[registrationName] || (listenerBank[registrationName] = {});
bankForRegistrationName[id] = 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 bankForRegistrationName = listenerBank[registrationName];
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) {
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) {
var events;
var plugins = EventPluginRegistry.plugins;
for (var i = 0, l = plugins.length; i < l; 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
);
if (extractedEvents) {
events = accumulate(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 = accumulate(eventQueue, events);
}
},
/**
* Dispatches all synthetic events on the event queue.
*
* @internal
*/
processEventQueue: function() {
// Set `eventQueue` to null before processing it so that we can tell if more
// events get enqueued while processing.
var processingEventQueue = eventQueue;
eventQueue = null;
forEachAccumulated(processingEventQueue, executeDispatchesAndRelease);
("production" !== "development" ? invariant(
!eventQueue,
'processEventQueue(): Additional events were enqueued while processing ' +
'an event queue. Support for this has not yet been implemented.'
) : invariant(!eventQueue));
},
/**
* These are needed for tests only. Do not use!
*/
__purge: function() {
listenerBank = {};
},
__getListenerBank: function() {
return listenerBank;
}
};
module.exports = EventPluginHub;
},{"./EventPluginRegistry":17,"./EventPluginUtils":18,"./ExecutionEnvironment":20,"./accumulate":87,"./forEachAccumulated":101,"./invariant":112,"./isEventSupported":113,"./monitorCodeUse":125}],17:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 EventPluginRegistry
* @typechecks static-only
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* 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);
("production" !== "development" ? invariant(
pluginIndex > -1,
'EventPluginRegistry: Cannot inject event plugins that do not exist in ' +
'the plugin ordering, `%s`.',
pluginName
) : invariant(pluginIndex > -1));
if (EventPluginRegistry.plugins[pluginIndex]) {
continue;
}
("production" !== "development" ? invariant(
PluginModule.extractEvents,
'EventPluginRegistry: Event plugins must implement an `extractEvents` ' +
'method, but `%s` does not.',
pluginName
) : invariant(PluginModule.extractEvents));
EventPluginRegistry.plugins[pluginIndex] = PluginModule;
var publishedEvents = PluginModule.eventTypes;
for (var eventName in publishedEvents) {
("production" !== "development" ? invariant(
publishEventForPlugin(
publishedEvents[eventName],
PluginModule,
eventName
),
'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.',
eventName,
pluginName
) : invariant(publishEventForPlugin(
publishedEvents[eventName],
PluginModule,
eventName
)));
}
}
}
/**
* 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) {
("production" !== "development" ? invariant(
!EventPluginRegistry.eventNameDispatchConfigs[eventName],
'EventPluginHub: More than one plugin attempted to publish the same ' +
'event name, `%s`.',
eventName
) : invariant(!EventPluginRegistry.eventNameDispatchConfigs[eventName]));
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) {
("production" !== "development" ? invariant(
!EventPluginRegistry.registrationNameModules[registrationName],
'EventPluginHub: More than one plugin attempted to publish the same ' +
'registration name, `%s`.',
registrationName
) : invariant(!EventPluginRegistry.registrationNameModules[registrationName]));
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) {
("production" !== "development" ? invariant(
!EventPluginOrder,
'EventPluginRegistry: Cannot inject event plugin ordering more than once.'
) : invariant(!EventPluginOrder));
// 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[pluginName] !== PluginModule) {
("production" !== "development" ? invariant(
!namesToPlugins[pluginName],
'EventPluginRegistry: Cannot inject two different event plugins ' +
'using the same name, `%s`.',
pluginName
) : invariant(!namesToPlugins[pluginName]));
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;
},{"./invariant":112}],18:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 EventPluginUtils
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var invariant = _dereq_("./invariant");
/**
* 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 ("production" !== "development") {
("production" !== "development" ? invariant(
InjectedMount && InjectedMount.getNode,
'EventPluginUtils.injection.injectMount(...): Injected Mount module ' +
'is missing getNode.'
) : invariant(InjectedMount && InjectedMount.getNode));
}
}
};
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 ("production" !== "development") {
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;
("production" !== "development" ? invariant(
idsIsArr === listenersIsArr && IDsLen === listenersLen,
'EventPluginUtils: Invalid `event`.'
) : invariant(idsIsArr === listenersIsArr && IDsLen === listenersLen));
};
}
/**
* Invokes `cb(event, listener, id)`. Avoids using call if no scope is
* provided. The `(listener,id)` pair effectively forms the "dispatch" but are
* kept separate to conserve memory.
*/
function forEachEventDispatch(event, cb) {
var dispatchListeners = event._dispatchListeners;
var dispatchIDs = event._dispatchIDs;
if ("production" !== "development") {
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.
cb(event, dispatchListeners[i], dispatchIDs[i]);
}
} else if (dispatchListeners) {
cb(event, dispatchListeners, dispatchIDs);
}
}
/**
* Default implementation of PluginModule.executeDispatch().
* @param {SyntheticEvent} SyntheticEvent to handle
* @param {function} Application-level callback
* @param {string} domID DOM id to pass to the callback.
*/
function executeDispatch(event, listener, domID) {
event.currentTarget = injection.Mount.getNode(domID);
var returnValue = listener(event, domID);
event.currentTarget = null;
return returnValue;
}
/**
* Standard/simple iteration through an event's collected dispatches.
*/
function executeDispatchesInOrder(event, executeDispatch) {
forEachEventDispatch(event, executeDispatch);
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 id of the first dispatch execution who's listener returns true, or
* null if no listener returned true.
*/
function executeDispatchesInOrderStopAtTrue(event) {
var dispatchListeners = event._dispatchListeners;
var dispatchIDs = event._dispatchIDs;
if ("production" !== "development") {
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;
}
/**
* 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 ("production" !== "development") {
validateEventDispatches(event);
}
var dispatchListener = event._dispatchListeners;
var dispatchID = event._dispatchIDs;
("production" !== "development" ? invariant(
!Array.isArray(dispatchListener),
'executeDirectDispatch(...): Invalid `event`.'
) : invariant(!Array.isArray(dispatchListener)));
var res = dispatchListener ?
dispatchListener(event, dispatchID) :
null;
event._dispatchListeners = null;
event._dispatchIDs = null;
return res;
}
/**
* @param {SyntheticEvent} event
* @return {bool} 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,
executeDispatch: executeDispatch,
executeDispatchesInOrder: executeDispatchesInOrder,
executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue,
hasDispatches: hasDispatches,
injection: injection,
useTouchEvents: false
};
module.exports = EventPluginUtils;
},{"./EventConstants":14,"./invariant":112}],19:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 EventPropagators
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPluginHub = _dereq_("./EventPluginHub");
var accumulate = _dereq_("./accumulate");
var forEachAccumulated = _dereq_("./forEachAccumulated");
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 ("production" !== "development") {
if (!domID) {
throw new Error('Dispatching id must not be null');
}
}
var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured;
var listener = listenerAtPhase(domID, event, phase);
if (listener) {
event._dispatchListeners = accumulate(event._dispatchListeners, listener);
event._dispatchIDs = accumulate(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 can not 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
);
}
}
/**
* 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 = accumulate(event._dispatchListeners, listener);
event._dispatchIDs = accumulate(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 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,
accumulateDirectDispatches: accumulateDirectDispatches,
accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches
};
module.exports = EventPropagators;
},{"./EventConstants":14,"./EventPluginHub":16,"./accumulate":87,"./forEachAccumulated":101}],20:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ExecutionEnvironment
*/
/*jslint evil: true */
"use strict";
var canUseDOM = typeof window !== 'undefined';
/**
* 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),
isInWorker: !canUseDOM // For now, this is true - might change in the future.
};
module.exports = ExecutionEnvironment;
},{}],21:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 LinkedValueUtils
* @typechecks static-only
*/
"use strict";
var ReactPropTypes = _dereq_("./ReactPropTypes");
var invariant = _dereq_("./invariant");
var warning = _dereq_("./warning");
var hasReadOnlyValue = {
'button': true,
'checkbox': true,
'image': true,
'hidden': true,
'radio': true,
'reset': true,
'submit': true
};
function _assertSingleLink(input) {
("production" !== "development" ? invariant(
input.props.checkedLink == null || input.props.valueLink == null,
'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(input.props.checkedLink == null || input.props.valueLink == null));
}
function _assertValueLink(input) {
_assertSingleLink(input);
("production" !== "development" ? invariant(
input.props.value == null && input.props.onChange == null,
'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(input.props.value == null && input.props.onChange == null));
}
function _assertCheckedLink(input) {
_assertSingleLink(input);
("production" !== "development" ? invariant(
input.props.checked == null && input.props.onChange == null,
'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(input.props.checked == null && input.props.onChange == null));
}
/**
* @param {SyntheticEvent} e change event to handle
*/
function _handleLinkedValueChange(e) {
/*jshint validthis:true */
this.props.valueLink.requestChange(e.target.value);
}
/**
* @param {SyntheticEvent} e change event to handle
*/
function _handleLinkedCheckChange(e) {
/*jshint validthis:true */
this.props.checkedLink.requestChange(e.target.checked);
}
/**
* Provide a linked `value` attribute for controlled forms. You should not use
* this outside of the ReactDOM controlled form components.
*/
var LinkedValueUtils = {
Mixin: {
propTypes: {
value: function(props, propName, componentName) {
if ("production" !== "development") {
("production" !== "development" ? warning(
!props[propName] ||
hasReadOnlyValue[props.type] ||
props.onChange ||
props.readOnly ||
props.disabled,
'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`.'
) : null);
}
},
checked: function(props, propName, componentName) {
if ("production" !== "development") {
("production" !== "development" ? warning(
!props[propName] ||
props.onChange ||
props.readOnly ||
props.disabled,
'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`.'
) : null);
}
},
onChange: ReactPropTypes.func
}
},
/**
* @param {ReactComponent} input Form component
* @return {*} current value of the input either from value prop or link.
*/
getValue: function(input) {
if (input.props.valueLink) {
_assertValueLink(input);
return input.props.valueLink.value;
}
return input.props.value;
},
/**
* @param {ReactComponent} input Form component
* @return {*} current checked status of the input either from checked prop
* or link.
*/
getChecked: function(input) {
if (input.props.checkedLink) {
_assertCheckedLink(input);
return input.props.checkedLink.value;
}
return input.props.checked;
},
/**
* @param {ReactComponent} input Form component
* @return {function} change callback either from onChange prop or link.
*/
getOnChange: function(input) {
if (input.props.valueLink) {
_assertValueLink(input);
return _handleLinkedValueChange;
} else if (input.props.checkedLink) {
_assertCheckedLink(input);
return _handleLinkedCheckChange;
}
return input.props.onChange;
}
};
module.exports = LinkedValueUtils;
},{"./ReactPropTypes":64,"./invariant":112,"./warning":134}],22:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 MobileSafariClickEventPlugin
* @typechecks static-only
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var emptyFunction = _dereq_("./emptyFunction");
var topLevelTypes = EventConstants.topLevelTypes;
/**
* 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.
*
* This particular plugin works around the bug by attaching an empty click
* listener on `touchstart` (which does fire on every element).
*/
var MobileSafariClickEventPlugin = {
eventTypes: 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 {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
if (topLevelType === topLevelTypes.topTouchStart) {
var target = nativeEvent.target;
if (target && !target.onclick) {
target.onclick = emptyFunction;
}
}
}
};
module.exports = MobileSafariClickEventPlugin;
},{"./EventConstants":14,"./emptyFunction":96}],23:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 PooledClass
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* Static poolers. Several custom versions for each potential number of
* arguments. A completely generic pooler is easy to implement, but would
* require accessing the `arguments` object. In each of these, `this` refers to
* the Class itself, not an instance. If any others are needed, simply add them
* here, or in their own files.
*/
var oneArgumentPooler = function(copyFieldsFrom) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, copyFieldsFrom);
return instance;
} else {
return new Klass(copyFieldsFrom);
}
};
var twoArgumentPooler = function(a1, a2) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2);
return instance;
} else {
return new Klass(a1, a2);
}
};
var threeArgumentPooler = function(a1, a2, a3) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3);
return instance;
} else {
return new Klass(a1, a2, a3);
}
};
var 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;
("production" !== "development" ? invariant(
instance instanceof Klass,
'Trying to release an instance into a pool of a different type.'
) : invariant(instance instanceof Klass));
if (instance.destructor) {
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,
fiveArgumentPooler: fiveArgumentPooler
};
module.exports = PooledClass;
},{"./invariant":112}],24:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 React
*/
"use strict";
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var EventPluginUtils = _dereq_("./EventPluginUtils");
var ReactChildren = _dereq_("./ReactChildren");
var ReactComponent = _dereq_("./ReactComponent");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactContext = _dereq_("./ReactContext");
var ReactCurrentOwner = _dereq_("./ReactCurrentOwner");
var ReactDOM = _dereq_("./ReactDOM");
var ReactDOMComponent = _dereq_("./ReactDOMComponent");
var ReactDefaultInjection = _dereq_("./ReactDefaultInjection");
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactMount = _dereq_("./ReactMount");
var ReactMultiChild = _dereq_("./ReactMultiChild");
var ReactPerf = _dereq_("./ReactPerf");
var ReactPropTypes = _dereq_("./ReactPropTypes");
var ReactServerRendering = _dereq_("./ReactServerRendering");
var ReactTextComponent = _dereq_("./ReactTextComponent");
var onlyChild = _dereq_("./onlyChild");
ReactDefaultInjection.inject();
var React = {
Children: {
map: ReactChildren.map,
forEach: ReactChildren.forEach,
only: onlyChild
},
DOM: ReactDOM,
PropTypes: ReactPropTypes,
initializeTouchEvents: function(shouldUseTouch) {
EventPluginUtils.useTouchEvents = shouldUseTouch;
},
createClass: ReactCompositeComponent.createClass,
constructAndRenderComponent: ReactMount.constructAndRenderComponent,
constructAndRenderComponentByID: ReactMount.constructAndRenderComponentByID,
renderComponent: ReactPerf.measure(
'React',
'renderComponent',
ReactMount.renderComponent
),
renderComponentToString: ReactServerRendering.renderComponentToString,
renderComponentToStaticMarkup:
ReactServerRendering.renderComponentToStaticMarkup,
unmountComponentAtNode: ReactMount.unmountComponentAtNode,
isValidClass: ReactCompositeComponent.isValidClass,
isValidComponent: ReactComponent.isValidComponent,
withContext: ReactContext.withContext,
__internals: {
Component: ReactComponent,
CurrentOwner: ReactCurrentOwner,
DOMComponent: ReactDOMComponent,
DOMPropertyOperations: DOMPropertyOperations,
InstanceHandles: ReactInstanceHandles,
Mount: ReactMount,
MultiChild: ReactMultiChild,
TextComponent: ReactTextComponent
}
};
if ("production" !== "development") {
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
if (ExecutionEnvironment.canUseDOM &&
window.top === window.self &&
navigator.userAgent.indexOf('Chrome') > -1) {
console.debug(
'Download the React DevTools for a better development experience: ' +
'http://fb.me/react-devtools'
);
}
}
// Version exists only in the open-source version of React, not in Facebook's
// internal version.
React.version = '0.10.0';
module.exports = React;
},{"./DOMPropertyOperations":9,"./EventPluginUtils":18,"./ExecutionEnvironment":20,"./ReactChildren":26,"./ReactComponent":27,"./ReactCompositeComponent":29,"./ReactContext":30,"./ReactCurrentOwner":31,"./ReactDOM":32,"./ReactDOMComponent":34,"./ReactDefaultInjection":44,"./ReactInstanceHandles":53,"./ReactMount":55,"./ReactMultiChild":57,"./ReactPerf":60,"./ReactPropTypes":64,"./ReactServerRendering":68,"./ReactTextComponent":70,"./onlyChild":128}],25:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactBrowserComponentMixin
*/
"use strict";
var ReactMount = _dereq_("./ReactMount");
var invariant = _dereq_("./invariant");
var ReactBrowserComponentMixin = {
/**
* Returns the DOM node rendered by this component.
*
* @return {DOMElement} The root node of this component.
* @final
* @protected
*/
getDOMNode: function() {
("production" !== "development" ? invariant(
this.isMounted(),
'getDOMNode(): A component must be mounted to have a DOM node.'
) : invariant(this.isMounted()));
return ReactMount.getNode(this._rootNodeID);
}
};
module.exports = ReactBrowserComponentMixin;
},{"./ReactMount":55,"./invariant":112}],26:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactChildren
*/
"use strict";
var PooledClass = _dereq_("./PooledClass");
var invariant = _dereq_("./invariant");
var traverseAllChildren = _dereq_("./traverseAllChildren");
var twoArgumentPooler = PooledClass.twoArgumentPooler;
var threeArgumentPooler = PooledClass.threeArgumentPooler;
/**
* 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.forEachFunction = forEachFunction;
this.forEachContext = forEachContext;
}
PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler);
function forEachSingleChild(traverseContext, child, name, i) {
var forEachBookKeeping = traverseContext;
forEachBookKeeping.forEachFunction.call(
forEachBookKeeping.forEachContext, child, i);
}
/**
* 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, mapFunction, mapContext) {
this.mapResult = mapResult;
this.mapFunction = mapFunction;
this.mapContext = mapContext;
}
PooledClass.addPoolingTo(MapBookKeeping, threeArgumentPooler);
function mapSingleChildIntoContext(traverseContext, child, name, i) {
var mapBookKeeping = traverseContext;
var mapResult = mapBookKeeping.mapResult;
var mappedChild =
mapBookKeeping.mapFunction.call(mapBookKeeping.mapContext, child, i);
// We found a component instance
("production" !== "development" ? invariant(
!mapResult.hasOwnProperty(name),
'ReactChildren.map(...): Encountered two children with the same key, ' +
'`%s`. Children keys must be unique.',
name
) : invariant(!mapResult.hasOwnProperty(name)));
mapResult[name] = mappedChild;
}
/**
* Maps children that are typically specified as `props.children`.
*
* The provided mapFunction(child, key, index) will be called for each
* leaf child.
*
* TODO: This may likely break any calls to `ReactChildren.map` that were
* previously relying on the fact that we guarded against null children.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} mapFunction.
* @param {*} mapContext Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/
function mapChildren(children, func, context) {
if (children == null) {
return children;
}
var mapResult = {};
var traverseContext = MapBookKeeping.getPooled(mapResult, func, context);
traverseAllChildren(children, mapSingleChildIntoContext, traverseContext);
MapBookKeeping.release(traverseContext);
return mapResult;
}
var ReactChildren = {
forEach: forEachChildren,
map: mapChildren
};
module.exports = ReactChildren;
},{"./PooledClass":23,"./invariant":112,"./traverseAllChildren":133}],27:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactComponent
*/
"use strict";
var ReactCurrentOwner = _dereq_("./ReactCurrentOwner");
var ReactOwner = _dereq_("./ReactOwner");
var ReactUpdates = _dereq_("./ReactUpdates");
var invariant = _dereq_("./invariant");
var keyMirror = _dereq_("./keyMirror");
var merge = _dereq_("./merge");
var monitorCodeUse = _dereq_("./monitorCodeUse");
/**
* Every React component is in one of these life cycles.
*/
var ComponentLifeCycle = keyMirror({
/**
* Mounted components have a DOM node representation and are capable of
* receiving new props.
*/
MOUNTED: null,
/**
* Unmounted components are inactive and cannot receive new props.
*/
UNMOUNTED: null
});
/**
* 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 ownerHasExplicitKeyWarning = {};
var ownerHasPropertyWarning = {};
var ownerHasMonitoredObjectMap = {};
var NUMERIC_PROPERTY_REGEX = /^\d+$/;
var injected = false;
/**
* 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.
*
* @private
*/
var unmountIDFromEnvironment = null;
/**
* The "image" of a component tree, is the platform specific (typically
* serialized) data that represents a tree of lower level UI building blocks.
* On the web, this "image" is HTML markup which describes a construction of
* low level `div` and `span` nodes. Other platforms may have different
* encoding of this "image". This must be injected.
*
* @private
*/
var mountImageIntoNode = null;
/**
* Warn if the component doesn't have an explicit key assigned to it.
* This component 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 {ReactComponent} component Component that requires a key.
*/
function validateExplicitKey(component) {
if (component.__keyValidated__ || component.props.key != null) {
return;
}
component.__keyValidated__ = true;
// We can't provide friendly warnings for top level components.
if (!ReactCurrentOwner.current) {
return;
}
// Name of the component whose render method tried to pass children.
var currentName = ReactCurrentOwner.current.constructor.displayName;
if (ownerHasExplicitKeyWarning.hasOwnProperty(currentName)) {
return;
}
ownerHasExplicitKeyWarning[currentName] = true;
var message = 'Each child in an array should have a unique "key" prop. ' +
'Check the render method of ' + currentName + '.';
var childOwnerName = null;
if (!component.isOwnedBy(ReactCurrentOwner.current)) {
// Name of the component that originally created this child.
childOwnerName =
component._owner &&
component._owner.constructor.displayName;
// 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.
message += ' It was passed a child from ' + childOwnerName + '.';
}
message += ' See http://fb.me/react-warning-keys for more information.';
monitorCodeUse('react_key_warning', {
component: currentName,
componentOwner: childOwnerName
});
console.warn(message);
}
/**
* Warn if the key is being defined as an object property but has an incorrect
* value.
*
* @internal
* @param {string} name Property name of the key.
* @param {ReactComponent} component Component that requires a key.
*/
function validatePropertyKey(name) {
if (NUMERIC_PROPERTY_REGEX.test(name)) {
// Name of the component whose render method tried to pass children.
var currentName = ReactCurrentOwner.current.constructor.displayName;
if (ownerHasPropertyWarning.hasOwnProperty(currentName)) {
return;
}
ownerHasPropertyWarning[currentName] = true;
monitorCodeUse('react_numeric_key_warning');
console.warn(
'Child objects should have non-numeric keys so ordering is preserved. ' +
'Check the render method of ' + currentName + '. ' +
'See http://fb.me/react-warning-keys for more information.'
);
}
}
/**
* Log that we're using an object map. We're considering deprecating this
* feature and replace it with proper Map and ImmutableMap data structures.
*
* @internal
*/
function monitorUseOfObjectMap() {
// Name of the component whose render method tried to pass children.
// We only use this to avoid spewing the logs. We lose additional
// owner stacks but hopefully one level is enough to trace the source.
var currentName = (ReactCurrentOwner.current &&
ReactCurrentOwner.current.constructor.displayName) || '';
if (ownerHasMonitoredObjectMap.hasOwnProperty(currentName)) {
return;
}
ownerHasMonitoredObjectMap[currentName] = true;
monitorCodeUse('react_object_map_children');
}
/**
* Ensure that every component 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 {*} component Statically passed child of any type.
* @return {boolean}
*/
function validateChildKeys(component) {
if (Array.isArray(component)) {
for (var i = 0; i < component.length; i++) {
var child = component[i];
if (ReactComponent.isValidComponent(child)) {
validateExplicitKey(child);
}
}
} else if (ReactComponent.isValidComponent(component)) {
// This component was passed in a valid location.
component.__keyValidated__ = true;
} else if (component && typeof component === 'object') {
monitorUseOfObjectMap();
for (var name in component) {
validatePropertyKey(name, component);
}
}
}
/**
* Components are the basic units of composition in React.
*
* Every component accepts a set of keyed input parameters known as "props" that
* are initialized by the constructor. Once a component is mounted, the props
* can be mutated using `setProps` or `replaceProps`.
*
* Every component is capable of the following operations:
*
* `mountComponent`
* Initializes the component, renders markup, and registers event listeners.
*
* `receiveComponent`
* Updates the rendered DOM nodes to match the given component.
*
* `unmountComponent`
* Releases any resources allocated by this component.
*
* Components can also be "owned" by other components. Being owned by another
* component means being constructed by that component. This is different from
* being the child of a component, which means having a DOM representation that
* is a child of the DOM representation of that component.
*
* @class ReactComponent
*/
var ReactComponent = {
injection: {
injectEnvironment: function(ReactComponentEnvironment) {
("production" !== "development" ? invariant(
!injected,
'ReactComponent: injectEnvironment() can only be called once.'
) : invariant(!injected));
mountImageIntoNode = ReactComponentEnvironment.mountImageIntoNode;
unmountIDFromEnvironment =
ReactComponentEnvironment.unmountIDFromEnvironment;
ReactComponent.BackendIDOperations =
ReactComponentEnvironment.BackendIDOperations;
ReactComponent.ReactReconcileTransaction =
ReactComponentEnvironment.ReactReconcileTransaction;
injected = true;
}
},
/**
* @param {?object} object
* @return {boolean} True if `object` is a valid component.
* @final
*/
isValidComponent: function(object) {
if (!object || !object.type || !object.type.prototype) {
return false;
}
// This is the safer way of duck checking the type of instance this is.
// The object can be a generic descriptor but the type property refers to
// the constructor and it's prototype can be used to inspect the type that
// will actually get mounted.
var prototype = object.type.prototype;
return (
typeof prototype.mountComponentIntoNode === 'function' &&
typeof prototype.receiveComponent === 'function'
);
},
/**
* @internal
*/
LifeCycle: ComponentLifeCycle,
/**
* Injected module that provides ability to mutate individual properties.
* Injected into the base class because many different subclasses need access
* to this.
*
* @internal
*/
BackendIDOperations: null,
/**
* React references `ReactReconcileTransaction` using this property in order
* to allow dependency injection.
*
* @internal
*/
ReactReconcileTransaction: null,
/**
* Base functionality for every ReactComponent constructor. Mixed into the
* `ReactComponent` prototype, but exposed statically for easy access.
*
* @lends {ReactComponent.prototype}
*/
Mixin: {
/**
* Checks whether or not this component is mounted.
*
* @return {boolean} True if mounted, false otherwise.
* @final
* @protected
*/
isMounted: function() {
return this._lifeCycleState === ComponentLifeCycle.MOUNTED;
},
/**
* Sets a subset of the props.
*
* @param {object} partialProps Subset of the next props.
* @param {?function} callback Called after props are updated.
* @final
* @public
*/
setProps: function(partialProps, callback) {
// Merge with `_pendingProps` if it exists, otherwise with existing props.
this.replaceProps(
merge(this._pendingProps || this.props, partialProps),
callback
);
},
/**
* Replaces all of the props.
*
* @param {object} props New props.
* @param {?function} callback Called after props are updated.
* @final
* @public
*/
replaceProps: function(props, callback) {
("production" !== "development" ? invariant(
this.isMounted(),
'replaceProps(...): Can only update a mounted component.'
) : invariant(this.isMounted()));
("production" !== "development" ? invariant(
this._mountDepth === 0,
'replaceProps(...): You called `setProps` or `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(this._mountDepth === 0));
this._pendingProps = props;
ReactUpdates.enqueueUpdate(this, callback);
},
/**
* Base constructor for all React components.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.construct.call(this, ...)`.
*
* @param {?object} initialProps
* @param {*} children
* @internal
*/
construct: function(initialProps, children) {
this.props = initialProps || {};
// Record the component responsible for creating this component.
this._owner = ReactCurrentOwner.current;
// All components start unmounted.
this._lifeCycleState = ComponentLifeCycle.UNMOUNTED;
this._pendingProps = null;
this._pendingCallbacks = null;
// Unlike _pendingProps and _pendingCallbacks, we won't use null to
// indicate that nothing is pending because it's possible for a component
// to have a null owner. Instead, an owner change is pending when
// this._owner !== this._pendingOwner.
this._pendingOwner = this._owner;
// Children can be more than one argument
var childrenLength = arguments.length - 1;
if (childrenLength === 1) {
if ("production" !== "development") {
validateChildKeys(children);
}
this.props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
if ("production" !== "development") {
validateChildKeys(arguments[i + 1]);
}
childArray[i] = arguments[i + 1];
}
this.props.children = childArray;
}
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* NOTE: This does not insert any nodes into the DOM.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.mountComponent.call(this, ...)`.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {number} mountDepth number of components in the owner hierarchy.
* @return {?string} Rendered markup to be inserted into the DOM.
* @internal
*/
mountComponent: function(rootID, transaction, mountDepth) {
("production" !== "development" ? invariant(
!this.isMounted(),
'mountComponent(%s, ...): Can only mount an unmounted component. ' +
'Make sure to avoid storing components between renders or reusing a ' +
'single component instance in multiple places.',
rootID
) : invariant(!this.isMounted()));
var props = this.props;
if (props.ref != null) {
ReactOwner.addComponentAsRefTo(this, props.ref, this._owner);
}
this._rootNodeID = rootID;
this._lifeCycleState = ComponentLifeCycle.MOUNTED;
this._mountDepth = mountDepth;
// Effectively: return '';
},
/**
* Releases any resources allocated by `mountComponent`.
*
* NOTE: This does not remove any nodes from the DOM.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.unmountComponent.call(this)`.
*
* @internal
*/
unmountComponent: function() {
("production" !== "development" ? invariant(
this.isMounted(),
'unmountComponent(): Can only unmount a mounted component.'
) : invariant(this.isMounted()));
var props = this.props;
if (props.ref != null) {
ReactOwner.removeComponentAsRefFrom(this, props.ref, this._owner);
}
unmountIDFromEnvironment(this._rootNodeID);
this._rootNodeID = null;
this._lifeCycleState = ComponentLifeCycle.UNMOUNTED;
},
/**
* Given a new instance of this component, updates the rendered DOM nodes
* as if that instance was rendered instead.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.receiveComponent.call(this, ...)`.
*
* @param {object} nextComponent Next set of properties.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
receiveComponent: function(nextComponent, transaction) {
("production" !== "development" ? invariant(
this.isMounted(),
'receiveComponent(...): Can only update a mounted component.'
) : invariant(this.isMounted()));
this._pendingOwner = nextComponent._owner;
this._pendingProps = nextComponent.props;
this._performUpdateIfNecessary(transaction);
},
/**
* Call `_performUpdateIfNecessary` within a new transaction.
*
* @internal
*/
performUpdateIfNecessary: function() {
var transaction = ReactComponent.ReactReconcileTransaction.getPooled();
transaction.perform(this._performUpdateIfNecessary, this, transaction);
ReactComponent.ReactReconcileTransaction.release(transaction);
},
/**
* If `_pendingProps` is set, update the component.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
_performUpdateIfNecessary: function(transaction) {
if (this._pendingProps == null) {
return;
}
var prevProps = this.props;
var prevOwner = this._owner;
this.props = this._pendingProps;
this._owner = this._pendingOwner;
this._pendingProps = null;
this.updateComponent(transaction, prevProps, prevOwner);
},
/**
* Updates the component's currently mounted representation.
*
* @param {ReactReconcileTransaction} transaction
* @param {object} prevProps
* @internal
*/
updateComponent: function(transaction, prevProps, prevOwner) {
var props = this.props;
// 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`.
if (this._owner !== prevOwner || props.ref !== prevProps.ref) {
if (prevProps.ref != null) {
ReactOwner.removeComponentAsRefFrom(
this, prevProps.ref, prevOwner
);
}
// Correct, even if the owner is the same, and only the ref has changed.
if (props.ref != null) {
ReactOwner.addComponentAsRefTo(this, props.ref, this._owner);
}
}
},
/**
* Mounts this component and inserts it into the DOM.
*
* @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
* @final
* @internal
* @see {ReactMount.renderComponent}
*/
mountComponentIntoNode: function(rootID, container, shouldReuseMarkup) {
var transaction = ReactComponent.ReactReconcileTransaction.getPooled();
transaction.perform(
this._mountComponentIntoNode,
this,
rootID,
container,
transaction,
shouldReuseMarkup
);
ReactComponent.ReactReconcileTransaction.release(transaction);
},
/**
* @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
* @final
* @private
*/
_mountComponentIntoNode: function(
rootID,
container,
transaction,
shouldReuseMarkup) {
var markup = this.mountComponent(rootID, transaction, 0);
mountImageIntoNode(markup, container, shouldReuseMarkup);
},
/**
* Checks if this component is owned by the supplied `owner` component.
*
* @param {ReactComponent} owner Component to check.
* @return {boolean} True if `owners` owns this component.
* @final
* @internal
*/
isOwnedBy: function(owner) {
return this._owner === owner;
},
/**
* Gets another component, that shares the same owner as this one, by ref.
*
* @param {string} ref of a sibling Component.
* @return {?ReactComponent} the actual sibling Component.
* @final
* @internal
*/
getSiblingByRef: function(ref) {
var owner = this._owner;
if (!owner || !owner.refs) {
return null;
}
return owner.refs[ref];
}
}
};
module.exports = ReactComponent;
},{"./ReactCurrentOwner":31,"./ReactOwner":59,"./ReactUpdates":71,"./invariant":112,"./keyMirror":118,"./merge":121,"./monitorCodeUse":125}],28:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactComponentBrowserEnvironment
*/
/*jslint evil: true */
"use strict";
var ReactDOMIDOperations = _dereq_("./ReactDOMIDOperations");
var ReactMarkupChecksum = _dereq_("./ReactMarkupChecksum");
var ReactMount = _dereq_("./ReactMount");
var ReactPerf = _dereq_("./ReactPerf");
var ReactReconcileTransaction = _dereq_("./ReactReconcileTransaction");
var getReactRootElementInContainer = _dereq_("./getReactRootElementInContainer");
var invariant = _dereq_("./invariant");
var ELEMENT_NODE_TYPE = 1;
var DOC_NODE_TYPE = 9;
/**
* Abstracts away all functionality of `ReactComponent` requires knowledge of
* the browser context.
*/
var ReactComponentBrowserEnvironment = {
ReactReconcileTransaction: ReactReconcileTransaction,
BackendIDOperations: ReactDOMIDOperations,
/**
* 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);
},
/**
* @param {string} markup Markup string to place into the DOM Element.
* @param {DOMElement} container DOM Element to insert markup into.
* @param {boolean} shouldReuseMarkup Should reuse the existing markup in the
* container if possible.
*/
mountImageIntoNode: ReactPerf.measure(
'ReactComponentBrowserEnvironment',
'mountImageIntoNode',
function(markup, container, shouldReuseMarkup) {
("production" !== "development" ? invariant(
container && (
container.nodeType === ELEMENT_NODE_TYPE ||
container.nodeType === DOC_NODE_TYPE
),
'mountComponentIntoNode(...): Target container is not valid.'
) : invariant(container && (
container.nodeType === ELEMENT_NODE_TYPE ||
container.nodeType === DOC_NODE_TYPE
)));
if (shouldReuseMarkup) {
if (ReactMarkupChecksum.canReuseMarkup(
markup,
getReactRootElementInContainer(container))) {
return;
} else {
("production" !== "development" ? invariant(
container.nodeType !== DOC_NODE_TYPE,
'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.'
) : invariant(container.nodeType !== DOC_NODE_TYPE));
if ("production" !== "development") {
console.warn(
'React attempted to use 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.'
);
}
}
}
("production" !== "development" ? invariant(
container.nodeType !== DOC_NODE_TYPE,
'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 renderComponentToString() for server rendering.'
) : invariant(container.nodeType !== DOC_NODE_TYPE));
container.innerHTML = markup;
}
)
};
module.exports = ReactComponentBrowserEnvironment;
},{"./ReactDOMIDOperations":36,"./ReactMarkupChecksum":54,"./ReactMount":55,"./ReactPerf":60,"./ReactReconcileTransaction":66,"./getReactRootElementInContainer":107,"./invariant":112}],29:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactCompositeComponent
*/
"use strict";
var ReactComponent = _dereq_("./ReactComponent");
var ReactContext = _dereq_("./ReactContext");
var ReactCurrentOwner = _dereq_("./ReactCurrentOwner");
var ReactErrorUtils = _dereq_("./ReactErrorUtils");
var ReactOwner = _dereq_("./ReactOwner");
var ReactPerf = _dereq_("./ReactPerf");
var ReactPropTransferer = _dereq_("./ReactPropTransferer");
var ReactPropTypeLocations = _dereq_("./ReactPropTypeLocations");
var ReactPropTypeLocationNames = _dereq_("./ReactPropTypeLocationNames");
var ReactUpdates = _dereq_("./ReactUpdates");
var instantiateReactComponent = _dereq_("./instantiateReactComponent");
var invariant = _dereq_("./invariant");
var keyMirror = _dereq_("./keyMirror");
var merge = _dereq_("./merge");
var mixInto = _dereq_("./mixInto");
var monitorCodeUse = _dereq_("./monitorCodeUse");
var objMap = _dereq_("./objMap");
var shouldUpdateReactComponent = _dereq_("./shouldUpdateReactComponent");
var warning = _dereq_("./warning");
/**
* Policies that describe methods in `ReactCompositeComponentInterface`.
*/
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 ReactCompositeComponent 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 = [];
/**
* Composite components are higher-level components that compose other composite
* or native components.
*
* To create a new type of `ReactCompositeComponent`, 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 `ReactCompositeComponentInterface` for
* more the comprehensive protocol. Any other properties and methods in the
* class specification will available on the prototype.
*
* @interface ReactCompositeComponentInterface
* @internal
*/
var ReactCompositeComponentInterface = {
/**
* 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(ConvenienceConstructor, displayName) {
ConvenienceConstructor.componentConstructor.displayName = displayName;
},
mixins: function(ConvenienceConstructor, mixins) {
if (mixins) {
for (var i = 0; i < mixins.length; i++) {
mixSpecIntoComponent(ConvenienceConstructor, mixins[i]);
}
}
},
childContextTypes: function(ConvenienceConstructor, childContextTypes) {
var Constructor = ConvenienceConstructor.componentConstructor;
validateTypeDef(
Constructor,
childContextTypes,
ReactPropTypeLocations.childContext
);
Constructor.childContextTypes = merge(
Constructor.childContextTypes,
childContextTypes
);
},
contextTypes: function(ConvenienceConstructor, contextTypes) {
var Constructor = ConvenienceConstructor.componentConstructor;
validateTypeDef(
Constructor,
contextTypes,
ReactPropTypeLocations.context
);
Constructor.contextTypes = merge(Constructor.contextTypes, contextTypes);
},
propTypes: function(ConvenienceConstructor, propTypes) {
var Constructor = ConvenienceConstructor.componentConstructor;
validateTypeDef(
Constructor,
propTypes,
ReactPropTypeLocations.prop
);
Constructor.propTypes = merge(Constructor.propTypes, propTypes);
},
statics: function(ConvenienceConstructor, statics) {
mixStaticSpecIntoComponent(ConvenienceConstructor, statics);
}
};
function validateTypeDef(Constructor, typeDef, location) {
for (var propName in typeDef) {
if (typeDef.hasOwnProperty(propName)) {
("production" !== "development" ? invariant(
typeof typeDef[propName] == 'function',
'%s: %s type `%s` is invalid; it must be a function, usually from ' +
'React.PropTypes.',
Constructor.displayName || 'ReactCompositeComponent',
ReactPropTypeLocationNames[location],
propName
) : invariant(typeof typeDef[propName] == 'function'));
}
}
}
function validateMethodOverride(proto, name) {
var specPolicy = ReactCompositeComponentInterface[name];
// Disallow overriding of base class methods unless explicitly allowed.
if (ReactCompositeComponentMixin.hasOwnProperty(name)) {
("production" !== "development" ? invariant(
specPolicy === SpecPolicy.OVERRIDE_BASE,
'ReactCompositeComponentInterface: You are attempting to override ' +
'`%s` from your class specification. Ensure that your method names ' +
'do not overlap with React methods.',
name
) : invariant(specPolicy === SpecPolicy.OVERRIDE_BASE));
}
// Disallow defining methods more than once unless explicitly allowed.
if (proto.hasOwnProperty(name)) {
("production" !== "development" ? invariant(
specPolicy === SpecPolicy.DEFINE_MANY ||
specPolicy === SpecPolicy.DEFINE_MANY_MERGED,
'ReactCompositeComponentInterface: You are attempting to define ' +
'`%s` on your component more than once. This conflict may be due ' +
'to a mixin.',
name
) : invariant(specPolicy === SpecPolicy.DEFINE_MANY ||
specPolicy === SpecPolicy.DEFINE_MANY_MERGED));
}
}
function validateLifeCycleOnReplaceState(instance) {
var compositeLifeCycleState = instance._compositeLifeCycleState;
("production" !== "development" ? invariant(
instance.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING,
'replaceState(...): Can only update a mounted or mounting component.'
) : invariant(instance.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING));
("production" !== "development" ? invariant(compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE,
'replaceState(...): Cannot update during an existing state transition ' +
'(such as within `render`). This could potentially cause an infinite ' +
'loop so it is forbidden.'
) : invariant(compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE));
("production" !== "development" ? invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING,
'replaceState(...): Cannot update while unmounting component. This ' +
'usually means you called setState() on an unmounted component.'
) : invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING));
}
/**
* Custom version of `mixInto` which handles policy validation and reserved
* specification keys when building `ReactCompositeComponent` classses.
*/
function mixSpecIntoComponent(ConvenienceConstructor, spec) {
("production" !== "development" ? invariant(
!isValidClass(spec),
'ReactCompositeComponent: You\'re attempting to ' +
'use a component class as a mixin. Instead, just use a regular object.'
) : invariant(!isValidClass(spec)));
("production" !== "development" ? invariant(
!ReactComponent.isValidComponent(spec),
'ReactCompositeComponent: You\'re attempting to ' +
'use a component as a mixin. Instead, just use a regular object.'
) : invariant(!ReactComponent.isValidComponent(spec)));
var Constructor = ConvenienceConstructor.componentConstructor;
var proto = Constructor.prototype;
for (var name in spec) {
var property = spec[name];
if (!spec.hasOwnProperty(name)) {
continue;
}
validateMethodOverride(proto, name);
if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
RESERVED_SPEC_KEYS[name](ConvenienceConstructor, property);
} else {
// Setup methods on prototype:
// The following member methods should not be automatically bound:
// 1. Expected ReactCompositeComponent methods (in the "interface").
// 2. Overridden methods (that were mixed in).
var isCompositeComponentMethod = name in ReactCompositeComponentInterface;
var isInherited = name in proto;
var markedDontBind = property && property.__reactDontBind;
var isFunction = typeof property === 'function';
var shouldAutoBind =
isFunction &&
!isCompositeComponentMethod &&
!isInherited &&
!markedDontBind;
if (shouldAutoBind) {
if (!proto.__reactAutoBindMap) {
proto.__reactAutoBindMap = {};
}
proto.__reactAutoBindMap[name] = property;
proto[name] = property;
} else {
if (isInherited) {
// For methods which are defined more than once, call the existing
// methods before calling the new property.
if (ReactCompositeComponentInterface[name] ===
SpecPolicy.DEFINE_MANY_MERGED) {
proto[name] = createMergedResultFunction(proto[name], property);
} else {
proto[name] = createChainedFunction(proto[name], property);
}
} else {
proto[name] = property;
}
}
}
}
}
function mixStaticSpecIntoComponent(ConvenienceConstructor, statics) {
if (!statics) {
return;
}
for (var name in statics) {
var property = statics[name];
if (!statics.hasOwnProperty(name)) {
return;
}
var isInherited = name in ConvenienceConstructor;
var result = property;
if (isInherited) {
var existingProperty = ConvenienceConstructor[name];
var existingType = typeof existingProperty;
var propertyType = typeof property;
("production" !== "development" ? invariant(
existingType === 'function' && propertyType === 'function',
'ReactCompositeComponent: You are attempting to define ' +
'`%s` on your component more than once, but that is only supported ' +
'for functions, which are chained together. This conflict may be ' +
'due to a mixin.',
name
) : invariant(existingType === 'function' && propertyType === 'function'));
result = createChainedFunction(existingProperty, property);
}
ConvenienceConstructor[name] = result;
ConvenienceConstructor.componentConstructor[name] = result;
}
}
/**
* 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 mergeObjectsWithNoDuplicateKeys(one, two) {
("production" !== "development" ? invariant(
one && two && typeof one === 'object' && typeof two === 'object',
'mergeObjectsWithNoDuplicateKeys(): Cannot merge non-objects'
) : invariant(one && two && typeof one === 'object' && typeof two === 'object'));
objMap(two, function(value, key) {
("production" !== "development" ? invariant(
one[key] === undefined,
'mergeObjectsWithNoDuplicateKeys(): ' +
'Tried to merge two objects with the same key: %s',
key
) : invariant(one[key] === undefined));
one[key] = value;
});
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;
}
return mergeObjectsWithNoDuplicateKeys(a, b);
};
}
/**
* 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);
};
}
if ("production" !== "development") {
var unmountedPropertyWhitelist = {
constructor: true,
construct: true,
isOwnedBy: true, // should be deprecated but can have code mod (internal)
type: true,
props: true,
// currently private but belong on the descriptor and are valid for use
// inside the framework:
__keyValidated__: true,
_owner: true,
_currentContext: true
};
var componentInstanceProperties = {
__keyValidated__: true,
__keySetters: true,
_compositeLifeCycleState: true,
_currentContext: true,
_defaultProps: true,
_instance: true,
_lifeCycleState: true,
_mountDepth: true,
_owner: true,
_pendingCallbacks: true,
_pendingContext: true,
_pendingForceUpdate: true,
_pendingOwner: true,
_pendingProps: true,
_pendingState: true,
_renderedComponent: true,
_rootNodeID: true,
context: true,
props: true,
refs: true,
state: true,
// These are known instance properties coming from other sources
_pendingQueries: true,
_queryPropListeners: true,
queryParams: true
};
var hasWarnedOnComponentType = {};
var warningStackCounter = 0;
var issueMembraneWarning = function(instance, key) {
var isWhitelisted = unmountedPropertyWhitelist.hasOwnProperty(key);
if (warningStackCounter > 0 || isWhitelisted) {
return;
}
var name = instance.constructor.displayName || 'Unknown';
var owner = ReactCurrentOwner.current;
var ownerName = (owner && owner.constructor.displayName) || 'Unknown';
var warningKey = key + '|' + name + '|' + ownerName;
if (hasWarnedOnComponentType.hasOwnProperty(warningKey)) {
// We have already warned for this combination. Skip it this time.
return;
}
hasWarnedOnComponentType[warningKey] = true;
var context = owner ? ' in ' + ownerName + '.' : ' at the top level.';
var staticMethodExample = '<' + name + ' />.type.' + key + '(...)';
monitorCodeUse('react_descriptor_property_access', { component: name });
console.warn(
'Invalid access to component property "' + key + '" on ' + name +
context + ' See http://fb.me/react-warning-descriptors .' +
' Use a static method instead: ' + staticMethodExample
);
};
var wrapInMembraneFunction = function(fn, thisBinding) {
if (fn.__reactMembraneFunction && fn.__reactMembraneSelf === thisBinding) {
return fn.__reactMembraneFunction;
}
return fn.__reactMembraneFunction = function() {
/**
* By getting this function, you've already received a warning. The
* internals of this function will likely cause more warnings. To avoid
* Spamming too much we disable any warning triggered inside of this
* stack.
*/
warningStackCounter++;
try {
// If the this binding is unchanged, we defer to the real component.
// This is important to keep some referential integrity in the
// internals. E.g. owner equality check.
var self = this === thisBinding ? this.__realComponentInstance : this;
return fn.apply(self, arguments);
} finally {
warningStackCounter--;
}
};
};
var defineMembraneProperty = function(membrane, prototype, key) {
Object.defineProperty(membrane, key, {
configurable: false,
enumerable: true,
get: function() {
if (this === membrane) {
// We're allowed to access the prototype directly.
return prototype[key];
}
issueMembraneWarning(this, key);
var realValue = this.__realComponentInstance[key];
// If the real value is a function, we need to provide a wrapper that
// disables nested warnings. The properties type and constructors are
// expected to the be constructors and therefore is often use with an
// equality check and we shouldn't try to rebind those.
if (typeof realValue === 'function' &&
key !== 'type' &&
key !== 'constructor') {
return wrapInMembraneFunction(realValue, this);
}
return realValue;
},
set: function(value) {
if (this === membrane) {
// We're allowed to set a value on the prototype directly.
prototype[key] = value;
return;
}
issueMembraneWarning(this, key);
this.__realComponentInstance[key] = value;
}
});
};
/**
* Creates a membrane prototype which wraps the original prototype. If any
* property is accessed in an unmounted state, a warning is issued.
*
* @param {object} prototype Original prototype.
* @return {object} The membrane prototype.
* @private
*/
var createMountWarningMembrane = function(prototype) {
var membrane = {};
var key;
for (key in prototype) {
defineMembraneProperty(membrane, prototype, key);
}
// These are properties that goes into the instance but not the prototype.
// We can create the membrane on the prototype even though this will
// result in a faulty hasOwnProperty check it's better perf.
for (key in componentInstanceProperties) {
if (componentInstanceProperties.hasOwnProperty(key) &&
!(key in prototype)) {
defineMembraneProperty(membrane, prototype, key);
}
}
return membrane;
};
/**
* Creates a membrane constructor which wraps the component that gets mounted.
*
* @param {function} constructor Original constructor.
* @return {function} The membrane constructor.
* @private
*/
var createDescriptorProxy = function(constructor) {
try {
var ProxyConstructor = function() {
this.__realComponentInstance = new constructor();
// We can only safely pass through known instance variables. Unknown
// expandos are not safe. Use the real mounted instance to avoid this
// problem if it blows something up.
Object.freeze(this);
};
ProxyConstructor.prototype = createMountWarningMembrane(
constructor.prototype
);
return ProxyConstructor;
} catch(x) {
// In IE8 define property will fail on non-DOM objects. If anything in
// the membrane creation fails, we'll bail out and just use the plain
// constructor without warnings.
return constructor;
}
};
}
/**
* `ReactCompositeComponent` maintains an auxiliary life cycle state in
* `this._compositeLifeCycleState` (which can be null).
*
* This is different from the life cycle state maintained by `ReactComponent` in
* `this._lifeCycleState`. The following diagram shows how the states overlap in
* time. There are times when the CompositeLifeCycle is null - at those times it
* is only meaningful to look at ComponentLifeCycle alone.
*
* Top Row: ReactComponent.ComponentLifeCycle
* Low Row: ReactComponent.CompositeLifeCycle
*
* +-------+------------------------------------------------------+--------+
* | UN | MOUNTED | UN |
* |MOUNTED| | MOUNTED|
* +-------+------------------------------------------------------+--------+
* | ^--------+ +------+ +------+ +------+ +--------^ |
* | | | | | | | | | | | |
* | 0--|MOUNTING|-0-|RECEIV|-0-|RECEIV|-0-|RECEIV|-0-| UN |--->0 |
* | | | |PROPS | | PROPS| | STATE| |MOUNTING| |
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | +--------+ +------+ +------+ +------+ +--------+ |
* | | | |
* +-------+------------------------------------------------------+--------+
*/
var CompositeLifeCycle = keyMirror({
/**
* Components in the process of being mounted respond to state changes
* differently.
*/
MOUNTING: null,
/**
* Components in the process of being unmounted are guarded against state
* changes.
*/
UNMOUNTING: null,
/**
* Components that are mounted and receiving new props respond to state
* changes differently.
*/
RECEIVING_PROPS: null,
/**
* Components that are mounted and receiving new state are guarded against
* additional state changes.
*/
RECEIVING_STATE: null
});
/**
* @lends {ReactCompositeComponent.prototype}
*/
var ReactCompositeComponentMixin = {
/**
* Base constructor for all composite component.
*
* @param {?object} initialProps
* @param {*} children
* @final
* @internal
*/
construct: function(initialProps, children) {
// Children can be either an array or more than one argument
ReactComponent.Mixin.construct.apply(this, arguments);
ReactOwner.Mixin.construct.apply(this, arguments);
this.state = null;
this._pendingState = null;
this.context = null;
this._currentContext = ReactContext.current;
this._pendingContext = null;
// The descriptor that was used to instantiate this component. Will be
// set by the instantiator instead of the constructor since this
// constructor is currently used by both instances and descriptors.
this._descriptor = null;
this._compositeLifeCycleState = null;
},
/**
* Components in the intermediate state now has cyclic references. To avoid
* breaking JSON serialization we expose a custom JSON format.
* @return {object} JSON compatible representation.
* @internal
* @final
*/
toJSON: function() {
return { type: this.type, props: this.props };
},
/**
* Checks whether or not this composite component is mounted.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function() {
return ReactComponent.Mixin.isMounted.call(this) &&
this._compositeLifeCycleState !== CompositeLifeCycle.MOUNTING;
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {number} mountDepth number of components in the owner hierarchy
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: ReactPerf.measure(
'ReactCompositeComponent',
'mountComponent',
function(rootID, transaction, mountDepth) {
ReactComponent.Mixin.mountComponent.call(
this,
rootID,
transaction,
mountDepth
);
this._compositeLifeCycleState = CompositeLifeCycle.MOUNTING;
this.context = this._processContext(this._currentContext);
this._defaultProps = this.getDefaultProps ? this.getDefaultProps() : null;
this.props = this._processProps(this.props);
if (this.__reactAutoBindMap) {
this._bindAutoBindMethods();
}
this.state = this.getInitialState ? this.getInitialState() : null;
("production" !== "development" ? invariant(
typeof this.state === 'object' && !Array.isArray(this.state),
'%s.getInitialState(): must return an object or null',
this.constructor.displayName || 'ReactCompositeComponent'
) : invariant(typeof this.state === 'object' && !Array.isArray(this.state)));
this._pendingState = null;
this._pendingForceUpdate = false;
if (this.componentWillMount) {
this.componentWillMount();
// When mounting, calls to `setState` by `componentWillMount` will set
// `this._pendingState` without triggering a re-render.
if (this._pendingState) {
this.state = this._pendingState;
this._pendingState = null;
}
}
this._renderedComponent = instantiateReactComponent(
this._renderValidatedComponent()
);
// Done with mounting, `setState` will now trigger UI changes.
this._compositeLifeCycleState = null;
var markup = this._renderedComponent.mountComponent(
rootID,
transaction,
mountDepth + 1
);
if (this.componentDidMount) {
transaction.getReactMountReady().enqueue(this, this.componentDidMount);
}
return markup;
}
),
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function() {
this._compositeLifeCycleState = CompositeLifeCycle.UNMOUNTING;
if (this.componentWillUnmount) {
this.componentWillUnmount();
}
this._compositeLifeCycleState = null;
this._defaultProps = null;
this._renderedComponent.unmountComponent();
this._renderedComponent = null;
ReactComponent.Mixin.unmountComponent.call(this);
// Some existing components rely on this.props even after they've been
// destroyed (in event handlers).
// TODO: this.props = null;
// TODO: this.state = null;
},
/**
* Sets a subset of the state. Always use this or `replaceState` 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.
*
* @param {object} partialState Next partial state to be merged with state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
setState: function(partialState, callback) {
("production" !== "development" ? invariant(
typeof partialState === 'object' || partialState == null,
'setState(...): takes an object of state variables to update.'
) : invariant(typeof partialState === 'object' || partialState == null));
if ("production" !== "development") {
("production" !== "development" ? warning(
partialState != null,
'setState(...): You passed an undefined or null state object; ' +
'instead, use forceUpdate().'
) : null);
}
// Merge with `_pendingState` if it exists, otherwise with existing state.
this.replaceState(
merge(this._pendingState || this.state, partialState),
callback
);
},
/**
* 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 {object} completeState Next state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
replaceState: function(completeState, callback) {
validateLifeCycleOnReplaceState(this);
this._pendingState = completeState;
ReactUpdates.enqueueUpdate(this, callback);
},
/**
* 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 = null;
var contextTypes = this.constructor.contextTypes;
if (contextTypes) {
maskedContext = {};
for (var contextName in contextTypes) {
maskedContext[contextName] = context[contextName];
}
if ("production" !== "development") {
this._checkPropTypes(
contextTypes,
maskedContext,
ReactPropTypeLocations.context
);
}
}
return maskedContext;
},
/**
* @param {object} currentContext
* @return {object}
* @private
*/
_processChildContext: function(currentContext) {
var childContext = this.getChildContext && this.getChildContext();
var displayName = this.constructor.displayName || 'ReactCompositeComponent';
if (childContext) {
("production" !== "development" ? invariant(
typeof this.constructor.childContextTypes === 'object',
'%s.getChildContext(): childContextTypes must be defined in order to ' +
'use getChildContext().',
displayName
) : invariant(typeof this.constructor.childContextTypes === 'object'));
if ("production" !== "development") {
this._checkPropTypes(
this.constructor.childContextTypes,
childContext,
ReactPropTypeLocations.childContext
);
}
for (var name in childContext) {
("production" !== "development" ? invariant(
name in this.constructor.childContextTypes,
'%s.getChildContext(): key "%s" is not defined in childContextTypes.',
displayName,
name
) : invariant(name in this.constructor.childContextTypes));
}
return merge(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) {
var props = merge(newProps);
var defaultProps = this._defaultProps;
for (var propName in defaultProps) {
if (typeof props[propName] === 'undefined') {
props[propName] = defaultProps[propName];
}
}
if ("production" !== "development") {
var propTypes = this.constructor.propTypes;
if (propTypes) {
this._checkPropTypes(propTypes, props, ReactPropTypeLocations.prop);
}
}
return props;
},
/**
* 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) {
var componentName = this.constructor.displayName;
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
propTypes[propName](props, propName, componentName, location);
}
}
},
performUpdateIfNecessary: function() {
var compositeLifeCycleState = this._compositeLifeCycleState;
// Do not trigger a state transition if we are in the middle of mounting or
// receiving props because both of those will already be doing this.
if (compositeLifeCycleState === CompositeLifeCycle.MOUNTING ||
compositeLifeCycleState === CompositeLifeCycle.RECEIVING_PROPS) {
return;
}
ReactComponent.Mixin.performUpdateIfNecessary.call(this);
},
/**
* If any of `_pendingProps`, `_pendingState`, or `_pendingForceUpdate` is
* set, update the component.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
_performUpdateIfNecessary: function(transaction) {
if (this._pendingProps == null &&
this._pendingState == null &&
this._pendingContext == null &&
!this._pendingForceUpdate) {
return;
}
var nextFullContext = this._pendingContext || this._currentContext;
var nextContext = this._processContext(nextFullContext);
this._pendingContext = null;
var nextProps = this.props;
if (this._pendingProps != null) {
nextProps = this._processProps(this._pendingProps);
this._pendingProps = null;
this._compositeLifeCycleState = CompositeLifeCycle.RECEIVING_PROPS;
if (this.componentWillReceiveProps) {
this.componentWillReceiveProps(nextProps, nextContext);
}
}
this._compositeLifeCycleState = CompositeLifeCycle.RECEIVING_STATE;
// Unlike props, state, and context, we specifically don't want to set
// _pendingOwner to null here because it's possible for a component to have
// a null owner, so we instead make `this._owner === this._pendingOwner`
// mean that there's no owner change pending.
var nextOwner = this._pendingOwner;
var nextState = this._pendingState || this.state;
this._pendingState = null;
try {
if (this._pendingForceUpdate ||
!this.shouldComponentUpdate ||
this.shouldComponentUpdate(nextProps, nextState, nextContext)) {
this._pendingForceUpdate = false;
// Will set `this.props`, `this.state` and `this.context`.
this._performComponentUpdate(
nextProps,
nextOwner,
nextState,
nextFullContext,
nextContext,
transaction
);
} else {
// If it's determined that a component should not update, we still want
// to set props and state.
this.props = nextProps;
this._owner = nextOwner;
this.state = nextState;
this._currentContext = nextFullContext;
this.context = nextContext;
}
} finally {
this._compositeLifeCycleState = null;
}
},
/**
* Merges new props and state, notifies delegate methods of update and
* performs update.
*
* @param {object} nextProps Next object to set as properties.
* @param {?ReactComponent} nextOwner Next component to set as owner
* @param {?object} nextState Next object to set as state.
* @param {?object} nextFullContext Next object to set as _currentContext.
* @param {?object} nextContext Next object to set as context.
* @param {ReactReconcileTransaction} transaction
* @private
*/
_performComponentUpdate: function(
nextProps,
nextOwner,
nextState,
nextFullContext,
nextContext,
transaction
) {
var prevProps = this.props;
var prevOwner = this._owner;
var prevState = this.state;
var prevContext = this.context;
if (this.componentWillUpdate) {
this.componentWillUpdate(nextProps, nextState, nextContext);
}
this.props = nextProps;
this._owner = nextOwner;
this.state = nextState;
this._currentContext = nextFullContext;
this.context = nextContext;
this.updateComponent(
transaction,
prevProps,
prevOwner,
prevState,
prevContext
);
if (this.componentDidUpdate) {
transaction.getReactMountReady().enqueue(
this,
this.componentDidUpdate.bind(this, prevProps, prevState, prevContext)
);
}
},
receiveComponent: function(nextComponent, transaction) {
if (nextComponent === this._descriptor) {
// Since props and context are immutable after the component is
// mounted, we can do a cheap identity compare here to determine
// if this is a superfluous reconcile.
return;
}
// Update the descriptor that was last used by this component instance
this._descriptor = nextComponent;
this._pendingContext = nextComponent._currentContext;
ReactComponent.Mixin.receiveComponent.call(
this,
nextComponent,
transaction
);
},
/**
* 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
* @param {object} prevProps
* @param {?ReactComponent} prevOwner
* @param {?object} prevState
* @param {?object} prevContext
* @internal
* @overridable
*/
updateComponent: ReactPerf.measure(
'ReactCompositeComponent',
'updateComponent',
function(transaction, prevProps, prevOwner, prevState, prevContext) {
ReactComponent.Mixin.updateComponent.call(
this,
transaction,
prevProps,
prevOwner
);
var prevComponentInstance = this._renderedComponent;
var nextComponent = this._renderValidatedComponent();
if (shouldUpdateReactComponent(prevComponentInstance, nextComponent)) {
prevComponentInstance.receiveComponent(nextComponent, transaction);
} else {
// These two IDs are actually the same! But nothing should rely on that.
var thisID = this._rootNodeID;
var prevComponentID = prevComponentInstance._rootNodeID;
prevComponentInstance.unmountComponent();
this._renderedComponent = instantiateReactComponent(nextComponent);
var nextMarkup = this._renderedComponent.mountComponent(
thisID,
transaction,
this._mountDepth + 1
);
ReactComponent.BackendIDOperations.dangerouslyReplaceNodeWithMarkupByID(
prevComponentID,
nextMarkup
);
}
}
),
/**
* 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 `shouldUpdateComponent`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/
forceUpdate: function(callback) {
var compositeLifeCycleState = this._compositeLifeCycleState;
("production" !== "development" ? invariant(
this.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING,
'forceUpdate(...): Can only force an update on mounted or mounting ' +
'components.'
) : invariant(this.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING));
("production" !== "development" ? invariant(
compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE &&
compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING,
'forceUpdate(...): Cannot force an update while unmounting component ' +
'or during an existing state transition (such as within `render`).'
) : invariant(compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE &&
compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING));
this._pendingForceUpdate = true;
ReactUpdates.enqueueUpdate(this, callback);
},
/**
* @private
*/
_renderValidatedComponent: ReactPerf.measure(
'ReactCompositeComponent',
'_renderValidatedComponent',
function() {
var renderedComponent;
var previousContext = ReactContext.current;
ReactContext.current = this._processChildContext(this._currentContext);
ReactCurrentOwner.current = this;
try {
renderedComponent = this.render();
} finally {
ReactContext.current = previousContext;
ReactCurrentOwner.current = null;
}
("production" !== "development" ? invariant(
ReactComponent.isValidComponent(renderedComponent),
'%s.render(): A valid ReactComponent must be returned. You may have ' +
'returned null, undefined, an array, or some other invalid object.',
this.constructor.displayName || 'ReactCompositeComponent'
) : invariant(ReactComponent.isValidComponent(renderedComponent)));
return renderedComponent;
}
),
/**
* @private
*/
_bindAutoBindMethods: function() {
for (var autoBindKey in this.__reactAutoBindMap) {
if (!this.__reactAutoBindMap.hasOwnProperty(autoBindKey)) {
continue;
}
var method = this.__reactAutoBindMap[autoBindKey];
this[autoBindKey] = this._bindAutoBindMethod(ReactErrorUtils.guard(
method,
this.constructor.displayName + '.' + autoBindKey
));
}
},
/**
* Binds a method to the component.
*
* @param {function} method Method to be bound.
* @private
*/
_bindAutoBindMethod: function(method) {
var component = this;
var boundMethod = function() {
return method.apply(component, arguments);
};
if ("production" !== "development") {
boundMethod.__reactBoundContext = component;
boundMethod.__reactBoundMethod = method;
boundMethod.__reactBoundArguments = null;
var componentName = component.constructor.displayName;
var _bind = boundMethod.bind;
boundMethod.bind = function(newThis ) {var args=Array.prototype.slice.call(arguments,1);
// 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) {
monitorCodeUse('react_bind_warning', { component: componentName });
console.warn(
'bind(): React component methods may only be bound to the ' +
'component instance. See ' + componentName
);
} else if (!args.length) {
monitorCodeUse('react_bind_warning', { component: componentName });
console.warn(
'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 ' + componentName
);
return boundMethod;
}
var reboundMethod = _bind.apply(boundMethod, arguments);
reboundMethod.__reactBoundContext = component;
reboundMethod.__reactBoundMethod = method;
reboundMethod.__reactBoundArguments = args;
return reboundMethod;
};
}
return boundMethod;
}
};
var ReactCompositeComponentBase = function() {};
mixInto(ReactCompositeComponentBase, ReactComponent.Mixin);
mixInto(ReactCompositeComponentBase, ReactOwner.Mixin);
mixInto(ReactCompositeComponentBase, ReactPropTransferer.Mixin);
mixInto(ReactCompositeComponentBase, ReactCompositeComponentMixin);
/**
* Checks if a value is a valid component constructor.
*
* @param {*}
* @return {boolean}
* @public
*/
function isValidClass(componentClass) {
return componentClass instanceof Function &&
'componentConstructor' in componentClass &&
componentClass.componentConstructor instanceof Function;
}
/**
* Module for creating composite components.
*
* @class ReactCompositeComponent
* @extends ReactComponent
* @extends ReactOwner
* @extends ReactPropTransferer
*/
var ReactCompositeComponent = {
LifeCycle: CompositeLifeCycle,
Base: ReactCompositeComponentBase,
/**
* 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() {};
Constructor.prototype = new ReactCompositeComponentBase();
Constructor.prototype.constructor = Constructor;
var DescriptorConstructor = Constructor;
var ConvenienceConstructor = function(props, children) {
var descriptor = new DescriptorConstructor();
descriptor.construct.apply(descriptor, arguments);
return descriptor;
};
ConvenienceConstructor.componentConstructor = Constructor;
Constructor.ConvenienceConstructor = ConvenienceConstructor;
ConvenienceConstructor.originalSpec = spec;
injectedMixins.forEach(
mixSpecIntoComponent.bind(null, ConvenienceConstructor)
);
mixSpecIntoComponent(ConvenienceConstructor, spec);
("production" !== "development" ? invariant(
Constructor.prototype.render,
'createClass(...): Class specification must implement a `render` method.'
) : invariant(Constructor.prototype.render));
if ("production" !== "development") {
if (Constructor.prototype.componentShouldUpdate) {
monitorCodeUse(
'react_component_should_update_warning',
{ component: spec.displayName }
);
console.warn(
(spec.displayName || 'A component') + ' 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.'
);
}
}
// Expose the convience constructor on the prototype so that it can be
// easily accessed on descriptors. E.g. <Foo />.type === Foo.type and for
// static methods like <Foo />.type.staticMethod();
// This should not be named constructor since this may not be the function
// that created the descriptor, and it may not even be a constructor.
ConvenienceConstructor.type = Constructor;
Constructor.prototype.type = Constructor;
// Reduce time spent doing lookups by setting these on the prototype.
for (var methodName in ReactCompositeComponentInterface) {
if (!Constructor.prototype[methodName]) {
Constructor.prototype[methodName] = null;
}
}
if ("production" !== "development") {
// In DEV the convenience constructor generates a proxy to another
// instance around it to warn about access to properties on the
// descriptor.
DescriptorConstructor = createDescriptorProxy(Constructor);
}
return ConvenienceConstructor;
},
isValidClass: isValidClass,
injection: {
injectMixin: function(mixin) {
injectedMixins.push(mixin);
}
}
};
module.exports = ReactCompositeComponent;
},{"./ReactComponent":27,"./ReactContext":30,"./ReactCurrentOwner":31,"./ReactErrorUtils":47,"./ReactOwner":59,"./ReactPerf":60,"./ReactPropTransferer":61,"./ReactPropTypeLocationNames":62,"./ReactPropTypeLocations":63,"./ReactUpdates":71,"./instantiateReactComponent":111,"./invariant":112,"./keyMirror":118,"./merge":121,"./mixInto":124,"./monitorCodeUse":125,"./objMap":126,"./shouldUpdateReactComponent":131,"./warning":134}],30:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactContext
*/
"use strict";
var merge = _dereq_("./merge");
/**
* Keeps track of the current context.
*
* The context is automatically passed down the component ownership hierarchy
* and is accessible via `this.context` on ReactCompositeComponents.
*/
var ReactContext = {
/**
* @internal
* @type {object}
*/
current: {},
/**
* Temporarily extends the current context while executing scopedCallback.
*
* A typical use case might look like
*
* render: function() {
* var children = ReactContext.withContext({foo: 'foo'} () => (
*
* ));
* return <div>{children}</div>;
* }
*
* @param {object} newContext New context to merge into the existing context
* @param {function} scopedCallback Callback to run with the new context
* @return {ReactComponent|array<ReactComponent>}
*/
withContext: function(newContext, scopedCallback) {
var result;
var previousContext = ReactContext.current;
ReactContext.current = merge(previousContext, newContext);
try {
result = scopedCallback();
} finally {
ReactContext.current = previousContext;
}
return result;
}
};
module.exports = ReactContext;
},{"./merge":121}],31:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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.
*
* The depth indicate how many composite components are above this render level.
*/
var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
module.exports = ReactCurrentOwner;
},{}],32:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDOM
* @typechecks static-only
*/
"use strict";
var ReactDOMComponent = _dereq_("./ReactDOMComponent");
var mergeInto = _dereq_("./mergeInto");
var objMapKeyVal = _dereq_("./objMapKeyVal");
/**
* 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.
*
* @param {string} tag Tag name (e.g. `div`).
* @param {boolean} omitClose True if the close tag should be omitted.
* @private
*/
function createDOMComponentClass(tag, omitClose) {
var Constructor = function() {};
Constructor.prototype = new ReactDOMComponent(tag, omitClose);
Constructor.prototype.constructor = Constructor;
Constructor.displayName = tag;
var ConvenienceConstructor = function(props, children) {
var instance = new Constructor();
instance.construct.apply(instance, arguments);
return instance;
};
// Expose the constructor on the ConvenienceConstructor and prototype so that
// it can be easily easily accessed on descriptors.
// E.g. <div />.type === div.type
ConvenienceConstructor.type = Constructor;
Constructor.prototype.type = Constructor;
Constructor.ConvenienceConstructor = ConvenienceConstructor;
ConvenienceConstructor.componentConstructor = Constructor;
return ConvenienceConstructor;
}
/**
* Creates a mapping from supported HTML tags to `ReactDOMComponent` classes.
* This is also accessible via `React.DOM`.
*
* @public
*/
var ReactDOM = objMapKeyVal({
a: false,
abbr: false,
address: false,
area: true,
article: false,
aside: false,
audio: false,
b: false,
base: true,
bdi: false,
bdo: false,
big: false,
blockquote: false,
body: false,
br: true,
button: false,
canvas: false,
caption: false,
cite: false,
code: false,
col: true,
colgroup: false,
data: false,
datalist: false,
dd: false,
del: false,
details: false,
dfn: false,
div: false,
dl: false,
dt: false,
em: false,
embed: true,
fieldset: false,
figcaption: false,
figure: false,
footer: false,
form: false, // NOTE: Injected, see `ReactDOMForm`.
h1: false,
h2: false,
h3: false,
h4: false,
h5: false,
h6: false,
head: false,
header: false,
hr: true,
html: false,
i: false,
iframe: false,
img: true,
input: true,
ins: false,
kbd: false,
keygen: true,
label: false,
legend: false,
li: false,
link: true,
main: false,
map: false,
mark: false,
menu: false,
menuitem: false, // NOTE: Close tag should be omitted, but causes problems.
meta: true,
meter: false,
nav: false,
noscript: false,
object: false,
ol: false,
optgroup: false,
option: false,
output: false,
p: false,
param: true,
pre: false,
progress: false,
q: false,
rp: false,
rt: false,
ruby: false,
s: false,
samp: false,
script: false,
section: false,
select: false,
small: false,
source: true,
span: false,
strong: false,
style: false,
sub: false,
summary: false,
sup: false,
table: false,
tbody: false,
td: false,
textarea: false, // NOTE: Injected, see `ReactDOMTextarea`.
tfoot: false,
th: false,
thead: false,
time: false,
title: false,
tr: false,
track: true,
u: false,
ul: false,
'var': false,
video: false,
wbr: true,
// SVG
circle: false,
defs: false,
g: false,
line: false,
linearGradient: false,
path: false,
polygon: false,
polyline: false,
radialGradient: false,
rect: false,
stop: false,
svg: false,
text: false
}, createDOMComponentClass);
var injection = {
injectComponentClasses: function(componentClasses) {
mergeInto(ReactDOM, componentClasses);
}
};
ReactDOM.injection = injection;
module.exports = ReactDOM;
},{"./ReactDOMComponent":34,"./mergeInto":123,"./objMapKeyVal":127}],33:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDOMButton
*/
"use strict";
var AutoFocusMixin = _dereq_("./AutoFocusMixin");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
var keyMirror = _dereq_("./keyMirror");
// Store a reference to the <button> `ReactDOMComponent`.
var button = ReactDOM.button;
var mouseListenerNames = keyMirror({
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 = ReactCompositeComponent.createClass({
displayName: 'ReactDOMButton',
mixins: [AutoFocusMixin, ReactBrowserComponentMixin],
render: function() {
var props = {};
// Copy the props; except the mouse listeners if we're disabled
for (var key in this.props) {
if (this.props.hasOwnProperty(key) &&
(!this.props.disabled || !mouseListenerNames[key])) {
props[key] = this.props[key];
}
}
return button(props, this.props.children);
}
});
module.exports = ReactDOMButton;
},{"./AutoFocusMixin":1,"./ReactBrowserComponentMixin":25,"./ReactCompositeComponent":29,"./ReactDOM":32,"./keyMirror":118}],34:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDOMComponent
* @typechecks static-only
*/
"use strict";
var CSSPropertyOperations = _dereq_("./CSSPropertyOperations");
var DOMProperty = _dereq_("./DOMProperty");
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactComponent = _dereq_("./ReactComponent");
var ReactEventEmitter = _dereq_("./ReactEventEmitter");
var ReactMount = _dereq_("./ReactMount");
var ReactMultiChild = _dereq_("./ReactMultiChild");
var ReactPerf = _dereq_("./ReactPerf");
var escapeTextForBrowser = _dereq_("./escapeTextForBrowser");
var invariant = _dereq_("./invariant");
var keyOf = _dereq_("./keyOf");
var merge = _dereq_("./merge");
var mixInto = _dereq_("./mixInto");
var deleteListener = ReactEventEmitter.deleteListener;
var listenTo = ReactEventEmitter.listenTo;
var registrationNameModules = ReactEventEmitter.registrationNameModules;
// For quickly matching children type, to test if can be treated as content.
var CONTENT_TYPES = {'string': true, 'number': true};
var STYLE = keyOf({style: null});
var ELEMENT_NODE_TYPE = 1;
/**
* @param {?object} props
*/
function assertValidProps(props) {
if (!props) {
return;
}
// Note the use of `==` which checks for null or undefined.
("production" !== "development" ? invariant(
props.children == null || props.dangerouslySetInnerHTML == null,
'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'
) : invariant(props.children == null || props.dangerouslySetInnerHTML == null));
("production" !== "development" ? invariant(
props.style == null || typeof props.style === 'object',
'The `style` prop expects a mapping from style properties to values, ' +
'not a string.'
) : invariant(props.style == null || typeof props.style === 'object'));
}
function putListener(id, registrationName, listener, transaction) {
var container = ReactMount.findReactContainerForID(id);
if (container) {
var doc = container.nodeType === ELEMENT_NODE_TYPE ?
container.ownerDocument :
container;
listenTo(registrationName, doc);
}
transaction.getPutListenerQueue().enqueuePutListener(
id,
registrationName,
listener
);
}
/**
* @constructor ReactDOMComponent
* @extends ReactComponent
* @extends ReactMultiChild
*/
function ReactDOMComponent(tag, omitClose) {
this._tagOpen = '<' + tag;
this._tagClose = omitClose ? '' : '</' + tag + '>';
this.tagName = tag.toUpperCase();
}
ReactDOMComponent.Mixin = {
/**
* 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 {number} mountDepth number of components in the owner hierarchy
* @return {string} The computed markup.
*/
mountComponent: ReactPerf.measure(
'ReactDOMComponent',
'mountComponent',
function(rootID, transaction, mountDepth) {
ReactComponent.Mixin.mountComponent.call(
this,
rootID,
transaction,
mountDepth
);
assertValidProps(this.props);
return (
this._createOpenTagMarkupAndPutListeners(transaction) +
this._createContentMarkup(transaction) +
this._tagClose
);
}
),
/**
* 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
* @return {string} Markup of opening tag.
*/
_createOpenTagMarkupAndPutListeners: function(transaction) {
var props = this.props;
var ret = this._tagOpen;
for (var propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
var propValue = props[propKey];
if (propValue == null) {
continue;
}
if (registrationNameModules[propKey]) {
putListener(this._rootNodeID, propKey, propValue, transaction);
} else {
if (propKey === STYLE) {
if (propValue) {
propValue = props.style = merge(props.style);
}
propValue = CSSPropertyOperations.createMarkupForStyles(propValue);
}
var 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
* @return {string} Content markup.
*/
_createContentMarkup: function(transaction) {
// Intentional use of != to avoid catching zero/false.
var innerHTML = this.props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
return innerHTML.__html;
}
} else {
var contentToUse =
CONTENT_TYPES[typeof this.props.children] ? this.props.children : null;
var childrenToUse = contentToUse != null ? null : this.props.children;
if (contentToUse != null) {
return escapeTextForBrowser(contentToUse);
} else if (childrenToUse != null) {
var mountImages = this.mountChildren(
childrenToUse,
transaction
);
return mountImages.join('');
}
}
return '';
},
receiveComponent: function(nextComponent, transaction) {
if (nextComponent === this) {
// Since props and context are immutable after the component is
// mounted, we can do a cheap identity compare here to determine
// if this is a superfluous reconcile.
// TODO: compare the descriptor
return;
}
assertValidProps(nextComponent.props);
ReactComponent.Mixin.receiveComponent.call(
this,
nextComponent,
transaction
);
},
/**
* 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 {object} prevProps
* @internal
* @overridable
*/
updateComponent: ReactPerf.measure(
'ReactDOMComponent',
'updateComponent',
function(transaction, prevProps, prevOwner) {
ReactComponent.Mixin.updateComponent.call(
this,
transaction,
prevProps,
prevOwner
);
this._updateDOMProperties(prevProps, transaction);
this._updateDOMChildren(prevProps, transaction);
}
),
/**
* 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 {ReactReconcileTransaction} transaction
*/
_updateDOMProperties: function(lastProps, transaction) {
var nextProps = this.props;
var propKey;
var styleName;
var styleUpdates;
for (propKey in lastProps) {
if (nextProps.hasOwnProperty(propKey) ||
!lastProps.hasOwnProperty(propKey)) {
continue;
}
if (propKey === STYLE) {
var lastStyle = lastProps[propKey];
for (styleName in lastStyle) {
if (lastStyle.hasOwnProperty(styleName)) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = '';
}
}
} else if (registrationNameModules[propKey]) {
deleteListener(this._rootNodeID, propKey);
} else if (
DOMProperty.isStandardName[propKey] ||
DOMProperty.isCustomAttribute(propKey)) {
ReactComponent.BackendIDOperations.deletePropertyByID(
this._rootNodeID,
propKey
);
}
}
for (propKey in nextProps) {
var nextProp = nextProps[propKey];
var lastProp = lastProps[propKey];
if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp) {
continue;
}
if (propKey === STYLE) {
if (nextProp) {
nextProp = nextProps.style = merge(nextProp);
}
if (lastProp) {
// Unset styles on `lastProp` but not on `nextProp`.
for (styleName in lastProp) {
if (lastProp.hasOwnProperty(styleName) &&
!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[propKey]) {
putListener(this._rootNodeID, propKey, nextProp, transaction);
} else if (
DOMProperty.isStandardName[propKey] ||
DOMProperty.isCustomAttribute(propKey)) {
ReactComponent.BackendIDOperations.updatePropertyByID(
this._rootNodeID,
propKey,
nextProp
);
}
}
if (styleUpdates) {
ReactComponent.BackendIDOperations.updateStylesByID(
this._rootNodeID,
styleUpdates
);
}
},
/**
* Reconciles the children with the various properties that affect the
* children content.
*
* @param {object} lastProps
* @param {ReactReconcileTransaction} transaction
*/
_updateDOMChildren: function(lastProps, transaction) {
var nextProps = this.props;
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);
} else if (lastHasContentOrHtml && !nextHasContentOrHtml) {
this.updateTextContent('');
}
if (nextContent != null) {
if (lastContent !== nextContent) {
this.updateTextContent('' + nextContent);
}
} else if (nextHtml != null) {
if (lastHtml !== nextHtml) {
ReactComponent.BackendIDOperations.updateInnerHTMLByID(
this._rootNodeID,
nextHtml
);
}
} else if (nextChildren != null) {
this.updateChildren(nextChildren, transaction);
}
},
/**
* Destroys all event registrations for this instance. Does not remove from
* the DOM. That must be done by the parent.
*
* @internal
*/
unmountComponent: function() {
this.unmountChildren();
ReactEventEmitter.deleteAllListeners(this._rootNodeID);
ReactComponent.Mixin.unmountComponent.call(this);
}
};
mixInto(ReactDOMComponent, ReactComponent.Mixin);
mixInto(ReactDOMComponent, ReactDOMComponent.Mixin);
mixInto(ReactDOMComponent, ReactMultiChild.Mixin);
mixInto(ReactDOMComponent, ReactBrowserComponentMixin);
module.exports = ReactDOMComponent;
},{"./CSSPropertyOperations":3,"./DOMProperty":8,"./DOMPropertyOperations":9,"./ReactBrowserComponentMixin":25,"./ReactComponent":27,"./ReactEventEmitter":48,"./ReactMount":55,"./ReactMultiChild":57,"./ReactPerf":60,"./escapeTextForBrowser":98,"./invariant":112,"./keyOf":119,"./merge":121,"./mixInto":124}],35:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDOMForm
*/
"use strict";
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
var ReactEventEmitter = _dereq_("./ReactEventEmitter");
var EventConstants = _dereq_("./EventConstants");
// Store a reference to the <form> `ReactDOMComponent`.
var form = ReactDOM.form;
/**
* Since onSubmit doesn't bubble OR capture on the top level in IE8, we need
* to capture it on the <form> element itself. There are lots of hacks we could
* do to accomplish this, but the most reliable is to make <form> a
* composite component and use `componentDidMount` to attach the event handlers.
*/
var ReactDOMForm = ReactCompositeComponent.createClass({
displayName: 'ReactDOMForm',
mixins: [ReactBrowserComponentMixin],
render: function() {
// TODO: Instead of using `ReactDOM` directly, we should use JSX. However,
// `jshint` fails to parse JSX so in order for linting to work in the open
// source repo, we need to just use `ReactDOM.form`.
return this.transferPropsTo(form(null, this.props.children));
},
componentDidMount: function() {
ReactEventEmitter.trapBubbledEvent(
EventConstants.topLevelTypes.topReset,
'reset',
this.getDOMNode()
);
ReactEventEmitter.trapBubbledEvent(
EventConstants.topLevelTypes.topSubmit,
'submit',
this.getDOMNode()
);
}
});
module.exports = ReactDOMForm;
},{"./EventConstants":14,"./ReactBrowserComponentMixin":25,"./ReactCompositeComponent":29,"./ReactDOM":32,"./ReactEventEmitter":48}],36:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDOMIDOperations
* @typechecks static-only
*/
/*jslint evil: true */
"use strict";
var CSSPropertyOperations = _dereq_("./CSSPropertyOperations");
var DOMChildrenOperations = _dereq_("./DOMChildrenOperations");
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var ReactMount = _dereq_("./ReactMount");
var ReactPerf = _dereq_("./ReactPerf");
var invariant = _dereq_("./invariant");
/**
* 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()`.'
};
var useWhitespaceWorkaround;
/**
* Operations used to process updates to DOM nodes. This is made injectable via
* `ReactComponent.BackendIDOperations`.
*/
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: ReactPerf.measure(
'ReactDOMIDOperations',
'updatePropertyByID',
function(id, name, value) {
var node = ReactMount.getNode(id);
("production" !== "development" ? invariant(
!INVALID_PROPERTY_ERRORS.hasOwnProperty(name),
'updatePropertyByID(...): %s',
INVALID_PROPERTY_ERRORS[name]
) : invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name)));
// 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);
}
}
),
/**
* Updates a DOM node to remove a property. This should only be used to remove
* DOM properties in `DOMProperty`.
*
* @param {string} id ID of the node to update.
* @param {string} name A property name to remove, see `DOMProperty`.
* @internal
*/
deletePropertyByID: ReactPerf.measure(
'ReactDOMIDOperations',
'deletePropertyByID',
function(id, name, value) {
var node = ReactMount.getNode(id);
("production" !== "development" ? invariant(
!INVALID_PROPERTY_ERRORS.hasOwnProperty(name),
'updatePropertyByID(...): %s',
INVALID_PROPERTY_ERRORS[name]
) : invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name)));
DOMPropertyOperations.deleteValueForProperty(node, name, value);
}
),
/**
* Updates a DOM node with new style values. If a value is specified as '',
* the corresponding style property will be unset.
*
* @param {string} id ID of the node to update.
* @param {object} styles Mapping from styles to values.
* @internal
*/
updateStylesByID: ReactPerf.measure(
'ReactDOMIDOperations',
'updateStylesByID',
function(id, styles) {
var node = ReactMount.getNode(id);
CSSPropertyOperations.setValueForStyles(node, styles);
}
),
/**
* Updates a DOM node's innerHTML.
*
* @param {string} id ID of the node to update.
* @param {string} html An HTML string.
* @internal
*/
updateInnerHTMLByID: ReactPerf.measure(
'ReactDOMIDOperations',
'updateInnerHTMLByID',
function(id, html) {
var node = ReactMount.getNode(id);
// 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
if (useWhitespaceWorkaround === undefined) {
// Feature detection; only IE8 is known to behave improperly like this.
var temp = document.createElement('div');
temp.innerHTML = ' ';
useWhitespaceWorkaround = temp.innerHTML === '';
}
if (useWhitespaceWorkaround) {
// 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.
node.parentNode.replaceChild(node, node);
}
if (useWhitespaceWorkaround && html.match(/^[ \r\n\t\f]/)) {
// Recover leading whitespace by temporarily prepending any character.
// \uFEFF has the potential advantage of being zero-width/invisible.
node.innerHTML = '\uFEFF' + html;
node.firstChild.deleteData(0, 1);
} else {
node.innerHTML = html;
}
}
),
/**
* Updates a DOM node's text content set by `props.content`.
*
* @param {string} id ID of the node to update.
* @param {string} content Text content.
* @internal
*/
updateTextContentByID: ReactPerf.measure(
'ReactDOMIDOperations',
'updateTextContentByID',
function(id, content) {
var node = ReactMount.getNode(id);
DOMChildrenOperations.updateTextContent(node, content);
}
),
/**
* 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: ReactPerf.measure(
'ReactDOMIDOperations',
'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: ReactPerf.measure(
'ReactDOMIDOperations',
'dangerouslyProcessChildrenUpdates',
function(updates, markup) {
for (var i = 0; i < updates.length; i++) {
updates[i].parentNode = ReactMount.getNode(updates[i].parentID);
}
DOMChildrenOperations.processUpdates(updates, markup);
}
)
};
module.exports = ReactDOMIDOperations;
},{"./CSSPropertyOperations":3,"./DOMChildrenOperations":7,"./DOMPropertyOperations":9,"./ReactMount":55,"./ReactPerf":60,"./invariant":112}],37:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDOMImg
*/
"use strict";
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
var ReactEventEmitter = _dereq_("./ReactEventEmitter");
var EventConstants = _dereq_("./EventConstants");
// Store a reference to the <img> `ReactDOMComponent`.
var img = ReactDOM.img;
/**
* Since onLoad doesn't bubble OR capture on the top level in IE8, we need to
* capture it on the <img> element itself. There are lots of hacks we could do
* to accomplish this, but the most reliable is to make <img> a composite
* component and use `componentDidMount` to attach the event handlers.
*/
var ReactDOMImg = ReactCompositeComponent.createClass({
displayName: 'ReactDOMImg',
tagName: 'IMG',
mixins: [ReactBrowserComponentMixin],
render: function() {
return img(this.props);
},
componentDidMount: function() {
var node = this.getDOMNode();
ReactEventEmitter.trapBubbledEvent(
EventConstants.topLevelTypes.topLoad,
'load',
node
);
ReactEventEmitter.trapBubbledEvent(
EventConstants.topLevelTypes.topError,
'error',
node
);
}
});
module.exports = ReactDOMImg;
},{"./EventConstants":14,"./ReactBrowserComponentMixin":25,"./ReactCompositeComponent":29,"./ReactDOM":32,"./ReactEventEmitter":48}],38:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDOMInput
*/
"use strict";
var AutoFocusMixin = _dereq_("./AutoFocusMixin");
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var LinkedValueUtils = _dereq_("./LinkedValueUtils");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
var ReactMount = _dereq_("./ReactMount");
var invariant = _dereq_("./invariant");
var merge = _dereq_("./merge");
// Store a reference to the <input> `ReactDOMComponent`.
var input = ReactDOM.input;
var instancesByReactID = {};
/**
* 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 = ReactCompositeComponent.createClass({
displayName: 'ReactDOMInput',
mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin],
getInitialState: function() {
var defaultValue = this.props.defaultValue;
return {
checked: this.props.defaultChecked || false,
value: defaultValue != null ? defaultValue : null
};
},
shouldComponentUpdate: function() {
// Defer any updates to this component during the `onChange` handler.
return !this._isChanging;
},
render: function() {
// Clone `this.props` so we don't mutate the input.
var props = merge(this.props);
props.defaultChecked = null;
props.defaultValue = null;
var value = LinkedValueUtils.getValue(this);
props.value = value != null ? value : this.state.value;
var checked = LinkedValueUtils.getChecked(this);
props.checked = checked != null ? checked : this.state.checked;
props.onChange = this._handleChange;
return input(props, this.props.children);
},
componentDidMount: function() {
var id = ReactMount.getID(this.getDOMNode());
instancesByReactID[id] = this;
},
componentWillUnmount: function() {
var rootNode = this.getDOMNode();
var id = ReactMount.getID(rootNode);
delete instancesByReactID[id];
},
componentDidUpdate: function(prevProps, prevState, prevContext) {
var rootNode = this.getDOMNode();
if (this.props.checked != null) {
DOMPropertyOperations.setValueForProperty(
rootNode,
'checked',
this.props.checked || false
);
}
var value = LinkedValueUtils.getValue(this);
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.
DOMPropertyOperations.setValueForProperty(rootNode, 'value', '' + value);
}
},
_handleChange: function(event) {
var returnValue;
var onChange = LinkedValueUtils.getOnChange(this);
if (onChange) {
this._isChanging = true;
returnValue = onChange.call(this, event);
this._isChanging = false;
}
this.setState({
checked: event.target.checked,
value: event.target.value
});
var name = this.props.name;
if (this.props.type === 'radio' && name != null) {
var rootNode = this.getDOMNode();
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, groupLen = group.length; i < groupLen; i++) {
var otherNode = group[i];
if (otherNode === rootNode ||
otherNode.form !== rootNode.form) {
continue;
}
var otherID = ReactMount.getID(otherNode);
("production" !== "development" ? invariant(
otherID,
'ReactDOMInput: Mixing React and non-React radio inputs with the ' +
'same `name` is not supported.'
) : invariant(otherID));
var otherInstance = instancesByReactID[otherID];
("production" !== "development" ? invariant(
otherInstance,
'ReactDOMInput: Unknown radio button ID %s.',
otherID
) : invariant(otherInstance));
// In some cases, this will actually change the `checked` state value.
// In other cases, there's no change but this forces a reconcile upon
// which componentDidUpdate will reset the DOM property to whatever it
// should be.
otherInstance.setState({
checked: false
});
}
}
return returnValue;
}
});
module.exports = ReactDOMInput;
},{"./AutoFocusMixin":1,"./DOMPropertyOperations":9,"./LinkedValueUtils":21,"./ReactBrowserComponentMixin":25,"./ReactCompositeComponent":29,"./ReactDOM":32,"./ReactMount":55,"./invariant":112,"./merge":121}],39:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDOMOption
*/
"use strict";
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
var warning = _dereq_("./warning");
// Store a reference to the <option> `ReactDOMComponent`.
var option = ReactDOM.option;
/**
* Implements an <option> native component that warns when `selected` is set.
*/
var ReactDOMOption = ReactCompositeComponent.createClass({
displayName: 'ReactDOMOption',
mixins: [ReactBrowserComponentMixin],
componentWillMount: function() {
// TODO (yungsters): Remove support for `selected` in <option>.
if ("production" !== "development") {
("production" !== "development" ? warning(
this.props.selected == null,
'Use the `defaultValue` or `value` props on <select> instead of ' +
'setting `selected` on <option>.'
) : null);
}
},
render: function() {
return option(this.props, this.props.children);
}
});
module.exports = ReactDOMOption;
},{"./ReactBrowserComponentMixin":25,"./ReactCompositeComponent":29,"./ReactDOM":32,"./warning":134}],40:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDOMSelect
*/
"use strict";
var AutoFocusMixin = _dereq_("./AutoFocusMixin");
var LinkedValueUtils = _dereq_("./LinkedValueUtils");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
var invariant = _dereq_("./invariant");
var merge = _dereq_("./merge");
// Store a reference to the <select> `ReactDOMComponent`.
var select = ReactDOM.select;
/**
* Validation function for `value` and `defaultValue`.
* @private
*/
function selectValueType(props, propName, componentName) {
if (props[propName] == null) {
return;
}
if (props.multiple) {
("production" !== "development" ? invariant(
Array.isArray(props[propName]),
'The `%s` prop supplied to <select> must be an array if `multiple` is ' +
'true.',
propName
) : invariant(Array.isArray(props[propName])));
} else {
("production" !== "development" ? invariant(
!Array.isArray(props[propName]),
'The `%s` prop supplied to <select> must be a scalar value if ' +
'`multiple` is false.',
propName
) : invariant(!Array.isArray(props[propName])));
}
}
/**
* If `value` is supplied, updates <option> elements on mount and update.
* @param {ReactComponent} component Instance of ReactDOMSelect
* @param {?*} propValue For uncontrolled components, null/undefined. For
* controlled components, a string (or with `multiple`, a list of strings).
* @private
*/
function updateOptions(component, propValue) {
var multiple = component.props.multiple;
var value = propValue != null ? propValue : component.state.value;
var options = component.getDOMNode().options;
var selectedValue, i, l;
if (multiple) {
selectedValue = {};
for (i = 0, l = value.length; i < l; ++i) {
selectedValue['' + value[i]] = true;
}
} else {
selectedValue = '' + value;
}
for (i = 0, l = options.length; i < l; i++) {
var selected = multiple ?
selectedValue.hasOwnProperty(options[i].value) :
options[i].value === selectedValue;
if (selected !== options[i].selected) {
options[i].selected = selected;
}
}
}
/**
* Implements a <select> native component that allows optionally setting the
* props `value` and `defaultValue`. If `multiple` is false, the prop must be a
* string. If `multiple` is true, the prop must be an array of strings.
*
* 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 = ReactCompositeComponent.createClass({
displayName: 'ReactDOMSelect',
mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin],
propTypes: {
defaultValue: selectValueType,
value: selectValueType
},
getInitialState: function() {
return {value: this.props.defaultValue || (this.props.multiple ? [] : '')};
},
componentWillReceiveProps: function(nextProps) {
if (!this.props.multiple && nextProps.multiple) {
this.setState({value: [this.state.value]});
} else if (this.props.multiple && !nextProps.multiple) {
this.setState({value: this.state.value[0]});
}
},
shouldComponentUpdate: function() {
// Defer any updates to this component during the `onChange` handler.
return !this._isChanging;
},
render: function() {
// Clone `this.props` so we don't mutate the input.
var props = merge(this.props);
props.onChange = this._handleChange;
props.value = null;
return select(props, this.props.children);
},
componentDidMount: function() {
updateOptions(this, LinkedValueUtils.getValue(this));
},
componentDidUpdate: function() {
var value = LinkedValueUtils.getValue(this);
if (value != null) {
updateOptions(this, value);
}
},
_handleChange: function(event) {
var returnValue;
var onChange = LinkedValueUtils.getOnChange(this);
if (onChange) {
this._isChanging = true;
returnValue = onChange.call(this, event);
this._isChanging = false;
}
var selectedValue;
if (this.props.multiple) {
selectedValue = [];
var options = event.target.options;
for (var i = 0, l = options.length; i < l; i++) {
if (options[i].selected) {
selectedValue.push(options[i].value);
}
}
} else {
selectedValue = event.target.value;
}
this.setState({value: selectedValue});
return returnValue;
}
});
module.exports = ReactDOMSelect;
},{"./AutoFocusMixin":1,"./LinkedValueUtils":21,"./ReactBrowserComponentMixin":25,"./ReactCompositeComponent":29,"./ReactDOM":32,"./invariant":112,"./merge":121}],41:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDOMSelection
*/
"use strict";
var getNodeForCharacterOffset = _dereq_("./getNodeForCharacterOffset");
var getTextContentAccessor = _dereq_("./getTextContentAccessor");
/**
* 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();
if (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);
var rangeLength = currentRange.toString().length;
var tempRange = currentRange.cloneRange();
tempRange.selectNodeContents(node);
tempRange.setEnd(currentRange.startContainer, currentRange.startOffset);
var start = 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;
detectionRange.detach();
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) {
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);
}
range.detach();
}
}
var ReactDOMSelection = {
/**
* @param {DOMElement} node
*/
getOffsets: function(node) {
var getOffsets = document.selection ? getIEOffsets : getModernOffsets;
return getOffsets(node);
},
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
setOffsets: function(node, offsets) {
var setOffsets = document.selection ? setIEOffsets : setModernOffsets;
setOffsets(node, offsets);
}
};
module.exports = ReactDOMSelection;
},{"./getNodeForCharacterOffset":106,"./getTextContentAccessor":108}],42:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDOMTextarea
*/
"use strict";
var AutoFocusMixin = _dereq_("./AutoFocusMixin");
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var LinkedValueUtils = _dereq_("./LinkedValueUtils");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
var invariant = _dereq_("./invariant");
var merge = _dereq_("./merge");
var warning = _dereq_("./warning");
// Store a reference to the <textarea> `ReactDOMComponent`.
var textarea = ReactDOM.textarea;
/**
* 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 = ReactCompositeComponent.createClass({
displayName: 'ReactDOMTextarea',
mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin],
getInitialState: function() {
var defaultValue = this.props.defaultValue;
// TODO (yungsters): Remove support for children content in <textarea>.
var children = this.props.children;
if (children != null) {
if ("production" !== "development") {
("production" !== "development" ? warning(
false,
'Use the `defaultValue` or `value` props instead of setting ' +
'children on <textarea>.'
) : null);
}
("production" !== "development" ? invariant(
defaultValue == null,
'If you supply `defaultValue` on a <textarea>, do not pass children.'
) : invariant(defaultValue == null));
if (Array.isArray(children)) {
("production" !== "development" ? invariant(
children.length <= 1,
'<textarea> can only have at most one child.'
) : invariant(children.length <= 1));
children = children[0];
}
defaultValue = '' + children;
}
if (defaultValue == null) {
defaultValue = '';
}
var value = LinkedValueUtils.getValue(this);
return {
// 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),
value: defaultValue
};
},
shouldComponentUpdate: function() {
// Defer any updates to this component during the `onChange` handler.
return !this._isChanging;
},
render: function() {
// Clone `this.props` so we don't mutate the input.
var props = merge(this.props);
var value = LinkedValueUtils.getValue(this);
("production" !== "development" ? invariant(
props.dangerouslySetInnerHTML == null,
'`dangerouslySetInnerHTML` does not make sense on <textarea>.'
) : invariant(props.dangerouslySetInnerHTML == null));
props.defaultValue = null;
props.value = value != null ? value : this.state.value;
props.onChange = this._handleChange;
// Always set children to the same thing. In IE9, the selection range will
// get reset if `textContent` is mutated.
return textarea(props, this.state.initialValue);
},
componentDidUpdate: function(prevProps, prevState, prevContext) {
var value = LinkedValueUtils.getValue(this);
if (value != null) {
var rootNode = this.getDOMNode();
// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
DOMPropertyOperations.setValueForProperty(rootNode, 'value', '' + value);
}
},
_handleChange: function(event) {
var returnValue;
var onChange = LinkedValueUtils.getOnChange(this);
if (onChange) {
this._isChanging = true;
returnValue = onChange.call(this, event);
this._isChanging = false;
}
this.setState({value: event.target.value});
return returnValue;
}
});
module.exports = ReactDOMTextarea;
},{"./AutoFocusMixin":1,"./DOMPropertyOperations":9,"./LinkedValueUtils":21,"./ReactBrowserComponentMixin":25,"./ReactCompositeComponent":29,"./ReactDOM":32,"./invariant":112,"./merge":121,"./warning":134}],43:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDefaultBatchingStrategy
*/
"use strict";
var ReactUpdates = _dereq_("./ReactUpdates");
var Transaction = _dereq_("./Transaction");
var emptyFunction = _dereq_("./emptyFunction");
var mixInto = _dereq_("./mixInto");
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();
}
mixInto(ReactDefaultBatchingStrategyTransaction, Transaction.Mixin);
mixInto(ReactDefaultBatchingStrategyTransaction, {
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, param) {
var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates;
ReactDefaultBatchingStrategy.isBatchingUpdates = true;
// The code is written this way to avoid extra allocations
if (alreadyBatchingUpdates) {
callback(param);
} else {
transaction.perform(callback, null, param);
}
}
};
module.exports = ReactDefaultBatchingStrategy;
},{"./ReactUpdates":71,"./Transaction":85,"./emptyFunction":96,"./mixInto":124}],44:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDefaultInjection
*/
"use strict";
var ReactInjection = _dereq_("./ReactInjection");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var DefaultDOMPropertyConfig = _dereq_("./DefaultDOMPropertyConfig");
var ChangeEventPlugin = _dereq_("./ChangeEventPlugin");
var ClientReactRootIndex = _dereq_("./ClientReactRootIndex");
var CompositionEventPlugin = _dereq_("./CompositionEventPlugin");
var DefaultEventPluginOrder = _dereq_("./DefaultEventPluginOrder");
var EnterLeaveEventPlugin = _dereq_("./EnterLeaveEventPlugin");
var MobileSafariClickEventPlugin = _dereq_("./MobileSafariClickEventPlugin");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactComponentBrowserEnvironment =
_dereq_("./ReactComponentBrowserEnvironment");
var ReactEventTopLevelCallback = _dereq_("./ReactEventTopLevelCallback");
var ReactDOM = _dereq_("./ReactDOM");
var ReactDOMButton = _dereq_("./ReactDOMButton");
var ReactDOMForm = _dereq_("./ReactDOMForm");
var ReactDOMImg = _dereq_("./ReactDOMImg");
var ReactDOMInput = _dereq_("./ReactDOMInput");
var ReactDOMOption = _dereq_("./ReactDOMOption");
var ReactDOMSelect = _dereq_("./ReactDOMSelect");
var ReactDOMTextarea = _dereq_("./ReactDOMTextarea");
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactMount = _dereq_("./ReactMount");
var SelectEventPlugin = _dereq_("./SelectEventPlugin");
var ServerReactRootIndex = _dereq_("./ServerReactRootIndex");
var SimpleEventPlugin = _dereq_("./SimpleEventPlugin");
var ReactDefaultBatchingStrategy = _dereq_("./ReactDefaultBatchingStrategy");
var createFullPageComponent = _dereq_("./createFullPageComponent");
function inject() {
ReactInjection.EventEmitter.injectTopLevelCallbackCreator(
ReactEventTopLevelCallback
);
/**
* 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,
CompositionEventPlugin: CompositionEventPlugin,
MobileSafariClickEventPlugin: MobileSafariClickEventPlugin,
SelectEventPlugin: SelectEventPlugin
});
ReactInjection.DOM.injectComponentClasses({
button: ReactDOMButton,
form: ReactDOMForm,
img: ReactDOMImg,
input: ReactDOMInput,
option: ReactDOMOption,
select: ReactDOMSelect,
textarea: ReactDOMTextarea,
html: createFullPageComponent(ReactDOM.html),
head: createFullPageComponent(ReactDOM.head),
title: createFullPageComponent(ReactDOM.title),
body: createFullPageComponent(ReactDOM.body)
});
// This needs to happen after createFullPageComponent() otherwise the mixin
// gets double injected.
ReactInjection.CompositeComponent.injectMixin(ReactBrowserComponentMixin);
ReactInjection.DOMProperty.injectDOMPropertyConfig(DefaultDOMPropertyConfig);
ReactInjection.Updates.injectBatchingStrategy(
ReactDefaultBatchingStrategy
);
ReactInjection.RootIndex.injectCreateReactRootIndex(
ExecutionEnvironment.canUseDOM ?
ClientReactRootIndex.createReactRootIndex :
ServerReactRootIndex.createReactRootIndex
);
ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment);
if ("production" !== "development") {
var url = (ExecutionEnvironment.canUseDOM && window.location.href) || '';
if ((/[?&]react_perf\b/).test(url)) {
var ReactDefaultPerf = _dereq_("./ReactDefaultPerf");
ReactDefaultPerf.start();
}
}
}
module.exports = {
inject: inject
};
},{"./ChangeEventPlugin":4,"./ClientReactRootIndex":5,"./CompositionEventPlugin":6,"./DefaultDOMPropertyConfig":11,"./DefaultEventPluginOrder":12,"./EnterLeaveEventPlugin":13,"./ExecutionEnvironment":20,"./MobileSafariClickEventPlugin":22,"./ReactBrowserComponentMixin":25,"./ReactComponentBrowserEnvironment":28,"./ReactDOM":32,"./ReactDOMButton":33,"./ReactDOMForm":35,"./ReactDOMImg":37,"./ReactDOMInput":38,"./ReactDOMOption":39,"./ReactDOMSelect":40,"./ReactDOMTextarea":42,"./ReactDefaultBatchingStrategy":43,"./ReactDefaultPerf":45,"./ReactEventTopLevelCallback":50,"./ReactInjection":51,"./ReactInstanceHandles":53,"./ReactMount":55,"./SelectEventPlugin":72,"./ServerReactRootIndex":73,"./SimpleEventPlugin":74,"./createFullPageComponent":92}],45:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDefaultPerf
* @typechecks static-only
*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
var ReactDefaultPerfAnalysis = _dereq_("./ReactDefaultPerfAnalysis");
var ReactMount = _dereq_("./ReactMount");
var ReactPerf = _dereq_("./ReactPerf");
var performanceNow = _dereq_("./performanceNow");
function roundFloat(val) {
return Math.floor(val * 100) / 100;
}
var ReactDefaultPerf = {
_allMeasurements: [], // last item in the list is the current one
_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),
'Total exclusive time (ms)': roundFloat(item.exclusive),
'Exclusive time per instance (ms)': roundFloat(item.exclusive / item.count),
'Instances': item.count
};
}));
console.log(
'Total time:',
ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms'
);
},
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'
);
},
printWasted: function(measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(
measurements,
true
);
console.table(summary.map(function(item) {
return {
'Owner > component': item.componentName,
'Wasted time (ms)': item.time,
'Instances': item.count
};
}));
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() {var args=Array.prototype.slice.call(arguments,0);
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: {},
counts: {},
writes: {},
displayNames: {},
totalTime: 0
});
start = performanceNow();
rv = func.apply(this, args);
ReactDefaultPerf._allMeasurements[
ReactDefaultPerf._allMeasurements.length - 1
].totalTime = performanceNow() - start;
return rv;
} else if (moduleName === 'ReactDOMIDOperations' ||
moduleName === 'ReactComponentBrowserEnvironment') {
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
ReactDefaultPerf._recordWrite(
args[0],
fnName,
totalTime,
Array.prototype.slice.call(args, 1)
);
}
return rv;
} else if (moduleName === 'ReactCompositeComponent' && (
fnName === 'mountComponent' ||
fnName === 'updateComponent' || // TODO: receiveComponent()?
fnName === '_renderValidatedComponent')) {
var rootNodeID = fnName === 'mountComponent' ?
args[0] :
this._rootNodeID;
var isRender = fnName === '_renderValidatedComponent';
var entry = ReactDefaultPerf._allMeasurements[
ReactDefaultPerf._allMeasurements.length - 1
];
if (isRender) {
entry.counts[rootNodeID] = entry.counts[rootNodeID] || 0;
entry.counts[rootNodeID] += 1;
}
start = performanceNow();
rv = func.apply(this, args);
totalTime = performanceNow() - start;
var typeOfLog = isRender ? entry.exclusive : entry.inclusive;
typeOfLog[rootNodeID] = typeOfLog[rootNodeID] || 0;
typeOfLog[rootNodeID] += totalTime;
entry.displayNames[rootNodeID] = {
current: this.constructor.displayName,
owner: this._owner ? this._owner.constructor.displayName : '<root>'
};
return rv;
} else {
return func.apply(this, args);
}
};
}
};
module.exports = ReactDefaultPerf;
},{"./DOMProperty":8,"./ReactDefaultPerfAnalysis":46,"./ReactMount":55,"./ReactPerf":60,"./performanceNow":129}],46:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactDefaultPerfAnalysis
*/
var merge = _dereq_("./merge");
// 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',
TEXT_CONTENT: 'set textContent',
'updatePropertyByID': 'update attribute',
'deletePropertyByID': 'delete attribute',
'updateStylesByID': 'update styles',
'updateInnerHTMLByID': 'set innerHTML',
'dangerouslyReplaceNodeWithMarkupByID': 'replace'
};
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 = [];
for (var i = 0; i < measurements.length; i++) {
var measurement = measurements[i];
var id;
for (id in measurement.writes) {
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 = merge(measurement.exclusive, measurement.inclusive);
for (var id in allIDs) {
displayName = measurement.displayNames[id].current;
candidates[displayName] = candidates[displayName] || {
componentName: displayName,
inclusive: 0,
exclusive: 0,
count: 0
};
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 = merge(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 = merge(measurement.exclusive, measurement.inclusive);
for (var id in allIDs) {
var isDirty = false;
// For each component that rendered, see if a component that triggerd
// a DOM op is in its subtree.
for (var i = 0; i < dirtyLeafIDs.length; i++) {
if (dirtyLeafIDs[i].indexOf(id) === 0) {
isDirty = true;
break;
}
}
if (!isDirty && measurement.counts[id] > 0) {
cleanComponents[id] = true;
}
}
return cleanComponents;
}
var ReactDefaultPerfAnalysis = {
getExclusiveSummary: getExclusiveSummary,
getInclusiveSummary: getInclusiveSummary,
getDOMSummary: getDOMSummary,
getTotalTime: getTotalTime
};
module.exports = ReactDefaultPerfAnalysis;
},{"./merge":121}],47:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactErrorUtils
* @typechecks
*/
"use strict";
var ReactErrorUtils = {
/**
* Creates a guarded version of a function. This is supposed to make debugging
* of event handlers easier. To aid debugging with the browser's debugger,
* this currently simply returns the original function.
*
* @param {function} func Function to be executed
* @param {string} name The name of the guard
* @return {function}
*/
guard: function(func, name) {
return func;
}
};
module.exports = ReactErrorUtils;
},{}],48:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactEventEmitter
* @typechecks static-only
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventListener = _dereq_("./EventListener");
var EventPluginHub = _dereq_("./EventPluginHub");
var EventPluginRegistry = _dereq_("./EventPluginRegistry");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var ReactEventEmitterMixin = _dereq_("./ReactEventEmitterMixin");
var ViewportMetrics = _dereq_("./ViewportMetrics");
var invariant = _dereq_("./invariant");
var isEventSupported = _dereq_("./isEventSupported");
var merge = _dereq_("./merge");
/**
* Summary of `ReactEventEmitter` event handling:
*
* - Top-level delegation is used to trap native browser events. We normalize
* and de-duplicate events to account for browser quirks.
*
* - 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 | .
* +------------+ . +-----------+
* + . +--------+|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 = {
topBlur: 'blur',
topChange: 'change',
topClick: 'click',
topCompositionEnd: 'compositionend',
topCompositionStart: 'compositionstart',
topCompositionUpdate: 'compositionupdate',
topContextMenu: 'contextmenu',
topCopy: 'copy',
topCut: 'cut',
topDoubleClick: 'dblclick',
topDrag: 'drag',
topDragEnd: 'dragend',
topDragEnter: 'dragenter',
topDragExit: 'dragexit',
topDragLeave: 'dragleave',
topDragOver: 'dragover',
topDragStart: 'dragstart',
topDrop: 'drop',
topFocus: 'focus',
topInput: 'input',
topKeyDown: 'keydown',
topKeyPress: 'keypress',
topKeyUp: 'keyup',
topMouseDown: 'mousedown',
topMouseMove: 'mousemove',
topMouseOut: 'mouseout',
topMouseOver: 'mouseover',
topMouseUp: 'mouseup',
topPaste: 'paste',
topScroll: 'scroll',
topSelectionChange: 'selectionchange',
topTouchCancel: 'touchcancel',
topTouchEnd: 'touchend',
topTouchMove: 'touchmove',
topTouchStart: 'touchstart',
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) {
if (mountAt[topListenersIDKey] == null) {
mountAt[topListenersIDKey] = reactTopListenersCounter++;
alreadyListeningTo[mountAt[topListenersIDKey]] = {};
}
return alreadyListeningTo[mountAt[topListenersIDKey]];
}
/**
* Traps top-level events by using event bubbling.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {string} handlerBaseName Event name (e.g. "click").
* @param {DOMEventTarget} element Element on which to attach listener.
* @internal
*/
function trapBubbledEvent(topLevelType, handlerBaseName, element) {
EventListener.listen(
element,
handlerBaseName,
ReactEventEmitter.TopLevelCallbackCreator.createTopLevelCallback(
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 {DOMEventTarget} element Element on which to attach listener.
* @internal
*/
function trapCapturedEvent(topLevelType, handlerBaseName, element) {
EventListener.capture(
element,
handlerBaseName,
ReactEventEmitter.TopLevelCallbackCreator.createTopLevelCallback(
topLevelType
)
);
}
/**
* `ReactEventEmitter` is used to attach top-level event listeners. For example:
*
* ReactEventEmitter.putListener('myID', 'onClick', myFunction);
*
* This would allocate a "registration" of `('onClick', myFunction)` on 'myID'.
*
* @internal
*/
var ReactEventEmitter = merge(ReactEventEmitterMixin, {
/**
* React references `ReactEventTopLevelCallback` using this property in order
* to allow dependency injection.
*/
TopLevelCallbackCreator: null,
injection: {
/**
* @param {function} TopLevelCallbackCreator
*/
injectTopLevelCallbackCreator: function(TopLevelCallbackCreator) {
ReactEventEmitter.TopLevelCallbackCreator = TopLevelCallbackCreator;
}
},
/**
* Sets whether or not any created callbacks should be enabled.
*
* @param {boolean} enabled True if callbacks should be enabled.
*/
setEnabled: function(enabled) {
("production" !== "development" ? invariant(
ExecutionEnvironment.canUseDOM,
'setEnabled(...): Cannot toggle event listening in a Worker thread. ' +
'This is likely a bug in the framework. Please report immediately.'
) : invariant(ExecutionEnvironment.canUseDOM));
if (ReactEventEmitter.TopLevelCallbackCreator) {
ReactEventEmitter.TopLevelCallbackCreator.setEnabled(enabled);
}
},
/**
* @return {boolean} True if callbacks are enabled.
*/
isEnabled: function() {
return !!(
ReactEventEmitter.TopLevelCallbackCreator &&
ReactEventEmitter.TopLevelCallbackCreator.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 {DOMDocument} contentDocument Document which owns the container
*/
listenTo: function(registrationName, contentDocument) {
var mountAt = contentDocument;
var isListening = getListeningForDocument(mountAt);
var dependencies = EventPluginRegistry.
registrationNameDependencies[registrationName];
var topLevelTypes = EventConstants.topLevelTypes;
for (var i = 0, l = dependencies.length; i < l; i++) {
var dependency = dependencies[i];
if (!isListening[dependency]) {
var topLevelType = topLevelTypes[dependency];
if (topLevelType === topLevelTypes.topWheel) {
if (isEventSupported('wheel')) {
trapBubbledEvent(topLevelTypes.topWheel, 'wheel', mountAt);
} else if (isEventSupported('mousewheel')) {
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
trapBubbledEvent(
topLevelTypes.topWheel,
'DOMMouseScroll',
mountAt);
}
} else if (topLevelType === topLevelTypes.topScroll) {
if (isEventSupported('scroll', true)) {
trapCapturedEvent(topLevelTypes.topScroll, 'scroll', mountAt);
} else {
trapBubbledEvent(topLevelTypes.topScroll, 'scroll', window);
}
} else if (topLevelType === topLevelTypes.topFocus ||
topLevelType === topLevelTypes.topBlur) {
if (isEventSupported('focus', true)) {
trapCapturedEvent(topLevelTypes.topFocus, 'focus', mountAt);
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
trapBubbledEvent(topLevelTypes.topFocus, 'focusin', mountAt);
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[dependency]) {
trapBubbledEvent(topLevelType, topEventMapping[dependency], mountAt);
}
isListening[dependency] = true;
}
}
},
/**
* 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;
EventListener.listen(window, 'scroll', refresh);
EventListener.listen(window, 'resize', refresh);
isMonitoringScrollValue = true;
}
},
eventNameDispatchConfigs: EventPluginHub.eventNameDispatchConfigs,
registrationNameModules: EventPluginHub.registrationNameModules,
putListener: EventPluginHub.putListener,
getListener: EventPluginHub.getListener,
deleteListener: EventPluginHub.deleteListener,
deleteAllListeners: EventPluginHub.deleteAllListeners,
trapBubbledEvent: trapBubbledEvent,
trapCapturedEvent: trapCapturedEvent
});
module.exports = ReactEventEmitter;
},{"./EventConstants":14,"./EventListener":15,"./EventPluginHub":16,"./EventPluginRegistry":17,"./ExecutionEnvironment":20,"./ReactEventEmitterMixin":49,"./ViewportMetrics":86,"./invariant":112,"./isEventSupported":113,"./merge":121}],49:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactEventEmitterMixin
*/
"use strict";
var EventPluginHub = _dereq_("./EventPluginHub");
var ReactUpdates = _dereq_("./ReactUpdates");
function runEventQueueInBatch(events) {
EventPluginHub.enqueueEvents(events);
EventPluginHub.processEventQueue();
}
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) {
var events = EventPluginHub.extractEvents(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent
);
// Event queue being processed in the same cycle allows `preventDefault`.
ReactUpdates.batchedUpdates(runEventQueueInBatch, events);
}
};
module.exports = ReactEventEmitterMixin;
},{"./EventPluginHub":16,"./ReactUpdates":71}],50:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactEventTopLevelCallback
* @typechecks static-only
*/
"use strict";
var PooledClass = _dereq_("./PooledClass");
var ReactEventEmitter = _dereq_("./ReactEventEmitter");
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactMount = _dereq_("./ReactMount");
var getEventTarget = _dereq_("./getEventTarget");
var mixInto = _dereq_("./mixInto");
/**
* @type {boolean}
* @private
*/
var _topLevelListenersEnabled = true;
/**
* 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;
}
/**
* Calls ReactEventEmitter.handleTopLevel for each node stored in bookKeeping's
* ancestor list. Separated from createTopLevelCallback to avoid try/finally
* deoptimization.
*
* @param {string} topLevelType
* @param {DOMEvent} nativeEvent
* @param {TopLevelCallbackBookKeeping} bookKeeping
*/
function handleTopLevelImpl(topLevelType, nativeEvent, bookKeeping) {
var topLevelTarget = ReactMount.getFirstReactDOM(
getEventTarget(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, l = bookKeeping.ancestors.length; i < l; i++) {
topLevelTarget = bookKeeping.ancestors[i];
var topLevelTargetID = ReactMount.getID(topLevelTarget) || '';
ReactEventEmitter.handleTopLevel(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent
);
}
}
// Used to store ancestor hierarchy in top level callback
function TopLevelCallbackBookKeeping() {
this.ancestors = [];
}
mixInto(TopLevelCallbackBookKeeping, {
destructor: function() {
this.ancestors.length = 0;
}
});
PooledClass.addPoolingTo(TopLevelCallbackBookKeeping);
/**
* Top-level callback creator used to implement event handling using delegation.
* This is used via dependency injection.
*/
var ReactEventTopLevelCallback = {
/**
* Sets whether or not any created callbacks should be enabled.
*
* @param {boolean} enabled True if callbacks should be enabled.
*/
setEnabled: function(enabled) {
_topLevelListenersEnabled = !!enabled;
},
/**
* @return {boolean} True if callbacks are enabled.
*/
isEnabled: function() {
return _topLevelListenersEnabled;
},
/**
* Creates a callback for the supplied `topLevelType` that could be added as
* a listener to the document. The callback computes a `topLevelTarget` which
* should be the root node of a mounted React component where the listener
* is attached.
*
* @param {string} topLevelType Record from `EventConstants`.
* @return {function} Callback for handling top-level events.
*/
createTopLevelCallback: function(topLevelType) {
return function(nativeEvent) {
if (!_topLevelListenersEnabled) {
return;
}
var bookKeeping = TopLevelCallbackBookKeeping.getPooled();
try {
handleTopLevelImpl(topLevelType, nativeEvent, bookKeeping);
} finally {
TopLevelCallbackBookKeeping.release(bookKeeping);
}
};
}
};
module.exports = ReactEventTopLevelCallback;
},{"./PooledClass":23,"./ReactEventEmitter":48,"./ReactInstanceHandles":53,"./ReactMount":55,"./getEventTarget":104,"./mixInto":124}],51:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactInjection
*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
var EventPluginHub = _dereq_("./EventPluginHub");
var ReactComponent = _dereq_("./ReactComponent");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactDOM = _dereq_("./ReactDOM");
var ReactEventEmitter = _dereq_("./ReactEventEmitter");
var ReactPerf = _dereq_("./ReactPerf");
var ReactRootIndex = _dereq_("./ReactRootIndex");
var ReactUpdates = _dereq_("./ReactUpdates");
var ReactInjection = {
Component: ReactComponent.injection,
CompositeComponent: ReactCompositeComponent.injection,
DOMProperty: DOMProperty.injection,
EventPluginHub: EventPluginHub.injection,
DOM: ReactDOM.injection,
EventEmitter: ReactEventEmitter.injection,
Perf: ReactPerf.injection,
RootIndex: ReactRootIndex.injection,
Updates: ReactUpdates.injection
};
module.exports = ReactInjection;
},{"./DOMProperty":8,"./EventPluginHub":16,"./ReactComponent":27,"./ReactCompositeComponent":29,"./ReactDOM":32,"./ReactEventEmitter":48,"./ReactPerf":60,"./ReactRootIndex":67,"./ReactUpdates":71}],52:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactInputSelection
*/
"use strict";
var ReactDOMSelection = _dereq_("./ReactDOMSelection");
var containsNode = _dereq_("./containsNode");
var focusNode = _dereq_("./focusNode");
var getActiveElement = _dereq_("./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) {
return elem && (
(elem.nodeName === 'INPUT' && elem.type === 'text') ||
elem.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') {
// 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') {
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;
},{"./ReactDOMSelection":41,"./containsNode":89,"./focusNode":100,"./getActiveElement":102}],53:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactInstanceHandles
* @typechecks static-only
*/
"use strict";
var ReactRootIndex = _dereq_("./ReactRootIndex");
var invariant = _dereq_("./invariant");
var SEPARATOR = '.';
var SEPARATOR_LENGTH = SEPARATOR.length;
/**
* Maximum depth of traversals before we consider the possibility of a bad ID.
*/
var MAX_TREE_DEPTH = 100;
/**
* 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) {
("production" !== "development" ? invariant(
isValidID(ancestorID) && isValidID(destinationID),
'getNextDescendantID(%s, %s): Received an invalid React DOM ID.',
ancestorID,
destinationID
) : invariant(isValidID(ancestorID) && isValidID(destinationID)));
("production" !== "development" ? invariant(
isAncestorIDOf(ancestorID, destinationID),
'getNextDescendantID(...): React has made an invalid assumption about ' +
'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.',
ancestorID,
destinationID
) : invariant(isAncestorIDOf(ancestorID, destinationID)));
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;
for (var 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);
("production" !== "development" ? invariant(
isValidID(longestCommonID),
'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s',
oneID,
twoID,
longestCommonID
) : invariant(isValidID(longestCommonID)));
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 {?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 || '';
("production" !== "development" ? invariant(
start !== stop,
'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.',
start
) : invariant(start !== stop));
var traverseUp = isAncestorIDOf(stop, start);
("production" !== "development" ? invariant(
traverseUp || isAncestorIDOf(start, stop),
'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' +
'not have a parent path.',
start,
stop
) : invariant(traverseUp || isAncestorIDOf(start, stop)));
// 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;
}
("production" !== "development" ? invariant(
depth++ < MAX_TREE_DEPTH,
'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' +
'traversing the React DOM ID tree. This may be due to malformed IDs: %s',
start, stop
) : invariant(depth++ < MAX_TREE_DEPTH));
}
}
/**
* 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);
}
},
/**
* 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);
},
/**
* Exposed for unit testing.
* @private
*/
_getFirstCommonAncestorID: getFirstCommonAncestorID,
/**
* Exposed for unit testing.
* @private
*/
_getNextDescendantID: getNextDescendantID,
isAncestorIDOf: isAncestorIDOf,
SEPARATOR: SEPARATOR
};
module.exports = ReactInstanceHandles;
},{"./ReactRootIndex":67,"./invariant":112}],54:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactMarkupChecksum
*/
"use strict";
var adler32 = _dereq_("./adler32");
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);
return markup.replace(
'>',
' ' + 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;
},{"./adler32":88}],55:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactMount
*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
var ReactEventEmitter = _dereq_("./ReactEventEmitter");
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactPerf = _dereq_("./ReactPerf");
var containsNode = _dereq_("./containsNode");
var getReactRootElementInContainer = _dereq_("./getReactRootElementInContainer");
var instantiateReactComponent = _dereq_("./instantiateReactComponent");
var invariant = _dereq_("./invariant");
var shouldUpdateReactComponent = _dereq_("./shouldUpdateReactComponent");
var SEPARATOR = ReactInstanceHandles.SEPARATOR;
var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME;
var nodeCache = {};
var ELEMENT_NODE_TYPE = 1;
var DOC_NODE_TYPE = 9;
/** Mapping from reactRootID to React component instance. */
var instancesByReactRootID = {};
/** Mapping from reactRootID to `container` nodes. */
var containersByReactRootID = {};
if ("production" !== "development") {
/** __DEV__-only mapping from reactRootID to root elements. */
var rootElementsByReactRootID = {};
}
// Used to store breadth-first search state in findComponentRoot.
var findComponentRootReusableArray = [];
/**
* @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) {
("production" !== "development" ? invariant(
!isValid(cached, id),
'ReactMount: Two valid but unequal nodes with the same `%s`: %s',
ATTR_NAME, id
) : invariant(!isValid(cached, id)));
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];
}
/**
* 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) {
("production" !== "development" ? invariant(
internalGetID(node) === id,
'ReactMount: Unexpected modification of `%s`',
ATTR_NAME
) : invariant(internalGetID(node) === id));
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;
}
/**
* Mounting is the process of initializing a React component by creatings its
* representative DOM elements and inserting them into a supplied `container`.
* Any prior content inside `container` is destroyed in the process.
*
* ReactMount.renderComponent(
* 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 = {
/** Time spent generating markup. */
totalInstantiationTime: 0,
/** Time spent inserting markup into the DOM. */
totalInjectionTime: 0,
/** Whether support for touch events should be initialized. */
useTouchEvents: false,
/** 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 {ReactComponent} nextComponent component instance to render
* @param {DOMElement} container container to render into
* @param {?function} callback function triggered on completion
*/
_updateRootComponent: function(
prevComponent,
nextComponent,
container,
callback) {
var nextProps = nextComponent.props;
ReactMount.scrollMonitor(container, function() {
prevComponent.replaceProps(nextProps, callback);
});
if ("production" !== "development") {
// 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) {
("production" !== "development" ? invariant(
container && (
container.nodeType === ELEMENT_NODE_TYPE ||
container.nodeType === DOC_NODE_TYPE
),
'_registerComponent(...): Target container is not a DOM element.'
) : invariant(container && (
container.nodeType === ELEMENT_NODE_TYPE ||
container.nodeType === DOC_NODE_TYPE
)));
ReactEventEmitter.ensureScrollValueMonitoring();
var reactRootID = ReactMount.registerContainer(container);
instancesByReactRootID[reactRootID] = nextComponent;
return reactRootID;
},
/**
* Render a new component into the DOM.
* @param {ReactComponent} nextComponent component instance to render
* @param {DOMElement} container container to render into
* @param {boolean} shouldReuseMarkup if we should skip the markup insertion
* @return {ReactComponent} nextComponent
*/
_renderNewRootComponent: ReactPerf.measure(
'ReactMount',
'_renderNewRootComponent',
function(
nextComponent,
container,
shouldReuseMarkup) {
var componentInstance = instantiateReactComponent(nextComponent);
var reactRootID = ReactMount._registerComponent(
componentInstance,
container
);
componentInstance.mountComponentIntoNode(
reactRootID,
container,
shouldReuseMarkup
);
if ("production" !== "development") {
// 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} nextComponent Component instance to render.
* @param {DOMElement} container DOM element to render into.
* @param {?function} callback function triggered on completion
* @return {ReactComponent} Component instance rendered in `container`.
*/
renderComponent: function(nextComponent, container, callback) {
var prevComponent = instancesByReactRootID[getReactRootID(container)];
if (prevComponent) {
if (shouldUpdateReactComponent(prevComponent, nextComponent)) {
return ReactMount._updateRootComponent(
prevComponent,
nextComponent,
container,
callback
);
} else {
ReactMount.unmountComponentAtNode(container);
}
}
var reactRootElement = getReactRootElementInContainer(container);
var containerHasReactMarkup =
reactRootElement && ReactMount.isRenderedByReact(reactRootElement);
var shouldReuseMarkup = containerHasReactMarkup && !prevComponent;
var component = ReactMount._renderNewRootComponent(
nextComponent,
container,
shouldReuseMarkup
);
callback && callback.call(component);
return component;
},
/**
* Constructs a component instance of `constructor` with `initialProps` and
* renders it into the supplied `container`.
*
* @param {function} constructor React component constructor.
* @param {?object} props Initial props of the component instance.
* @param {DOMElement} container DOM element to render into.
* @return {ReactComponent} Component instance rendered in `container`.
*/
constructAndRenderComponent: function(constructor, props, container) {
return ReactMount.renderComponent(constructor(props), container);
},
/**
* Constructs a component instance of `constructor` with `initialProps` and
* renders it into a container node identified by supplied `id`.
*
* @param {function} componentConstructor React component constructor
* @param {?object} props Initial props of the component instance.
* @param {string} id ID of the DOM element to render into.
* @return {ReactComponent} Component instance rendered in the container node.
*/
constructAndRenderComponentByID: function(constructor, props, id) {
var domNode = document.getElementById(id);
("production" !== "development" ? invariant(
domNode,
'Tried to get element with id of "%s" but it is not present on the page.',
id
) : invariant(domNode));
return ReactMount.constructAndRenderComponent(constructor, props, domNode);
},
/**
* 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) {
var reactRootID = getReactRootID(container);
var component = instancesByReactRootID[reactRootID];
if (!component) {
return false;
}
ReactMount.unmountComponentFromNode(component, container);
delete instancesByReactRootID[reactRootID];
delete containersByReactRootID[reactRootID];
if ("production" !== "development") {
delete rootElementsByReactRootID[reactRootID];
}
return true;
},
/**
* 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}
*/
unmountComponentFromNode: function(instance, container) {
instance.unmountComponent();
if (container.nodeType === DOC_NODE_TYPE) {
container = container.documentElement;
}
// http://jsperf.com/emptying-a-node
while (container.lastChild) {
container.removeChild(container.lastChild);
}
},
/**
* 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 ("production" !== "development") {
var rootElement = rootElementsByReactRootID[reactRootID];
if (rootElement && rootElement.parentNode !== container) {
("production" !== "development" ? invariant(
// Call internalGetID here because getID calls isValid which calls
// findReactContainerForID (this function).
internalGetID(rootElement) === reactRootID,
'ReactMount: Root element ID differed from reactRootID.'
) : invariant(// Call internalGetID here because getID calls isValid which calls
// findReactContainerForID (this function).
internalGetID(rootElement) === reactRootID));
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 {
console.warn(
'ReactMount: Root element has been removed from its original ' +
'container. New container:', rootElement.parentNode
);
}
}
}
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);
},
/**
* True if the supplied `node` is rendered by React.
*
* @param {*} node DOM Element to check.
* @return {boolean} True if the DOM Element appears to be rendered by React.
* @internal
*/
isRenderedByReact: function(node) {
if (node.nodeType !== 1) {
// Not a DOMElement, therefore not a React component
return false;
}
var id = ReactMount.getID(node);
return id ? id.charAt(0) === SEPARATOR : false;
},
/**
* Traverses up the ancestors of the supplied node to find a node that is a
* DOM representation of a React component.
*
* @param {*} node
* @return {?DOMEventTarget}
* @internal
*/
getFirstReactDOM: function(node) {
var current = node;
while (current && current.parentNode !== current) {
if (ReactMount.isRenderedByReact(current)) {
return current;
}
current = current.parentNode;
}
return null;
},
/**
* 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;
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;
("production" !== "development" ? 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 or nesting <p> ' +
'or <a> tags. Try inspecting the child nodes of the element with React ' +
'ID `%s`.',
targetID,
ReactMount.getID(ancestorNode)
) : invariant(false));
},
/**
* React ID utilities.
*/
getReactRootID: getReactRootID,
getID: getID,
setID: setID,
getNode: getNode,
purgeID: purgeID
};
module.exports = ReactMount;
},{"./DOMProperty":8,"./ReactEventEmitter":48,"./ReactInstanceHandles":53,"./ReactPerf":60,"./containsNode":89,"./getReactRootElementInContainer":107,"./instantiateReactComponent":111,"./invariant":112,"./shouldUpdateReactComponent":131}],56:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactMountReady
*/
"use strict";
var PooledClass = _dereq_("./PooledClass");
var mixInto = _dereq_("./mixInto");
/**
* 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 `ReactMountReady.getPooled()`.
*
* @param {?array<function>} initialCollection
* @class ReactMountReady
* @implements PooledClass
* @internal
*/
function ReactMountReady(initialCollection) {
this._queue = initialCollection || null;
}
mixInto(ReactMountReady, {
/**
* Enqueues a callback to be invoked when `notifyAll` is invoked. This is used
* to enqueue calls to `componentDidMount` and `componentDidUpdate`.
*
* @param {ReactComponent} component Component being rendered.
* @param {function(DOMElement)} callback Invoked when `notifyAll` is invoked.
* @internal
*/
enqueue: function(component, callback) {
this._queue = this._queue || [];
this._queue.push({component: component, callback: callback});
},
/**
* 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 queue = this._queue;
if (queue) {
this._queue = null;
for (var i = 0, l = queue.length; i < l; i++) {
var component = queue[i].component;
var callback = queue[i].callback;
callback.call(component);
}
queue.length = 0;
}
},
/**
* Resets the internal queue.
*
* @internal
*/
reset: function() {
this._queue = null;
},
/**
* `PooledClass` looks for this.
*/
destructor: function() {
this.reset();
}
});
PooledClass.addPoolingTo(ReactMountReady);
module.exports = ReactMountReady;
},{"./PooledClass":23,"./mixInto":124}],57:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactMultiChild
* @typechecks static-only
*/
"use strict";
var ReactComponent = _dereq_("./ReactComponent");
var ReactMultiChildUpdateTypes = _dereq_("./ReactMultiChildUpdateTypes");
var flattenChildren = _dereq_("./flattenChildren");
var instantiateReactComponent = _dereq_("./instantiateReactComponent");
var shouldUpdateReactComponent = _dereq_("./shouldUpdateReactComponent");
/**
* 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 enqueueMarkup(parentID, markup, toIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.INSERT_MARKUP,
markupIndex: markupQueue.push(markup) - 1,
textContent: 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,
textContent: 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,
textContent: null,
fromIndex: fromIndex,
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,
textContent: textContent,
fromIndex: null,
toIndex: null
});
}
/**
* Processes any enqueued updates.
*
* @private
*/
function processQueue() {
if (updateQueue.length) {
ReactComponent.BackendIDOperations.dangerouslyProcessChildrenUpdates(
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: {
/**
* 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) {
var children = flattenChildren(nestedChildren);
var mountImages = [];
var index = 0;
this._renderedChildren = children;
for (var name in children) {
var child = children[name];
if (children.hasOwnProperty(name)) {
// The rendered children must be turned into instances as they're
// mounted.
var childInstance = instantiateReactComponent(child);
children[name] = childInstance;
// Inlined for performance, see `ReactInstanceHandles.createReactID`.
var rootID = this._rootNodeID + name;
var mountImage = childInstance.mountComponent(
rootID,
transaction,
this._mountDepth + 1
);
childInstance._mountIndex = index;
mountImages.push(mountImage);
index++;
}
}
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.
for (var name in prevChildren) {
if (prevChildren.hasOwnProperty(name)) {
this._unmountChildByName(prevChildren[name], name);
}
}
// Set new text content.
this.setTextContent(nextContent);
errorThrown = false;
} finally {
updateDepth--;
if (!updateDepth) {
errorThrown ? clearQueue() : processQueue();
}
}
},
/**
* Updates the rendered children with new children.
*
* @param {?object} nextNestedChildren Nested child maps.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
updateChildren: function(nextNestedChildren, transaction) {
updateDepth++;
var errorThrown = true;
try {
this._updateChildren(nextNestedChildren, transaction);
errorThrown = false;
} finally {
updateDepth--;
if (!updateDepth) {
errorThrown ? clearQueue() : processQueue();
}
}
},
/**
* Improve performance by isolating this hot code path from the try/catch
* block in `updateChildren`.
*
* @param {?object} nextNestedChildren Nested child maps.
* @param {ReactReconcileTransaction} transaction
* @final
* @protected
*/
_updateChildren: function(nextNestedChildren, transaction) {
var nextChildren = flattenChildren(nextNestedChildren);
var prevChildren = this._renderedChildren;
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 (shouldUpdateReactComponent(prevChild, nextChild)) {
this.moveChild(prevChild, nextIndex, lastIndex);
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
prevChild.receiveComponent(nextChild, transaction);
prevChild._mountIndex = nextIndex;
} else {
if (prevChild) {
// Update `lastIndex` before `_mountIndex` gets unset by unmounting.
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
this._unmountChildByName(prevChild, name);
}
// The child must be instantiated before it's mounted.
var nextChildInstance = instantiateReactComponent(nextChild);
this._mountChildByNameAtIndex(
nextChildInstance, name, nextIndex, transaction
);
}
nextIndex++;
}
// Remove children that are no longer present.
for (name in prevChildren) {
if (prevChildren.hasOwnProperty(name) &&
!(nextChildren && nextChildren[name])) {
this._unmountChildByName(prevChildren[name], 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;
for (var name in renderedChildren) {
var renderedChild = renderedChildren[name];
// TODO: When is this not true?
if (renderedChild.unmountComponent) {
renderedChild.unmountComponent();
}
}
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) {
enqueueMarkup(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);
},
/**
* 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) {
// Inlined for performance, see `ReactInstanceHandles.createReactID`.
var rootID = this._rootNodeID + name;
var mountImage = child.mountComponent(
rootID,
transaction,
this._mountDepth + 1
);
child._mountIndex = index;
this.createChild(child, mountImage);
this._renderedChildren = this._renderedChildren || {};
this._renderedChildren[name] = child;
},
/**
* Unmounts a rendered child by name.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to unmount.
* @param {string} name Name of the child in `this._renderedChildren`.
* @private
*/
_unmountChildByName: function(child, name) {
// TODO: When is this not true?
if (ReactComponent.isValidComponent(child)) {
this.removeChild(child);
child._mountIndex = null;
child.unmountComponent();
delete this._renderedChildren[name];
}
}
}
};
module.exports = ReactMultiChild;
},{"./ReactComponent":27,"./ReactMultiChildUpdateTypes":58,"./flattenChildren":99,"./instantiateReactComponent":111,"./shouldUpdateReactComponent":131}],58:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactMultiChildUpdateTypes
*/
"use strict";
var keyMirror = _dereq_("./keyMirror");
/**
* 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,
TEXT_CONTENT: null
});
module.exports = ReactMultiChildUpdateTypes;
},{"./keyMirror":118}],59:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactOwner
*/
"use strict";
var emptyObject = _dereq_("./emptyObject");
var invariant = _dereq_("./invariant");
/**
* 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) {
("production" !== "development" ? invariant(
ReactOwner.isValidOwner(owner),
'addComponentAsRefTo(...): Only a ReactOwner can have refs. This ' +
'usually means that you\'re trying to add a ref to a component that ' +
'doesn\'t have an owner (that is, was not created inside of another ' +
'component\'s `render` method). Try rendering this component inside of ' +
'a new top-level component which will hold the ref.'
) : invariant(ReactOwner.isValidOwner(owner)));
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) {
("production" !== "development" ? invariant(
ReactOwner.isValidOwner(owner),
'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. This ' +
'usually means that you\'re trying to remove a ref to a component that ' +
'doesn\'t have an owner (that is, was not created inside of another ' +
'component\'s `render` method). Try rendering this component inside of ' +
'a new top-level component which will hold the ref.'
) : invariant(ReactOwner.isValidOwner(owner)));
// Check that `component` is still the current ref because we do not want to
// detach the ref if another component stole it.
if (owner.refs[ref] === component) {
owner.detachRef(ref);
}
},
/**
* A ReactComponent must mix this in to have refs.
*
* @lends {ReactOwner.prototype}
*/
Mixin: {
construct: function() {
this.refs = emptyObject;
},
/**
* 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) {
("production" !== "development" ? invariant(
component.isOwnedBy(this),
'attachRef(%s, ...): Only a component\'s owner can store a ref to it.',
ref
) : invariant(component.isOwnedBy(this)));
var refs = this.refs === emptyObject ? (this.refs = {}) : this.refs;
refs[ref] = component;
},
/**
* Detaches a reference name.
*
* @param {string} ref Name to dereference.
* @final
* @private
*/
detachRef: function(ref) {
delete this.refs[ref];
}
}
};
module.exports = ReactOwner;
},{"./emptyObject":97,"./invariant":112}],60:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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,
/**
* 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 ("production" !== "development") {
var measuredFunc = null;
return function() {
if (ReactPerf.enableMeasure) {
if (!measuredFunc) {
measuredFunc = ReactPerf.storedMeasure(objName, fnName, func);
}
return measuredFunc.apply(this, arguments);
}
return func.apply(this, arguments);
};
}
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;
},{}],61:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactPropTransferer
*/
"use strict";
var emptyFunction = _dereq_("./emptyFunction");
var invariant = _dereq_("./invariant");
var joinClasses = _dereq_("./joinClasses");
var merge = _dereq_("./merge");
/**
* Creates a transfer strategy that will merge prop values using the supplied
* `mergeStrategy`. If a prop was previously unset, this just sets it.
*
* @param {function} mergeStrategy
* @return {function}
*/
function createTransferStrategy(mergeStrategy) {
return function(props, key, value) {
if (!props.hasOwnProperty(key)) {
props[key] = value;
} else {
props[key] = mergeStrategy(props[key], value);
}
};
}
/**
* Transfer strategies dictate how props are transferred by `transferPropsTo`.
* NOTE: if you add any more exceptions to this list you should be sure to
* update `cloneWithProps()` accordingly.
*/
var TransferStrategies = {
/**
* Never transfer `children`.
*/
children: emptyFunction,
/**
* Transfer the `className` prop by merging them.
*/
className: createTransferStrategy(joinClasses),
/**
* Never transfer the `key` prop.
*/
key: emptyFunction,
/**
* Never transfer the `ref` prop.
*/
ref: emptyFunction,
/**
* Transfer the `style` prop (which is an object) by merging them.
*/
style: createTransferStrategy(merge)
};
/**
* ReactPropTransferer are capable of transferring props to another component
* using a `transferPropsTo` method.
*
* @class ReactPropTransferer
*/
var ReactPropTransferer = {
TransferStrategies: TransferStrategies,
/**
* Merge two props objects using TransferStrategies.
*
* @param {object} oldProps original props (they take precedence)
* @param {object} newProps new props to merge in
* @return {object} a new object containing both sets of props merged.
*/
mergeProps: function(oldProps, newProps) {
var props = merge(oldProps);
for (var thisKey in newProps) {
if (!newProps.hasOwnProperty(thisKey)) {
continue;
}
var transferStrategy = TransferStrategies[thisKey];
if (transferStrategy && TransferStrategies.hasOwnProperty(thisKey)) {
transferStrategy(props, thisKey, newProps[thisKey]);
} else if (!props.hasOwnProperty(thisKey)) {
props[thisKey] = newProps[thisKey];
}
}
return props;
},
/**
* @lends {ReactPropTransferer.prototype}
*/
Mixin: {
/**
* Transfer props from this component to a target component.
*
* Props that do not have an explicit transfer strategy will be transferred
* only if the target component does not already have the prop set.
*
* This is usually used to pass down props to a returned root component.
*
* @param {ReactComponent} component Component receiving the properties.
* @return {ReactComponent} The supplied `component`.
* @final
* @protected
*/
transferPropsTo: function(component) {
("production" !== "development" ? invariant(
component._owner === this,
'%s: You can\'t call transferPropsTo() on a component that you ' +
'don\'t own, %s. This usually means you are calling ' +
'transferPropsTo() on a component passed in as props or children.',
this.constructor.displayName,
component.constructor.displayName
) : invariant(component._owner === this));
component.props = ReactPropTransferer.mergeProps(
component.props,
this.props
);
return component;
}
}
};
module.exports = ReactPropTransferer;
},{"./emptyFunction":96,"./invariant":112,"./joinClasses":117,"./merge":121}],62:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactPropTypeLocationNames
*/
"use strict";
var ReactPropTypeLocationNames = {};
if ("production" !== "development") {
ReactPropTypeLocationNames = {
prop: 'prop',
context: 'context',
childContext: 'child context'
};
}
module.exports = ReactPropTypeLocationNames;
},{}],63:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactPropTypeLocations
*/
"use strict";
var keyMirror = _dereq_("./keyMirror");
var ReactPropTypeLocations = keyMirror({
prop: null,
context: null,
childContext: null
});
module.exports = ReactPropTypeLocations;
},{"./keyMirror":118}],64:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactPropTypes
*/
"use strict";
var ReactComponent = _dereq_("./ReactComponent");
var ReactPropTypeLocationNames = _dereq_("./ReactPropTypeLocationNames");
var warning = _dereq_("./warning");
var createObjectFrom = _dereq_("./createObjectFrom");
/**
* 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 Props = require('ReactPropTypes');
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* warning(
* propValue == null ||
* typeof propValue === 'string' ||
* propValue instanceof URI,
* 'Invalid `%s` supplied to `%s`, expected string or URI.',
* propName,
* componentName
* );
* }
* },
* render: function() { ... }
* });
*
* @internal
*/
var Props = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
shape: createShapeTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
arrayOf: createArrayOfTypeChecker,
instanceOf: createInstanceTypeChecker,
renderable: createRenderableTypeChecker(),
component: createComponentTypeChecker(),
any: createAnyTypeChecker()
};
var ANONYMOUS = '<<anonymous>>';
function isRenderable(propValue) {
switch(typeof propValue) {
case 'number':
case 'string':
return true;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isRenderable);
}
if (ReactComponent.isValidComponent(propValue)) {
return true;
}
for (var k in propValue) {
if (!isRenderable(propValue[k])) {
return false;
}
}
return true;
default:
return false;
}
}
// Equivalent of typeof but with special handling for arrays
function getPropType(propValue) {
var propType = typeof propValue;
if (propType === 'object' && Array.isArray(propValue)) {
return 'array';
}
return propType;
}
function createAnyTypeChecker() {
function validateAnyType(
shouldWarn, propValue, propName, componentName, location
) {
return true; // is always valid
}
return createChainableTypeChecker(validateAnyType);
}
function createPrimitiveTypeChecker(expectedType) {
function validatePrimitiveType(
shouldWarn, propValue, propName, componentName, location
) {
var propType = getPropType(propValue);
var isValid = propType === expectedType;
if (shouldWarn) {
("production" !== "development" ? warning(
isValid,
'Invalid %s `%s` of type `%s` supplied to `%s`, expected `%s`.',
ReactPropTypeLocationNames[location],
propName,
propType,
componentName,
expectedType
) : null);
}
return isValid;
}
return createChainableTypeChecker(validatePrimitiveType);
}
function createEnumTypeChecker(expectedValues) {
var expectedEnum = createObjectFrom(expectedValues);
function validateEnumType(
shouldWarn, propValue, propName, componentName, location
) {
var isValid = expectedEnum[propValue];
if (shouldWarn) {
("production" !== "development" ? warning(
isValid,
'Invalid %s `%s` supplied to `%s`, expected one of %s.',
ReactPropTypeLocationNames[location],
propName,
componentName,
JSON.stringify(Object.keys(expectedEnum))
) : null);
}
return isValid;
}
return createChainableTypeChecker(validateEnumType);
}
function createShapeTypeChecker(shapeTypes) {
function validateShapeType(
shouldWarn, propValue, propName, componentName, location
) {
var propType = getPropType(propValue);
var isValid = propType === 'object';
if (isValid) {
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (checker && !checker(propValue, key, componentName, location)) {
return false;
}
}
}
if (shouldWarn) {
("production" !== "development" ? warning(
isValid,
'Invalid %s `%s` of type `%s` supplied to `%s`, expected `object`.',
ReactPropTypeLocationNames[location],
propName,
propType,
componentName
) : null);
}
return isValid;
}
return createChainableTypeChecker(validateShapeType);
}
function createInstanceTypeChecker(expectedClass) {
function validateInstanceType(
shouldWarn, propValue, propName, componentName, location
) {
var isValid = propValue instanceof expectedClass;
if (shouldWarn) {
("production" !== "development" ? warning(
isValid,
'Invalid %s `%s` supplied to `%s`, expected instance of `%s`.',
ReactPropTypeLocationNames[location],
propName,
componentName,
expectedClass.name || ANONYMOUS
) : null);
}
return isValid;
}
return createChainableTypeChecker(validateInstanceType);
}
function createArrayOfTypeChecker(propTypeChecker) {
function validateArrayType(
shouldWarn, propValue, propName, componentName, location
) {
var isValid = Array.isArray(propValue);
if (isValid) {
for (var i = 0; i < propValue.length; i++) {
if (!propTypeChecker(propValue, i, componentName, location)) {
return false;
}
}
}
if (shouldWarn) {
("production" !== "development" ? warning(
isValid,
'Invalid %s `%s` supplied to `%s`, expected an array.',
ReactPropTypeLocationNames[location],
propName,
componentName
) : null);
}
return isValid;
}
return createChainableTypeChecker(validateArrayType);
}
function createRenderableTypeChecker() {
function validateRenderableType(
shouldWarn, propValue, propName, componentName, location
) {
var isValid = isRenderable(propValue);
if (shouldWarn) {
("production" !== "development" ? warning(
isValid,
'Invalid %s `%s` supplied to `%s`, expected a renderable prop.',
ReactPropTypeLocationNames[location],
propName,
componentName
) : null);
}
return isValid;
}
return createChainableTypeChecker(validateRenderableType);
}
function createComponentTypeChecker() {
function validateComponentType(
shouldWarn, propValue, propName, componentName, location
) {
var isValid = ReactComponent.isValidComponent(propValue);
if (shouldWarn) {
("production" !== "development" ? warning(
isValid,
'Invalid %s `%s` supplied to `%s`, expected a React component.',
ReactPropTypeLocationNames[location],
propName,
componentName
) : null);
}
return isValid;
}
return createChainableTypeChecker(validateComponentType);
}
function createUnionTypeChecker(arrayOfValidators) {
return function(props, propName, componentName, location) {
var isValid = false;
for (var ii = 0; ii < arrayOfValidators.length; ii++) {
var validate = arrayOfValidators[ii];
if (typeof validate.weak === 'function') {
validate = validate.weak;
}
if (validate(props, propName, componentName, location)) {
isValid = true;
break;
}
}
("production" !== "development" ? warning(
isValid,
'Invalid %s `%s` supplied to `%s`.',
ReactPropTypeLocationNames[location],
propName,
componentName || ANONYMOUS
) : null);
return isValid;
};
}
function createChainableTypeChecker(validate) {
function checkType(
isRequired, shouldWarn, props, propName, componentName, location
) {
var propValue = props[propName];
if (propValue != null) {
// Only validate if there is a value to check.
return validate(
shouldWarn,
propValue,
propName,
componentName || ANONYMOUS,
location
);
} else {
var isValid = !isRequired;
if (shouldWarn) {
("production" !== "development" ? warning(
isValid,
'Required %s `%s` was not specified in `%s`.',
ReactPropTypeLocationNames[location],
propName,
componentName || ANONYMOUS
) : null);
}
return isValid;
}
}
var checker = checkType.bind(null, false, true);
checker.weak = checkType.bind(null, false, false);
checker.isRequired = checkType.bind(null, true, true);
checker.weak.isRequired = checkType.bind(null, true, false);
checker.isRequired.weak = checker.weak.isRequired;
return checker;
}
module.exports = Props;
},{"./ReactComponent":27,"./ReactPropTypeLocationNames":62,"./createObjectFrom":94,"./warning":134}],65:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactPutListenerQueue
*/
"use strict";
var PooledClass = _dereq_("./PooledClass");
var ReactEventEmitter = _dereq_("./ReactEventEmitter");
var mixInto = _dereq_("./mixInto");
function ReactPutListenerQueue() {
this.listenersToPut = [];
}
mixInto(ReactPutListenerQueue, {
enqueuePutListener: function(rootNodeID, propKey, propValue) {
this.listenersToPut.push({
rootNodeID: rootNodeID,
propKey: propKey,
propValue: propValue
});
},
putListeners: function() {
for (var i = 0; i < this.listenersToPut.length; i++) {
var listenerToPut = this.listenersToPut[i];
ReactEventEmitter.putListener(
listenerToPut.rootNodeID,
listenerToPut.propKey,
listenerToPut.propValue
);
}
},
reset: function() {
this.listenersToPut.length = 0;
},
destructor: function() {
this.reset();
}
});
PooledClass.addPoolingTo(ReactPutListenerQueue);
module.exports = ReactPutListenerQueue;
},{"./PooledClass":23,"./ReactEventEmitter":48,"./mixInto":124}],66:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactReconcileTransaction
* @typechecks static-only
*/
"use strict";
var PooledClass = _dereq_("./PooledClass");
var ReactEventEmitter = _dereq_("./ReactEventEmitter");
var ReactInputSelection = _dereq_("./ReactInputSelection");
var ReactMountReady = _dereq_("./ReactMountReady");
var ReactPutListenerQueue = _dereq_("./ReactPutListenerQueue");
var Transaction = _dereq_("./Transaction");
var mixInto = _dereq_("./mixInto");
/**
* 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 `ReactEventEmitter` before the
* reconciliation.
*/
initialize: function() {
var currentlyEnabled = ReactEventEmitter.isEnabled();
ReactEventEmitter.setEnabled(false);
return currentlyEnabled;
},
/**
* @param {boolean} previouslyEnabled Enabled status of `ReactEventEmitter`
* before the reconciliation occured. `close` restores the previous value.
*/
close: function(previouslyEnabled) {
ReactEventEmitter.setEnabled(previouslyEnabled);
}
};
/**
* Provides a `ReactMountReady` 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();
},
/**
* After DOM is flushed, invoke all registered `onDOMReady` callbacks.
*/
close: function() {
this.reactMountReady.notifyAll();
}
};
var PUT_LISTENER_QUEUEING = {
initialize: function() {
this.putListenerQueue.reset();
},
close: function() {
this.putListenerQueue.putListeners();
}
};
/**
* 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 = [
PUT_LISTENER_QUEUEING,
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() {
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 = ReactMountReady.getPooled(null);
this.putListenerQueue = ReactPutListenerQueue.getPooled();
}
var Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array<object>} List of operation wrap proceedures.
* TODO: convert to array<TransactionWrapper>
*/
getTransactionWrappers: function() {
return TRANSACTION_WRAPPERS;
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
* TODO: convert to ReactMountReady
*/
getReactMountReady: function() {
return this.reactMountReady;
},
getPutListenerQueue: function() {
return this.putListenerQueue;
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be resused.
*/
destructor: function() {
ReactMountReady.release(this.reactMountReady);
this.reactMountReady = null;
ReactPutListenerQueue.release(this.putListenerQueue);
this.putListenerQueue = null;
}
};
mixInto(ReactReconcileTransaction, Transaction.Mixin);
mixInto(ReactReconcileTransaction, Mixin);
PooledClass.addPoolingTo(ReactReconcileTransaction);
module.exports = ReactReconcileTransaction;
},{"./PooledClass":23,"./ReactEventEmitter":48,"./ReactInputSelection":52,"./ReactMountReady":56,"./ReactPutListenerQueue":65,"./Transaction":85,"./mixInto":124}],67:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactRootIndex
* @typechecks
*/
"use strict";
var ReactRootIndexInjection = {
/**
* @param {function} _createReactRootIndex
*/
injectCreateReactRootIndex: function(_createReactRootIndex) {
ReactRootIndex.createReactRootIndex = _createReactRootIndex;
}
};
var ReactRootIndex = {
createReactRootIndex: null,
injection: ReactRootIndexInjection
};
module.exports = ReactRootIndex;
},{}],68:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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.
*
* @typechecks static-only
* @providesModule ReactServerRendering
*/
"use strict";
var ReactComponent = _dereq_("./ReactComponent");
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactMarkupChecksum = _dereq_("./ReactMarkupChecksum");
var ReactServerRenderingTransaction =
_dereq_("./ReactServerRenderingTransaction");
var instantiateReactComponent = _dereq_("./instantiateReactComponent");
var invariant = _dereq_("./invariant");
/**
* @param {ReactComponent} component
* @return {string} the HTML markup
*/
function renderComponentToString(component) {
("production" !== "development" ? invariant(
ReactComponent.isValidComponent(component),
'renderComponentToString(): You must pass a valid ReactComponent.'
) : invariant(ReactComponent.isValidComponent(component)));
("production" !== "development" ? invariant(
!(arguments.length === 2 && typeof arguments[1] === 'function'),
'renderComponentToString(): This function became synchronous and now ' +
'returns the generated markup. Please remove the second parameter.'
) : invariant(!(arguments.length === 2 && typeof arguments[1] === 'function')));
var transaction;
try {
var id = ReactInstanceHandles.createReactRootID();
transaction = ReactServerRenderingTransaction.getPooled(false);
return transaction.perform(function() {
var componentInstance = instantiateReactComponent(component);
var markup = componentInstance.mountComponent(id, transaction, 0);
return ReactMarkupChecksum.addChecksumToMarkup(markup);
}, null);
} finally {
ReactServerRenderingTransaction.release(transaction);
}
}
/**
* @param {ReactComponent} component
* @return {string} the HTML markup, without the extra React ID and checksum
* (for generating static pages)
*/
function renderComponentToStaticMarkup(component) {
("production" !== "development" ? invariant(
ReactComponent.isValidComponent(component),
'renderComponentToStaticMarkup(): You must pass a valid ReactComponent.'
) : invariant(ReactComponent.isValidComponent(component)));
var transaction;
try {
var id = ReactInstanceHandles.createReactRootID();
transaction = ReactServerRenderingTransaction.getPooled(true);
return transaction.perform(function() {
var componentInstance = instantiateReactComponent(component);
return componentInstance.mountComponent(id, transaction, 0);
}, null);
} finally {
ReactServerRenderingTransaction.release(transaction);
}
}
module.exports = {
renderComponentToString: renderComponentToString,
renderComponentToStaticMarkup: renderComponentToStaticMarkup
};
},{"./ReactComponent":27,"./ReactInstanceHandles":53,"./ReactMarkupChecksum":54,"./ReactServerRenderingTransaction":69,"./instantiateReactComponent":111,"./invariant":112}],69:[function(_dereq_,module,exports){
/**
* Copyright 2014 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 ReactServerRenderingTransaction
* @typechecks
*/
"use strict";
var PooledClass = _dereq_("./PooledClass");
var ReactMountReady = _dereq_("./ReactMountReady");
var ReactPutListenerQueue = _dereq_("./ReactPutListenerQueue");
var Transaction = _dereq_("./Transaction");
var emptyFunction = _dereq_("./emptyFunction");
var mixInto = _dereq_("./mixInto");
/**
* Provides a `ReactMountReady` 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
};
var PUT_LISTENER_QUEUEING = {
initialize: function() {
this.putListenerQueue.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 = [
PUT_LISTENER_QUEUEING,
ON_DOM_READY_QUEUEING
];
/**
* @class ReactServerRenderingTransaction
* @param {boolean} renderToStaticMarkup
*/
function ReactServerRenderingTransaction(renderToStaticMarkup) {
this.reinitializeTransaction();
this.renderToStaticMarkup = renderToStaticMarkup;
this.reactMountReady = ReactMountReady.getPooled(null);
this.putListenerQueue = ReactPutListenerQueue.getPooled();
}
var Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array} Empty list of operation wrap proceedures.
*/
getTransactionWrappers: function() {
return TRANSACTION_WRAPPERS;
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
* TODO: convert to ReactMountReady
*/
getReactMountReady: function() {
return this.reactMountReady;
},
getPutListenerQueue: function() {
return this.putListenerQueue;
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be resused.
*/
destructor: function() {
ReactMountReady.release(this.reactMountReady);
this.reactMountReady = null;
ReactPutListenerQueue.release(this.putListenerQueue);
this.putListenerQueue = null;
}
};
mixInto(ReactServerRenderingTransaction, Transaction.Mixin);
mixInto(ReactServerRenderingTransaction, Mixin);
PooledClass.addPoolingTo(ReactServerRenderingTransaction);
module.exports = ReactServerRenderingTransaction;
},{"./PooledClass":23,"./ReactMountReady":56,"./ReactPutListenerQueue":65,"./Transaction":85,"./emptyFunction":96,"./mixInto":124}],70:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactTextComponent
* @typechecks static-only
*/
"use strict";
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactComponent = _dereq_("./ReactComponent");
var escapeTextForBrowser = _dereq_("./escapeTextForBrowser");
var mixInto = _dereq_("./mixInto");
/**
* 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 ReactTextComponent
* @extends ReactComponent
* @internal
*/
var ReactTextComponent = function(initialText) {
this.construct({text: initialText});
};
/**
* Used to clone the text descriptor object before it's mounted.
*
* @param {object} props
* @return {object} A new ReactTextComponent instance
*/
ReactTextComponent.ConvenienceConstructor = function(props) {
return new ReactTextComponent(props.text);
};
mixInto(ReactTextComponent, ReactComponent.Mixin);
mixInto(ReactTextComponent, ReactBrowserComponentMixin);
mixInto(ReactTextComponent, {
/**
* 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
* @param {number} mountDepth number of components in the owner hierarchy
* @return {string} Markup for this text node.
* @internal
*/
mountComponent: function(rootID, transaction, mountDepth) {
ReactComponent.Mixin.mountComponent.call(
this,
rootID,
transaction,
mountDepth
);
var escapedText = escapeTextForBrowser(this.props.text);
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 {object} nextComponent Contains the next text content.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
receiveComponent: function(nextComponent, transaction) {
var nextProps = nextComponent.props;
if (nextProps.text !== this.props.text) {
this.props.text = nextProps.text;
ReactComponent.BackendIDOperations.updateTextContentByID(
this._rootNodeID,
nextProps.text
);
}
}
});
// Expose the constructor on itself and the prototype for consistency with other
// descriptors.
ReactTextComponent.type = ReactTextComponent;
ReactTextComponent.prototype.type = ReactTextComponent;
module.exports = ReactTextComponent;
},{"./DOMPropertyOperations":9,"./ReactBrowserComponentMixin":25,"./ReactComponent":27,"./escapeTextForBrowser":98,"./mixInto":124}],71:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ReactUpdates
*/
"use strict";
var ReactPerf = _dereq_("./ReactPerf");
var invariant = _dereq_("./invariant");
var dirtyComponents = [];
var batchingStrategy = null;
function ensureBatchingStrategy() {
("production" !== "development" ? invariant(batchingStrategy, 'ReactUpdates: must inject a batching strategy') : invariant(batchingStrategy));
}
function batchedUpdates(callback, param) {
ensureBatchingStrategy();
batchingStrategy.batchedUpdates(callback, param);
}
/**
* Array comparator for ReactComponents by owner depth
*
* @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 mountDepthComparator(c1, c2) {
return c1._mountDepth - c2._mountDepth;
}
function runBatchedUpdates() {
// 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(mountDepthComparator);
for (var i = 0; i < dirtyComponents.length; i++) {
// If a component is unmounted before pending changes apply, ignore them
// TODO: Queue unmounts in the same list to avoid this happening at all
var component = dirtyComponents[i];
if (component.isMounted()) {
// 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;
component.performUpdateIfNecessary();
if (callbacks) {
for (var j = 0; j < callbacks.length; j++) {
callbacks[j].call(component);
}
}
}
}
}
function clearDirtyComponents() {
dirtyComponents.length = 0;
}
var flushBatchedUpdates = ReactPerf.measure(
'ReactUpdates',
'flushBatchedUpdates',
function() {
// Run these in separate functions so the JIT can optimize
try {
runBatchedUpdates();
} finally {
clearDirtyComponents();
}
}
);
/**
* 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, callback) {
("production" !== "development" ? invariant(
!callback || typeof callback === "function",
'enqueueUpdate(...): You called `setProps`, `replaceProps`, ' +
'`setState`, `replaceState`, or `forceUpdate` with a callback that ' +
'isn\'t callable.'
) : invariant(!callback || typeof callback === "function"));
ensureBatchingStrategy();
if (!batchingStrategy.isBatchingUpdates) {
component.performUpdateIfNecessary();
callback && callback.call(component);
return;
}
dirtyComponents.push(component);
if (callback) {
if (component._pendingCallbacks) {
component._pendingCallbacks.push(callback);
} else {
component._pendingCallbacks = [callback];
}
}
}
var ReactUpdatesInjection = {
injectBatchingStrategy: function(_batchingStrategy) {
("production" !== "development" ? invariant(
_batchingStrategy,
'ReactUpdates: must provide a batching strategy'
) : invariant(_batchingStrategy));
("production" !== "development" ? invariant(
typeof _batchingStrategy.batchedUpdates === 'function',
'ReactUpdates: must provide a batchedUpdates() function'
) : invariant(typeof _batchingStrategy.batchedUpdates === 'function'));
("production" !== "development" ? invariant(
typeof _batchingStrategy.isBatchingUpdates === 'boolean',
'ReactUpdates: must provide an isBatchingUpdates boolean attribute'
) : invariant(typeof _batchingStrategy.isBatchingUpdates === 'boolean'));
batchingStrategy = _batchingStrategy;
}
};
var ReactUpdates = {
batchedUpdates: batchedUpdates,
enqueueUpdate: enqueueUpdate,
flushBatchedUpdates: flushBatchedUpdates,
injection: ReactUpdatesInjection
};
module.exports = ReactUpdates;
},{"./ReactPerf":60,"./invariant":112}],72:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SelectEventPlugin
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPropagators = _dereq_("./EventPropagators");
var ReactInputSelection = _dereq_("./ReactInputSelection");
var SyntheticEvent = _dereq_("./SyntheticEvent");
var getActiveElement = _dereq_("./getActiveElement");
var isTextInputElement = _dereq_("./isTextInputElement");
var keyOf = _dereq_("./keyOf");
var shallowEqual = _dereq_("./shallowEqual");
var topLevelTypes = EventConstants.topLevelTypes;
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;
/**
* 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
* @param {object}
*/
function getSelection(node) {
if ('selectionStart' in node &&
ReactInputSelection.hasSelectionCapabilities(node)) {
return {
start: node.selectionStart,
end: node.selectionEnd
};
} else if (document.selection) {
var range = document.selection.createRange();
return {
parentElement: range.parentElement(),
text: range.text,
top: range.boundingTop,
left: range.boundingLeft
};
} else {
var selection = window.getSelection();
return {
anchorNode: selection.anchorNode,
anchorOffset: selection.anchorOffset,
focusNode: selection.focusNode,
focusOffset: selection.focusOffset
};
}
}
/**
* Poll selection to see whether it's changed.
*
* @param {object} nativeEvent
* @return {?SyntheticEvent}
*/
function constructSelectEvent(nativeEvent) {
// 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;
}
// 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
);
syntheticEvent.type = 'select';
syntheticEvent.target = activeElement;
EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent);
return syntheticEvent;
}
}
/**
* 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) {
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);
// Chrome and IE fire non-standard event when selection is changed (and
// sometimes when it hasn't).
// 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.
case topLevelTypes.topSelectionChange:
case topLevelTypes.topKeyDown:
case topLevelTypes.topKeyUp:
return constructSelectEvent(nativeEvent);
}
}
};
module.exports = SelectEventPlugin;
},{"./EventConstants":14,"./EventPropagators":19,"./ReactInputSelection":52,"./SyntheticEvent":78,"./getActiveElement":102,"./isTextInputElement":115,"./keyOf":119,"./shallowEqual":130}],73:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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;
},{}],74:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SimpleEventPlugin
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPluginUtils = _dereq_("./EventPluginUtils");
var EventPropagators = _dereq_("./EventPropagators");
var SyntheticClipboardEvent = _dereq_("./SyntheticClipboardEvent");
var SyntheticEvent = _dereq_("./SyntheticEvent");
var SyntheticFocusEvent = _dereq_("./SyntheticFocusEvent");
var SyntheticKeyboardEvent = _dereq_("./SyntheticKeyboardEvent");
var SyntheticMouseEvent = _dereq_("./SyntheticMouseEvent");
var SyntheticDragEvent = _dereq_("./SyntheticDragEvent");
var SyntheticTouchEvent = _dereq_("./SyntheticTouchEvent");
var SyntheticUIEvent = _dereq_("./SyntheticUIEvent");
var SyntheticWheelEvent = _dereq_("./SyntheticWheelEvent");
var invariant = _dereq_("./invariant");
var keyOf = _dereq_("./keyOf");
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
blur: {
phasedRegistrationNames: {
bubbled: keyOf({onBlur: true}),
captured: keyOf({onBlurCapture: 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})
}
},
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})
}
},
error: {
phasedRegistrationNames: {
bubbled: keyOf({onError: true}),
captured: keyOf({onErrorCapture: 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})
}
},
reset: {
phasedRegistrationNames: {
bubbled: keyOf({onReset: true}),
captured: keyOf({onResetCapture: true})
}
},
scroll: {
phasedRegistrationNames: {
bubbled: keyOf({onScroll: true}),
captured: keyOf({onScrollCapture: true})
}
},
submit: {
phasedRegistrationNames: {
bubbled: keyOf({onSubmit: true}),
captured: keyOf({onSubmitCapture: 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})
}
},
wheel: {
phasedRegistrationNames: {
bubbled: keyOf({onWheel: true}),
captured: keyOf({onWheelCapture: true})
}
}
};
var topLevelEventsToDispatchConfig = {
topBlur: eventTypes.blur,
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,
topError: eventTypes.error,
topFocus: eventTypes.focus,
topInput: eventTypes.input,
topKeyDown: eventTypes.keyDown,
topKeyPress: eventTypes.keyPress,
topKeyUp: eventTypes.keyUp,
topLoad: eventTypes.load,
topMouseDown: eventTypes.mouseDown,
topMouseMove: eventTypes.mouseMove,
topMouseOut: eventTypes.mouseOut,
topMouseOver: eventTypes.mouseOver,
topMouseUp: eventTypes.mouseUp,
topPaste: eventTypes.paste,
topReset: eventTypes.reset,
topScroll: eventTypes.scroll,
topSubmit: eventTypes.submit,
topTouchCancel: eventTypes.touchCancel,
topTouchEnd: eventTypes.touchEnd,
topTouchMove: eventTypes.touchMove,
topTouchStart: eventTypes.touchStart,
topWheel: eventTypes.wheel
};
for (var topLevelType in topLevelEventsToDispatchConfig) {
topLevelEventsToDispatchConfig[topLevelType].dependencies = [topLevelType];
}
var SimpleEventPlugin = {
eventTypes: eventTypes,
/**
* Same as the default implementation, except cancels the event when return
* value is false.
*
* @param {object} Event to be dispatched.
* @param {function} Application-level callback.
* @param {string} domID DOM ID to pass to the callback.
*/
executeDispatch: function(event, listener, domID) {
var returnValue = EventPluginUtils.executeDispatch(event, listener, domID);
if (returnValue === false) {
event.stopPropagation();
event.preventDefault();
}
},
/**
* @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) {
var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
if (!dispatchConfig) {
return null;
}
var EventConstructor;
switch (topLevelType) {
case topLevelTypes.topInput:
case topLevelTypes.topLoad:
case topLevelTypes.topError:
case topLevelTypes.topReset:
case topLevelTypes.topSubmit:
// HTML Events
// @see http://www.w3.org/TR/html5/index.html#events-0
EventConstructor = SyntheticEvent;
break;
case topLevelTypes.topKeyDown:
case topLevelTypes.topKeyPress:
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;
}
("production" !== "development" ? invariant(
EventConstructor,
'SimpleEventPlugin: Unhandled event type, `%s`.',
topLevelType
) : invariant(EventConstructor));
var event = EventConstructor.getPooled(
dispatchConfig,
topLevelTargetID,
nativeEvent
);
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
};
module.exports = SimpleEventPlugin;
},{"./EventConstants":14,"./EventPluginUtils":18,"./EventPropagators":19,"./SyntheticClipboardEvent":75,"./SyntheticDragEvent":77,"./SyntheticEvent":78,"./SyntheticFocusEvent":79,"./SyntheticKeyboardEvent":80,"./SyntheticMouseEvent":81,"./SyntheticTouchEvent":82,"./SyntheticUIEvent":83,"./SyntheticWheelEvent":84,"./invariant":112,"./keyOf":119}],75:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SyntheticClipboardEvent
* @typechecks static-only
*/
"use strict";
var SyntheticEvent = _dereq_("./SyntheticEvent");
/**
* @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) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface);
module.exports = SyntheticClipboardEvent;
},{"./SyntheticEvent":78}],76:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SyntheticCompositionEvent
* @typechecks static-only
*/
"use strict";
var SyntheticEvent = _dereq_("./SyntheticEvent");
/**
* @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) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticEvent.augmentClass(
SyntheticCompositionEvent,
CompositionEventInterface
);
module.exports = SyntheticCompositionEvent;
},{"./SyntheticEvent":78}],77:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SyntheticDragEvent
* @typechecks static-only
*/
"use strict";
var SyntheticMouseEvent = _dereq_("./SyntheticMouseEvent");
/**
* @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) {
SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface);
module.exports = SyntheticDragEvent;
},{"./SyntheticMouseEvent":81}],78:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SyntheticEvent
* @typechecks static-only
*/
"use strict";
var PooledClass = _dereq_("./PooledClass");
var emptyFunction = _dereq_("./emptyFunction");
var getEventTarget = _dereq_("./getEventTarget");
var merge = _dereq_("./merge");
var mergeInto = _dereq_("./mergeInto");
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var EventInterface = {
type: null,
target: getEventTarget,
// 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) {
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 {
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;
}
mergeInto(SyntheticEvent.prototype, {
preventDefault: function() {
this.defaultPrevented = true;
var event = this.nativeEvent;
event.preventDefault ? event.preventDefault() : event.returnValue = false;
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
},
stopPropagation: function() {
var event = this.nativeEvent;
event.stopPropagation ? event.stopPropagation() : 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);
mergeInto(prototype, Class.prototype);
Class.prototype = prototype;
Class.prototype.constructor = Class;
Class.Interface = merge(Super.Interface, Interface);
Class.augmentClass = Super.augmentClass;
PooledClass.addPoolingTo(Class, PooledClass.threeArgumentPooler);
};
PooledClass.addPoolingTo(SyntheticEvent, PooledClass.threeArgumentPooler);
module.exports = SyntheticEvent;
},{"./PooledClass":23,"./emptyFunction":96,"./getEventTarget":104,"./merge":121,"./mergeInto":123}],79:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SyntheticFocusEvent
* @typechecks static-only
*/
"use strict";
var SyntheticUIEvent = _dereq_("./SyntheticUIEvent");
/**
* @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) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface);
module.exports = SyntheticFocusEvent;
},{"./SyntheticUIEvent":83}],80:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SyntheticKeyboardEvent
* @typechecks static-only
*/
"use strict";
var SyntheticUIEvent = _dereq_("./SyntheticUIEvent");
var getEventKey = _dereq_("./getEventKey");
/**
* @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,
// Legacy Interface
'char': null,
charCode: null,
keyCode: null,
which: 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 SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface);
module.exports = SyntheticKeyboardEvent;
},{"./SyntheticUIEvent":83,"./getEventKey":103}],81:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SyntheticMouseEvent
* @typechecks static-only
*/
"use strict";
var SyntheticUIEvent = _dereq_("./SyntheticUIEvent");
var ViewportMetrics = _dereq_("./ViewportMetrics");
/**
* @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,
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) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface);
module.exports = SyntheticMouseEvent;
},{"./SyntheticUIEvent":83,"./ViewportMetrics":86}],82:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SyntheticTouchEvent
* @typechecks static-only
*/
"use strict";
var SyntheticUIEvent = _dereq_("./SyntheticUIEvent");
/**
* @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
};
/**
* @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) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface);
module.exports = SyntheticTouchEvent;
},{"./SyntheticUIEvent":83}],83:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SyntheticUIEvent
* @typechecks static-only
*/
"use strict";
var SyntheticEvent = _dereq_("./SyntheticEvent");
/**
* @interface UIEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var UIEventInterface = {
view: null,
detail: 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 {SyntheticEvent}
*/
function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface);
module.exports = SyntheticUIEvent;
},{"./SyntheticEvent":78}],84:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 SyntheticWheelEvent
* @typechecks static-only
*/
"use strict";
var SyntheticMouseEvent = _dereq_("./SyntheticMouseEvent");
/**
* @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) {
SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface);
module.exports = SyntheticWheelEvent;
},{"./SyntheticMouseEvent":81}],85:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 Transaction
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* `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>
*
* Bonus:
* - Reports timing metrics by method name and wrapper index.
*
* 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 upates.
*
* 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 = [];
} else {
this.wrapperInitData.length = 0;
}
if (!this.timingMetrics) {
this.timingMetrics = {};
}
this.timingMetrics.methodInvocationTime = 0;
if (!this.timingMetrics.wrapperInitTimes) {
this.timingMetrics.wrapperInitTimes = [];
} else {
this.timingMetrics.wrapperInitTimes.length = 0;
}
if (!this.timingMetrics.wrapperCloseTimes) {
this.timingMetrics.wrapperCloseTimes = [];
} else {
this.timingMetrics.wrapperCloseTimes.length = 0;
}
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.
*
* @param {function} method Member of scope to call.
* @param {Object} scope Scope to invoke from.
* @param {Object?=} args... Arguments to pass to the method (optional).
* Helps prevent need to bind in many cases.
* @return Return value from `method`.
*/
perform: function(method, scope, a, b, c, d, e, f) {
("production" !== "development" ? invariant(
!this.isInTransaction(),
'Transaction.perform(...): Cannot initialize a transaction when there ' +
'is already an outstanding transaction.'
) : invariant(!this.isInTransaction()));
var memberStart = Date.now();
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 {
var memberEnd = Date.now();
this.methodInvocationTime += (memberEnd - memberStart);
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;
var wrapperInitTimes = this.timingMetrics.wrapperInitTimes;
for (var i = startIndex; i < transactionWrappers.length; i++) {
var initStart = Date.now();
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 {
var curInitTime = wrapperInitTimes[i];
var initEnd = Date.now();
wrapperInitTimes[i] = (curInitTime || 0) + (initEnd - initStart);
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) {
("production" !== "development" ? invariant(
this.isInTransaction(),
'Transaction.closeAll(): Cannot close transaction when none are open.'
) : invariant(this.isInTransaction()));
var transactionWrappers = this.transactionWrappers;
var wrapperCloseTimes = this.timingMetrics.wrapperCloseTimes;
for (var i = startIndex; i < transactionWrappers.length; i++) {
var wrapper = transactionWrappers[i];
var closeStart = Date.now();
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 {
var closeEnd = Date.now();
var curCloseTime = wrapperCloseTimes[i];
wrapperCloseTimes[i] = (curCloseTime || 0) + (closeEnd - closeStart);
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 occured.
*/
OBSERVED_ERROR: {}
};
module.exports = Transaction;
},{"./invariant":112}],86:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 ViewportMetrics
*/
"use strict";
var getUnboundedScrollPosition = _dereq_("./getUnboundedScrollPosition");
var ViewportMetrics = {
currentScrollLeft: 0,
currentScrollTop: 0,
refreshScrollValues: function() {
var scrollPosition = getUnboundedScrollPosition(window);
ViewportMetrics.currentScrollLeft = scrollPosition.x;
ViewportMetrics.currentScrollTop = scrollPosition.y;
}
};
module.exports = ViewportMetrics;
},{"./getUnboundedScrollPosition":109}],87:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 accumulate
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* Accumulates items that must not be null or undefined.
*
* This is used to conserve memory by avoiding array allocations.
*
* @return {*|array<*>} An accumulation of items.
*/
function accumulate(current, next) {
("production" !== "development" ? invariant(
next != null,
'accumulate(...): Accumulated items must be not be null or undefined.'
) : invariant(next != null));
if (current == null) {
return next;
} else {
// 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) {
return current.concat(next);
} else {
if (nextIsArray) {
return [current].concat(next);
} else {
return [current, next];
}
}
}
}
module.exports = accumulate;
},{"./invariant":112}],88:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 adler32
*/
/* jslint bitwise:true */
"use strict";
var MOD = 65521;
// This is a clean-room implementation of adler32 designed for detecting
// if markup is not what we expect it to be. It does not need to be
// cryptographically strong, only reasonable good at detecting if markup
// generated on the server is different than that on the client.
function adler32(data) {
var a = 1;
var b = 0;
for (var i = 0; i < data.length; i++) {
a = (a + data.charCodeAt(i)) % MOD;
b = (b + a) % MOD;
}
return a | (b << 16);
}
module.exports = adler32;
},{}],89:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 containsNode
* @typechecks
*/
var isTextNode = _dereq_("./isTextNode");
/*jslint bitwise:true */
/**
* 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(outerNode, innerNode) {
if (!outerNode || !innerNode) {
return false;
} else if (outerNode === innerNode) {
return true;
} else if (isTextNode(outerNode)) {
return false;
} else if (isTextNode(innerNode)) {
return containsNode(outerNode, innerNode.parentNode);
} else if (outerNode.contains) {
return outerNode.contains(innerNode);
} else if (outerNode.compareDocumentPosition) {
return !!(outerNode.compareDocumentPosition(innerNode) & 16);
} else {
return false;
}
}
module.exports = containsNode;
},{"./isTextNode":116}],90:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 copyProperties
*/
/**
* Copy properties from one or more objects (up to 5) into the first object.
* This is a shallow copy. It mutates the first object and also returns it.
*
* NOTE: `arguments` has a very significant performance penalty, which is why
* we don't support unlimited arguments.
*/
function copyProperties(obj, a, b, c, d, e, f) {
obj = obj || {};
if ("production" !== "development") {
if (f) {
throw new Error('Too many arguments passed to copyProperties');
}
}
var args = [a, b, c, d, e];
var ii = 0, v;
while (args[ii]) {
v = args[ii++];
for (var k in v) {
obj[k] = v[k];
}
// IE ignores toString in object iteration.. See:
// webreflection.blogspot.com/2007/07/quick-fix-internet-explorer-and.html
if (v.hasOwnProperty && v.hasOwnProperty('toString') &&
(typeof v.toString != 'undefined') && (obj.toString !== v.toString)) {
obj.toString = v.toString;
}
}
return obj;
}
module.exports = copyProperties;
},{}],91:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 createArrayFrom
* @typechecks
*/
var toArray = _dereq_("./toArray");
/**
* 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
(// HTMLCollection/NodeList
(Array.isArray(obj) ||
// arguments
('callee' in obj) || '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 createArrayFrom = require('createArrayFrom');
*
* function takesOneOrMoreThings(things) {
* things = createArrayFrom(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 createArrayFrom(obj) {
if (!hasArrayNature(obj)) {
return [obj];
} else if (Array.isArray(obj)) {
return obj.slice();
} else {
return toArray(obj);
}
}
module.exports = createArrayFrom;
},{"./toArray":132}],92:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 createFullPageComponent
* @typechecks
*/
"use strict";
// Defeat circular references by requiring this directly.
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var invariant = _dereq_("./invariant");
/**
* Create a component that will throw an exception when unmounted.
*
* 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.
*
* @param {function} componentClass convenience constructor to wrap
* @return {function} convenience constructor of new component
*/
function createFullPageComponent(componentClass) {
var FullPageComponent = ReactCompositeComponent.createClass({
displayName: 'ReactFullPageComponent' + (
componentClass.componentConstructor.displayName || ''
),
componentWillUnmount: function() {
("production" !== "development" ? 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.constructor.displayName
) : invariant(false));
},
render: function() {
return this.transferPropsTo(componentClass(null, this.props.children));
}
});
return FullPageComponent;
}
module.exports = createFullPageComponent;
},{"./ReactCompositeComponent":29,"./invariant":112}],93:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 createNodesFromMarkup
* @typechecks
*/
/*jslint evil: true, sub: true */
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var createArrayFrom = _dereq_("./createArrayFrom");
var getMarkupWrap = _dereq_("./getMarkupWrap");
var invariant = _dereq_("./invariant");
/**
* 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;
("production" !== "development" ? invariant(!!dummyNode, 'createNodesFromMarkup dummy not initialized') : invariant(!!dummyNode));
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) {
("production" !== "development" ? invariant(
handleScript,
'createNodesFromMarkup(...): Unexpected <script> element rendered.'
) : invariant(handleScript));
createArrayFrom(scripts).forEach(handleScript);
}
var nodes = createArrayFrom(node.childNodes);
while (node.lastChild) {
node.removeChild(node.lastChild);
}
return nodes;
}
module.exports = createNodesFromMarkup;
},{"./ExecutionEnvironment":20,"./createArrayFrom":91,"./getMarkupWrap":105,"./invariant":112}],94:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 createObjectFrom
*/
/**
* Construct an object from an array of keys
* and optionally specified value or list of values.
*
* >>> createObjectFrom(['a','b','c']);
* {a: true, b: true, c: true}
*
* >>> createObjectFrom(['a','b','c'], false);
* {a: false, b: false, c: false}
*
* >>> createObjectFrom(['a','b','c'], 'monkey');
* {c:'monkey', b:'monkey' c:'monkey'}
*
* >>> createObjectFrom(['a','b','c'], [1,2,3]);
* {a: 1, b: 2, c: 3}
*
* >>> createObjectFrom(['women', 'men'], [true, false]);
* {women: true, men: false}
*
* @param Array list of keys
* @param mixed optional value or value array. defaults true.
* @returns object
*/
function createObjectFrom(keys, values /* = true */) {
if ("production" !== "development") {
if (!Array.isArray(keys)) {
throw new TypeError('Must pass an array of keys.');
}
}
var object = {};
var isArray = Array.isArray(values);
if (typeof values == 'undefined') {
values = true;
}
for (var ii = keys.length; ii--;) {
object[keys[ii]] = isArray ? values[ii] : values;
}
return object;
}
module.exports = createObjectFrom;
},{}],95:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 dangerousStyleValue
* @typechecks static-only
*/
"use strict";
var CSSProperty = _dereq_("./CSSProperty");
/**
* Convert a value into the proper css writable value. The `styleName` name
* name should be logical (no hyphens), as specified
* in `CSSProperty.isUnitlessNumber`.
*
* @param {string} styleName CSS property name such as `topMargin`.
* @param {*} value CSS property value such as `10px`.
* @return {string} Normalized style value with dimensions applied.
*/
function dangerousStyleValue(styleName, 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 || CSSProperty.isUnitlessNumber[styleName]) {
return '' + value; // cast to string
}
return value + 'px';
}
module.exports = dangerousStyleValue;
},{"./CSSProperty":2}],96:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 emptyFunction
*/
var copyProperties = _dereq_("./copyProperties");
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() {}
copyProperties(emptyFunction, {
thatReturns: makeEmptyFunction,
thatReturnsFalse: makeEmptyFunction(false),
thatReturnsTrue: makeEmptyFunction(true),
thatReturnsNull: makeEmptyFunction(null),
thatReturnsThis: function() { return this; },
thatReturnsArgument: function(arg) { return arg; }
});
module.exports = emptyFunction;
},{"./copyProperties":90}],97:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 emptyObject
*/
"use strict";
var emptyObject = {};
if ("production" !== "development") {
Object.freeze(emptyObject);
}
module.exports = emptyObject;
},{}],98:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 escapeTextForBrowser
* @typechecks static-only
*/
"use strict";
var ESCAPE_LOOKUP = {
"&": "&",
">": ">",
"<": "<",
"\"": """,
"'": "'",
"/": "/"
};
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 escapeTextForBrowser(text) {
return ('' + text).replace(ESCAPE_REGEX, escaper);
}
module.exports = escapeTextForBrowser;
},{}],99:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 flattenChildren
*/
"use strict";
var invariant = _dereq_("./invariant");
var traverseAllChildren = _dereq_("./traverseAllChildren");
/**
* @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;
("production" !== "development" ? invariant(
!result.hasOwnProperty(name),
'flattenChildren(...): Encountered two children with the same key, `%s`. ' +
'Children keys must be unique.',
name
) : invariant(!result.hasOwnProperty(name)));
if (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;
},{"./invariant":112,"./traverseAllChildren":133}],100:[function(_dereq_,module,exports){
/**
* Copyright 2014 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 focusNode
*/
"use strict";
/**
* IE8 throws if an input/textarea is disabled and we try to focus it.
* Focus only when necessary.
*
* @param {DOMElement} node input/textarea to focus
*/
function focusNode(node) {
if (!node.disabled) {
node.focus();
}
}
module.exports = focusNode;
},{}],101:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 forEachAccumulated
*/
"use strict";
/**
* @param {array} 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;
},{}],102:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 getActiveElement
* @typechecks
*/
/**
* 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 body is not yet defined.
*/
function getActiveElement() /*?DOMElement*/ {
try {
return document.activeElement || document.body;
} catch (e) {
return document.body;
}
}
module.exports = getActiveElement;
},{}],103:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 getEventKey
* @typechecks static-only
*/
"use strict";
/**
* 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 "which/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) {
return 'key' in nativeEvent ?
normalizeKey[nativeEvent.key] || nativeEvent.key :
translateToKey[nativeEvent.which || nativeEvent.keyCode] || 'Unidentified';
}
module.exports = getEventKey;
},{}],104:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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;
},{}],105:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 getMarkupWrap
*/
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var invariant = _dereq_("./invariant");
/**
* 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 = {
// Force wrapping for SVG elements because if they get created inside a <div>,
// they will be initialized in the wrong namespace (and will not display).
'circle': true,
'defs': true,
'g': true,
'line': true,
'linearGradient': true,
'path': true,
'polygon': true,
'polyline': true,
'radialGradient': true,
'rect': true,
'stop': true,
'text': true
};
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>', '</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,
'circle': svgWrap,
'defs': svgWrap,
'g': svgWrap,
'line': svgWrap,
'linearGradient': svgWrap,
'path': svgWrap,
'polygon': svgWrap,
'polyline': svgWrap,
'radialGradient': svgWrap,
'rect': svgWrap,
'stop': svgWrap,
'text': svgWrap
};
/**
* 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) {
("production" !== "development" ? invariant(!!dummyNode, 'Markup wrapping node not initialized') : invariant(!!dummyNode));
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;
},{"./ExecutionEnvironment":20,"./invariant":112}],106:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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;
},{}],107:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 getReactRootElementInContainer
*/
"use strict";
var DOC_NODE_TYPE = 9;
/**
* @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;
}
}
module.exports = getReactRootElementInContainer;
},{}],108:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 getTextContentAccessor
*/
"use strict";
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
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.createElement('div') ?
'textContent' :
'innerText';
}
return contentKey;
}
module.exports = getTextContentAccessor;
},{"./ExecutionEnvironment":20}],109:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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;
},{}],110:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 hyphenate
* @typechecks
*/
var _uppercasePattern = /([A-Z])/g;
/**
* Hyphenates a camelcased string, for example:
*
* > hyphenate('backgroundColor')
* < "background-color"
*
* @param {string} string
* @return {string}
*/
function hyphenate(string) {
return string.replace(_uppercasePattern, '-$1').toLowerCase();
}
module.exports = hyphenate;
},{}],111:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 instantiateReactComponent
* @typechecks static-only
*/
"use strict";
var warning = _dereq_("./warning");
/**
* Validate a `componentDescriptor`. This should be exposed publicly in a follow
* up diff.
*
* @param {object} descriptor
* @return {boolean} Returns true if this is a valid descriptor of a Component.
*/
function isValidComponentDescriptor(descriptor) {
return (
typeof descriptor.constructor === 'function' &&
typeof descriptor.constructor.prototype.construct === 'function' &&
typeof descriptor.constructor.prototype.mountComponent === 'function' &&
typeof descriptor.constructor.prototype.receiveComponent === 'function'
);
}
/**
* Given a `componentDescriptor` create an instance that will actually be
* mounted. Currently it just extracts an existing clone from composite
* components but this is an implementation detail which will change.
*
* @param {object} descriptor
* @return {object} A new instance of componentDescriptor's constructor.
* @protected
*/
function instantiateReactComponent(descriptor) {
if ("production" !== "development") {
("production" !== "development" ? warning(
isValidComponentDescriptor(descriptor),
'Only React Components are valid for mounting.'
) : null);
// We use the clone of a composite component instead of the original
// instance. This allows us to warn you if you're are accessing the wrong
// instance.
var instance = descriptor.__realComponentInstance || descriptor;
instance._descriptor = descriptor;
return instance;
}
// In prod we don't clone, we simply use the same instance for unaffected
// behavior. We have to keep the descriptor around for comparison later on.
// This should ideally be accepted in the constructor of the instance but
// since that is currently overloaded, we just manually attach it here.
descriptor._descriptor = descriptor;
return descriptor;
}
module.exports = instantiateReactComponent;
},{"./warning":134}],112:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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.
*/
var invariant = function(condition) {
if (!condition) {
var error = new Error(
'Minified exception occured; use the non-minified dev environment for ' +
'the full error message and additional helpful warnings.'
);
error.framesToPop = 1;
throw error;
}
};
if ("production" !== "development") {
invariant = function(condition, format, a, b, c, d, e, f) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
if (!condition) {
var args = [a, b, c, d, e, f];
var argIndex = 0;
var error = new Error(
'Invariant Violation: ' +
format.replace(/%s/g, function() { return args[argIndex++]; })
);
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
};
}
module.exports = invariant;
},{}],113:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 isEventSupported
*/
"use strict";
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
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;
},{"./ExecutionEnvironment":20}],114:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 isNode
* @typechecks
*/
/**
* @param {*} object The object to check.
* @return {boolean} Whether or not the object is a DOM node.
*/
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;
},{}],115:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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) {
return elem && (
(elem.nodeName === 'INPUT' && supportedInputTypes[elem.type]) ||
elem.nodeName === 'TEXTAREA'
);
}
module.exports = isTextInputElement;
},{}],116:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 isTextNode
* @typechecks
*/
var isNode = _dereq_("./isNode");
/**
* @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;
},{"./isNode":114}],117:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 joinClasses
* @typechecks static-only
*/
"use strict";
/**
* Combines multiple className strings into one.
* http://jsperf.com/joinclasses-args-vs-array
*
* @param {...?string} classes
* @return {string}
*/
function joinClasses(className/*, ... */) {
if (!className) {
className = '';
}
var nextClass;
var argLength = arguments.length;
if (argLength > 1) {
for (var ii = 1; ii < argLength; ii++) {
nextClass = arguments[ii];
nextClass && (className += ' ' + nextClass);
}
}
return className;
}
module.exports = joinClasses;
},{}],118:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 keyMirror
* @typechecks static-only
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* 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;
("production" !== "development" ? invariant(
obj instanceof Object && !Array.isArray(obj),
'keyMirror(...): Argument must be an object.'
) : invariant(obj instanceof Object && !Array.isArray(obj)));
for (key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = key;
}
return ret;
};
module.exports = keyMirror;
},{"./invariant":112}],119:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 keyOf
*/
/**
* Allows extraction of a minified key. Let's the build system minify keys
* without loosing 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.
*/
var keyOf = function(oneKeyObj) {
var key;
for (key in oneKeyObj) {
if (!oneKeyObj.hasOwnProperty(key)) {
continue;
}
return key;
}
return null;
};
module.exports = keyOf;
},{}],120:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 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)) {
return cache[string];
} else {
return cache[string] = callback.call(this, string);
}
};
}
module.exports = memoizeStringOnly;
},{}],121:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 merge
*/
"use strict";
var mergeInto = _dereq_("./mergeInto");
/**
* Shallow merges two structures into a return value, without mutating either.
*
* @param {?object} one Optional object with properties to merge from.
* @param {?object} two Optional object with properties to merge from.
* @return {object} The shallow extension of one by two.
*/
var merge = function(one, two) {
var result = {};
mergeInto(result, one);
mergeInto(result, two);
return result;
};
module.exports = merge;
},{"./mergeInto":123}],122:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 mergeHelpers
*
* requiresPolyfills: Array.isArray
*/
"use strict";
var invariant = _dereq_("./invariant");
var keyMirror = _dereq_("./keyMirror");
/**
* Maximum number of levels to traverse. Will catch circular structures.
* @const
*/
var MAX_MERGE_DEPTH = 36;
/**
* We won't worry about edge cases like new String('x') or new Boolean(true).
* Functions are considered terminals, and arrays are not.
* @param {*} o The item/object/value to test.
* @return {boolean} true iff the argument is a terminal.
*/
var isTerminal = function(o) {
return typeof o !== 'object' || o === null;
};
var mergeHelpers = {
MAX_MERGE_DEPTH: MAX_MERGE_DEPTH,
isTerminal: isTerminal,
/**
* Converts null/undefined values into empty object.
*
* @param {?Object=} arg Argument to be normalized (nullable optional)
* @return {!Object}
*/
normalizeMergeArg: function(arg) {
return arg === undefined || arg === null ? {} : arg;
},
/**
* If merging Arrays, a merge strategy *must* be supplied. If not, it is
* likely the caller's fault. If this function is ever called with anything
* but `one` and `two` being `Array`s, it is the fault of the merge utilities.
*
* @param {*} one Array to merge into.
* @param {*} two Array to merge from.
*/
checkMergeArrayArgs: function(one, two) {
("production" !== "development" ? invariant(
Array.isArray(one) && Array.isArray(two),
'Tried to merge arrays, instead got %s and %s.',
one,
two
) : invariant(Array.isArray(one) && Array.isArray(two)));
},
/**
* @param {*} one Object to merge into.
* @param {*} two Object to merge from.
*/
checkMergeObjectArgs: function(one, two) {
mergeHelpers.checkMergeObjectArg(one);
mergeHelpers.checkMergeObjectArg(two);
},
/**
* @param {*} arg
*/
checkMergeObjectArg: function(arg) {
("production" !== "development" ? invariant(
!isTerminal(arg) && !Array.isArray(arg),
'Tried to merge an object, instead got %s.',
arg
) : invariant(!isTerminal(arg) && !Array.isArray(arg)));
},
/**
* Checks that a merge was not given a circular object or an object that had
* too great of depth.
*
* @param {number} Level of recursion to validate against maximum.
*/
checkMergeLevel: function(level) {
("production" !== "development" ? invariant(
level < MAX_MERGE_DEPTH,
'Maximum deep merge depth exceeded. You may be attempting to merge ' +
'circular structures in an unsupported way.'
) : invariant(level < MAX_MERGE_DEPTH));
},
/**
* Checks that the supplied merge strategy is valid.
*
* @param {string} Array merge strategy.
*/
checkArrayStrategy: function(strategy) {
("production" !== "development" ? invariant(
strategy === undefined || strategy in mergeHelpers.ArrayStrategies,
'You must provide an array strategy to deep merge functions to ' +
'instruct the deep merge how to resolve merging two arrays.'
) : invariant(strategy === undefined || strategy in mergeHelpers.ArrayStrategies));
},
/**
* Set of possible behaviors of merge algorithms when encountering two Arrays
* that must be merged together.
* - `clobber`: The left `Array` is ignored.
* - `indexByIndex`: The result is achieved by recursively deep merging at
* each index. (not yet supported.)
*/
ArrayStrategies: keyMirror({
Clobber: true,
IndexByIndex: true
})
};
module.exports = mergeHelpers;
},{"./invariant":112,"./keyMirror":118}],123:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 mergeInto
* @typechecks static-only
*/
"use strict";
var mergeHelpers = _dereq_("./mergeHelpers");
var checkMergeObjectArg = mergeHelpers.checkMergeObjectArg;
/**
* Shallow merges two structures by mutating the first parameter.
*
* @param {object} one Object to be merged into.
* @param {?object} two Optional object with properties to merge from.
*/
function mergeInto(one, two) {
checkMergeObjectArg(one);
if (two != null) {
checkMergeObjectArg(two);
for (var key in two) {
if (!two.hasOwnProperty(key)) {
continue;
}
one[key] = two[key];
}
}
}
module.exports = mergeInto;
},{"./mergeHelpers":122}],124:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 mixInto
*/
"use strict";
/**
* Simply copies properties to the prototype.
*/
var mixInto = function(constructor, methodBag) {
var methodName;
for (methodName in methodBag) {
if (!methodBag.hasOwnProperty(methodName)) {
continue;
}
constructor.prototype[methodName] = methodBag[methodName];
}
};
module.exports = mixInto;
},{}],125:[function(_dereq_,module,exports){
/**
* Copyright 2014 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 monitorCodeUse
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* Provides open-source compatible instrumentation for monitoring certain API
* uses before we're ready to issue a warning or refactor. It accepts an event
* name which may only contain the characters [a-z0-9_] and an optional data
* object with further information.
*/
function monitorCodeUse(eventName, data) {
("production" !== "development" ? invariant(
eventName && !/[^a-z0-9_]/.test(eventName),
'You must provide an eventName using only the characters [a-z0-9_]'
) : invariant(eventName && !/[^a-z0-9_]/.test(eventName)));
}
module.exports = monitorCodeUse;
},{"./invariant":112}],126:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 objMap
*/
"use strict";
/**
* For each key/value pair, invokes callback func and constructs a resulting
* object which contains, for every key in obj, values that are the result of
* of invoking the function:
*
* func(value, key, iteration)
*
* @param {?object} obj Object to map keys over
* @param {function} func Invoked for each key/val pair.
* @param {?*} context
* @return {?object} Result of mapping or null if obj is falsey
*/
function objMap(obj, func, context) {
if (!obj) {
return null;
}
var i = 0;
var ret = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
ret[key] = func.call(context, obj[key], key, i++);
}
}
return ret;
}
module.exports = objMap;
},{}],127:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 objMapKeyVal
*/
"use strict";
/**
* Behaves the same as `objMap` but invokes func with the key first, and value
* second. Use `objMap` unless you need this special case.
* Invokes func as:
*
* func(key, value, iteration)
*
* @param {?object} obj Object to map keys over
* @param {!function} func Invoked for each key/val pair.
* @param {?*} context
* @return {?object} Result of mapping or null if obj is falsey
*/
function objMapKeyVal(obj, func, context) {
if (!obj) {
return null;
}
var i = 0;
var ret = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
ret[key] = func.call(context, key, obj[key], i++);
}
}
return ret;
}
module.exports = objMapKeyVal;
},{}],128:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 onlyChild
*/
"use strict";
var ReactComponent = _dereq_("./ReactComponent");
var invariant = _dereq_("./invariant");
/**
* 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) {
("production" !== "development" ? invariant(
ReactComponent.isValidComponent(children),
'onlyChild must be passed a children with exactly one child.'
) : invariant(ReactComponent.isValidComponent(children)));
return children;
}
module.exports = onlyChild;
},{"./ReactComponent":27,"./invariant":112}],129:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 performanceNow
* @typechecks static-only
*/
"use strict";
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
/**
* 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 due to Facebook's webdriver
* infrastructure.
*/
var performance = null;
if (ExecutionEnvironment.canUseDOM) {
performance = window.performance || window.webkitPerformance;
}
if (!performance || !performance.now) {
performance = Date;
}
var performanceNow = performance.now.bind(performance);
module.exports = performanceNow;
},{"./ExecutionEnvironment":20}],130:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 shallowEqual
*/
"use strict";
/**
* Performs equality by iterating through keys on an object and returning
* false when any key has values which are not strictly equal between
* objA and objB. Returns true when the values of all keys are strictly equal.
*
* @return {boolean}
*/
function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
var key;
// Test for A's keys different from B.
for (key in objA) {
if (objA.hasOwnProperty(key) &&
(!objB.hasOwnProperty(key) || objA[key] !== objB[key])) {
return false;
}
}
// Test for B'a keys missing from A.
for (key in objB) {
if (objB.hasOwnProperty(key) && !objA.hasOwnProperty(key)) {
return false;
}
}
return true;
}
module.exports = shallowEqual;
},{}],131:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 shouldUpdateReactComponent
* @typechecks static-only
*/
"use strict";
/**
* Given a `prevComponentInstance` and `nextComponent`, determines if
* `prevComponentInstance` should be updated as opposed to being destroyed or
* replaced by a new instance. The second argument is a descriptor. Future
* versions of the reconciler should only compare descriptors to other
* descriptors.
*
* @param {?object} prevComponentInstance
* @param {?object} nextDescriptor
* @return {boolean} True if `prevComponentInstance` should be updated.
* @protected
*/
function shouldUpdateReactComponent(prevComponentInstance, nextDescriptor) {
// TODO: Remove warning after a release.
if (prevComponentInstance && nextDescriptor &&
prevComponentInstance.constructor === nextDescriptor.constructor && (
(prevComponentInstance.props && prevComponentInstance.props.key) ===
(nextDescriptor.props && nextDescriptor.props.key)
)) {
if (prevComponentInstance._owner === nextDescriptor._owner) {
return true;
} else {
if ("production" !== "development") {
if (prevComponentInstance.state) {
console.warn(
'A recent change to React has been found to impact your code. ' +
'A mounted component will now be unmounted and replaced by a ' +
'component (of the same class) if their owners are different. ' +
'Previously, ownership was not considered when updating.',
prevComponentInstance,
nextDescriptor
);
}
}
}
}
return false;
}
module.exports = shouldUpdateReactComponent;
},{}],132:[function(_dereq_,module,exports){
/**
* Copyright 2014 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 toArray
* @typechecks
*/
var invariant = _dereq_("./invariant");
/**
* Convert array-like objects to arrays.
*
* This API assumes the caller knows the contents of the data type. For less
* well defined inputs use createArrayFrom.
*
* @param {object|function} 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).
("production" !== "development" ? invariant(
!Array.isArray(obj) &&
(typeof obj === 'object' || typeof obj === 'function'),
'toArray: Array-like object expected'
) : invariant(!Array.isArray(obj) &&
(typeof obj === 'object' || typeof obj === 'function')));
("production" !== "development" ? invariant(
typeof length === 'number',
'toArray: Object needs a length property'
) : invariant(typeof length === 'number'));
("production" !== "development" ? invariant(
length === 0 ||
(length - 1) in obj,
'toArray: Object should have keys for indices'
) : invariant(length === 0 ||
(length - 1) in obj));
// 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;
},{"./invariant":112}],133:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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 traverseAllChildren
*/
"use strict";
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactTextComponent = _dereq_("./ReactTextComponent");
var invariant = _dereq_("./invariant");
var SEPARATOR = ReactInstanceHandles.SEPARATOR;
var SUBSEPARATOR = ':';
/**
* TODO: Test that:
* 1. `mapChildren` transforms strings and numbers into `ReactTextComponent`.
* 2. it('should fail when supplied duplicate key', function() {
* 3. That a single child and an array with one item have the same key pattern.
* });
*/
var userProvidedKeyEscaperLookup = {
'=': '=0',
'.': '=1',
':': '=2'
};
var userProvidedKeyEscapeRegex = /[=.:]/g;
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.props && component.props.key != null) {
// Explicit key
return wrapUserProvidedKey(component.props.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 {*} key 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 {!number} indexSoFar Number of children encountered until this point.
* @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.
*/
var traverseAllChildrenImpl =
function(children, nameSoFar, indexSoFar, callback, traverseContext) {
var subtreeCount = 0; // Count of children found in the current subtree.
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
var child = children[i];
var nextName = (
nameSoFar +
(nameSoFar ? SUBSEPARATOR : SEPARATOR) +
getComponentKey(child, i)
);
var nextIndex = indexSoFar + subtreeCount;
subtreeCount += traverseAllChildrenImpl(
child,
nextName,
nextIndex,
callback,
traverseContext
);
}
} else {
var type = typeof children;
var isOnlyChild = nameSoFar === '';
// 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
var storageName =
isOnlyChild ? SEPARATOR + getComponentKey(children, 0) : nameSoFar;
if (children == null || type === 'boolean') {
// All of the above are perceived as null.
callback(traverseContext, null, storageName, indexSoFar);
subtreeCount = 1;
} else if (children.type && children.type.prototype &&
children.type.prototype.mountComponentIntoNode) {
callback(traverseContext, children, storageName, indexSoFar);
subtreeCount = 1;
} else {
if (type === 'object') {
("production" !== "development" ? invariant(
!children || children.nodeType !== 1,
'traverseAllChildren(...): Encountered an invalid child; DOM ' +
'elements are not valid children of React components.'
) : invariant(!children || children.nodeType !== 1));
for (var key in children) {
if (children.hasOwnProperty(key)) {
subtreeCount += traverseAllChildrenImpl(
children[key],
(
nameSoFar + (nameSoFar ? SUBSEPARATOR : SEPARATOR) +
wrapUserProvidedKey(key) + SUBSEPARATOR +
getComponentKey(children[key], 0)
),
indexSoFar + subtreeCount,
callback,
traverseContext
);
}
}
} else if (type === 'string') {
var normalizedText = new ReactTextComponent(children);
callback(traverseContext, normalizedText, storageName, indexSoFar);
subtreeCount += 1;
} else if (type === 'number') {
var normalizedNumber = new ReactTextComponent('' + children);
callback(traverseContext, normalizedNumber, storageName, indexSoFar);
subtreeCount += 1;
}
}
}
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.
*/
function traverseAllChildren(children, callback, traverseContext) {
if (children !== null && children !== undefined) {
traverseAllChildrenImpl(children, '', 0, callback, traverseContext);
}
}
module.exports = traverseAllChildren;
},{"./ReactInstanceHandles":53,"./ReactTextComponent":70,"./invariant":112}],134:[function(_dereq_,module,exports){
/**
* Copyright 2014 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 warning
*/
"use strict";
var emptyFunction = _dereq_("./emptyFunction");
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = emptyFunction;
if ("production" !== "development") {
warning = function(condition, format ) {var args=Array.prototype.slice.call(arguments,2);
if (format === undefined) {
throw new Error(
'`warning(condition, format, ...args)` requires a warning ' +
'message argument'
);
}
if (!condition) {
var argIndex = 0;
console.warn('Warning: ' + format.replace(/%s/g, function() {return args[argIndex++];}));
}
};
}
module.exports = warning;
},{"./emptyFunction":96}]},{},[24])
(24)
}); |
frontend/src/components/Header.js | Jtcruthers/Whether | import React from 'react';
import styles from '../css/Header.css'
import {Link} from 'react-router-dom'
const Header = () => (
<div className="topnav">
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<span>Whether</span>
</div>
);
export default Header;
|
src/components/Markdown/Separator.js | jonahjoughin/blog.jough.in | import React from 'react';
const Separator = () => (
<hr className = {"mb5 b--near-black w4 bb bw1"}/>
);
export default Separator;
|
app/components/H1/index.js | bsr203/react-boilerplate | import React from 'react';
import styles from './styles.css';
function H1(props) {
return (
<h1 className={styles.heading1} { ...props } />
);
}
export default H1;
|
components/time_picker/TimePickerDialog.js | rubenmoya/react-toolbox | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import time from '../utils/time';
import Clock from './Clock';
const factory = (Dialog) => {
class TimePickerDialog extends Component {
static propTypes = {
active: PropTypes.bool,
cancelLabel: PropTypes.string,
className: PropTypes.string,
format: PropTypes.oneOf(['24hr', 'ampm']),
name: PropTypes.string,
okLabel: PropTypes.string,
onDismiss: PropTypes.func,
onEscKeyDown: PropTypes.func,
onOverlayClick: PropTypes.func,
onSelect: PropTypes.func,
theme: PropTypes.shape({
am: PropTypes.string,
amFormat: PropTypes.string,
ampm: PropTypes.string,
button: PropTypes.string,
dialog: PropTypes.string,
header: PropTypes.string,
hours: PropTypes.string,
hoursDisplay: PropTypes.string,
minutes: PropTypes.string,
minutesDisplay: PropTypes.string,
pm: PropTypes.string,
pmFormat: PropTypes.string,
separator: PropTypes.string,
}),
value: PropTypes.instanceOf(Date),
};
static defaultProps = {
active: false,
cancelLabel: 'Cancel',
format: '24hr',
okLabel: 'Ok',
value: new Date(),
};
state = {
display: 'hours',
displayTime: new Date(this.props.value.getTime()),
};
componentWillReceiveProps(nextProps) {
if (nextProps.value.getTime() !== this.state.displayTime.getTime()) {
this.setState({ displayTime: new Date(nextProps.value.getTime()) });
}
}
componentDidUpdate(prevProps) {
if (!prevProps.active && this.props.active) {
setTimeout(this.clockNode.handleCalculateShape, 1000);
}
}
handleClockChange = (value) => {
this.setState({ displayTime: value });
};
handleSelect = (event) => {
this.props.onSelect(this.state.displayTime, event);
};
toggleTimeMode = () => {
this.setState({ displayTime: time.toggleTimeMode(this.state.displayTime) });
};
handleHandMoved = () => {
if (this.state.display === 'hours') this.setState({ display: 'minutes' });
};
switchDisplay = (event) => {
this.setState({ display: event.target.id });
};
actions = [{
label: this.props.cancelLabel,
className: this.props.theme.button,
onClick: this.props.onDismiss,
}, {
label: this.props.okLabel,
className: this.props.theme.button,
name: this.props.name,
onClick: this.handleSelect,
}];
formatHours() {
if (this.props.format === 'ampm') {
return this.state.displayTime.getHours() % 12 || 12;
}
return this.state.displayTime.getHours();
}
renderAMPMLabels() {
const { theme } = this.props;
if (this.props.format !== 'ampm') return undefined;
return (
<div className={theme.ampm}>
<span className={theme.am} onClick={this.toggleTimeMode}>AM</span>
<span className={theme.pm} onClick={this.toggleTimeMode}>PM</span>
</div>
);
}
render() {
const { theme } = this.props;
const display = `${this.state.display}Display`;
const format = `${time.getTimeMode(this.state.displayTime)}Format`;
const className = cn([theme.dialog, theme[display], theme[format]], this.props.className);
return (
<Dialog
actions={this.actions}
active={this.props.active}
className={className}
onEscKeyDown={this.props.onEscKeyDown}
onOverlayClick={this.props.onOverlayClick}
>
<header className={theme.header}>
<span id="hours" className={theme.hours} onClick={this.switchDisplay}>
{(`0${this.formatHours()}`).slice(-2)}
</span>
<span className={theme.separator}>:</span>
<span id="minutes" className={theme.minutes} onClick={this.switchDisplay}>
{(`0${this.state.displayTime.getMinutes()}`).slice(-2)}
</span>
{this.renderAMPMLabels()}
</header>
<Clock
ref={(node) => { this.clockNode = node; }}
display={this.state.display}
format={this.props.format}
onChange={this.handleClockChange}
onHandMoved={this.handleHandMoved}
theme={this.props.theme}
time={this.state.displayTime}
/>
</Dialog>
);
}
}
return TimePickerDialog;
};
export default factory;
|
countries/src/index.js | cglsoft/react_postgreSQL | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
app/containers/BootStrap/BSTextDanger/index.js | perry-ugroop/ugroop-react-dup2 | /**
* Created by Yang on 18/11/16.
*/
import React from 'react';
const BSTextDanger = (props) => <div className={`text-danger ${props.className}`} id={props.id}>
{props.children}
</div>;
BSTextDanger.propTypes = {
className: React.PropTypes.any,
children: React.PropTypes.any,
id: React.PropTypes.any,
};
export default BSTextDanger;
|
src/rocks/contact-layer/index.js | animachine/animachine | import React from 'react'
import ReactDOM from 'react-dom'
import ContactLayer from './ContactLayer'
BETON.define({
id: 'contact-layer',
dependencies: ['workspace', 'project-manager', 'dom-picker'],
init: ({workspace, projectManager, domPicker}) => {
let node
function handleRef(component) {
node = ReactDOM.findDOMNode(component)
}
function handlePick(e) {
const domPicker = BETON.require('dom-picker')
const {setPickedDOMNode} = domPicker.actions
const {clientX: x, clientY: y} = e
const timeline = projectManager.state.currentTimeline
if (!timeline) {
return
}
function isInPreview(node) {
return timeline.previews.some(({rootTarget}) => {
return rootTarget.contains(node)
})
}
function getOwnerTrack(node) {
return timeline.tracks.find(track => {
return track.targets.indexOf(pickedDOMNode) !== -1
})
}
node.style.pointerEvents = 'none'
const pickedDOMNode = document.elementFromPoint(x, y)
node.style.pointerEvents = 'auto'
setPickedDOMNode(null)
timeline.currentTrack = null
if (!isInPreview(pickedDOMNode)) {
return
}
let selectedTrack
if (e.metaKey || e.ctrlKey) { //select the first picked node
selectedTrack = getOwnerTrack(pickedDOMNode)
}
else if (false) {
//select the first track under straight the mouse
node.style.pointerEvents = 'none'
const testeds = []
let next = pickedDOMNode
while (!selectedTrack && isInPreview(next)) {
selectedTrack = getOwnerTrack(next)
if (!selectedTrack) {
testeds.push({node: next, pointerEvents: next.style.pointerEvents})
next.style.pointerEvents = 'none'
next = document.elementFromPoint(x, y)
}
}
testeds.forEach(({node, pointerEvents}) => {
node.style.pointerEvents = pointerEvents
})
node.style.pointerEvents = 'auto'
}
else {
const containers = []
timeline.tracks.forEach(track => {
track.targets.forEach((target) => {
if (target.contains(pickedDOMNode)) {
containers.push({target, track})
}
})
})
const closest = containers
.sort((a, b) => a.target.contains(b.target) ? 1 : -1)
.shift()
if (closest) {
selectedTrack = closest.track
}
}
if (selectedTrack) {
selectedTrack.parent('Timeline').currentTrack = selectedTrack
// setPickedDOMNode(null)
}
else {
setPickedDOMNode(pickedDOMNode)
}
}
workspace.setTabContent('hole', (
<ContactLayer
ref = {handleRef}
onPick = {handlePick}
/>
))
}
})
function isPickableDomElem(deTest) {
//TODO use .compareDocumentPosition()
if (!deTest) {
return false
}
return step(deTest)
function step(de) {
if (!de) {
return false
}
else if (de.nodeType === 9) {
return false
}
else if (de.hasAttribute('data-am-pick')) {
return true
}
else if (de.hasAttribute('data-am-nopick')) {
return false
}
else if (de === document.body) {
return de !== deTest
}
else if (de) {
return step(de.parentNode)
}
}
}
|
classic/src/scenes/wbfa/generated/FARDesktop.pro.js | wavebox/waveboxapp | import React from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faDesktop } from '@fortawesome/pro-regular-svg-icons/faDesktop'
export default class FARDesktop extends React.Component {
render () {
return (<FontAwesomeIcon {...this.props} icon={faDesktop} />)
}
}
|
src/SubRouterFactory.js | TransferGo/react-subrouter | import React from 'react';
import SubRouter from './SubRouter.js';
function SubRouterFactory(routes, defaultRoute){
class Index extends SubRouter {
constructor(props, state){
super(props, state, routes, defaultRoute);
}
}
Index.childContextTypes = {
isActive: React.PropTypes.func,
getSubRouteAtDepth: React.PropTypes.func,
changeSubRoute: React.PropTypes.func,
subRouteDepth: React.PropTypes.number,
};
return Index;
}
module.exports = SubRouterFactory;
|
src/svg-icons/action/explore.js | spiermar/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionExplore = (props) => (
<SvgIcon {...props}>
<path d="M12 10.9c-.61 0-1.1.49-1.1 1.1s.49 1.1 1.1 1.1c.61 0 1.1-.49 1.1-1.1s-.49-1.1-1.1-1.1zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm2.19 12.19L6 18l3.81-8.19L18 6l-3.81 8.19z"/>
</SvgIcon>
);
ActionExplore = pure(ActionExplore);
ActionExplore.displayName = 'ActionExplore';
ActionExplore.muiName = 'SvgIcon';
export default ActionExplore;
|
jenkins-design-language/src/js/components/material-ui/svg-icons/image/filter-7.js | alvarolobato/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ImageFilter7 = (props) => (
<SvgIcon {...props}>
<path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zm-8-2l4-8V5h-6v2h4l-4 8h2z"/>
</SvgIcon>
);
ImageFilter7.displayName = 'ImageFilter7';
ImageFilter7.muiName = 'SvgIcon';
export default ImageFilter7;
|
ajax/libs/highcharts/5.0.1/js/highmaps.src.js | redmunds/cdnjs | /**
* @license Highmaps JS v5.0.1 (2016-10-26)
*
* (c) 2011-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
(function(root, factory) {
if (typeof module === 'object' && module.exports) {
module.exports = root.document ?
factory(root) :
factory;
} else {
root.Highcharts = factory(root);
}
}(typeof window !== 'undefined' ? window : this, function(win) {
var Highcharts = (function() {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
/* global window */
var win = window,
doc = win.document;
var SVG_NS = 'http://www.w3.org/2000/svg',
userAgent = (win.navigator && win.navigator.userAgent) || '',
svg = doc && doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect,
isMS = /(edge|msie|trident)/i.test(userAgent) && !window.opera,
vml = !svg,
isFirefox = /Firefox/.test(userAgent),
hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4; // issue #38
var Highcharts = win.Highcharts ? win.Highcharts.error(16, true) : {
product: 'Highmaps',
version: '5.0.1',
deg2rad: Math.PI * 2 / 360,
doc: doc,
hasBidiBug: hasBidiBug,
hasTouch: doc && doc.documentElement.ontouchstart !== undefined,
isMS: isMS,
isWebKit: /AppleWebKit/.test(userAgent),
isFirefox: isFirefox,
isTouchDevice: /(Mobile|Android|Windows Phone)/.test(userAgent),
SVG_NS: SVG_NS,
idCounter: 0,
chartCount: 0,
seriesTypes: {},
symbolSizes: {},
svg: svg,
vml: vml,
win: win,
charts: [],
marginNames: ['plotTop', 'marginRight', 'marginBottom', 'plotLeft'],
noop: function() {
return undefined;
}
};
return Highcharts;
}());
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var timers = [];
var charts = H.charts,
doc = H.doc,
win = H.win;
/**
* Provide error messages for debugging, with links to online explanation
*/
H.error = function(code, stop) {
var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code;
if (stop) {
throw new Error(msg);
}
// else ...
if (win.console) {
console.log(msg); // eslint-disable-line no-console
}
};
/**
* An animator object. One instance applies to one property (attribute or style prop)
* on one element.
*
* @param {object} elem The element to animate. May be a DOM element or a Highcharts SVGElement wrapper.
* @param {object} options Animation options, including duration, easing, step and complete.
* @param {object} prop The property to animate.
*/
H.Fx = function(elem, options, prop) {
this.options = options;
this.elem = elem;
this.prop = prop;
};
H.Fx.prototype = {
/**
* Animating a path definition on SVGElement
* @returns {undefined}
*/
dSetter: function() {
var start = this.paths[0],
end = this.paths[1],
ret = [],
now = this.now,
i = start.length,
startVal;
if (now === 1) { // land on the final path without adjustment points appended in the ends
ret = this.toD;
} else if (i === end.length && now < 1) {
while (i--) {
startVal = parseFloat(start[i]);
ret[i] =
isNaN(startVal) ? // a letter instruction like M or L
start[i] :
now * (parseFloat(end[i] - startVal)) + startVal;
}
} else { // if animation is finished or length not matching, land on right value
ret = end;
}
this.elem.attr('d', ret);
},
/**
* Update the element with the current animation step
* @returns {undefined}
*/
update: function() {
var elem = this.elem,
prop = this.prop, // if destroyed, it is null
now = this.now,
step = this.options.step;
// Animation setter defined from outside
if (this[prop + 'Setter']) {
this[prop + 'Setter']();
// Other animations on SVGElement
} else if (elem.attr) {
if (elem.element) {
elem.attr(prop, now);
}
// HTML styles, raw HTML content like container size
} else {
elem.style[prop] = now + this.unit;
}
if (step) {
step.call(elem, now, this);
}
},
/**
* Run an animation
*/
run: function(from, to, unit) {
var self = this,
timer = function(gotoEnd) {
return timer.stopped ? false : self.step(gotoEnd);
},
i;
this.startTime = +new Date();
this.start = from;
this.end = to;
this.unit = unit;
this.now = this.start;
this.pos = 0;
timer.elem = this.elem;
if (timer() && timers.push(timer) === 1) {
timer.timerId = setInterval(function() {
for (i = 0; i < timers.length; i++) {
if (!timers[i]()) {
timers.splice(i--, 1);
}
}
if (!timers.length) {
clearInterval(timer.timerId);
}
}, 13);
}
},
/**
* Run a single step in the animation
* @param {Boolean} gotoEnd Whether to go to then endpoint of the animation after abort
* @returns {Boolean} True if animation continues
*/
step: function(gotoEnd) {
var t = +new Date(),
ret,
done,
options = this.options,
elem = this.elem,
complete = options.complete,
duration = options.duration,
curAnim = options.curAnim,
i;
if (elem.attr && !elem.element) { // #2616, element including flag is destroyed
ret = false;
} else if (gotoEnd || t >= duration + this.startTime) {
this.now = this.end;
this.pos = 1;
this.update();
curAnim[this.prop] = true;
done = true;
for (i in curAnim) {
if (curAnim[i] !== true) {
done = false;
}
}
if (done && complete) {
complete.call(elem);
}
ret = false;
} else {
this.pos = options.easing((t - this.startTime) / duration);
this.now = this.start + ((this.end - this.start) * this.pos);
this.update();
ret = true;
}
return ret;
},
/**
* Prepare start and end values so that the path can be animated one to one
*/
initPath: function(elem, fromD, toD) {
fromD = fromD || '';
var shift,
startX = elem.startX,
endX = elem.endX,
bezier = fromD.indexOf('C') > -1,
numParams = bezier ? 7 : 3,
fullLength,
slice,
i,
start = fromD.split(' '),
end = toD.slice(), // copy
isArea = elem.isArea,
positionFactor = isArea ? 2 : 1,
reverse;
/**
* In splines make move points have six parameters like bezier curves
*/
function sixify(arr) {
i = arr.length;
while (i--) {
if (arr[i] === 'M' || arr[i] === 'L') {
arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]);
}
}
}
/**
* Insert an array at the given position of another array
*/
function insertSlice(arr, subArr, index) {
[].splice.apply(
arr, [index, 0].concat(subArr)
);
}
/**
* If shifting points, prepend a dummy point to the end path.
*/
function prepend(arr, other) {
while (arr.length < fullLength) {
// Move to, line to or curve to?
arr[0] = other[fullLength - arr.length];
// Prepend a copy of the first point
insertSlice(arr, arr.slice(0, numParams), 0);
// For areas, the bottom path goes back again to the left, so we need
// to append a copy of the last point.
if (isArea) {
insertSlice(arr, arr.slice(arr.length - numParams), arr.length);
i--;
}
}
arr[0] = 'M';
}
/**
* Copy and append last point until the length matches the end length
*/
function append(arr, other) {
var i = (fullLength - arr.length) / numParams;
while (i > 0 && i--) {
// Pull out the slice that is going to be appended or inserted. In a line graph,
// the positionFactor is 1, and the last point is sliced out. In an area graph,
// the positionFactor is 2, causing the middle two points to be sliced out, since
// an area path starts at left, follows the upper path then turns and follows the
// bottom back.
slice = arr.slice().splice(
(arr.length / positionFactor) - numParams,
numParams * positionFactor
);
// Move to, line to or curve to?
slice[0] = other[fullLength - numParams - (i * numParams)];
// Disable first control point
if (bezier) {
slice[numParams - 6] = slice[numParams - 2];
slice[numParams - 5] = slice[numParams - 1];
}
// Now insert the slice, either in the middle (for areas) or at the end (for lines)
insertSlice(arr, slice, arr.length / positionFactor);
if (isArea) {
i--;
}
}
}
if (bezier) {
sixify(start);
sixify(end);
}
// For sideways animation, find out how much we need to shift to get the start path Xs
// to match the end path Xs.
if (startX && endX) {
for (i = 0; i < startX.length; i++) {
if (startX[i] === endX[0]) { // Moving left, new points coming in on right
shift = i;
break;
} else if (startX[0] === endX[endX.length - startX.length + i]) { // Moving right
shift = i;
reverse = true;
break;
}
}
if (shift === undefined) {
start = [];
}
}
if (start.length && H.isNumber(shift)) {
// The common target length for the start and end array, where both
// arrays are padded in opposite ends
fullLength = end.length + shift * positionFactor * numParams;
if (!reverse) {
prepend(end, start);
append(start, end);
} else {
prepend(start, end);
append(end, start);
}
}
return [start, end];
}
}; // End of Fx prototype
/**
* Extend an object with the members of another
* @param {Object} a The object to be extended
* @param {Object} b The object to add to the first one
*/
H.extend = function(a, b) {
var n;
if (!a) {
a = {};
}
for (n in b) {
a[n] = b[n];
}
return a;
};
/**
* Deep merge two or more objects and return a third object. If the first argument is
* true, the contents of the second object is copied into the first object.
* Previously this function redirected to jQuery.extend(true), but this had two limitations.
* First, it deep merged arrays, which lead to workarounds in Highcharts. Second,
* it copied properties from extended prototypes.
*/
H.merge = function() {
var i,
args = arguments,
len,
ret = {},
doCopy = function(copy, original) {
var value, key;
// An object is replacing a primitive
if (typeof copy !== 'object') {
copy = {};
}
for (key in original) {
if (original.hasOwnProperty(key)) {
value = original[key];
// Copy the contents of objects, but not arrays or DOM nodes
if (H.isObject(value, true) &&
key !== 'renderTo' && typeof value.nodeType !== 'number') {
copy[key] = doCopy(copy[key] || {}, value);
// Primitives and arrays are copied over directly
} else {
copy[key] = original[key];
}
}
}
return copy;
};
// If first argument is true, copy into the existing object. Used in setOptions.
if (args[0] === true) {
ret = args[1];
args = Array.prototype.slice.call(args, 2);
}
// For each argument, extend the return
len = args.length;
for (i = 0; i < len; i++) {
ret = doCopy(ret, args[i]);
}
return ret;
};
/**
* Shortcut for parseInt
* @param {Object} s
* @param {Number} mag Magnitude
*/
H.pInt = function(s, mag) {
return parseInt(s, mag || 10);
};
/**
* Check for string
* @param {Object} s
*/
H.isString = function(s) {
return typeof s === 'string';
};
/**
* Check for object
* @param {Object} obj
* @param {Boolean} strict Also checks that the object is not an array
*/
H.isArray = function(obj) {
var str = Object.prototype.toString.call(obj);
return str === '[object Array]' || str === '[object Array Iterator]';
};
/**
* Check for array
* @param {Object} obj
*/
H.isObject = function(obj, strict) {
return obj && typeof obj === 'object' && (!strict || !H.isArray(obj));
};
/**
* Check for number
* @param {Object} n
*/
H.isNumber = function(n) {
return typeof n === 'number' && !isNaN(n);
};
/**
* Remove last occurence of an item from an array
* @param {Array} arr
* @param {Mixed} item
*/
H.erase = function(arr, item) {
var i = arr.length;
while (i--) {
if (arr[i] === item) {
arr.splice(i, 1);
break;
}
}
//return arr;
};
/**
* Returns true if the object is not null or undefined.
* @param {Object} obj
*/
H.defined = function(obj) {
return obj !== undefined && obj !== null;
};
/**
* Set or get an attribute or an object of attributes. Can't use jQuery attr because
* it attempts to set expando properties on the SVG element, which is not allowed.
*
* @param {Object} elem The DOM element to receive the attribute(s)
* @param {String|Object} prop The property or an abject of key-value pairs
* @param {String} value The value if a single property is set
*/
H.attr = function(elem, prop, value) {
var key,
ret;
// if the prop is a string
if (H.isString(prop)) {
// set the value
if (H.defined(value)) {
elem.setAttribute(prop, value);
// get the value
} else if (elem && elem.getAttribute) { // elem not defined when printing pie demo...
ret = elem.getAttribute(prop);
}
// else if prop is defined, it is a hash of key/value pairs
} else if (H.defined(prop) && H.isObject(prop)) {
for (key in prop) {
elem.setAttribute(key, prop[key]);
}
}
return ret;
};
/**
* Check if an element is an array, and if not, make it into an array.
*/
H.splat = function(obj) {
return H.isArray(obj) ? obj : [obj];
};
/**
* Set a timeout if the delay is given, otherwise perform the function synchronously
* @param {Function} fn The function to perform
* @param {Number} delay Delay in milliseconds
* @param {Ojbect} context The context
* @returns {Nubmer} An identifier for the timeout
*/
H.syncTimeout = function(fn, delay, context) {
if (delay) {
return setTimeout(fn, delay, context);
}
fn.call(0, context);
};
/**
* Return the first value that is defined.
*/
H.pick = function() {
var args = arguments,
i,
arg,
length = args.length;
for (i = 0; i < length; i++) {
arg = args[i];
if (arg !== undefined && arg !== null) {
return arg;
}
}
};
/**
* Set CSS on a given element
* @param {Object} el
* @param {Object} styles Style object with camel case property names
*/
H.css = function(el, styles) {
if (H.isMS && !H.svg) { // #2686
if (styles && styles.opacity !== undefined) {
styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')';
}
}
H.extend(el.style, styles);
};
/**
* Utility function to create element with attributes and styles
* @param {Object} tag
* @param {Object} attribs
* @param {Object} styles
* @param {Object} parent
* @param {Object} nopad
*/
H.createElement = function(tag, attribs, styles, parent, nopad) {
var el = doc.createElement(tag),
css = H.css;
if (attribs) {
H.extend(el, attribs);
}
if (nopad) {
css(el, {
padding: 0,
border: 'none',
margin: 0
});
}
if (styles) {
css(el, styles);
}
if (parent) {
parent.appendChild(el);
}
return el;
};
/**
* Extend a prototyped class by new members
* @param {Object} parent
* @param {Object} members
*/
H.extendClass = function(Parent, members) {
var object = function() {};
object.prototype = new Parent();
H.extend(object.prototype, members);
return object;
};
/**
* Pad a string to a given length by adding 0 to the beginning
* @param {Number} number
* @param {Number} length
*/
H.pad = function(number, length, padder) {
return new Array((length || 2) + 1 - String(number).length).join(padder || 0) + number;
};
/**
* Return a length based on either the integer value, or a percentage of a base.
*/
H.relativeLength = function(value, base) {
return (/%$/).test(value) ? base * parseFloat(value) / 100 : parseFloat(value);
};
/**
* Wrap a method with extended functionality, preserving the original function
* @param {Object} obj The context object that the method belongs to
* @param {String} method The name of the method to extend
* @param {Function} func A wrapper function callback. This function is called with the same arguments
* as the original function, except that the original function is unshifted and passed as the first
* argument.
*/
H.wrap = function(obj, method, func) {
var proceed = obj[method];
obj[method] = function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(proceed);
return func.apply(this, args);
};
};
H.getTZOffset = function(timestamp) {
var d = H.Date;
return ((d.hcGetTimezoneOffset && d.hcGetTimezoneOffset(timestamp)) || d.hcTimezoneOffset || 0) * 60000;
};
/**
* Based on http://www.php.net/manual/en/function.strftime.php
* @param {String} format
* @param {Number} timestamp
* @param {Boolean} capitalize
*/
H.dateFormat = function(format, timestamp, capitalize) {
if (!H.defined(timestamp) || isNaN(timestamp)) {
return H.defaultOptions.lang.invalidDate || '';
}
format = H.pick(format, '%Y-%m-%d %H:%M:%S');
var D = H.Date,
date = new D(timestamp - H.getTZOffset(timestamp)),
key, // used in for constuct below
// get the basic time values
hours = date[D.hcGetHours](),
day = date[D.hcGetDay](),
dayOfMonth = date[D.hcGetDate](),
month = date[D.hcGetMonth](),
fullYear = date[D.hcGetFullYear](),
lang = H.defaultOptions.lang,
langWeekdays = lang.weekdays,
shortWeekdays = lang.shortWeekdays,
pad = H.pad,
// List all format keys. Custom formats can be added from the outside.
replacements = H.extend({
// Day
'a': shortWeekdays ? shortWeekdays[day] : langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon'
'A': langWeekdays[day], // Long weekday, like 'Monday'
'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31
'e': pad(dayOfMonth, 2, ' '), // Day of the month, 1 through 31
'w': day,
// Week (none implemented)
//'W': weekNumber(),
// Month
'b': lang.shortMonths[month], // Short month, like 'Jan'
'B': lang.months[month], // Long month, like 'January'
'm': pad(month + 1), // Two digit month number, 01 through 12
// Year
'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009
'Y': fullYear, // Four digits year, like 2009
// Time
'H': pad(hours), // Two digits hours in 24h format, 00 through 23
'k': hours, // Hours in 24h format, 0 through 23
'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11
'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12
'M': pad(date[D.hcGetMinutes]()), // Two digits minutes, 00 through 59
'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM
'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM
'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59
'L': pad(Math.round(timestamp % 1000), 3) // Milliseconds (naming from Ruby)
}, H.dateFormats);
// do the replaces
for (key in replacements) {
while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster
format = format.replace(
'%' + key,
typeof replacements[key] === 'function' ?
replacements[key](timestamp) :
replacements[key]
);
}
}
// Optionally capitalize the string and return
return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format;
};
/**
* Format a single variable. Similar to sprintf, without the % prefix.
*/
H.formatSingle = function(format, val) {
var floatRegex = /f$/,
decRegex = /\.([0-9])/,
lang = H.defaultOptions.lang,
decimals;
if (floatRegex.test(format)) { // float
decimals = format.match(decRegex);
decimals = decimals ? decimals[1] : -1;
if (val !== null) {
val = H.numberFormat(
val,
decimals,
lang.decimalPoint,
format.indexOf(',') > -1 ? lang.thousandsSep : ''
);
}
} else {
val = H.dateFormat(format, val);
}
return val;
};
/**
* Format a string according to a subset of the rules of Python's String.format method.
*/
H.format = function(str, ctx) {
var splitter = '{',
isInside = false,
segment,
valueAndFormat,
path,
i,
len,
ret = [],
val,
index;
while (str) {
index = str.indexOf(splitter);
if (index === -1) {
break;
}
segment = str.slice(0, index);
if (isInside) { // we're on the closing bracket looking back
valueAndFormat = segment.split(':');
path = valueAndFormat.shift().split('.'); // get first and leave format
len = path.length;
val = ctx;
// Assign deeper paths
for (i = 0; i < len; i++) {
val = val[path[i]];
}
// Format the replacement
if (valueAndFormat.length) {
val = H.formatSingle(valueAndFormat.join(':'), val);
}
// Push the result and advance the cursor
ret.push(val);
} else {
ret.push(segment);
}
str = str.slice(index + 1); // the rest
isInside = !isInside; // toggle
splitter = isInside ? '}' : '{'; // now look for next matching bracket
}
ret.push(str);
return ret.join('');
};
/**
* Get the magnitude of a number
*/
H.getMagnitude = function(num) {
return Math.pow(10, Math.floor(Math.log(num) / Math.LN10));
};
/**
* Take an interval and normalize it to multiples of 1, 2, 2.5 and 5
* @param {Number} interval
* @param {Array} multiples
* @param {Number} magnitude
* @param {Object} options
*/
H.normalizeTickInterval = function(interval, multiples, magnitude, allowDecimals, preventExceed) {
var normalized,
i,
retInterval = interval;
// round to a tenfold of 1, 2, 2.5 or 5
magnitude = H.pick(magnitude, 1);
normalized = interval / magnitude;
// multiples for a linear scale
if (!multiples) {
multiples = [1, 2, 2.5, 5, 10];
// the allowDecimals option
if (allowDecimals === false) {
if (magnitude === 1) {
multiples = [1, 2, 5, 10];
} else if (magnitude <= 0.1) {
multiples = [1 / magnitude];
}
}
}
// normalize the interval to the nearest multiple
for (i = 0; i < multiples.length; i++) {
retInterval = multiples[i];
if ((preventExceed && retInterval * magnitude >= interval) || // only allow tick amounts smaller than natural
(!preventExceed && (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2))) {
break;
}
}
// multiply back to the correct magnitude
retInterval *= magnitude;
return retInterval;
};
/**
* Utility method that sorts an object array and keeping the order of equal items.
* ECMA script standard does not specify the behaviour when items are equal.
*/
H.stableSort = function(arr, sortFunction) {
var length = arr.length,
sortValue,
i;
// Add index to each item
for (i = 0; i < length; i++) {
arr[i].safeI = i; // stable sort index
}
arr.sort(function(a, b) {
sortValue = sortFunction(a, b);
return sortValue === 0 ? a.safeI - b.safeI : sortValue;
});
// Remove index from items
for (i = 0; i < length; i++) {
delete arr[i].safeI; // stable sort index
}
};
/**
* Non-recursive method to find the lowest member of an array. Math.min raises a maximum
* call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
* method is slightly slower, but safe.
*/
H.arrayMin = function(data) {
var i = data.length,
min = data[0];
while (i--) {
if (data[i] < min) {
min = data[i];
}
}
return min;
};
/**
* Non-recursive method to find the lowest member of an array. Math.min raises a maximum
* call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
* method is slightly slower, but safe.
*/
H.arrayMax = function(data) {
var i = data.length,
max = data[0];
while (i--) {
if (data[i] > max) {
max = data[i];
}
}
return max;
};
/**
* Utility method that destroys any SVGElement or VMLElement that are properties on the given object.
* It loops all properties and invokes destroy if there is a destroy method. The property is
* then delete'ed.
* @param {Object} The object to destroy properties on
* @param {Object} Exception, do not destroy this property, only delete it.
*/
H.destroyObjectProperties = function(obj, except) {
var n;
for (n in obj) {
// If the object is non-null and destroy is defined
if (obj[n] && obj[n] !== except && obj[n].destroy) {
// Invoke the destroy
obj[n].destroy();
}
// Delete the property from the object.
delete obj[n];
}
};
/**
* Discard an element by moving it to the bin and delete
* @param {Object} The HTML node to discard
*/
H.discardElement = function(element) {
var garbageBin = H.garbageBin;
// create a garbage bin element, not part of the DOM
if (!garbageBin) {
garbageBin = H.createElement('div');
}
// move the node and empty bin
if (element) {
garbageBin.appendChild(element);
}
garbageBin.innerHTML = '';
};
/**
* Fix JS round off float errors
* @param {Number} num
*/
H.correctFloat = function(num, prec) {
return parseFloat(
num.toPrecision(prec || 14)
);
};
/**
* Set the global animation to either a given value, or fall back to the
* given chart's animation option
* @param {Object} animation
* @param {Object} chart
*/
H.setAnimation = function(animation, chart) {
chart.renderer.globalAnimation = H.pick(animation, chart.options.chart.animation, true);
};
/**
* Get the animation in object form, where a disabled animation is always
* returned with duration: 0
*/
H.animObject = function(animation) {
return H.isObject(animation) ? H.merge(animation) : {
duration: animation ? 500 : 0
};
};
/**
* The time unit lookup
*/
H.timeUnits = {
millisecond: 1,
second: 1000,
minute: 60000,
hour: 3600000,
day: 24 * 3600000,
week: 7 * 24 * 3600000,
month: 28 * 24 * 3600000,
year: 364 * 24 * 3600000
};
/**
* Format a number and return a string based on input settings
* @param {Number} number The input number to format
* @param {Number} decimals The amount of decimals
* @param {String} decimalPoint The decimal point, defaults to the one given in the lang options
* @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options
*/
H.numberFormat = function(number, decimals, decimalPoint, thousandsSep) {
number = +number || 0;
decimals = +decimals;
var lang = H.defaultOptions.lang,
origDec = (number.toString().split('.')[1] || '').length,
decimalComponent,
strinteger,
thousands,
absNumber = Math.abs(number),
ret;
if (decimals === -1) {
decimals = Math.min(origDec, 20); // Preserve decimals. Not huge numbers (#3793).
} else if (!H.isNumber(decimals)) {
decimals = 2;
}
// A string containing the positive integer component of the number
strinteger = String(H.pInt(absNumber.toFixed(decimals)));
// Leftover after grouping into thousands. Can be 0, 1 or 3.
thousands = strinteger.length > 3 ? strinteger.length % 3 : 0;
// Language
decimalPoint = H.pick(decimalPoint, lang.decimalPoint);
thousandsSep = H.pick(thousandsSep, lang.thousandsSep);
// Start building the return
ret = number < 0 ? '-' : '';
// Add the leftover after grouping into thousands. For example, in the number 42 000 000,
// this line adds 42.
ret += thousands ? strinteger.substr(0, thousands) + thousandsSep : '';
// Add the remaining thousands groups, joined by the thousands separator
ret += strinteger.substr(thousands).replace(/(\d{3})(?=\d)/g, '$1' + thousandsSep);
// Add the decimal point and the decimal component
if (decimals) {
// Get the decimal component, and add power to avoid rounding errors with float numbers (#4573)
decimalComponent = Math.abs(absNumber - strinteger + Math.pow(10, -Math.max(decimals, origDec) - 1));
ret += decimalPoint + decimalComponent.toFixed(decimals).slice(2);
}
return ret;
};
/**
* Easing definition
* @param {Number} pos Current position, ranging from 0 to 1
*/
Math.easeInOutSine = function(pos) {
return -0.5 * (Math.cos(Math.PI * pos) - 1);
};
/**
* Internal method to return CSS value for given element and property
*/
H.getStyle = function(el, prop) {
var style;
// For width and height, return the actual inner pixel size (#4913)
if (prop === 'width') {
return Math.min(el.offsetWidth, el.scrollWidth) -
H.getStyle(el, 'padding-left') -
H.getStyle(el, 'padding-right');
} else if (prop === 'height') {
return Math.min(el.offsetHeight, el.scrollHeight) -
H.getStyle(el, 'padding-top') -
H.getStyle(el, 'padding-bottom');
}
// Otherwise, get the computed style
style = win.getComputedStyle(el, undefined);
return style && H.pInt(style.getPropertyValue(prop));
};
/**
* Return the index of an item in an array, or -1 if not found
*/
H.inArray = function(item, arr) {
return arr.indexOf ? arr.indexOf(item) : [].indexOf.call(arr, item);
};
/**
* Filter an array
*/
H.grep = function(elements, callback) {
return [].filter.call(elements, callback);
};
/**
* Map an array
*/
H.map = function(arr, fn) {
var results = [],
i = 0,
len = arr.length;
for (; i < len; i++) {
results[i] = fn.call(arr[i], arr[i], i, arr);
}
return results;
};
/**
* Get the element's offset position, corrected by overflow:auto.
*/
H.offset = function(el) {
var docElem = doc.documentElement,
box = el.getBoundingClientRect();
return {
top: box.top + (win.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0),
left: box.left + (win.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0)
};
};
/**
* Stop running animation.
* A possible extension to this would be to stop a single property, when
* we want to continue animating others. Then assign the prop to the timer
* in the Fx.run method, and check for the prop here. This would be an improvement
* in all cases where we stop the animation from .attr. Instead of stopping
* everything, we can just stop the actual attributes we're setting.
*/
H.stop = function(el) {
var i = timers.length;
// Remove timers related to this element (#4519)
while (i--) {
if (timers[i].elem === el) {
timers[i].stopped = true; // #4667
}
}
};
/**
* Utility for iterating over an array.
* @param {Array} arr
* @param {Function} fn
*/
H.each = function(arr, fn, ctx) { // modern browsers
return Array.prototype.forEach.call(arr, fn, ctx);
};
/**
* Add an event listener
*/
H.addEvent = function(el, type, fn) {
var events = el.hcEvents = el.hcEvents || {};
function wrappedFn(e) {
e.target = e.srcElement || win; // #2820
fn.call(el, e);
}
// Handle DOM events in modern browsers
if (el.addEventListener) {
el.addEventListener(type, fn, false);
// Handle old IE implementation
} else if (el.attachEvent) {
if (!el.hcEventsIE) {
el.hcEventsIE = {};
}
// Link wrapped fn with original fn, so we can get this in removeEvent
el.hcEventsIE[fn.toString()] = wrappedFn;
el.attachEvent('on' + type, wrappedFn);
}
if (!events[type]) {
events[type] = [];
}
events[type].push(fn);
};
/**
* Remove event added with addEvent
*/
H.removeEvent = function(el, type, fn) {
var events,
hcEvents = el.hcEvents,
index;
function removeOneEvent(type, fn) {
if (el.removeEventListener) {
el.removeEventListener(type, fn, false);
} else if (el.attachEvent) {
fn = el.hcEventsIE[fn.toString()];
el.detachEvent('on' + type, fn);
}
}
function removeAllEvents() {
var types,
len,
n;
if (!el.nodeName) {
return; // break on non-DOM events
}
if (type) {
types = {};
types[type] = true;
} else {
types = hcEvents;
}
for (n in types) {
if (hcEvents[n]) {
len = hcEvents[n].length;
while (len--) {
removeOneEvent(n, hcEvents[n][len]);
}
}
}
}
if (hcEvents) {
if (type) {
events = hcEvents[type] || [];
if (fn) {
index = H.inArray(fn, events);
if (index > -1) {
events.splice(index, 1);
hcEvents[type] = events;
}
removeOneEvent(type, fn);
} else {
removeAllEvents();
hcEvents[type] = [];
}
} else {
removeAllEvents();
el.hcEvents = {};
}
}
};
/**
* Fire an event on a custom object
*/
H.fireEvent = function(el, type, eventArguments, defaultFunction) {
var e,
hcEvents = el.hcEvents,
events,
len,
i,
fn;
eventArguments = eventArguments || {};
if (doc.createEvent && (el.dispatchEvent || el.fireEvent)) {
e = doc.createEvent('Events');
e.initEvent(type, true, true);
//e.target = el;
H.extend(e, eventArguments);
if (el.dispatchEvent) {
el.dispatchEvent(e);
} else {
el.fireEvent(type, e);
}
} else if (hcEvents) {
events = hcEvents[type] || [];
len = events.length;
if (!eventArguments.target) { // We're running a custom event
H.extend(eventArguments, {
// Attach a simple preventDefault function to skip default handler if called.
// The built-in defaultPrevented property is not overwritable (#5112)
preventDefault: function() {
eventArguments.defaultPrevented = true;
},
// Setting target to native events fails with clicking the zoom-out button in Chrome.
target: el,
// If the type is not set, we're running a custom event (#2297). If it is set,
// we're running a browser event, and setting it will cause en error in
// IE8 (#2465).
type: type
});
}
for (i = 0; i < len; i++) {
fn = events[i];
// If the event handler return false, prevent the default handler from executing
if (fn && fn.call(el, eventArguments) === false) {
eventArguments.preventDefault();
}
}
}
// Run the default if not prevented
if (defaultFunction && !eventArguments.defaultPrevented) {
defaultFunction(eventArguments);
}
};
/**
* The global animate method, which uses Fx to create individual animators.
*/
H.animate = function(el, params, opt) {
var start,
unit = '',
end,
fx,
args,
prop;
if (!H.isObject(opt)) { // Number or undefined/null
args = arguments;
opt = {
duration: args[2],
easing: args[3],
complete: args[4]
};
}
if (!H.isNumber(opt.duration)) {
opt.duration = 400;
}
opt.easing = typeof opt.easing === 'function' ? opt.easing : (Math[opt.easing] || Math.easeInOutSine);
opt.curAnim = H.merge(params);
for (prop in params) {
fx = new H.Fx(el, opt, prop);
end = null;
if (prop === 'd') {
fx.paths = fx.initPath(
el,
el.d,
params.d
);
fx.toD = params.d;
start = 0;
end = 1;
} else if (el.attr) {
start = el.attr(prop);
} else {
start = parseFloat(H.getStyle(el, prop)) || 0;
if (prop !== 'opacity') {
unit = 'px';
}
}
if (!end) {
end = params[prop];
}
if (end.match && end.match('px')) {
end = end.replace(/px/g, ''); // #4351
}
fx.run(start, end, unit);
}
};
/**
* The series type factory.
*
* @param {string} type The series type name.
* @param {string} parent The parent series type name.
* @param {object} options The additional default options that is merged with the parent's options.
* @param {object} props The properties (functions and primitives) to set on the new prototype.
* @param {object} pointProps Members for a series-specific Point prototype if needed.
*/
H.seriesType = function(type, parent, options, props, pointProps) { // docs: add to API + extending Highcharts
var defaultOptions = H.getOptions(),
seriesTypes = H.seriesTypes;
// Merge the options
defaultOptions.plotOptions[type] = H.merge(
defaultOptions.plotOptions[parent],
options
);
// Create the class
seriesTypes[type] = H.extendClass(seriesTypes[parent] || function() {}, props);
seriesTypes[type].prototype.type = type;
// Create the point class if needed
if (pointProps) {
seriesTypes[type].prototype.pointClass = H.extendClass(H.Point, pointProps);
}
return seriesTypes[type];
};
/**
* Register Highcharts as a plugin in jQuery
*/
if (win.jQuery) {
win.jQuery.fn.highcharts = function() {
var args = [].slice.call(arguments);
if (this[0]) { // this[0] is the renderTo div
// Create the chart
if (args[0]) {
new H[ // eslint-disable-line no-new
H.isString(args[0]) ? args.shift() : 'Chart' // Constructor defaults to Chart
](this[0], args[0], args[1]);
return this;
}
// When called without parameters or with the return argument, return an existing chart
return charts[H.attr(this[0], 'data-highcharts-chart')];
}
};
}
/**
* Compatibility section to add support for legacy IE. This can be removed if old IE
* support is not needed.
*/
if (doc && !doc.defaultView) {
H.getStyle = function(el, prop) {
var val,
alias = {
width: 'clientWidth',
height: 'clientHeight'
}[prop];
if (el.style[prop]) {
return H.pInt(el.style[prop]);
}
if (prop === 'opacity') {
prop = 'filter';
}
// Getting the rendered width and height
if (alias) {
el.style.zoom = 1;
return Math.max(el[alias] - 2 * H.getStyle(el, 'padding'), 0);
}
val = el.currentStyle[prop.replace(/\-(\w)/g, function(a, b) {
return b.toUpperCase();
})];
if (prop === 'filter') {
val = val.replace(
/alpha\(opacity=([0-9]+)\)/,
function(a, b) {
return b / 100;
}
);
}
return val === '' ? 1 : H.pInt(val);
};
}
if (!Array.prototype.forEach) {
H.each = function(arr, fn, ctx) { // legacy
var i = 0,
len = arr.length;
for (; i < len; i++) {
if (fn.call(ctx, arr[i], i, arr) === false) {
return i;
}
}
};
}
if (!Array.prototype.indexOf) {
H.inArray = function(item, arr) {
var len,
i = 0;
if (arr) {
len = arr.length;
for (; i < len; i++) {
if (arr[i] === item) {
return i;
}
}
}
return -1;
};
}
if (!Array.prototype.filter) {
H.grep = function(elements, fn) {
var ret = [],
i = 0,
length = elements.length;
for (; i < length; i++) {
if (fn(elements[i], i)) {
ret.push(elements[i]);
}
}
return ret;
};
}
//--- End compatibility section ---
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var each = H.each,
isNumber = H.isNumber,
map = H.map,
merge = H.merge,
pInt = H.pInt;
/**
* Handle color operations. The object methods are chainable.
* @param {String} input The input color in either rbga or hex format
*/
H.Color = function(input) {
// Backwards compatibility, allow instanciation without new
if (!(this instanceof H.Color)) {
return new H.Color(input);
}
// Initialize
this.init(input);
};
H.Color.prototype = {
// Collection of parsers. This can be extended from the outside by pushing parsers
// to Highcharts.Color.prototype.parsers.
parsers: [{
// RGBA color
regex: /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/,
parse: function(result) {
return [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)];
}
}, {
// HEX color
regex: /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/,
parse: function(result) {
return [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1];
}
}, {
// RGB color
regex: /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/,
parse: function(result) {
return [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1];
}
}],
// Collection of named colors. Can be extended from the outside by adding colors
// to Highcharts.Color.prototype.names.
names: {
white: '#ffffff',
black: '#000000'
},
/**
* Parse the input color to rgba array
* @param {String} input
*/
init: function(input) {
var result,
rgba,
i,
parser;
this.input = input = this.names[input] || input;
// Gradients
if (input && input.stops) {
this.stops = map(input.stops, function(stop) {
return new H.Color(stop[1]);
});
// Solid colors
} else {
i = this.parsers.length;
while (i-- && !rgba) {
parser = this.parsers[i];
result = parser.regex.exec(input);
if (result) {
rgba = parser.parse(result);
}
}
}
this.rgba = rgba || [];
},
/**
* Return the color a specified format
* @param {String} format
*/
get: function(format) {
var input = this.input,
rgba = this.rgba,
ret;
if (this.stops) {
ret = merge(input);
ret.stops = [].concat(ret.stops);
each(this.stops, function(stop, i) {
ret.stops[i] = [ret.stops[i][0], stop.get(format)];
});
// it's NaN if gradient colors on a column chart
} else if (rgba && isNumber(rgba[0])) {
if (format === 'rgb' || (!format && rgba[3] === 1)) {
ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')';
} else if (format === 'a') {
ret = rgba[3];
} else {
ret = 'rgba(' + rgba.join(',') + ')';
}
} else {
ret = input;
}
return ret;
},
/**
* Brighten the color
* @param {Number} alpha
*/
brighten: function(alpha) {
var i,
rgba = this.rgba;
if (this.stops) {
each(this.stops, function(stop) {
stop.brighten(alpha);
});
} else if (isNumber(alpha) && alpha !== 0) {
for (i = 0; i < 3; i++) {
rgba[i] += pInt(alpha * 255);
if (rgba[i] < 0) {
rgba[i] = 0;
}
if (rgba[i] > 255) {
rgba[i] = 255;
}
}
}
return this;
},
/**
* Set the color's opacity to a given alpha value
* @param {Number} alpha
*/
setOpacity: function(alpha) {
this.rgba[3] = alpha;
return this;
}
};
H.color = function(input) {
return new H.Color(input);
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var color = H.color,
each = H.each,
getTZOffset = H.getTZOffset,
isTouchDevice = H.isTouchDevice,
merge = H.merge,
pick = H.pick,
svg = H.svg,
win = H.win;
/* ****************************************************************************
* Handle the options *
*****************************************************************************/
H.defaultOptions = {
symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'],
lang: {
loading: 'Loading...',
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December'
],
shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
// invalidDate: '',
decimalPoint: '.',
numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels
resetZoom: 'Reset zoom',
resetZoomTitle: 'Reset zoom level 1:1',
thousandsSep: ' '
},
global: {
useUTC: true,
//timezoneOffset: 0
},
chart: {
//animation: true,
//alignTicks: false,
//reflow: true,
//className: null,
//events: { load, selection },
//margin: [null],
//marginTop: null,
//marginRight: null,
//marginBottom: null,
//marginLeft: null,
borderRadius: 0,
colorCount: 10,
defaultSeriesType: 'line',
ignoreHiddenSeries: true,
//inverted: false,
spacing: [10, 10, 15, 10],
//spacingTop: 10,
//spacingRight: 10,
//spacingBottom: 15,
//spacingLeft: 10,
//zoomType: ''
resetZoomButton: {
theme: {
zIndex: 20
},
position: {
align: 'right',
x: -10,
//verticalAlign: 'top',
y: 10
}
// relativeTo: 'plot'
},
width: null,
height: null
},
defs: {
dropShadow: { // used by tooltip
tagName: 'filter',
id: 'drop-shadow',
opacity: 0.5,
children: [{
tagName: 'feGaussianBlur',
in: 'SourceAlpha',
stdDeviation: 1
}, {
tagName: 'feOffset',
dx: 1,
dy: 1
}, {
tagName: 'feComponentTransfer',
children: [{
tagName: 'feFuncA',
type: 'linear',
slope: 0.3
}]
}, {
tagName: 'feMerge',
children: [{
tagName: 'feMergeNode'
}, {
tagName: 'feMergeNode',
in: 'SourceGraphic'
}]
}]
},
style: {
tagName: 'style',
textContent: '.highcharts-tooltip{' +
'filter:url(#drop-shadow)' +
'}'
}
},
title: {
text: 'Chart title',
align: 'center',
// floating: false,
margin: 15,
// x: 0,
// verticalAlign: 'top',
// y: null,
widthAdjust: -44
},
subtitle: {
text: '',
align: 'center',
// floating: false
// x: 0,
// verticalAlign: 'top',
// y: null,
widthAdjust: -44
},
plotOptions: {},
labels: {
//items: [],
style: {
//font: defaultFont,
position: 'absolute',
color: '#333333'
}
},
legend: {
enabled: true,
align: 'center',
//floating: false,
layout: 'horizontal',
labelFormatter: function() {
return this.name;
},
//borderWidth: 0,
borderColor: '#999999',
borderRadius: 0,
navigation: {
// animation: true,
// arrowSize: 12
// style: {} // text styles
},
// margin: 20,
// reversed: false,
// backgroundColor: null,
/*style: {
padding: '5px'
},*/
itemCheckboxStyle: {
position: 'absolute',
width: '13px', // for IE precision
height: '13px'
},
// itemWidth: undefined,
squareSymbol: true,
// symbolRadius: 0,
// symbolWidth: 16,
symbolPadding: 5,
verticalAlign: 'bottom',
// width: undefined,
x: 0,
y: 0,
title: {
//text: null
}
},
loading: {
// hideDuration: 100,
// showDuration: 0
},
tooltip: {
enabled: true,
animation: svg,
//crosshairs: null,
borderRadius: 3,
dateTimeLabelFormats: {
millisecond: '%A, %b %e, %H:%M:%S.%L',
second: '%A, %b %e, %H:%M:%S',
minute: '%A, %b %e, %H:%M',
hour: '%A, %b %e, %H:%M',
day: '%A, %b %e, %Y',
week: 'Week from %A, %b %e, %Y',
month: '%B %Y',
year: '%Y'
},
footerFormat: '',
//formatter: defaultFormatter,
/* todo: em font-size when finished comparing against HC4
headerFormat: '<span style="font-size: 0.85em">{point.key}</span><br/>',
*/
padding: 8,
//shape: 'callout',
//shared: false,
snap: isTouchDevice ? 25 : 10,
headerFormat: '<span class="highcharts-header">{point.key}</span><br/>',
pointFormat: '<span class="highcharts-color-{point.colorIndex}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>',
//xDateFormat: '%A, %b %e, %Y',
//valueDecimals: null,
//valuePrefix: '',
//valueSuffix: ''
},
credits: {
enabled: true,
href: 'http://www.highcharts.com',
position: {
align: 'right',
x: -10,
verticalAlign: 'bottom',
y: -5
},
text: 'Highcharts.com'
}
};
/**
* Set the time methods globally based on the useUTC option. Time method can be either
* local time or UTC (default).
*/
function setTimeMethods() {
var globalOptions = H.defaultOptions.global,
Date,
useUTC = globalOptions.useUTC,
GET = useUTC ? 'getUTC' : 'get',
SET = useUTC ? 'setUTC' : 'set';
H.Date = Date = globalOptions.Date || win.Date; // Allow using a different Date class
Date.hcTimezoneOffset = useUTC && globalOptions.timezoneOffset;
Date.hcGetTimezoneOffset = useUTC && globalOptions.getTimezoneOffset;
Date.hcMakeTime = function(year, month, date, hours, minutes, seconds) {
var d;
if (useUTC) {
d = Date.UTC.apply(0, arguments);
d += getTZOffset(d);
} else {
d = new Date(
year,
month,
pick(date, 1),
pick(hours, 0),
pick(minutes, 0),
pick(seconds, 0)
).getTime();
}
return d;
};
each(['Minutes', 'Hours', 'Day', 'Date', 'Month', 'FullYear'], function(s) {
Date['hcGet' + s] = GET + s;
});
each(['Milliseconds', 'Seconds', 'Minutes', 'Hours', 'Date', 'Month', 'FullYear'], function(s) {
Date['hcSet' + s] = SET + s;
});
}
/**
* Merge the default options with custom options and return the new options structure
* @param {Object} options The new custom options
*/
H.setOptions = function(options) {
// Copy in the default options
H.defaultOptions = merge(true, H.defaultOptions, options);
// Apply UTC
setTimeMethods();
return H.defaultOptions;
};
/**
* Get the updated default options. Until 3.0.7, merely exposing defaultOptions for outside modules
* wasn't enough because the setOptions method created a new object.
*/
H.getOptions = function() {
return H.defaultOptions;
};
// Series defaults
H.defaultPlotOptions = H.defaultOptions.plotOptions;
// set the default time methods
setTimeMethods();
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var SVGElement,
SVGRenderer,
addEvent = H.addEvent,
animate = H.animate,
attr = H.attr,
charts = H.charts,
color = H.color,
css = H.css,
createElement = H.createElement,
defined = H.defined,
deg2rad = H.deg2rad,
destroyObjectProperties = H.destroyObjectProperties,
doc = H.doc,
each = H.each,
extend = H.extend,
erase = H.erase,
grep = H.grep,
hasTouch = H.hasTouch,
isArray = H.isArray,
isFirefox = H.isFirefox,
isMS = H.isMS,
isObject = H.isObject,
isString = H.isString,
isWebKit = H.isWebKit,
merge = H.merge,
noop = H.noop,
pick = H.pick,
pInt = H.pInt,
removeEvent = H.removeEvent,
splat = H.splat,
stop = H.stop,
svg = H.svg,
SVG_NS = H.SVG_NS,
symbolSizes = H.symbolSizes,
win = H.win;
/**
* A wrapper object for SVG elements
*/
SVGElement = H.SVGElement = function() {
return this;
};
SVGElement.prototype = {
// Default base for animation
opacity: 1,
SVG_NS: SVG_NS,
// For labels, these CSS properties are applied to the <text> node directly
textProps: ['direction', 'fontSize', 'fontWeight', 'fontFamily', 'fontStyle', 'color',
'lineHeight', 'width', 'textDecoration', 'textOverflow', 'textShadow'
],
/**
* Initialize the SVG renderer
* @param {Object} renderer
* @param {String} nodeName
*/
init: function(renderer, nodeName) {
var wrapper = this;
wrapper.element = nodeName === 'span' ?
createElement(nodeName) :
doc.createElementNS(wrapper.SVG_NS, nodeName);
wrapper.renderer = renderer;
},
/**
* Animate a given attribute
* @param {Object} params
* @param {Number} options Options include duration, easing, step and complete
* @param {Function} complete Function to perform at the end of animation
*/
animate: function(params, options, complete) {
var animOptions = pick(options, this.renderer.globalAnimation, true);
stop(this); // stop regardless of animation actually running, or reverting to .attr (#607)
if (animOptions) {
if (complete) { // allows using a callback with the global animation without overwriting it
animOptions.complete = complete;
}
animate(this, params, animOptions);
} else {
this.attr(params, null, complete);
}
return this;
},
/**
* Build an SVG gradient out of a common JavaScript configuration object
*/
colorGradient: function(color, prop, elem) {
var renderer = this.renderer,
colorObject,
gradName,
gradAttr,
radAttr,
gradients,
gradientObject,
stops,
stopColor,
stopOpacity,
radialReference,
n,
id,
key = [],
value;
// Apply linear or radial gradients
if (color.linearGradient) {
gradName = 'linearGradient';
} else if (color.radialGradient) {
gradName = 'radialGradient';
}
if (gradName) {
gradAttr = color[gradName];
gradients = renderer.gradients;
stops = color.stops;
radialReference = elem.radialReference;
// Keep < 2.2 kompatibility
if (isArray(gradAttr)) {
color[gradName] = gradAttr = {
x1: gradAttr[0],
y1: gradAttr[1],
x2: gradAttr[2],
y2: gradAttr[3],
gradientUnits: 'userSpaceOnUse'
};
}
// Correct the radial gradient for the radial reference system
if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) {
radAttr = gradAttr; // Save the radial attributes for updating
gradAttr = merge(gradAttr,
renderer.getRadialAttr(radialReference, radAttr), {
gradientUnits: 'userSpaceOnUse'
}
);
}
// Build the unique key to detect whether we need to create a new element (#1282)
for (n in gradAttr) {
if (n !== 'id') {
key.push(n, gradAttr[n]);
}
}
for (n in stops) {
key.push(stops[n]);
}
key = key.join(',');
// Check if a gradient object with the same config object is created within this renderer
if (gradients[key]) {
id = gradients[key].attr('id');
} else {
// Set the id and create the element
gradAttr.id = id = 'highcharts-' + H.idCounter++;
gradients[key] = gradientObject = renderer.createElement(gradName)
.attr(gradAttr)
.add(renderer.defs);
gradientObject.radAttr = radAttr;
// The gradient needs to keep a list of stops to be able to destroy them
gradientObject.stops = [];
each(stops, function(stop) {
var stopObject;
if (stop[1].indexOf('rgba') === 0) {
colorObject = H.color(stop[1]);
stopColor = colorObject.get('rgb');
stopOpacity = colorObject.get('a');
} else {
stopColor = stop[1];
stopOpacity = 1;
}
stopObject = renderer.createElement('stop').attr({
offset: stop[0],
'stop-color': stopColor,
'stop-opacity': stopOpacity
}).add(gradientObject);
// Add the stop element to the gradient
gradientObject.stops.push(stopObject);
});
}
// Set the reference to the gradient object
value = 'url(' + renderer.url + '#' + id + ')';
elem.setAttribute(prop, value);
elem.gradient = key;
// Allow the color to be concatenated into tooltips formatters etc. (#2995)
color.toString = function() {
return value;
};
}
},
/**
* Apply a polyfill to the text-stroke CSS property, by copying the text element
* and apply strokes to the copy.
*
* Contrast checks at http://jsfiddle.net/highcharts/43soe9m1/2/
*/
applyTextShadow: function(textShadow) {
var elem = this.element,
tspans,
hasContrast = textShadow.indexOf('contrast') !== -1,
styles = {},
forExport = this.renderer.forExport,
// IE10 and IE11 report textShadow in elem.style even though it doesn't work. Check
// this again with new IE release. In exports, the rendering is passed to PhantomJS.
supports = this.renderer.forExport || (elem.style.textShadow !== undefined && !isMS);
// When the text shadow is set to contrast, use dark stroke for light text and vice versa
if (hasContrast) {
styles.textShadow = textShadow = textShadow.replace(/contrast/g, this.renderer.getContrast(elem.style.fill));
}
// Safari with retina displays as well as PhantomJS bug (#3974). Firefox does not tolerate this,
// it removes the text shadows.
if (isWebKit || forExport) {
styles.textRendering = 'geometricPrecision';
}
/* Selective side-by-side testing in supported browser (http://jsfiddle.net/highcharts/73L1ptrh/)
if (elem.textContent.indexOf('2.') === 0) {
elem.style['text-shadow'] = 'none';
supports = false;
}
// */
// No reason to polyfill, we've got native support
if (supports) {
this.css(styles); // Apply altered textShadow or textRendering workaround
} else {
this.fakeTS = true; // Fake text shadow
// In order to get the right y position of the clones,
// copy over the y setter
this.ySetter = this.xSetter;
tspans = [].slice.call(elem.getElementsByTagName('tspan'));
each(textShadow.split(/\s?,\s?/g), function(textShadow) {
var firstChild = elem.firstChild,
color,
strokeWidth;
textShadow = textShadow.split(' ');
color = textShadow[textShadow.length - 1];
// Approximately tune the settings to the text-shadow behaviour
strokeWidth = textShadow[textShadow.length - 2];
if (strokeWidth) {
each(tspans, function(tspan, y) {
var clone;
// Let the first line start at the correct X position
if (y === 0) {
tspan.setAttribute('x', elem.getAttribute('x'));
y = elem.getAttribute('y');
tspan.setAttribute('y', y || 0);
if (y === null) {
elem.setAttribute('y', 0);
}
}
// Create the clone and apply shadow properties
clone = tspan.cloneNode(1);
attr(clone, {
'class': 'highcharts-text-shadow',
'fill': color,
'stroke': color,
'stroke-opacity': 1 / Math.max(pInt(strokeWidth), 3),
'stroke-width': strokeWidth,
'stroke-linejoin': 'round'
});
elem.insertBefore(clone, firstChild);
});
}
});
}
},
/**
* Set or get a given attribute
* @param {Object|String} hash
* @param {Mixed|Undefined} val
*/
attr: function(hash, val, complete) {
var key,
value,
element = this.element,
hasSetSymbolSize,
ret = this,
skipAttr,
setter;
// single key-value pair
if (typeof hash === 'string' && val !== undefined) {
key = hash;
hash = {};
hash[key] = val;
}
// used as a getter: first argument is a string, second is undefined
if (typeof hash === 'string') {
ret = (this[hash + 'Getter'] || this._defaultGetter).call(this, hash, element);
// setter
} else {
for (key in hash) {
value = hash[key];
skipAttr = false;
if (this.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) {
if (!hasSetSymbolSize) {
this.symbolAttr(hash);
hasSetSymbolSize = true;
}
skipAttr = true;
}
if (this.rotation && (key === 'x' || key === 'y')) {
this.doTransform = true;
}
if (!skipAttr) {
setter = this[key + 'Setter'] || this._defaultSetter;
setter.call(this, value, key, element);
}
}
// Update transform. Do this outside the loop to prevent redundant updating for batch setting
// of attributes.
if (this.doTransform) {
this.updateTransform();
this.doTransform = false;
}
}
// In accordance with animate, run a complete callback
if (complete) {
complete();
}
return ret;
},
/**
* Add a class name to an element
*/
addClass: function(className, replace) {
var currentClassName = this.attr('class') || '';
if (currentClassName.indexOf(className) === -1) {
if (!replace) {
className = (currentClassName + (currentClassName ? ' ' : '') + className).replace(' ', ' ');
}
this.attr('class', className);
}
return this;
},
hasClass: function(className) {
return attr(this.element, 'class').indexOf(className) !== -1;
},
removeClass: function(className) {
attr(this.element, 'class', (attr(this.element, 'class') || '').replace(className, ''));
return this;
},
/**
* If one of the symbol size affecting parameters are changed,
* check all the others only once for each call to an element's
* .attr() method
* @param {Object} hash
*/
symbolAttr: function(hash) {
var wrapper = this;
each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function(key) {
wrapper[key] = pick(hash[key], wrapper[key]);
});
wrapper.attr({
d: wrapper.renderer.symbols[wrapper.symbolName](
wrapper.x,
wrapper.y,
wrapper.width,
wrapper.height,
wrapper
)
});
},
/**
* Apply a clipping path to this object
* @param {String} id
*/
clip: function(clipRect) {
return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : 'none');
},
/**
* Calculate the coordinates needed for drawing a rectangle crisply and return the
* calculated attributes
* @param {Number} strokeWidth
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
crisp: function(rect, strokeWidth) {
var wrapper = this,
key,
attribs = {},
normalizer;
strokeWidth = strokeWidth || rect.strokeWidth || 0;
normalizer = Math.round(strokeWidth) % 2 / 2; // Math.round because strokeWidth can sometimes have roundoff errors
// normalize for crisp edges
rect.x = Math.floor(rect.x || wrapper.x || 0) + normalizer;
rect.y = Math.floor(rect.y || wrapper.y || 0) + normalizer;
rect.width = Math.floor((rect.width || wrapper.width || 0) - 2 * normalizer);
rect.height = Math.floor((rect.height || wrapper.height || 0) - 2 * normalizer);
if (defined(rect.strokeWidth)) {
rect.strokeWidth = strokeWidth;
}
for (key in rect) {
if (wrapper[key] !== rect[key]) { // only set attribute if changed
wrapper[key] = attribs[key] = rect[key];
}
}
return attribs;
},
/**
* Set styles for the element
* @param {Object} styles
*/
css: function(styles) {
var elemWrapper = this,
oldStyles = elemWrapper.styles,
newStyles = {},
elem = elemWrapper.element,
textWidth,
n,
serializedCss = '',
hyphenate,
hasNew = !oldStyles;
// convert legacy
if (styles && styles.color) {
styles.fill = styles.color;
}
// Filter out existing styles to increase performance (#2640)
if (oldStyles) {
for (n in styles) {
if (styles[n] !== oldStyles[n]) {
newStyles[n] = styles[n];
hasNew = true;
}
}
}
if (hasNew) {
textWidth = elemWrapper.textWidth =
(styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width)) ||
elemWrapper.textWidth; // #3501
// Merge the new styles with the old ones
if (oldStyles) {
styles = extend(
oldStyles,
newStyles
);
}
// store object
elemWrapper.styles = styles;
if (textWidth && (!svg && elemWrapper.renderer.forExport)) {
delete styles.width;
}
// serialize and set style attribute
if (isMS && !svg) {
css(elemWrapper.element, styles);
} else {
hyphenate = function(a, b) {
return '-' + b.toLowerCase();
};
for (n in styles) {
serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';';
}
attr(elem, 'style', serializedCss); // #1881
}
// Rebuild text after added
if (elemWrapper.added && textWidth) {
elemWrapper.renderer.buildText(elemWrapper);
}
}
return elemWrapper;
},
/**
* Get a computed style
*/
getStyle: function(prop) {
return win.getComputedStyle(this.element || this, '').getPropertyValue(prop);
},
/**
* Get a computed style in pixel values
*/
strokeWidth: function() {
var val = this.getStyle('stroke-width'),
ret,
dummy;
// Read pixel values directly
if (val.indexOf('px') === val.length - 2) {
ret = pInt(val);
// Other values like em, pt etc need to be measured
} else {
dummy = doc.createElementNS(SVG_NS, 'rect');
attr(dummy, {
'width': val,
'stroke-width': 0
});
this.element.parentNode.appendChild(dummy);
ret = dummy.getBBox().width;
dummy.parentNode.removeChild(dummy);
}
return ret;
},
/**
* Add an event listener
* @param {String} eventType
* @param {Function} handler
*/
on: function(eventType, handler) {
var svgElement = this,
element = svgElement.element;
// touch
if (hasTouch && eventType === 'click') {
element.ontouchstart = function(e) {
svgElement.touchEventFired = Date.now();
e.preventDefault();
handler.call(element, e);
};
element.onclick = function(e) {
if (win.navigator.userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269
handler.call(element, e);
}
};
} else {
// simplest possible event model for internal use
element['on' + eventType] = handler;
}
return this;
},
/**
* Set the coordinates needed to draw a consistent radial gradient across
* pie slices regardless of positioning inside the chart. The format is
* [centerX, centerY, diameter] in pixels.
*/
setRadialReference: function(coordinates) {
var existingGradient = this.renderer.gradients[this.element.gradient];
this.element.radialReference = coordinates;
// On redrawing objects with an existing gradient, the gradient needs
// to be repositioned (#3801)
if (existingGradient && existingGradient.radAttr) {
existingGradient.animate(
this.renderer.getRadialAttr(
coordinates,
existingGradient.radAttr
)
);
}
return this;
},
/**
* Move an object and its children by x and y values
* @param {Number} x
* @param {Number} y
*/
translate: function(x, y) {
return this.attr({
translateX: x,
translateY: y
});
},
/**
* Invert a group, rotate and flip
*/
invert: function(inverted) {
var wrapper = this;
wrapper.inverted = inverted;
wrapper.updateTransform();
return wrapper;
},
/**
* Private method to update the transform attribute based on internal
* properties
*/
updateTransform: function() {
var wrapper = this,
translateX = wrapper.translateX || 0,
translateY = wrapper.translateY || 0,
scaleX = wrapper.scaleX,
scaleY = wrapper.scaleY,
inverted = wrapper.inverted,
rotation = wrapper.rotation,
element = wrapper.element,
transform;
// flipping affects translate as adjustment for flipping around the group's axis
if (inverted) {
translateX += wrapper.attr('width');
translateY += wrapper.attr('height');
}
// Apply translate. Nearly all transformed elements have translation, so instead
// of checking for translate = 0, do it always (#1767, #1846).
transform = ['translate(' + translateX + ',' + translateY + ')'];
// apply rotation
if (inverted) {
transform.push('rotate(90) scale(-1,1)');
} else if (rotation) { // text rotation
transform.push('rotate(' + rotation + ' ' + (element.getAttribute('x') || 0) + ' ' + (element.getAttribute('y') || 0) + ')');
// Delete bBox memo when the rotation changes
//delete wrapper.bBox;
}
// apply scale
if (defined(scaleX) || defined(scaleY)) {
transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')');
}
if (transform.length) {
element.setAttribute('transform', transform.join(' '));
}
},
/**
* Bring the element to the front
*/
toFront: function() {
var element = this.element;
element.parentNode.appendChild(element);
return this;
},
/**
* Break down alignment options like align, verticalAlign, x and y
* to x and y relative to the chart.
*
* @param {Object} alignOptions
* @param {Boolean} alignByTranslate
* @param {String[Object} box The box to align to, needs a width and height. When the
* box is a string, it refers to an object in the Renderer. For example, when
* box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height
* x and y properties.
*
*/
align: function(alignOptions, alignByTranslate, box) {
var align,
vAlign,
x,
y,
attribs = {},
alignTo,
renderer = this.renderer,
alignedObjects = renderer.alignedObjects,
alignFactor,
vAlignFactor;
// First call on instanciate
if (alignOptions) {
this.alignOptions = alignOptions;
this.alignByTranslate = alignByTranslate;
if (!box || isString(box)) { // boxes other than renderer handle this internally
this.alignTo = alignTo = box || 'renderer';
erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize
alignedObjects.push(this);
box = null; // reassign it below
}
// When called on resize, no arguments are supplied
} else {
alignOptions = this.alignOptions;
alignByTranslate = this.alignByTranslate;
alignTo = this.alignTo;
}
box = pick(box, renderer[alignTo], renderer);
// Assign variables
align = alignOptions.align;
vAlign = alignOptions.verticalAlign;
x = (box.x || 0) + (alignOptions.x || 0); // default: left align
y = (box.y || 0) + (alignOptions.y || 0); // default: top align
// Align
if (align === 'right') {
alignFactor = 1;
} else if (align === 'center') {
alignFactor = 2;
}
if (alignFactor) {
x += (box.width - (alignOptions.width || 0)) / alignFactor;
}
attribs[alignByTranslate ? 'translateX' : 'x'] = Math.round(x);
// Vertical align
if (vAlign === 'bottom') {
vAlignFactor = 1;
} else if (vAlign === 'middle') {
vAlignFactor = 2;
}
if (vAlignFactor) {
y += (box.height - (alignOptions.height || 0)) / vAlignFactor;
}
attribs[alignByTranslate ? 'translateY' : 'y'] = Math.round(y);
// Animate only if already placed
this[this.placed ? 'animate' : 'attr'](attribs);
this.placed = true;
this.alignAttr = attribs;
return this;
},
/**
* Get the bounding box (width, height, x and y) for the element
*/
getBBox: function(reload, rot) {
var wrapper = this,
bBox, // = wrapper.bBox,
renderer = wrapper.renderer,
width,
height,
rotation,
rad,
element = wrapper.element,
styles = wrapper.styles,
fontSize,
textStr = wrapper.textStr,
textShadow,
elemStyle = element.style,
toggleTextShadowShim,
cache = renderer.cache,
cacheKeys = renderer.cacheKeys,
cacheKey;
rotation = pick(rot, wrapper.rotation);
rad = rotation * deg2rad;
fontSize = element && SVGElement.prototype.getStyle.call(element, 'font-size');
if (textStr !== undefined) {
cacheKey =
// Since numbers are monospaced, and numerical labels appear a lot in a chart,
// we assume that a label of n characters has the same bounding box as others
// of the same length.
textStr.toString().replace(/[0-9]/g, '0') +
// Properties that affect bounding box
['', rotation || 0, fontSize, element.style.width].join(',');
}
if (cacheKey && !reload) {
bBox = cache[cacheKey];
}
// No cache found
if (!bBox) {
// SVG elements
if (element.namespaceURI === wrapper.SVG_NS || renderer.forExport) {
try { // Fails in Firefox if the container has display: none.
// When the text shadow shim is used, we need to hide the fake shadows
// to get the correct bounding box (#3872)
toggleTextShadowShim = this.fakeTS && function(display) {
each(element.querySelectorAll('.highcharts-text-shadow'), function(tspan) {
tspan.style.display = display;
});
};
// Workaround for #3842, Firefox reporting wrong bounding box for shadows
if (isFirefox && elemStyle.textShadow) {
textShadow = elemStyle.textShadow;
elemStyle.textShadow = '';
} else if (toggleTextShadowShim) {
toggleTextShadowShim('none');
}
bBox = element.getBBox ?
// SVG: use extend because IE9 is not allowed to change width and height in case
// of rotation (below)
extend({}, element.getBBox()) :
// Legacy IE in export mode
{
width: element.offsetWidth,
height: element.offsetHeight
};
// #3842
if (textShadow) {
elemStyle.textShadow = textShadow;
} else if (toggleTextShadowShim) {
toggleTextShadowShim('');
}
} catch (e) {}
// If the bBox is not set, the try-catch block above failed. The other condition
// is for Opera that returns a width of -Infinity on hidden elements.
if (!bBox || bBox.width < 0) {
bBox = {
width: 0,
height: 0
};
}
// VML Renderer or useHTML within SVG
} else {
bBox = wrapper.htmlGetBBox();
}
// True SVG elements as well as HTML elements in modern browsers using the .useHTML option
// need to compensated for rotation
if (renderer.isSVG) {
width = bBox.width;
height = bBox.height;
// Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669, #2568)
if (isMS && styles && styles.fontSize === '11px' && height.toPrecision(3) === '16.9') {
bBox.height = height = 14;
}
// Adjust for rotated text
if (rotation) {
bBox.width = Math.abs(height * Math.sin(rad)) + Math.abs(width * Math.cos(rad));
bBox.height = Math.abs(height * Math.cos(rad)) + Math.abs(width * Math.sin(rad));
}
}
// Cache it. When loading a chart in a hidden iframe in Firefox and IE/Edge, the
// bounding box height is 0, so don't cache it (#5620).
if (cacheKey && bBox.height > 0) {
// Rotate (#4681)
while (cacheKeys.length > 250) {
delete cache[cacheKeys.shift()];
}
if (!cache[cacheKey]) {
cacheKeys.push(cacheKey);
}
cache[cacheKey] = bBox;
}
}
return bBox;
},
/**
* Show the element
*/
show: function(inherit) {
return this.attr({
visibility: inherit ? 'inherit' : 'visible'
});
},
/**
* Hide the element
*/
hide: function() {
return this.attr({
visibility: 'hidden'
});
},
fadeOut: function(duration) {
var elemWrapper = this;
elemWrapper.animate({
opacity: 0
}, {
duration: duration || 150,
complete: function() {
elemWrapper.attr({
y: -9999
}); // #3088, assuming we're only using this for tooltips
}
});
},
/**
* Add the element
* @param {Object|Undefined} parent Can be an element, an element wrapper or undefined
* to append the element to the renderer.box.
*/
add: function(parent) {
var renderer = this.renderer,
element = this.element,
inserted;
if (parent) {
this.parentGroup = parent;
}
// mark as inverted
this.parentInverted = parent && parent.inverted;
// build formatted text
if (this.textStr !== undefined) {
renderer.buildText(this);
}
// Mark as added
this.added = true;
// If we're adding to renderer root, or other elements in the group
// have a z index, we need to handle it
if (!parent || parent.handleZ || this.zIndex) {
inserted = this.zIndexSetter();
}
// If zIndex is not handled, append at the end
if (!inserted) {
(parent ? parent.element : renderer.box).appendChild(element);
}
// fire an event for internal hooks
if (this.onAdd) {
this.onAdd();
}
return this;
},
/**
* Removes a child either by removeChild or move to garbageBin.
* Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
*/
safeRemoveChild: function(element) {
var parentNode = element.parentNode;
if (parentNode) {
parentNode.removeChild(element);
}
},
/**
* Destroy the element and element wrapper
*/
destroy: function() {
var wrapper = this,
element = wrapper.element || {},
parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup,
grandParent,
key,
i;
// remove events
element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null;
stop(wrapper); // stop running animations
if (wrapper.clipPath) {
wrapper.clipPath = wrapper.clipPath.destroy();
}
// Destroy stops in case this is a gradient object
if (wrapper.stops) {
for (i = 0; i < wrapper.stops.length; i++) {
wrapper.stops[i] = wrapper.stops[i].destroy();
}
wrapper.stops = null;
}
// remove element
wrapper.safeRemoveChild(element);
// In case of useHTML, clean up empty containers emulating SVG groups (#1960, #2393, #2697).
while (parentToClean && parentToClean.div && parentToClean.div.childNodes.length === 0) {
grandParent = parentToClean.parentGroup;
wrapper.safeRemoveChild(parentToClean.div);
delete parentToClean.div;
parentToClean = grandParent;
}
// remove from alignObjects
if (wrapper.alignTo) {
erase(wrapper.renderer.alignedObjects, wrapper);
}
for (key in wrapper) {
delete wrapper[key];
}
return null;
},
xGetter: function(key) {
if (this.element.nodeName === 'circle') {
if (key === 'x') {
key = 'cx';
} else if (key === 'y') {
key = 'cy';
}
}
return this._defaultGetter(key);
},
/**
* Get the current value of an attribute or pseudo attribute, used mainly
* for animation.
*/
_defaultGetter: function(key) {
var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0);
if (/^[\-0-9\.]+$/.test(ret)) { // is numerical
ret = parseFloat(ret);
}
return ret;
},
dSetter: function(value, key, element) {
if (value && value.join) { // join path
value = value.join(' ');
}
if (/(NaN| {2}|^$)/.test(value)) {
value = 'M 0 0';
}
element.setAttribute(key, value);
this[key] = value;
},
alignSetter: function(value) {
var convert = {
left: 'start',
center: 'middle',
right: 'end'
};
this.element.setAttribute('text-anchor', convert[value]);
},
opacitySetter: function(value, key, element) {
this[key] = value;
element.setAttribute(key, value);
},
titleSetter: function(value) {
var titleNode = this.element.getElementsByTagName('title')[0];
if (!titleNode) {
titleNode = doc.createElementNS(this.SVG_NS, 'title');
this.element.appendChild(titleNode);
}
// Remove text content if it exists
if (titleNode.firstChild) {
titleNode.removeChild(titleNode.firstChild);
}
titleNode.appendChild(
doc.createTextNode(
(String(pick(value), '')).replace(/<[^>]*>/g, '') // #3276, #3895
)
);
},
textSetter: function(value) {
if (value !== this.textStr) {
// Delete bBox memo when the text changes
delete this.bBox;
this.textStr = value;
if (this.added) {
this.renderer.buildText(this);
}
}
},
fillSetter: function(value, key, element) {
if (typeof value === 'string') {
element.setAttribute(key, value);
} else if (value) {
this.colorGradient(value, key, element);
}
},
visibilitySetter: function(value, key, element) {
// IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881, #3909)
if (value === 'inherit') {
element.removeAttribute(key);
} else {
element.setAttribute(key, value);
}
},
zIndexSetter: function(value, key) {
var renderer = this.renderer,
parentGroup = this.parentGroup,
parentWrapper = parentGroup || renderer,
parentNode = parentWrapper.element || renderer.box,
childNodes,
otherElement,
otherZIndex,
element = this.element,
inserted,
run = this.added,
i;
if (defined(value)) {
element.zIndex = value; // So we can read it for other elements in the group
value = +value;
if (this[key] === value) { // Only update when needed (#3865)
run = false;
}
this[key] = value;
}
// Insert according to this and other elements' zIndex. Before .add() is called,
// nothing is done. Then on add, or by later calls to zIndexSetter, the node
// is placed on the right place in the DOM.
if (run) {
value = this.zIndex;
if (value && parentGroup) {
parentGroup.handleZ = true;
}
childNodes = parentNode.childNodes;
for (i = 0; i < childNodes.length && !inserted; i++) {
otherElement = childNodes[i];
otherZIndex = otherElement.zIndex;
if (otherElement !== element && (
// Insert before the first element with a higher zIndex
pInt(otherZIndex) > value ||
// If no zIndex given, insert before the first element with a zIndex
(!defined(value) && defined(otherZIndex)) ||
// Negative zIndex versus no zIndex:
// On all levels except the highest. If the parent is <svg>,
// then we don't want to put items before <desc> or <defs>
(value < 0 && !defined(otherZIndex) && parentNode !== renderer.box)
)) {
parentNode.insertBefore(element, otherElement);
inserted = true;
}
}
if (!inserted) {
parentNode.appendChild(element);
}
}
return inserted;
},
_defaultSetter: function(value, key, element) {
element.setAttribute(key, value);
}
};
// Some shared setters and getters
SVGElement.prototype.yGetter = SVGElement.prototype.xGetter;
SVGElement.prototype.translateXSetter = SVGElement.prototype.translateYSetter =
SVGElement.prototype.rotationSetter = SVGElement.prototype.verticalAlignSetter =
SVGElement.prototype.scaleXSetter = SVGElement.prototype.scaleYSetter = function(value, key) {
this[key] = value;
this.doTransform = true;
};
/**
* The default SVG renderer
*/
SVGRenderer = H.SVGRenderer = function() {
this.init.apply(this, arguments);
};
SVGRenderer.prototype = {
Element: SVGElement,
SVG_NS: SVG_NS,
/**
* Initialize the SVGRenderer
* @param {Object} container
* @param {Number} width
* @param {Number} height
* @param {Boolean} forExport
*/
init: function(container, width, height, style, forExport, allowHTML) {
var renderer = this,
boxWrapper,
element,
desc;
boxWrapper = renderer.createElement('svg')
.attr({
'version': '1.1',
'class': 'highcharts-root'
});
element = boxWrapper.element;
container.appendChild(element);
// For browsers other than IE, add the namespace attribute (#1978)
if (container.innerHTML.indexOf('xmlns') === -1) {
attr(element, 'xmlns', this.SVG_NS);
}
// object properties
renderer.isSVG = true;
renderer.box = element;
renderer.boxWrapper = boxWrapper;
renderer.alignedObjects = [];
// Page url used for internal references. #24, #672, #1070
renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ?
win.location.href
.replace(/#.*?$/, '') // remove the hash
.replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes
.replace(/ /g, '%20') : // replace spaces (needed for Safari only)
'';
// Add description
desc = this.createElement('desc').add();
desc.element.appendChild(doc.createTextNode('Created with Highmaps 5.0.1'));
renderer.defs = this.createElement('defs').add();
renderer.allowHTML = allowHTML;
renderer.forExport = forExport;
renderer.gradients = {}; // Object where gradient SvgElements are stored
renderer.cache = {}; // Cache for numerical bounding boxes
renderer.cacheKeys = [];
renderer.imgCount = 0;
renderer.setSize(width, height, false);
// Issue 110 workaround:
// In Firefox, if a div is positioned by percentage, its pixel position may land
// between pixels. The container itself doesn't display this, but an SVG element
// inside this container will be drawn at subpixel precision. In order to draw
// sharp lines, this must be compensated for. This doesn't seem to work inside
// iframes though (like in jsFiddle).
var subPixelFix, rect;
if (isFirefox && container.getBoundingClientRect) {
renderer.subPixelFix = subPixelFix = function() {
css(container, {
left: 0,
top: 0
});
rect = container.getBoundingClientRect();
css(container, {
left: (Math.ceil(rect.left) - rect.left) + 'px',
top: (Math.ceil(rect.top) - rect.top) + 'px'
});
};
// run the fix now
subPixelFix();
// run it on resize
addEvent(win, 'resize', subPixelFix);
}
},
/**
* General method for adding a definition. Can be used for gradients, fills, filters etc.
*
* @return SVGElement The inserted node
*/
definition: function(def) {
var ren = this;
function recurse(config, parent) {
var ret;
each(splat(config), function(item) {
var node = ren.createElement(item.tagName),
key,
attr = {};
// Set attributes
for (key in item) {
if (key !== 'tagName' && key !== 'children' && key !== 'textContent') {
attr[key] = item[key];
}
}
node.attr(attr);
// Add to the tree
node.add(parent || ren.defs);
// Add text content
if (item.textContent) {
node.element.appendChild(doc.createTextNode(item.textContent));
}
// Recurse
recurse(item.children || [], node);
ret = node;
});
// Return last node added (on top level it's the only one)
return ret;
}
return recurse(def);
},
/**
* Detect whether the renderer is hidden. This happens when one of the parent elements
* has display: none. #608.
*/
isHidden: function() {
return !this.boxWrapper.getBBox().width;
},
/**
* Destroys the renderer and its allocated members.
*/
destroy: function() {
var renderer = this,
rendererDefs = renderer.defs;
renderer.box = null;
renderer.boxWrapper = renderer.boxWrapper.destroy();
// Call destroy on all gradient elements
destroyObjectProperties(renderer.gradients || {});
renderer.gradients = null;
// Defs are null in VMLRenderer
// Otherwise, destroy them here.
if (rendererDefs) {
renderer.defs = rendererDefs.destroy();
}
// Remove sub pixel fix handler
// We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed
// See issue #982
if (renderer.subPixelFix) {
removeEvent(win, 'resize', renderer.subPixelFix);
}
renderer.alignedObjects = null;
return null;
},
/**
* Create a wrapper for an SVG element
* @param {Object} nodeName
*/
createElement: function(nodeName) {
var wrapper = new this.Element();
wrapper.init(this, nodeName);
return wrapper;
},
/**
* Dummy function for plugins
*/
draw: noop,
/**
* Get converted radial gradient attributes
*/
getRadialAttr: function(radialReference, gradAttr) {
return {
cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2],
cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2],
r: gradAttr.r * radialReference[2]
};
},
/**
* Parse a simple HTML string into SVG tspans
*
* @param {Object} textNode The parent text SVG node
*/
buildText: function(wrapper) {
var textNode = wrapper.element,
renderer = this,
forExport = renderer.forExport,
textStr = pick(wrapper.textStr, '').toString(),
hasMarkup = textStr.indexOf('<') !== -1,
lines,
childNodes = textNode.childNodes,
clsRegex,
styleRegex,
hrefRegex,
wasTooLong,
parentX = attr(textNode, 'x'),
textStyles = wrapper.styles,
width = wrapper.textWidth,
textLineHeight = textStyles && textStyles.lineHeight,
textShadow = textStyles && textStyles.textShadow,
ellipsis = textStyles && textStyles.textOverflow === 'ellipsis',
i = childNodes.length,
tempParent = width && !wrapper.added && this.box,
getLineHeight = function(tspan) {
var fontSizeStyle;
return textLineHeight ?
pInt(textLineHeight) :
renderer.fontMetrics(
fontSizeStyle,
tspan
).h;
},
unescapeAngleBrackets = function(inputStr) {
return inputStr.replace(/</g, '<').replace(/>/g, '>');
};
/// remove old text
while (i--) {
textNode.removeChild(childNodes[i]);
}
// Skip tspans, add text directly to text node. The forceTSpan is a hook
// used in text outline hack.
if (!hasMarkup && !textShadow && !ellipsis && !width && textStr.indexOf(' ') === -1) {
textNode.appendChild(doc.createTextNode(unescapeAngleBrackets(textStr)));
// Complex strings, add more logic
} else {
clsRegex = /<.*class="([^"]+)".*>/;
styleRegex = /<.*style="([^"]+)".*>/;
hrefRegex = /<.*href="(http[^"]+)".*>/;
if (tempParent) {
tempParent.appendChild(textNode); // attach it to the DOM to read offset width
}
if (hasMarkup) {
lines = textStr
.replace(/<(b|strong)>/g, '<span style="font-weight:bold">')
.replace(/<(i|em)>/g, '<span style="font-style:italic">')
.replace(/<a/g, '<span')
.replace(/<\/(b|strong|i|em|a)>/g, '</span>')
.split(/<br.*?>/g);
} else {
lines = [textStr];
}
// Trim empty lines (#5261)
lines = grep(lines, function(line) {
return line !== '';
});
// build the lines
each(lines, function buildTextLines(line, lineNo) {
var spans,
spanNo = 0;
line = line
.replace(/^\s+|\s+$/g, '') // Trim to prevent useless/costly process on the spaces (#5258)
.replace(/<span/g, '|||<span')
.replace(/<\/span>/g, '</span>|||');
spans = line.split('|||');
each(spans, function buildTextSpans(span) {
if (span !== '' || spans.length === 1) {
var attributes = {},
tspan = doc.createElementNS(renderer.SVG_NS, 'tspan'),
spanCls,
spanStyle; // #390
if (clsRegex.test(span)) {
spanCls = span.match(clsRegex)[1];
attr(tspan, 'class', spanCls);
}
if (styleRegex.test(span)) {
spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2');
attr(tspan, 'style', spanStyle);
}
if (hrefRegex.test(span) && !forExport) { // Not for export - #1529
attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"');
css(tspan, {
cursor: 'pointer'
});
}
span = unescapeAngleBrackets(span.replace(/<(.|\n)*?>/g, '') || ' ');
// Nested tags aren't supported, and cause crash in Safari (#1596)
if (span !== ' ') {
// add the text node
tspan.appendChild(doc.createTextNode(span));
if (!spanNo) { // first span in a line, align it to the left
if (lineNo && parentX !== null) {
attributes.x = parentX;
}
} else {
attributes.dx = 0; // #16
}
// add attributes
attr(tspan, attributes);
// Append it
textNode.appendChild(tspan);
// first span on subsequent line, add the line height
if (!spanNo && lineNo) {
// allow getting the right offset height in exporting in IE
if (!svg && forExport) {
css(tspan, {
display: 'block'
});
}
// Set the line height based on the font size of either
// the text element or the tspan element
attr(
tspan,
'dy',
getLineHeight(tspan)
);
}
/*if (width) {
renderer.breakText(wrapper, width);
}*/
// Check width and apply soft breaks or ellipsis
if (width) {
var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273
noWrap = textStyles.whiteSpace === 'nowrap',
hasWhiteSpace = spans.length > 1 || lineNo || (words.length > 1 && !noWrap),
tooLong,
actualWidth,
rest = [],
dy = getLineHeight(tspan),
rotation = wrapper.rotation,
wordStr = span, // for ellipsis
cursor = wordStr.length, // binary search cursor
bBox;
while ((hasWhiteSpace || ellipsis) && (words.length || rest.length)) {
wrapper.rotation = 0; // discard rotation when computing box
bBox = wrapper.getBBox(true);
actualWidth = bBox.width;
// Old IE cannot measure the actualWidth for SVG elements (#2314)
if (!svg && renderer.forExport) {
actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles);
}
tooLong = actualWidth > width;
// For ellipsis, do a binary search for the correct string length
if (wasTooLong === undefined) {
wasTooLong = tooLong; // First time
}
if (ellipsis && wasTooLong) {
cursor /= 2;
if (wordStr === '' || (!tooLong && cursor < 0.5)) {
words = []; // All ok, break out
} else {
wordStr = span.substring(0, wordStr.length + (tooLong ? -1 : 1) * Math.ceil(cursor));
words = [wordStr + (width > 3 ? '\u2026' : '')];
tspan.removeChild(tspan.firstChild);
}
// Looping down, this is the first word sequence that is not too long,
// so we can move on to build the next line.
} else if (!tooLong || words.length === 1) {
words = rest;
rest = [];
if (words.length && !noWrap) {
tspan = doc.createElementNS(SVG_NS, 'tspan');
attr(tspan, {
dy: dy,
x: parentX
});
if (spanStyle) { // #390
attr(tspan, 'style', spanStyle);
}
textNode.appendChild(tspan);
}
if (actualWidth > width) { // a single word is pressing it out
width = actualWidth;
}
} else { // append to existing line tspan
tspan.removeChild(tspan.firstChild);
rest.unshift(words.pop());
}
if (words.length) {
tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-')));
}
}
wrapper.rotation = rotation;
}
spanNo++;
}
}
});
});
if (wasTooLong) {
wrapper.attr('title', wrapper.textStr);
}
if (tempParent) {
tempParent.removeChild(textNode); // attach it to the DOM to read offset width
}
// Apply the text shadow
if (textShadow && wrapper.applyTextShadow) {
wrapper.applyTextShadow(textShadow);
}
}
},
/*
breakText: function (wrapper, width) {
var bBox = wrapper.getBBox(),
node = wrapper.element,
textLength = node.textContent.length,
pos = Math.round(width * textLength / bBox.width), // try this position first, based on average character width
increment = 0,
finalPos;
if (bBox.width > width) {
while (finalPos === undefined) {
textLength = node.getSubStringLength(0, pos);
if (textLength <= width) {
if (increment === -1) {
finalPos = pos;
} else {
increment = 1;
}
} else {
if (increment === 1) {
finalPos = pos - 1;
} else {
increment = -1;
}
}
pos += increment;
}
}
console.log('width', width, 'stringWidth', node.getSubStringLength(0, finalPos))
},
*/
/**
* Returns white for dark colors and black for bright colors
*/
getContrast: function(rgba) {
rgba = color(rgba).rgba;
return rgba[0] + rgba[1] + rgba[2] > 2 * 255 ? '#000000' : '#FFFFFF';
},
/**
* Create a button with preset states
* @param {String} text
* @param {Number} x
* @param {Number} y
* @param {Function} callback
* @param {Object} normalState
* @param {Object} hoverState
* @param {Object} pressedState
*/
button: function(text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape) {
var label = this.label(text, x, y, shape, null, null, null, null, 'button'),
curState = 0;
// Default, non-stylable attributes
label.attr(merge({
'padding': 8,
'r': 2
}, normalState));
// Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667).
addEvent(label.element, isMS ? 'mouseover' : 'mouseenter', function() {
if (curState !== 3) {
label.setState(1);
}
});
addEvent(label.element, isMS ? 'mouseout' : 'mouseleave', function() {
if (curState !== 3) {
label.setState(curState);
}
});
label.setState = function(state) {
// Hover state is temporary, don't record it
if (state !== 1) {
label.state = curState = state;
}
// Update visuals
label.removeClass(/highcharts-button-(normal|hover|pressed|disabled)/)
.addClass('highcharts-button-' + ['normal', 'hover', 'pressed', 'disabled'][state || 0]);
};
return label
.on('click', function(e) {
if (curState !== 3) {
callback.call(label, e);
}
});
},
/**
* Make a straight line crisper by not spilling out to neighbour pixels
* @param {Array} points
* @param {Number} width
*/
crispLine: function(points, width) {
// points format: ['M', 0, 0, 'L', 100, 0]
// normalize to a crisp line
if (points[1] === points[4]) {
// Substract due to #1129. Now bottom and left axis gridlines behave the same.
points[1] = points[4] = Math.round(points[1]) - (width % 2 / 2);
}
if (points[2] === points[5]) {
points[2] = points[5] = Math.round(points[2]) + (width % 2 / 2);
}
return points;
},
/**
* Draw a path
* @param {Array} path An SVG path in array form
*/
path: function(path) {
var attribs = {
};
if (isArray(path)) {
attribs.d = path;
} else if (isObject(path)) { // attributes
extend(attribs, path);
}
return this.createElement('path').attr(attribs);
},
/**
* Draw and return an SVG circle
* @param {Number} x The x position
* @param {Number} y The y position
* @param {Number} r The radius
*/
circle: function(x, y, r) {
var attribs = isObject(x) ? x : {
x: x,
y: y,
r: r
},
wrapper = this.createElement('circle');
// Setting x or y translates to cx and cy
wrapper.xSetter = wrapper.ySetter = function(value, key, element) {
element.setAttribute('c' + key, value);
};
return wrapper.attr(attribs);
},
/**
* Draw and return an arc
* @param {Number} x X position
* @param {Number} y Y position
* @param {Number} r Radius
* @param {Number} innerR Inner radius like used in donut charts
* @param {Number} start Starting angle
* @param {Number} end Ending angle
*/
arc: function(x, y, r, innerR, start, end) {
var arc;
if (isObject(x)) {
y = x.y;
r = x.r;
innerR = x.innerR;
start = x.start;
end = x.end;
x = x.x;
}
// Arcs are defined as symbols for the ability to set
// attributes in attr and animate
arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, {
innerR: innerR || 0,
start: start || 0,
end: end || 0
});
arc.r = r; // #959
return arc;
},
/**
* Draw and return a rectangle
* @param {Number} x Left position
* @param {Number} y Top position
* @param {Number} width
* @param {Number} height
* @param {Number} r Border corner radius
* @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing
*/
rect: function(x, y, width, height, r, strokeWidth) {
r = isObject(x) ? x.r : r;
var wrapper = this.createElement('rect'),
attribs = isObject(x) ? x : x === undefined ? {} : {
x: x,
y: y,
width: Math.max(width, 0),
height: Math.max(height, 0)
};
if (r) {
attribs.r = r;
}
wrapper.rSetter = function(value, key, element) {
attr(element, {
rx: value,
ry: value
});
};
return wrapper.attr(attribs);
},
/**
* Resize the box and re-align all aligned elements
* @param {Object} width
* @param {Object} height
* @param {Boolean} animate
*
*/
setSize: function(width, height, animate) {
var renderer = this,
alignedObjects = renderer.alignedObjects,
i = alignedObjects.length;
renderer.width = width;
renderer.height = height;
renderer.boxWrapper.animate({
width: width,
height: height
}, {
step: function() {
this.attr({
viewBox: '0 0 ' + this.attr('width') + ' ' + this.attr('height')
});
},
duration: pick(animate, true) ? undefined : 0
});
while (i--) {
alignedObjects[i].align();
}
},
/**
* Create a group
* @param {String} name The group will be given a class name of 'highcharts-{name}'.
* This can be used for styling and scripting.
*/
g: function(name) {
var elem = this.createElement('g');
return name ? elem.attr({
'class': 'highcharts-' + name
}) : elem;
},
/**
* Display an image
* @param {String} src
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
image: function(src, x, y, width, height) {
var attribs = {
preserveAspectRatio: 'none'
},
elemWrapper;
// optional properties
if (arguments.length > 1) {
extend(attribs, {
x: x,
y: y,
width: width,
height: height
});
}
elemWrapper = this.createElement('image').attr(attribs);
// set the href in the xlink namespace
if (elemWrapper.element.setAttributeNS) {
elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink',
'href', src);
} else {
// could be exporting in IE
// using href throws "not supported" in ie7 and under, requries regex shim to fix later
elemWrapper.element.setAttribute('hc-svg-href', src);
}
return elemWrapper;
},
/**
* Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object.
*
* @param {Object} symbol
* @param {Object} x
* @param {Object} y
* @param {Object} radius
* @param {Object} options
*/
symbol: function(symbol, x, y, width, height, options) {
var ren = this,
obj,
// get the symbol definition function
symbolFn = this.symbols[symbol],
// check if there's a path defined for this symbol
path = defined(x) && symbolFn && symbolFn(
Math.round(x),
Math.round(y),
width,
height,
options
),
imageRegex = /^url\((.*?)\)$/,
imageSrc,
centerImage;
if (symbolFn) {
obj = this.path(path);
// expando properties for use in animate and attr
extend(obj, {
symbolName: symbol,
x: x,
y: y,
width: width,
height: height
});
if (options) {
extend(obj, options);
}
// image symbols
} else if (imageRegex.test(symbol)) {
imageSrc = symbol.match(imageRegex)[1];
// Create the image synchronously, add attribs async
obj = this.image(imageSrc);
// The image width is not always the same as the symbol width. The
// image may be centered within the symbol, as is the case when
// image shapes are used as label backgrounds, for example in flags.
obj.imgwidth = pick(
symbolSizes[imageSrc] && symbolSizes[imageSrc].width,
options && options.width
);
obj.imgheight = pick(
symbolSizes[imageSrc] && symbolSizes[imageSrc].height,
options && options.height
);
/**
* Set the size and position
*/
centerImage = function() {
obj.attr({
width: obj.width,
height: obj.height
});
};
/**
* Width and height setters that take both the image's physical size
* and the label size into consideration, and translates the image
* to center within the label.
*/
each(['width', 'height'], function(key) {
obj[key + 'Setter'] = function(value, key) {
var attribs = {},
imgSize = this['img' + key],
trans = key === 'width' ? 'translateX' : 'translateY';
this[key] = value;
if (defined(imgSize)) {
if (this.element) {
this.element.setAttribute(key, imgSize);
}
if (!this.alignByTranslate) {
attribs[trans] = ((this[key] || 0) - imgSize) / 2;
this.attr(attribs);
}
}
};
});
if (defined(x)) {
obj.attr({
x: x,
y: y
});
}
obj.isImg = true;
if (defined(obj.imgwidth) && defined(obj.imgheight)) {
centerImage();
} else {
// Initialize image to be 0 size so export will still function if there's no cached sizes.
obj.attr({
width: 0,
height: 0
});
// Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8,
// the created element must be assigned to a variable in order to load (#292).
createElement('img', {
onload: function() {
var chart = charts[ren.chartIndex];
// Special case for SVGs on IE11, the width is not accessible until the image is
// part of the DOM (#2854).
if (this.width === 0) {
css(this, {
position: 'absolute',
top: '-999em'
});
doc.body.appendChild(this);
}
// Center the image
symbolSizes[imageSrc] = { // Cache for next
width: this.width,
height: this.height
};
obj.imgwidth = this.width;
obj.imgheight = this.height;
if (obj.element) {
centerImage();
}
// Clean up after #2854 workaround.
if (this.parentNode) {
this.parentNode.removeChild(this);
}
// Fire the load event when all external images are loaded
ren.imgCount--;
if (!ren.imgCount && chart && chart.onload) {
chart.onload();
}
},
src: imageSrc
});
this.imgCount++;
}
}
return obj;
},
/**
* An extendable collection of functions for defining symbol paths.
*/
symbols: {
'circle': function(x, y, w, h) {
var cpw = 0.166 * w;
return [
'M', x + w / 2, y,
'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h,
'C', x - cpw, y + h, x - cpw, y, x + w / 2, y,
'Z'
];
},
'square': function(x, y, w, h) {
return [
'M', x, y,
'L', x + w, y,
x + w, y + h,
x, y + h,
'Z'
];
},
'triangle': function(x, y, w, h) {
return [
'M', x + w / 2, y,
'L', x + w, y + h,
x, y + h,
'Z'
];
},
'triangle-down': function(x, y, w, h) {
return [
'M', x, y,
'L', x + w, y,
x + w / 2, y + h,
'Z'
];
},
'diamond': function(x, y, w, h) {
return [
'M', x + w / 2, y,
'L', x + w, y + h / 2,
x + w / 2, y + h,
x, y + h / 2,
'Z'
];
},
'arc': function(x, y, w, h, options) {
var start = options.start,
radius = options.r || w || h,
end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561)
innerRadius = options.innerR,
open = options.open,
cosStart = Math.cos(start),
sinStart = Math.sin(start),
cosEnd = Math.cos(end),
sinEnd = Math.sin(end),
longArc = options.end - start < Math.PI ? 0 : 1;
return [
'M',
x + radius * cosStart,
y + radius * sinStart,
'A', // arcTo
radius, // x radius
radius, // y radius
0, // slanting
longArc, // long or short arc
1, // clockwise
x + radius * cosEnd,
y + radius * sinEnd,
open ? 'M' : 'L',
x + innerRadius * cosEnd,
y + innerRadius * sinEnd,
'A', // arcTo
innerRadius, // x radius
innerRadius, // y radius
0, // slanting
longArc, // long or short arc
0, // clockwise
x + innerRadius * cosStart,
y + innerRadius * sinStart,
open ? '' : 'Z' // close
];
},
/**
* Callout shape used for default tooltips, also used for rounded rectangles in VML
*/
callout: function(x, y, w, h, options) {
var arrowLength = 6,
halfDistance = 6,
r = Math.min((options && options.r) || 0, w, h),
safeDistance = r + halfDistance,
anchorX = options && options.anchorX,
anchorY = options && options.anchorY,
path;
path = [
'M', x + r, y,
'L', x + w - r, y, // top side
'C', x + w, y, x + w, y, x + w, y + r, // top-right corner
'L', x + w, y + h - r, // right side
'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner
'L', x + r, y + h, // bottom side
'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner
'L', x, y + r, // left side
'C', x, y, x, y, x + r, y // top-right corner
];
if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side
path.splice(13, 3,
'L', x + w, anchorY - halfDistance,
x + w + arrowLength, anchorY,
x + w, anchorY + halfDistance,
x + w, y + h - r
);
} else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side
path.splice(33, 3,
'L', x, anchorY + halfDistance,
x - arrowLength, anchorY,
x, anchorY - halfDistance,
x, y + r
);
} else if (anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace bottom
path.splice(23, 3,
'L', anchorX + halfDistance, y + h,
anchorX, y + h + arrowLength,
anchorX - halfDistance, y + h,
x + r, y + h
);
} else if (anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace top
path.splice(3, 3,
'L', anchorX - halfDistance, y,
anchorX, y - arrowLength,
anchorX + halfDistance, y,
w - r, y
);
}
return path;
}
},
/**
* Define a clipping rectangle
* @param {String} id
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
clipRect: function(x, y, width, height) {
var wrapper,
id = 'highcharts-' + H.idCounter++,
clipPath = this.createElement('clipPath').attr({
id: id
}).add(this.defs);
wrapper = this.rect(x, y, width, height, 0).add(clipPath);
wrapper.id = id;
wrapper.clipPath = clipPath;
wrapper.count = 0;
return wrapper;
},
/**
* Add text to the SVG object
* @param {String} str
* @param {Number} x Left position
* @param {Number} y Top position
* @param {Boolean} useHTML Use HTML to render the text
*/
text: function(str, x, y, useHTML) {
// declare variables
var renderer = this,
fakeSVG = !svg && renderer.forExport,
wrapper,
attribs = {};
if (useHTML && (renderer.allowHTML || !renderer.forExport)) {
return renderer.html(str, x, y);
}
attribs.x = Math.round(x || 0); // X is always needed for line-wrap logic
if (y) {
attribs.y = Math.round(y);
}
if (str || str === 0) {
attribs.text = str;
}
wrapper = renderer.createElement('text')
.attr(attribs);
// Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063)
if (fakeSVG) {
wrapper.css({
position: 'absolute'
});
}
if (!useHTML) {
wrapper.xSetter = function(value, key, element) {
var tspans = element.getElementsByTagName('tspan'),
tspan,
parentVal = element.getAttribute(key),
i;
for (i = 0; i < tspans.length; i++) {
tspan = tspans[i];
// If the x values are equal, the tspan represents a linebreak
if (tspan.getAttribute(key) === parentVal) {
tspan.setAttribute(key, value);
}
}
element.setAttribute(key, value);
};
}
return wrapper;
},
/**
* Utility to return the baseline offset and total line height from the font size
*/
fontMetrics: function(fontSize, elem) { // eslint-disable-line no-unused-vars
var lineHeight,
baseline;
fontSize = elem && SVGElement.prototype.getStyle.call(elem, 'font-size');
fontSize = /px/.test(fontSize) ? pInt(fontSize) : /em/.test(fontSize) ? parseFloat(fontSize) * 12 : 12;
// Empirical values found by comparing font size and bounding box height.
// Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/
lineHeight = fontSize < 24 ? fontSize + 3 : Math.round(fontSize * 1.2);
baseline = Math.round(lineHeight * 0.8);
return {
h: lineHeight,
b: baseline,
f: fontSize
};
},
/**
* Correct X and Y positioning of a label for rotation (#1764)
*/
rotCorr: function(baseline, rotation, alterY) {
var y = baseline;
if (rotation && alterY) {
y = Math.max(y * Math.cos(rotation * deg2rad), 4);
}
return {
x: (-baseline / 3) * Math.sin(rotation * deg2rad),
y: y
};
},
/**
* Add a label, a text item that can hold a colored or gradient background
* as well as a border and shadow.
* @param {string} str
* @param {Number} x
* @param {Number} y
* @param {String} shape
* @param {Number} anchorX In case the shape has a pointer, like a flag, this is the
* coordinates it should be pinned to
* @param {Number} anchorY
* @param {Boolean} baseline Whether to position the label relative to the text baseline,
* like renderer.text, or to the upper border of the rectangle.
* @param {String} className Class name for the group
*/
label: function(str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) {
var renderer = this,
wrapper = renderer.g(className !== 'button' && 'label'),
text = wrapper.text = renderer.text('', 0, 0, useHTML)
.attr({
zIndex: 1
}),
box,
bBox,
alignFactor = 0,
padding = 3,
paddingLeft = 0,
width,
height,
wrapperX,
wrapperY,
textAlign,
deferredAttr = {},
strokeWidth,
baselineOffset,
hasBGImage = /^url\((.*?)\)$/.test(shape),
needsBox = hasBGImage,
getCrispAdjust,
updateBoxSize,
updateTextPadding,
boxAttr;
if (className) {
wrapper.addClass('highcharts-' + className);
}
needsBox = true; // for styling
getCrispAdjust = function() {
return box.strokeWidth() % 2 / 2;
};
/**
* This function runs after the label is added to the DOM (when the bounding box is
* available), and after the text of the label is updated to detect the new bounding
* box and reflect it in the border box.
*/
updateBoxSize = function() {
var style = text.element.style,
crispAdjust,
attribs = {};
bBox = (width === undefined || height === undefined || textAlign) && defined(text.textStr) &&
text.getBBox(); //#3295 && 3514 box failure when string equals 0
wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft;
wrapper.height = (height || bBox.height || 0) + 2 * padding;
// Update the label-scoped y offset
baselineOffset = padding + renderer.fontMetrics(style && style.fontSize, text).b;
if (needsBox) {
// Create the border box if it is not already present
if (!box) {
wrapper.box = box = renderer.symbols[shape] || hasBGImage ? // Symbol definition exists (#5324)
renderer.symbol(shape) :
renderer.rect();
box.addClass(
(className === 'button' ? '' : 'highcharts-label-box') + // Don't use label className for buttons
(className ? ' highcharts-' + className + '-box' : '')
);
box.add(wrapper);
crispAdjust = getCrispAdjust();
attribs.x = crispAdjust;
attribs.y = (baseline ? -baselineOffset : 0) + crispAdjust;
}
// Apply the box attributes
attribs.width = Math.round(wrapper.width);
attribs.height = Math.round(wrapper.height);
box.attr(extend(attribs, deferredAttr));
deferredAttr = {};
}
};
/**
* This function runs after setting text or padding, but only if padding is changed
*/
updateTextPadding = function() {
var textX = paddingLeft + padding,
textY;
// determin y based on the baseline
textY = baseline ? 0 : baselineOffset;
// compensate for alignment
if (defined(width) && bBox && (textAlign === 'center' || textAlign === 'right')) {
textX += {
center: 0.5,
right: 1
}[textAlign] * (width - bBox.width);
}
// update if anything changed
if (textX !== text.x || textY !== text.y) {
text.attr('x', textX);
if (textY !== undefined) {
text.attr('y', textY);
}
}
// record current values
text.x = textX;
text.y = textY;
};
/**
* Set a box attribute, or defer it if the box is not yet created
* @param {Object} key
* @param {Object} value
*/
boxAttr = function(key, value) {
if (box) {
box.attr(key, value);
} else {
deferredAttr[key] = value;
}
};
/**
* After the text element is added, get the desired size of the border box
* and add it before the text in the DOM.
*/
wrapper.onAdd = function() {
text.add(wrapper);
wrapper.attr({
text: (str || str === 0) ? str : '', // alignment is available now // #3295: 0 not rendered if given as a value
x: x,
y: y
});
if (box && defined(anchorX)) {
wrapper.attr({
anchorX: anchorX,
anchorY: anchorY
});
}
};
/*
* Add specific attribute setters.
*/
// only change local variables
wrapper.widthSetter = function(value) {
width = value;
};
wrapper.heightSetter = function(value) {
height = value;
};
wrapper['text-alignSetter'] = function(value) {
textAlign = value;
};
wrapper.paddingSetter = function(value) {
if (defined(value) && value !== padding) {
padding = wrapper.padding = value;
updateTextPadding();
}
};
wrapper.paddingLeftSetter = function(value) {
if (defined(value) && value !== paddingLeft) {
paddingLeft = value;
updateTextPadding();
}
};
// change local variable and prevent setting attribute on the group
wrapper.alignSetter = function(value) {
value = {
left: 0,
center: 0.5,
right: 1
}[value];
if (value !== alignFactor) {
alignFactor = value;
if (bBox) { // Bounding box exists, means we're dynamically changing
wrapper.attr({
x: wrapperX
}); // #5134
}
}
};
// apply these to the box and the text alike
wrapper.textSetter = function(value) {
if (value !== undefined) {
text.textSetter(value);
}
updateBoxSize();
updateTextPadding();
};
// apply these to the box but not to the text
wrapper['stroke-widthSetter'] = function(value, key) {
if (value) {
needsBox = true;
}
strokeWidth = this['stroke-width'] = value;
boxAttr(key, value);
};
wrapper.rSetter = function(value, key) {
boxAttr(key, value);
};
wrapper.anchorXSetter = function(value, key) {
anchorX = value;
boxAttr(key, Math.round(value) - getCrispAdjust() - wrapperX);
};
wrapper.anchorYSetter = function(value, key) {
anchorY = value;
boxAttr(key, value - wrapperY);
};
// rename attributes
wrapper.xSetter = function(value) {
wrapper.x = value; // for animation getter
if (alignFactor) {
value -= alignFactor * ((width || bBox.width) + 2 * padding);
}
wrapperX = Math.round(value);
wrapper.attr('translateX', wrapperX);
};
wrapper.ySetter = function(value) {
wrapperY = wrapper.y = Math.round(value);
wrapper.attr('translateY', wrapperY);
};
// Redirect certain methods to either the box or the text
var baseCss = wrapper.css;
return extend(wrapper, {
/**
* Pick up some properties and apply them to the text instead of the wrapper
*/
css: function(styles) {
if (styles) {
var textStyles = {};
styles = merge(styles); // create a copy to avoid altering the original object (#537)
each(wrapper.textProps, function(prop) {
if (styles[prop] !== undefined) {
textStyles[prop] = styles[prop];
delete styles[prop];
}
});
text.css(textStyles);
}
return baseCss.call(wrapper, styles);
},
/**
* Return the bounding box of the box, not the group
*/
getBBox: function() {
return {
width: bBox.width + 2 * padding,
height: bBox.height + 2 * padding,
x: bBox.x - padding,
y: bBox.y - padding
};
},
/**
* Destroy and release memory.
*/
destroy: function() {
// Added by button implementation
removeEvent(wrapper.element, 'mouseenter');
removeEvent(wrapper.element, 'mouseleave');
if (text) {
text = text.destroy();
}
if (box) {
box = box.destroy();
}
// Call base implementation to destroy the rest
SVGElement.prototype.destroy.call(wrapper);
// Release local pointers (#1298)
wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = null;
}
});
}
}; // end SVGRenderer
// general renderer
H.Renderer = SVGRenderer;
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var attr = H.attr,
createElement = H.createElement,
css = H.css,
defined = H.defined,
each = H.each,
extend = H.extend,
isFirefox = H.isFirefox,
isMS = H.isMS,
isWebKit = H.isWebKit,
pInt = H.pInt,
SVGElement = H.SVGElement,
SVGRenderer = H.SVGRenderer,
win = H.win,
wrap = H.wrap;
// extend SvgElement for useHTML option
extend(SVGElement.prototype, {
/**
* Apply CSS to HTML elements. This is used in text within SVG rendering and
* by the VML renderer
*/
htmlCss: function(styles) {
var wrapper = this,
element = wrapper.element,
textWidth = styles && element.tagName === 'SPAN' && styles.width;
if (textWidth) {
delete styles.width;
wrapper.textWidth = textWidth;
wrapper.updateTransform();
}
if (styles && styles.textOverflow === 'ellipsis') {
styles.whiteSpace = 'nowrap';
styles.overflow = 'hidden';
}
wrapper.styles = extend(wrapper.styles, styles);
css(wrapper.element, styles);
return wrapper;
},
/**
* VML and useHTML method for calculating the bounding box based on offsets
* @param {Boolean} refresh Whether to force a fresh value from the DOM or to
* use the cached value
*
* @return {Object} A hash containing values for x, y, width and height
*/
htmlGetBBox: function() {
var wrapper = this,
element = wrapper.element;
// faking getBBox in exported SVG in legacy IE
// faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?)
if (element.nodeName === 'text') {
element.style.position = 'absolute';
}
return {
x: element.offsetLeft,
y: element.offsetTop,
width: element.offsetWidth,
height: element.offsetHeight
};
},
/**
* VML override private method to update elements based on internal
* properties based on SVG transform
*/
htmlUpdateTransform: function() {
// aligning non added elements is expensive
if (!this.added) {
this.alignOnAdd = true;
return;
}
var wrapper = this,
renderer = wrapper.renderer,
elem = wrapper.element,
translateX = wrapper.translateX || 0,
translateY = wrapper.translateY || 0,
x = wrapper.x || 0,
y = wrapper.y || 0,
align = wrapper.textAlign || 'left',
alignCorrection = {
left: 0,
center: 0.5,
right: 1
}[align],
styles = wrapper.styles;
// apply translate
css(elem, {
marginLeft: translateX,
marginTop: translateY
});
// apply inversion
if (wrapper.inverted) { // wrapper is a group
each(elem.childNodes, function(child) {
renderer.invertChild(child, elem);
});
}
if (elem.tagName === 'SPAN') {
var rotation = wrapper.rotation,
baseline,
textWidth = pInt(wrapper.textWidth),
whiteSpace = styles && styles.whiteSpace,
currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth, wrapper.textAlign].join(',');
if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed
baseline = renderer.fontMetrics(elem.style.fontSize).b;
// Renderer specific handling of span rotation
if (defined(rotation)) {
wrapper.setSpanRotation(rotation, alignCorrection, baseline);
}
// Reset multiline/ellipsis in order to read width (#4928, #5417)
css(elem, {
width: '',
whiteSpace: whiteSpace || 'nowrap'
});
// Update textWidth
if (elem.offsetWidth > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254
css(elem, {
width: textWidth + 'px',
display: 'block',
whiteSpace: whiteSpace || 'normal' // #3331
});
}
wrapper.getSpanCorrection(elem.offsetWidth, baseline, alignCorrection, rotation, align);
}
// apply position with correction
css(elem, {
left: (x + (wrapper.xCorr || 0)) + 'px',
top: (y + (wrapper.yCorr || 0)) + 'px'
});
// force reflow in webkit to apply the left and top on useHTML element (#1249)
if (isWebKit) {
baseline = elem.offsetHeight; // assigned to baseline for lint purpose
}
// record current text transform
wrapper.cTT = currentTextTransform;
}
},
/**
* Set the rotation of an individual HTML span
*/
setSpanRotation: function(rotation, alignCorrection, baseline) {
var rotationStyle = {},
cssTransformKey = isMS ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : win.opera ? '-o-transform' : '';
rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)';
rotationStyle[cssTransformKey + (isFirefox ? 'Origin' : '-origin')] = rotationStyle.transformOrigin = (alignCorrection * 100) + '% ' + baseline + 'px';
css(this.element, rotationStyle);
},
/**
* Get the correction in X and Y positioning as the element is rotated.
*/
getSpanCorrection: function(width, baseline, alignCorrection) {
this.xCorr = -width * alignCorrection;
this.yCorr = -baseline;
}
});
// Extend SvgRenderer for useHTML option.
extend(SVGRenderer.prototype, {
/**
* Create HTML text node. This is used by the VML renderer as well as the SVG
* renderer through the useHTML option.
*
* @param {String} str
* @param {Number} x
* @param {Number} y
*/
html: function(str, x, y) {
var wrapper = this.createElement('span'),
element = wrapper.element,
renderer = wrapper.renderer,
isSVG = renderer.isSVG,
addSetters = function(element, style) {
// These properties are set as attributes on the SVG group, and as
// identical CSS properties on the div. (#3542)
each(['opacity', 'visibility'], function(prop) {
wrap(element, prop + 'Setter', function(proceed, value, key, elem) {
proceed.call(this, value, key, elem);
style[key] = value;
});
});
};
// Text setter
wrapper.textSetter = function(value) {
if (value !== element.innerHTML) {
delete this.bBox;
}
element.innerHTML = this.textStr = value;
wrapper.htmlUpdateTransform();
};
// Add setters for the element itself (#4938)
if (isSVG) { // #4938, only for HTML within SVG
addSetters(wrapper, wrapper.element.style);
}
// Various setters which rely on update transform
wrapper.xSetter = wrapper.ySetter = wrapper.alignSetter = wrapper.rotationSetter = function(value, key) {
if (key === 'align') {
key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML.
}
wrapper[key] = value;
wrapper.htmlUpdateTransform();
};
// Set the default attributes
wrapper
.attr({
text: str,
x: Math.round(x),
y: Math.round(y)
})
.css({
position: 'absolute'
});
// Keep the whiteSpace style outside the wrapper.styles collection
element.style.whiteSpace = 'nowrap';
// Use the HTML specific .css method
wrapper.css = wrapper.htmlCss;
// This is specific for HTML within SVG
if (isSVG) {
wrapper.add = function(svgGroupWrapper) {
var htmlGroup,
container = renderer.box.parentNode,
parentGroup,
parents = [];
this.parentGroup = svgGroupWrapper;
// Create a mock group to hold the HTML elements
if (svgGroupWrapper) {
htmlGroup = svgGroupWrapper.div;
if (!htmlGroup) {
// Read the parent chain into an array and read from top down
parentGroup = svgGroupWrapper;
while (parentGroup) {
parents.push(parentGroup);
// Move up to the next parent group
parentGroup = parentGroup.parentGroup;
}
// Ensure dynamically updating position when any parent is translated
each(parents.reverse(), function(parentGroup) {
var htmlGroupStyle,
cls = attr(parentGroup.element, 'class');
if (cls) {
cls = {
className: cls
};
} // else null
// Create a HTML div and append it to the parent div to emulate
// the SVG group structure
htmlGroup = parentGroup.div = parentGroup.div || createElement('div', cls, {
position: 'absolute',
left: (parentGroup.translateX || 0) + 'px',
top: (parentGroup.translateY || 0) + 'px',
display: parentGroup.display,
opacity: parentGroup.opacity, // #5075
pointerEvents: parentGroup.styles && parentGroup.styles.pointerEvents // #5595
}, htmlGroup || container); // the top group is appended to container
// Shortcut
htmlGroupStyle = htmlGroup.style;
// Set listeners to update the HTML div's position whenever the SVG group
// position is changed
extend(parentGroup, {
translateXSetter: function(value, key) {
htmlGroupStyle.left = value + 'px';
parentGroup[key] = value;
parentGroup.doTransform = true;
},
translateYSetter: function(value, key) {
htmlGroupStyle.top = value + 'px';
parentGroup[key] = value;
parentGroup.doTransform = true;
}
});
addSetters(parentGroup, htmlGroupStyle);
});
}
} else {
htmlGroup = container;
}
htmlGroup.appendChild(element);
// Shared with VML:
wrapper.added = true;
if (wrapper.alignOnAdd) {
wrapper.htmlUpdateTransform();
}
return wrapper;
};
}
return wrapper;
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var correctFloat = H.correctFloat,
defined = H.defined,
destroyObjectProperties = H.destroyObjectProperties,
isNumber = H.isNumber,
merge = H.merge,
pick = H.pick,
stop = H.stop,
deg2rad = H.deg2rad;
/**
* The Tick class
*/
H.Tick = function(axis, pos, type, noLabel) {
this.axis = axis;
this.pos = pos;
this.type = type || '';
this.isNew = true;
if (!type && !noLabel) {
this.addLabel();
}
};
H.Tick.prototype = {
/**
* Write the tick label
*/
addLabel: function() {
var tick = this,
axis = tick.axis,
options = axis.options,
chart = axis.chart,
categories = axis.categories,
names = axis.names,
pos = tick.pos,
labelOptions = options.labels,
str,
tickPositions = axis.tickPositions,
isFirst = pos === tickPositions[0],
isLast = pos === tickPositions[tickPositions.length - 1],
value = categories ?
pick(categories[pos], names[pos], pos) :
pos,
label = tick.label,
tickPositionInfo = tickPositions.info,
dateTimeLabelFormat;
// Set the datetime label format. If a higher rank is set for this position, use that. If not,
// use the general format.
if (axis.isDatetimeAxis && tickPositionInfo) {
dateTimeLabelFormat =
options.dateTimeLabelFormats[
tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName
];
}
// set properties for access in render method
tick.isFirst = isFirst;
tick.isLast = isLast;
// get the string
str = axis.labelFormatter.call({
axis: axis,
chart: chart,
isFirst: isFirst,
isLast: isLast,
dateTimeLabelFormat: dateTimeLabelFormat,
value: axis.isLog ? correctFloat(axis.lin2log(value)) : value
});
// prepare CSS
//css = width && { width: Math.max(1, Math.round(width - 2 * (labelOptions.padding || 10))) + 'px' };
// first call
if (!defined(label)) {
tick.label = label =
defined(str) && labelOptions.enabled ?
chart.renderer.text(
str,
0,
0,
labelOptions.useHTML
)
.add(axis.labelGroup):
null;
tick.labelLength = label && label.getBBox().width; // Un-rotated length
tick.rotation = 0; // Base value to detect change for new calls to getBBox
// update
} else if (label) {
label.attr({
text: str
});
}
},
/**
* Get the offset height or width of the label
*/
getLabelSize: function() {
return this.label ?
this.label.getBBox()[this.axis.horiz ? 'height' : 'width'] :
0;
},
/**
* Handle the label overflow by adjusting the labels to the left and right edge, or
* hide them if they collide into the neighbour label.
*/
handleOverflow: function(xy) {
var axis = this.axis,
pxPos = xy.x,
chartWidth = axis.chart.chartWidth,
spacing = axis.chart.spacing,
leftBound = pick(axis.labelLeft, Math.min(axis.pos, spacing[3])),
rightBound = pick(axis.labelRight, Math.max(axis.pos + axis.len, chartWidth - spacing[1])),
label = this.label,
rotation = this.rotation,
factor = {
left: 0,
center: 0.5,
right: 1
}[axis.labelAlign],
labelWidth = label.getBBox().width,
slotWidth = axis.getSlotWidth(),
modifiedSlotWidth = slotWidth,
xCorrection = factor,
goRight = 1,
leftPos,
rightPos,
textWidth,
css = {};
// Check if the label overshoots the chart spacing box. If it does, move it.
// If it now overshoots the slotWidth, add ellipsis.
if (!rotation) {
leftPos = pxPos - factor * labelWidth;
rightPos = pxPos + (1 - factor) * labelWidth;
if (leftPos < leftBound) {
modifiedSlotWidth = xy.x + modifiedSlotWidth * (1 - factor) - leftBound;
} else if (rightPos > rightBound) {
modifiedSlotWidth = rightBound - xy.x + modifiedSlotWidth * factor;
goRight = -1;
}
modifiedSlotWidth = Math.min(slotWidth, modifiedSlotWidth); // #4177
if (modifiedSlotWidth < slotWidth && axis.labelAlign === 'center') {
xy.x += goRight * (slotWidth - modifiedSlotWidth - xCorrection *
(slotWidth - Math.min(labelWidth, modifiedSlotWidth)));
}
// If the label width exceeds the available space, set a text width to be
// picked up below. Also, if a width has been set before, we need to set a new
// one because the reported labelWidth will be limited by the box (#3938).
if (labelWidth > modifiedSlotWidth || (axis.autoRotation && (label.styles || {}).width)) {
textWidth = modifiedSlotWidth;
}
// Add ellipsis to prevent rotated labels to be clipped against the edge of the chart
} else if (rotation < 0 && pxPos - factor * labelWidth < leftBound) {
textWidth = Math.round(pxPos / Math.cos(rotation * deg2rad) - leftBound);
} else if (rotation > 0 && pxPos + factor * labelWidth > rightBound) {
textWidth = Math.round((chartWidth - pxPos) / Math.cos(rotation * deg2rad));
}
if (textWidth) {
css.width = textWidth;
if (!(axis.options.labels.style || {}).textOverflow) {
css.textOverflow = 'ellipsis';
}
label.css(css);
}
},
/**
* Get the x and y position for ticks and labels
*/
getPosition: function(horiz, pos, tickmarkOffset, old) {
var axis = this.axis,
chart = axis.chart,
cHeight = (old && chart.oldChartHeight) || chart.chartHeight;
return {
x: horiz ?
axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB : axis.left + axis.offset +
(axis.opposite ?
((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left :
0
),
y: horiz ?
cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) : cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB
};
},
/**
* Get the x, y position of the tick label
*/
getLabelPosition: function(x, y, label, horiz, labelOptions, tickmarkOffset, index, step) {
var axis = this.axis,
transA = axis.transA,
reversed = axis.reversed,
staggerLines = axis.staggerLines,
rotCorr = axis.tickRotCorr || {
x: 0,
y: 0
},
yOffset = labelOptions.y,
line;
if (!defined(yOffset)) {
if (axis.side === 0) {
yOffset = label.rotation ? -8 : -label.getBBox().height;
} else if (axis.side === 2) {
yOffset = rotCorr.y + 8;
} else {
// #3140, #3140
yOffset = Math.cos(label.rotation * deg2rad) * (rotCorr.y - label.getBBox(false, 0).height / 2);
}
}
x = x + labelOptions.x + rotCorr.x - (tickmarkOffset && horiz ?
tickmarkOffset * transA * (reversed ? -1 : 1) : 0);
y = y + yOffset - (tickmarkOffset && !horiz ?
tickmarkOffset * transA * (reversed ? 1 : -1) : 0);
// Correct for staggered labels
if (staggerLines) {
line = (index / (step || 1) % staggerLines);
if (axis.opposite) {
line = staggerLines - line - 1;
}
y += line * (axis.labelOffset / staggerLines);
}
return {
x: x,
y: Math.round(y)
};
},
/**
* Extendible method to return the path of the marker
*/
getMarkPath: function(x, y, tickLength, tickWidth, horiz, renderer) {
return renderer.crispLine([
'M',
x,
y,
'L',
x + (horiz ? 0 : -tickLength),
y + (horiz ? tickLength : 0)
], tickWidth);
},
/**
* Put everything in place
*
* @param index {Number}
* @param old {Boolean} Use old coordinates to prepare an animation into new position
*/
render: function(index, old, opacity) {
var tick = this,
axis = tick.axis,
options = axis.options,
chart = axis.chart,
renderer = chart.renderer,
horiz = axis.horiz,
type = tick.type,
label = tick.label,
pos = tick.pos,
labelOptions = options.labels,
gridLine = tick.gridLine,
tickPrefix = type ? type + 'Tick' : 'tick',
tickSize = axis.tickSize(tickPrefix),
gridLinePath,
mark = tick.mark,
isNewMark = !mark,
step = labelOptions.step,
attribs = {},
show = true,
tickmarkOffset = axis.tickmarkOffset,
xy = tick.getPosition(horiz, pos, tickmarkOffset, old),
x = xy.x,
y = xy.y,
reverseCrisp = ((horiz && x === axis.pos + axis.len) ||
(!horiz && y === axis.pos)) ? -1 : 1; // #1480, #1687
opacity = pick(opacity, 1);
this.isActive = true;
// Create the grid line
if (!gridLine) {
if (!type) {
attribs.zIndex = 1;
}
if (old) {
attribs.opacity = 0;
}
tick.gridLine = gridLine = renderer.path()
.attr(attribs)
.addClass('highcharts-' + (type ? type + '-' : '') + 'grid-line')
.add(axis.gridGroup);
}
// If the parameter 'old' is set, the current call will be followed
// by another call, therefore do not do any animations this time
if (!old && gridLine) {
gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLine.strokeWidth() * reverseCrisp, old, true);
if (gridLinePath) {
gridLine[tick.isNew ? 'attr' : 'animate']({
d: gridLinePath,
opacity: opacity
});
}
}
// create the tick mark
if (tickSize) {
// negate the length
if (axis.opposite) {
tickSize[0] = -tickSize[0];
}
// First time, create it
if (isNewMark) {
tick.mark = mark = renderer.path()
.addClass('highcharts-' + (type ? type + '-' : '') + 'tick')
.add(axis.axisGroup);
}
mark[isNewMark ? 'attr' : 'animate']({
d: tick.getMarkPath(x, y, tickSize[0], mark.strokeWidth() * reverseCrisp, horiz, renderer),
opacity: opacity
});
}
// the label is created on init - now move it into place
if (label && isNumber(x)) {
label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step);
// Apply show first and show last. If the tick is both first and last, it is
// a single centered tick, in which case we show the label anyway (#2100).
if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) ||
(tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) {
show = false;
// Handle label overflow and show or hide accordingly
} else if (horiz && !axis.isRadial && !labelOptions.step &&
!labelOptions.rotation && !old && opacity !== 0) {
tick.handleOverflow(xy);
}
// apply step
if (step && index % step) {
// show those indices dividable by step
show = false;
}
// Set the new position, and show or hide
if (show && isNumber(xy.y)) {
xy.opacity = opacity;
label[tick.isNew ? 'attr' : 'animate'](xy);
} else {
stop(label); // #5332
label.attr('y', -9999); // #1338
}
tick.isNew = false;
}
},
/**
* Destructor for the tick prototype
*/
destroy: function() {
destroyObjectProperties(this, this.axis);
}
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var arrayMax = H.arrayMax,
arrayMin = H.arrayMin,
defined = H.defined,
destroyObjectProperties = H.destroyObjectProperties,
each = H.each,
erase = H.erase,
merge = H.merge,
pick = H.pick;
/*
* The object wrapper for plot lines and plot bands
* @param {Object} options
*/
H.PlotLineOrBand = function(axis, options) {
this.axis = axis;
if (options) {
this.options = options;
this.id = options.id;
}
};
H.PlotLineOrBand.prototype = {
/**
* Render the plot line or plot band. If it is already existing,
* move it.
*/
render: function() {
var plotLine = this,
axis = plotLine.axis,
horiz = axis.horiz,
options = plotLine.options,
optionsLabel = options.label,
label = plotLine.label,
to = options.to,
from = options.from,
value = options.value,
isBand = defined(from) && defined(to),
isLine = defined(value),
svgElem = plotLine.svgElem,
isNew = !svgElem,
path = [],
addEvent,
eventType,
color = options.color,
zIndex = pick(options.zIndex, 0),
events = options.events,
attribs = {
'class': 'highcharts-plot-' + (isBand ? 'band ' : 'line ') + (options.className || '')
},
groupAttribs = {},
renderer = axis.chart.renderer,
groupName = isBand ? 'bands' : 'lines',
group,
log2lin = axis.log2lin;
// logarithmic conversion
if (axis.isLog) {
from = log2lin(from);
to = log2lin(to);
value = log2lin(value);
}
// Grouping and zIndex
groupAttribs.zIndex = zIndex;
groupName += '-' + zIndex;
group = axis[groupName];
if (!group) {
axis[groupName] = group = renderer.g('plot-' + groupName)
.attr(groupAttribs).add();
}
// Create the path
if (isNew) {
plotLine.svgElem = svgElem =
renderer
.path()
.attr(attribs).add(group);
}
// Set the path or return
if (isLine) {
path = axis.getPlotLinePath(value, svgElem.strokeWidth());
} else if (isBand) { // plot band
path = axis.getPlotBandPath(from, to, options);
} else {
return;
}
// common for lines and bands
if (isNew && path && path.length) {
svgElem.attr({
d: path
});
// events
if (events) {
addEvent = function(eventType) {
svgElem.on(eventType, function(e) {
events[eventType].apply(plotLine, [e]);
});
};
for (eventType in events) {
addEvent(eventType);
}
}
} else if (svgElem) {
if (path) {
svgElem.show();
svgElem.animate({
d: path
});
} else {
svgElem.hide();
if (label) {
plotLine.label = label = label.destroy();
}
}
}
// the plot band/line label
if (optionsLabel && defined(optionsLabel.text) && path && path.length &&
axis.width > 0 && axis.height > 0 && !path.flat) {
// apply defaults
optionsLabel = merge({
align: horiz && isBand && 'center',
x: horiz ? !isBand && 4 : 10,
verticalAlign: !horiz && isBand && 'middle',
y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4,
rotation: horiz && !isBand && 90
}, optionsLabel);
this.renderLabel(optionsLabel, path, isBand, zIndex);
} else if (label) { // move out of sight
label.hide();
}
// chainable
return plotLine;
},
/**
* Render and align label for plot line or band.
*/
renderLabel: function(optionsLabel, path, isBand, zIndex) {
var plotLine = this,
label = plotLine.label,
renderer = plotLine.axis.chart.renderer,
attribs,
xs,
ys,
x,
y;
// add the SVG element
if (!label) {
attribs = {
align: optionsLabel.textAlign || optionsLabel.align,
rotation: optionsLabel.rotation,
'class': 'highcharts-plot-' + (isBand ? 'band' : 'line') + '-label ' + (optionsLabel.className || '')
};
attribs.zIndex = zIndex;
plotLine.label = label = renderer.text(
optionsLabel.text,
0,
0,
optionsLabel.useHTML
)
.attr(attribs)
.add();
}
// get the bounding box and align the label
// #3000 changed to better handle choice between plotband or plotline
xs = [path[1], path[4], (isBand ? path[6] : path[1])];
ys = [path[2], path[5], (isBand ? path[7] : path[2])];
x = arrayMin(xs);
y = arrayMin(ys);
label.align(optionsLabel, false, {
x: x,
y: y,
width: arrayMax(xs) - x,
height: arrayMax(ys) - y
});
label.show();
},
/**
* Remove the plot line or band
*/
destroy: function() {
// remove it from the lookup
erase(this.axis.plotLinesAndBands, this);
delete this.axis;
destroyObjectProperties(this);
}
};
/**
* Object with members for extending the Axis prototype
* @todo Extend directly instead of adding object to Highcharts first
*/
H.AxisPlotLineOrBandExtension = {
/**
* Create the path for a plot band
*/
getPlotBandPath: function(from, to) {
var toPath = this.getPlotLinePath(to, null, null, true),
path = this.getPlotLinePath(from, null, null, true);
if (path && toPath) {
// Flat paths don't need labels (#3836)
path.flat = path.toString() === toPath.toString();
path.push(
toPath[4],
toPath[5],
toPath[1],
toPath[2]
);
} else { // outside the axis area
path = null;
}
return path;
},
addPlotBand: function(options) {
return this.addPlotBandOrLine(options, 'plotBands');
},
addPlotLine: function(options) {
return this.addPlotBandOrLine(options, 'plotLines');
},
/**
* Add a plot band or plot line after render time
*
* @param options {Object} The plotBand or plotLine configuration object
*/
addPlotBandOrLine: function(options, coll) {
var obj = new H.PlotLineOrBand(this, options).render(),
userOptions = this.userOptions;
if (obj) { // #2189
// Add it to the user options for exporting and Axis.update
if (coll) {
userOptions[coll] = userOptions[coll] || [];
userOptions[coll].push(options);
}
this.plotLinesAndBands.push(obj);
}
return obj;
},
/**
* Remove a plot band or plot line from the chart by id
* @param {Object} id
*/
removePlotBandOrLine: function(id) {
var plotLinesAndBands = this.plotLinesAndBands,
options = this.options,
userOptions = this.userOptions,
i = plotLinesAndBands.length;
while (i--) {
if (plotLinesAndBands[i].id === id) {
plotLinesAndBands[i].destroy();
}
}
each([options.plotLines || [], userOptions.plotLines || [], options.plotBands || [], userOptions.plotBands || []], function(arr) {
i = arr.length;
while (i--) {
if (arr[i].id === id) {
erase(arr, arr[i]);
}
}
});
}
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
animObject = H.animObject,
arrayMax = H.arrayMax,
arrayMin = H.arrayMin,
AxisPlotLineOrBandExtension = H.AxisPlotLineOrBandExtension,
color = H.color,
correctFloat = H.correctFloat,
defaultOptions = H.defaultOptions,
defined = H.defined,
deg2rad = H.deg2rad,
destroyObjectProperties = H.destroyObjectProperties,
each = H.each,
error = H.error,
extend = H.extend,
fireEvent = H.fireEvent,
format = H.format,
getMagnitude = H.getMagnitude,
grep = H.grep,
inArray = H.inArray,
isArray = H.isArray,
isNumber = H.isNumber,
isString = H.isString,
merge = H.merge,
normalizeTickInterval = H.normalizeTickInterval,
pick = H.pick,
PlotLineOrBand = H.PlotLineOrBand,
removeEvent = H.removeEvent,
splat = H.splat,
syncTimeout = H.syncTimeout,
Tick = H.Tick;
/**
* Create a new axis object
* @param {Object} chart
* @param {Object} options
*/
H.Axis = function() {
this.init.apply(this, arguments);
};
H.Axis.prototype = {
/**
* Default options for the X axis - the Y axis has extended defaults
*/
defaultOptions: {
// allowDecimals: null,
// alternateGridColor: null,
// categories: [],
dateTimeLabelFormats: {
millisecond: '%H:%M:%S.%L',
second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M',
day: '%e. %b',
week: '%e. %b',
month: '%b \'%y',
year: '%Y'
},
endOnTick: false,
// reversed: false,
labels: {
enabled: true,
// rotation: 0,
// align: 'center',
// step: null,
x: 0
//y: undefined
/*formatter: function () {
return this.value;
},*/
},
//linkedTo: null,
//max: undefined,
//min: undefined,
minPadding: 0.01,
maxPadding: 0.01,
//minRange: null,
//minorTickInterval: null,
minorTickLength: 2,
minorTickPosition: 'outside', // inside or outside
//opposite: false,
//offset: 0,
//plotBands: [{
// events: {},
// zIndex: 1,
// labels: { align, x, verticalAlign, y, style, rotation, textAlign }
//}],
//plotLines: [{
// events: {}
// dashStyle: {}
// zIndex:
// labels: { align, x, verticalAlign, y, style, rotation, textAlign }
//}],
//reversed: false,
// showFirstLabel: true,
// showLastLabel: true,
startOfWeek: 1,
startOnTick: false,
//tickInterval: null,
tickLength: 10,
tickmarkPlacement: 'between', // on or between
tickPixelInterval: 100,
tickPosition: 'outside',
title: {
//text: null,
align: 'middle', // low, middle or high
//margin: 0 for horizontal, 10 for vertical axes,
//rotation: 0,
//side: 'outside',
//x: 0,
//y: 0
},
type: 'linear', // linear, logarithmic or datetime
//visible: true
},
/**
* This options set extends the defaultOptions for Y axes
*/
defaultYAxisOptions: {
endOnTick: true,
tickPixelInterval: 72,
showLastLabel: true,
labels: {
x: -8
},
maxPadding: 0.05,
minPadding: 0.05,
startOnTick: true,
title: {
rotation: 270,
text: 'Values'
},
stackLabels: {
enabled: false,
//align: dynamic,
//y: dynamic,
//x: dynamic,
//verticalAlign: dynamic,
//textAlign: dynamic,
//rotation: 0,
formatter: function() {
return H.numberFormat(this.total, -1);
}
}
},
/**
* These options extend the defaultOptions for left axes
*/
defaultLeftAxisOptions: {
labels: {
x: -15
},
title: {
rotation: 270
}
},
/**
* These options extend the defaultOptions for right axes
*/
defaultRightAxisOptions: {
labels: {
x: 15
},
title: {
rotation: 90
}
},
/**
* These options extend the defaultOptions for bottom axes
*/
defaultBottomAxisOptions: {
labels: {
autoRotation: [-45],
x: 0
// overflow: undefined,
// staggerLines: null
},
title: {
rotation: 0
}
},
/**
* These options extend the defaultOptions for top axes
*/
defaultTopAxisOptions: {
labels: {
autoRotation: [-45],
x: 0
// overflow: undefined
// staggerLines: null
},
title: {
rotation: 0
}
},
/**
* Initialize the axis
*/
init: function(chart, userOptions) {
var isXAxis = userOptions.isX,
axis = this;
axis.chart = chart;
// Flag, is the axis horizontal
axis.horiz = chart.inverted ? !isXAxis : isXAxis;
// Flag, isXAxis
axis.isXAxis = isXAxis;
axis.coll = axis.coll || (isXAxis ? 'xAxis' : 'yAxis');
axis.opposite = userOptions.opposite; // needed in setOptions
axis.side = userOptions.side || (axis.horiz ?
(axis.opposite ? 0 : 2) : // top : bottom
(axis.opposite ? 1 : 3)); // right : left
axis.setOptions(userOptions);
var options = this.options,
type = options.type,
isDatetimeAxis = type === 'datetime';
axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format
// Flag, stagger lines or not
axis.userOptions = userOptions;
//axis.axisTitleMargin = undefined,// = options.title.margin,
axis.minPixelPadding = 0;
axis.reversed = options.reversed;
axis.visible = options.visible !== false;
axis.zoomEnabled = options.zoomEnabled !== false;
// Initial categories
axis.hasNames = type === 'category' || options.categories === true;
axis.categories = options.categories || axis.hasNames;
axis.names = axis.names || []; // Preserve on update (#3830)
// Elements
//axis.axisGroup = undefined;
//axis.gridGroup = undefined;
//axis.axisTitle = undefined;
//axis.axisLine = undefined;
// Shorthand types
axis.isLog = type === 'logarithmic';
axis.isDatetimeAxis = isDatetimeAxis;
// Flag, if axis is linked to another axis
axis.isLinked = defined(options.linkedTo);
// Linked axis.
//axis.linkedParent = undefined;
// Tick positions
//axis.tickPositions = undefined; // array containing predefined positions
// Tick intervals
//axis.tickInterval = undefined;
//axis.minorTickInterval = undefined;
// Major ticks
axis.ticks = {};
axis.labelEdge = [];
// Minor ticks
axis.minorTicks = {};
// List of plotLines/Bands
axis.plotLinesAndBands = [];
// Alternate bands
axis.alternateBands = {};
// Axis metrics
//axis.left = undefined;
//axis.top = undefined;
//axis.width = undefined;
//axis.height = undefined;
//axis.bottom = undefined;
//axis.right = undefined;
//axis.transA = undefined;
//axis.transB = undefined;
//axis.oldTransA = undefined;
axis.len = 0;
//axis.oldMin = undefined;
//axis.oldMax = undefined;
//axis.oldUserMin = undefined;
//axis.oldUserMax = undefined;
//axis.oldAxisLength = undefined;
axis.minRange = axis.userMinRange = options.minRange || options.maxZoom;
axis.range = options.range;
axis.offset = options.offset || 0;
// Dictionary for stacks
axis.stacks = {};
axis.oldStacks = {};
axis.stacksTouched = 0;
// Min and max in the data
//axis.dataMin = undefined,
//axis.dataMax = undefined,
// The axis range
axis.max = null;
axis.min = null;
// User set min and max
//axis.userMin = undefined,
//axis.userMax = undefined,
// Crosshair options
axis.crosshair = pick(options.crosshair, splat(chart.options.tooltip.crosshairs)[isXAxis ? 0 : 1], false);
// Run Axis
var eventType,
events = axis.options.events;
// Register
if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update()
if (isXAxis) { // #2713
chart.axes.splice(chart.xAxis.length, 0, axis);
} else {
chart.axes.push(axis);
}
chart[axis.coll].push(axis);
}
axis.series = axis.series || []; // populated by Series
// inverted charts have reversed xAxes as default
if (chart.inverted && isXAxis && axis.reversed === undefined) {
axis.reversed = true;
}
axis.removePlotBand = axis.removePlotBandOrLine;
axis.removePlotLine = axis.removePlotBandOrLine;
// register event listeners
for (eventType in events) {
addEvent(axis, eventType, events[eventType]);
}
// extend logarithmic axis
if (axis.isLog) {
axis.val2lin = axis.log2lin;
axis.lin2val = axis.lin2log;
}
},
/**
* Merge and set options
*/
setOptions: function(userOptions) {
this.options = merge(
this.defaultOptions,
this.coll === 'yAxis' && this.defaultYAxisOptions, [this.defaultTopAxisOptions, this.defaultRightAxisOptions,
this.defaultBottomAxisOptions, this.defaultLeftAxisOptions
][this.side],
merge(
defaultOptions[this.coll], // if set in setOptions (#1053)
userOptions
)
);
},
/**
* The default label formatter. The context is a special config object for the label.
*/
defaultLabelFormatter: function() {
var axis = this.axis,
value = this.value,
categories = axis.categories,
dateTimeLabelFormat = this.dateTimeLabelFormat,
numericSymbols = defaultOptions.lang.numericSymbols,
i = numericSymbols && numericSymbols.length,
multi,
ret,
formatOption = axis.options.labels.format,
// make sure the same symbol is added for all labels on a linear axis
numericSymbolDetector = axis.isLog ? value : axis.tickInterval;
if (formatOption) {
ret = format(formatOption, this);
} else if (categories) {
ret = value;
} else if (dateTimeLabelFormat) { // datetime axis
ret = H.dateFormat(dateTimeLabelFormat, value);
} else if (i && numericSymbolDetector >= 1000) {
// Decide whether we should add a numeric symbol like k (thousands) or M (millions).
// If we are to enable this in tooltip or other places as well, we can move this
// logic to the numberFormatter and enable it by a parameter.
while (i-- && ret === undefined) {
multi = Math.pow(1000, i + 1);
if (numericSymbolDetector >= multi && (value * 10) % multi === 0 && numericSymbols[i] !== null && value !== 0) { // #5480
ret = H.numberFormat(value / multi, -1) + numericSymbols[i];
}
}
}
if (ret === undefined) {
if (Math.abs(value) >= 10000) { // add thousands separators
ret = H.numberFormat(value, -1);
} else { // small numbers
ret = H.numberFormat(value, -1, undefined, ''); // #2466
}
}
return ret;
},
/**
* Get the minimum and maximum for the series of each axis
*/
getSeriesExtremes: function() {
var axis = this,
chart = axis.chart;
axis.hasVisibleSeries = false;
// Reset properties in case we're redrawing (#3353)
axis.dataMin = axis.dataMax = axis.threshold = null;
axis.softThreshold = !axis.isXAxis;
if (axis.buildStacks) {
axis.buildStacks();
}
// loop through this axis' series
each(axis.series, function(series) {
if (series.visible || !chart.options.chart.ignoreHiddenSeries) {
var seriesOptions = series.options,
xData,
threshold = seriesOptions.threshold,
seriesDataMin,
seriesDataMax;
axis.hasVisibleSeries = true;
// Validate threshold in logarithmic axes
if (axis.isLog && threshold <= 0) {
threshold = null;
}
// Get dataMin and dataMax for X axes
if (axis.isXAxis) {
xData = series.xData;
if (xData.length) {
// If xData contains values which is not numbers, then filter them out.
// To prevent performance hit, we only do this after we have already
// found seriesDataMin because in most cases all data is valid. #5234.
seriesDataMin = arrayMin(xData);
if (!isNumber(seriesDataMin) && !(seriesDataMin instanceof Date)) { // Date for #5010
xData = grep(xData, function(x) {
return isNumber(x);
});
seriesDataMin = arrayMin(xData); // Do it again with valid data
}
axis.dataMin = Math.min(pick(axis.dataMin, xData[0]), seriesDataMin);
axis.dataMax = Math.max(pick(axis.dataMax, xData[0]), arrayMax(xData));
}
// Get dataMin and dataMax for Y axes, as well as handle stacking and processed data
} else {
// Get this particular series extremes
series.getExtremes();
seriesDataMax = series.dataMax;
seriesDataMin = series.dataMin;
// Get the dataMin and dataMax so far. If percentage is used, the min and max are
// always 0 and 100. If seriesDataMin and seriesDataMax is null, then series
// doesn't have active y data, we continue with nulls
if (defined(seriesDataMin) && defined(seriesDataMax)) {
axis.dataMin = Math.min(pick(axis.dataMin, seriesDataMin), seriesDataMin);
axis.dataMax = Math.max(pick(axis.dataMax, seriesDataMax), seriesDataMax);
}
// Adjust to threshold
if (defined(threshold)) {
axis.threshold = threshold;
}
// If any series has a hard threshold, it takes precedence
if (!seriesOptions.softThreshold || axis.isLog) {
axis.softThreshold = false;
}
}
}
});
},
/**
* Translate from axis value to pixel position on the chart, or back
*
*/
translate: function(val, backwards, cvsCoord, old, handleLog, pointPlacement) {
var axis = this.linkedParent || this, // #1417
sign = 1,
cvsOffset = 0,
localA = old ? axis.oldTransA : axis.transA,
localMin = old ? axis.oldMin : axis.min,
returnValue,
minPixelPadding = axis.minPixelPadding,
doPostTranslate = (axis.isOrdinal || axis.isBroken || (axis.isLog && handleLog)) && axis.lin2val;
if (!localA) {
localA = axis.transA;
}
// In vertical axes, the canvas coordinates start from 0 at the top like in
// SVG.
if (cvsCoord) {
sign *= -1; // canvas coordinates inverts the value
cvsOffset = axis.len;
}
// Handle reversed axis
if (axis.reversed) {
sign *= -1;
cvsOffset -= sign * (axis.sector || axis.len);
}
// From pixels to value
if (backwards) { // reverse translation
val = val * sign + cvsOffset;
val -= minPixelPadding;
returnValue = val / localA + localMin; // from chart pixel to value
if (doPostTranslate) { // log and ordinal axes
returnValue = axis.lin2val(returnValue);
}
// From value to pixels
} else {
if (doPostTranslate) { // log and ordinal axes
val = axis.val2lin(val);
}
if (pointPlacement === 'between') {
pointPlacement = 0.5;
}
returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) +
(isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0);
}
return returnValue;
},
/**
* Utility method to translate an axis value to pixel position.
* @param {Number} value A value in terms of axis units
* @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart
* or just the axis/pane itself.
*/
toPixels: function(value, paneCoordinates) {
return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos);
},
/*
* Utility method to translate a pixel position in to an axis value
* @param {Number} pixel The pixel value coordinate
* @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the
* axis/pane itself.
*/
toValue: function(pixel, paneCoordinates) {
return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true);
},
/**
* Create the path for a plot line that goes from the given value on
* this axis, across the plot to the opposite side
* @param {Number} value
* @param {Number} lineWidth Used for calculation crisp line
* @param {Number] old Use old coordinates (for resizing and rescaling)
*/
getPlotLinePath: function(value, lineWidth, old, force, translatedValue) {
var axis = this,
chart = axis.chart,
axisLeft = axis.left,
axisTop = axis.top,
x1,
y1,
x2,
y2,
cHeight = (old && chart.oldChartHeight) || chart.chartHeight,
cWidth = (old && chart.oldChartWidth) || chart.chartWidth,
skip,
transB = axis.transB,
/**
* Check if x is between a and b. If not, either move to a/b or skip,
* depending on the force parameter.
*/
between = function(x, a, b) {
if (x < a || x > b) {
if (force) {
x = Math.min(Math.max(a, x), b);
} else {
skip = true;
}
}
return x;
};
translatedValue = pick(translatedValue, axis.translate(value, null, null, old));
x1 = x2 = Math.round(translatedValue + transB);
y1 = y2 = Math.round(cHeight - translatedValue - transB);
if (!isNumber(translatedValue)) { // no min or max
skip = true;
} else if (axis.horiz) {
y1 = axisTop;
y2 = cHeight - axis.bottom;
x1 = x2 = between(x1, axisLeft, axisLeft + axis.width);
} else {
x1 = axisLeft;
x2 = cWidth - axis.right;
y1 = y2 = between(y1, axisTop, axisTop + axis.height);
}
return skip && !force ?
null :
chart.renderer.crispLine(['M', x1, y1, 'L', x2, y2], lineWidth || 1);
},
/**
* Set the tick positions of a linear axis to round values like whole tens or every five.
*/
getLinearTickPositions: function(tickInterval, min, max) {
var pos,
lastPos,
roundedMin = correctFloat(Math.floor(min / tickInterval) * tickInterval),
roundedMax = correctFloat(Math.ceil(max / tickInterval) * tickInterval),
tickPositions = [];
// For single points, add a tick regardless of the relative position (#2662)
if (min === max && isNumber(min)) {
return [min];
}
// Populate the intermediate values
pos = roundedMin;
while (pos <= roundedMax) {
// Place the tick on the rounded value
tickPositions.push(pos);
// Always add the raw tickInterval, not the corrected one.
pos = correctFloat(pos + tickInterval);
// If the interval is not big enough in the current min - max range to actually increase
// the loop variable, we need to break out to prevent endless loop. Issue #619
if (pos === lastPos) {
break;
}
// Record the last value
lastPos = pos;
}
return tickPositions;
},
/**
* Return the minor tick positions. For logarithmic axes, reuse the same logic
* as for major ticks.
*/
getMinorTickPositions: function() {
var axis = this,
options = axis.options,
tickPositions = axis.tickPositions,
minorTickInterval = axis.minorTickInterval,
minorTickPositions = [],
pos,
i,
pointRangePadding = axis.pointRangePadding || 0,
min = axis.min - pointRangePadding, // #1498
max = axis.max + pointRangePadding, // #1498
range = max - min,
len;
// If minor ticks get too dense, they are hard to read, and may cause long running script. So we don't draw them.
if (range && range / minorTickInterval < axis.len / 3) { // #3875
if (axis.isLog) {
len = tickPositions.length;
for (i = 1; i < len; i++) {
minorTickPositions = minorTickPositions.concat(
axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true)
);
}
} else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314
minorTickPositions = minorTickPositions.concat(
axis.getTimeTicks(
axis.normalizeTimeTickInterval(minorTickInterval),
min,
max,
options.startOfWeek
)
);
} else {
for (pos = min + (tickPositions[0] - min) % minorTickInterval; pos <= max; pos += minorTickInterval) {
minorTickPositions.push(pos);
}
}
}
if (minorTickPositions.length !== 0) { // don't change the extremes, when there is no minor ticks
axis.trimTicks(minorTickPositions, options.startOnTick, options.endOnTick); // #3652 #3743 #1498
}
return minorTickPositions;
},
/**
* Adjust the min and max for the minimum range. Keep in mind that the series data is
* not yet processed, so we don't have information on data cropping and grouping, or
* updated axis.pointRange or series.pointRange. The data can't be processed until
* we have finally established min and max.
*/
adjustForMinRange: function() {
var axis = this,
options = axis.options,
min = axis.min,
max = axis.max,
zoomOffset,
spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange,
closestDataRange,
i,
distance,
xData,
loopLength,
minArgs,
maxArgs,
minRange;
// Set the automatic minimum range based on the closest point distance
if (axis.isXAxis && axis.minRange === undefined && !axis.isLog) {
if (defined(options.min) || defined(options.max)) {
axis.minRange = null; // don't do this again
} else {
// Find the closest distance between raw data points, as opposed to
// closestPointRange that applies to processed points (cropped and grouped)
each(axis.series, function(series) {
xData = series.xData;
loopLength = series.xIncrement ? 1 : xData.length - 1;
for (i = loopLength; i > 0; i--) {
distance = xData[i] - xData[i - 1];
if (closestDataRange === undefined || distance < closestDataRange) {
closestDataRange = distance;
}
}
});
axis.minRange = Math.min(closestDataRange * 5, axis.dataMax - axis.dataMin);
}
}
// if minRange is exceeded, adjust
if (max - min < axis.minRange) {
minRange = axis.minRange;
zoomOffset = (minRange - max + min) / 2;
// if min and max options have been set, don't go beyond it
minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)];
if (spaceAvailable) { // if space is available, stay within the data range
minArgs[2] = axis.isLog ? axis.log2lin(axis.dataMin) : axis.dataMin;
}
min = arrayMax(minArgs);
maxArgs = [min + minRange, pick(options.max, min + minRange)];
if (spaceAvailable) { // if space is availabe, stay within the data range
maxArgs[2] = axis.isLog ? axis.log2lin(axis.dataMax) : axis.dataMax;
}
max = arrayMin(maxArgs);
// now if the max is adjusted, adjust the min back
if (max - min < minRange) {
minArgs[0] = max - minRange;
minArgs[1] = pick(options.min, max - minRange);
min = arrayMax(minArgs);
}
}
// Record modified extremes
axis.min = min;
axis.max = max;
},
/**
* Find the closestPointRange across all series
*/
getClosest: function() {
var ret;
if (this.categories) {
ret = 1;
} else {
each(this.series, function(series) {
var seriesClosest = series.closestPointRange;
if (!series.noSharedTooltip && defined(seriesClosest)) {
ret = defined(ret) ?
Math.min(ret, seriesClosest) :
seriesClosest;
}
});
}
return ret;
},
/**
* When a point name is given and no x, search for the name in the existing categories,
* or if categories aren't provided, search names or create a new category (#2522).
*/
nameToX: function(point) {
var explicitCategories = isArray(this.categories),
names = explicitCategories ? this.categories : this.names,
nameX = point.options.x,
x;
point.series.requireSorting = false;
if (!defined(nameX)) {
nameX = this.options.uniqueNames === false ?
point.series.autoIncrement() :
inArray(point.name, names);
}
if (nameX === -1) { // The name is not found in currenct categories
if (!explicitCategories) {
x = names.length;
}
} else {
x = nameX;
}
// Write the last point's name to the names array
this.names[x] = point.name;
return x;
},
/**
* When changes have been done to series data, update the axis.names.
*/
updateNames: function() {
var axis = this;
if (this.names.length > 0) {
this.names.length = 0;
this.minRange = undefined;
each(this.series || [], function(series) {
// When adding a series, points are not yet generated
if (!series.points || series.isDirtyData) {
series.processData();
series.generatePoints();
}
each(series.points, function(point, i) {
var x;
if (point.options && point.options.x === undefined) {
x = axis.nameToX(point);
if (x !== point.x) {
point.x = x;
series.xData[i] = x;
}
}
});
});
}
},
/**
* Update translation information
*/
setAxisTranslation: function(saveOld) {
var axis = this,
range = axis.max - axis.min,
pointRange = axis.axisPointRange || 0,
closestPointRange,
minPointOffset = 0,
pointRangePadding = 0,
linkedParent = axis.linkedParent,
ordinalCorrection,
hasCategories = !!axis.categories,
transA = axis.transA,
isXAxis = axis.isXAxis;
// Adjust translation for padding. Y axis with categories need to go through the same (#1784).
if (isXAxis || hasCategories || pointRange) {
if (linkedParent) {
minPointOffset = linkedParent.minPointOffset;
pointRangePadding = linkedParent.pointRangePadding;
} else {
// Get the closest points
closestPointRange = axis.getClosest();
each(axis.series, function(series) {
var seriesPointRange = hasCategories ?
1 :
(isXAxis ?
pick(series.options.pointRange, closestPointRange, 0) :
(axis.axisPointRange || 0)), // #2806
pointPlacement = series.options.pointPlacement;
pointRange = Math.max(pointRange, seriesPointRange);
if (!axis.single) {
// minPointOffset is the value padding to the left of the axis in order to make
// room for points with a pointRange, typically columns. When the pointPlacement option
// is 'between' or 'on', this padding does not apply.
minPointOffset = Math.max(
minPointOffset,
isString(pointPlacement) ? 0 : seriesPointRange / 2
);
// Determine the total padding needed to the length of the axis to make room for the
// pointRange. If the series' pointPlacement is 'on', no padding is added.
pointRangePadding = Math.max(
pointRangePadding,
pointPlacement === 'on' ? 0 : seriesPointRange
);
}
});
}
// Record minPointOffset and pointRangePadding
ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853
axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection;
axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection;
// pointRange means the width reserved for each point, like in a column chart
axis.pointRange = Math.min(pointRange, range);
// closestPointRange means the closest distance between points. In columns
// it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange
// is some other value
if (isXAxis) {
axis.closestPointRange = closestPointRange;
}
}
// Secondary values
if (saveOld) {
axis.oldTransA = transA;
}
axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1);
axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend
axis.minPixelPadding = transA * minPointOffset;
},
minFromRange: function() {
return this.max - this.range;
},
/**
* Set the tick positions to round values and optionally extend the extremes
* to the nearest tick
*/
setTickInterval: function(secondPass) {
var axis = this,
chart = axis.chart,
options = axis.options,
isLog = axis.isLog,
log2lin = axis.log2lin,
isDatetimeAxis = axis.isDatetimeAxis,
isXAxis = axis.isXAxis,
isLinked = axis.isLinked,
maxPadding = options.maxPadding,
minPadding = options.minPadding,
length,
linkedParentExtremes,
tickIntervalOption = options.tickInterval,
minTickInterval,
tickPixelIntervalOption = options.tickPixelInterval,
categories = axis.categories,
threshold = axis.threshold,
softThreshold = axis.softThreshold,
thresholdMin,
thresholdMax,
hardMin,
hardMax;
if (!isDatetimeAxis && !categories && !isLinked) {
this.getTickAmount();
}
// Min or max set either by zooming/setExtremes or initial options
hardMin = pick(axis.userMin, options.min);
hardMax = pick(axis.userMax, options.max);
// Linked axis gets the extremes from the parent axis
if (isLinked) {
axis.linkedParent = chart[axis.coll][options.linkedTo];
linkedParentExtremes = axis.linkedParent.getExtremes();
axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin);
axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax);
if (options.type !== axis.linkedParent.options.type) {
error(11, 1); // Can't link axes of different type
}
// Initial min and max from the extreme data values
} else {
// Adjust to hard threshold
if (!softThreshold && defined(threshold)) {
if (axis.dataMin >= threshold) {
thresholdMin = threshold;
minPadding = 0;
} else if (axis.dataMax <= threshold) {
thresholdMax = threshold;
maxPadding = 0;
}
}
axis.min = pick(hardMin, thresholdMin, axis.dataMin);
axis.max = pick(hardMax, thresholdMax, axis.dataMax);
}
if (isLog) {
if (!secondPass && Math.min(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978
error(10, 1); // Can't plot negative values on log axis
}
// The correctFloat cures #934, float errors on full tens. But it
// was too aggressive for #4360 because of conversion back to lin,
// therefore use precision 15.
axis.min = correctFloat(log2lin(axis.min), 15);
axis.max = correctFloat(log2lin(axis.max), 15);
}
// handle zoomed range
if (axis.range && defined(axis.max)) {
axis.userMin = axis.min = hardMin = Math.max(axis.min, axis.minFromRange()); // #618
axis.userMax = hardMax = axis.max;
axis.range = null; // don't use it when running setExtremes
}
// Hook for Highstock Scroller. Consider combining with beforePadding.
fireEvent(axis, 'foundExtremes');
// Hook for adjusting this.min and this.max. Used by bubble series.
if (axis.beforePadding) {
axis.beforePadding();
}
// adjust min and max for the minimum range
axis.adjustForMinRange();
// Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding
// into account, we do this after computing tick interval (#1337).
if (!categories && !axis.axisPointRange && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) {
length = axis.max - axis.min;
if (length) {
if (!defined(hardMin) && minPadding) {
axis.min -= length * minPadding;
}
if (!defined(hardMax) && maxPadding) {
axis.max += length * maxPadding;
}
}
}
// Handle options for floor, ceiling, softMin and softMax
if (isNumber(options.floor)) {
axis.min = Math.max(axis.min, options.floor);
} else if (isNumber(options.softMin)) {
axis.min = Math.min(axis.min, options.softMin);
}
if (isNumber(options.ceiling)) {
axis.max = Math.min(axis.max, options.ceiling);
} else if (isNumber(options.softMax)) {
axis.max = Math.max(axis.max, options.softMax);
}
// When the threshold is soft, adjust the extreme value only if
// the data extreme and the padded extreme land on either side of the threshold. For example,
// a series of [0, 1, 2, 3] would make the yAxis add a tick for -1 because of the
// default minPadding and startOnTick options. This is prevented by the softThreshold
// option.
if (softThreshold && defined(axis.dataMin)) {
threshold = threshold || 0;
if (!defined(hardMin) && axis.min < threshold && axis.dataMin >= threshold) {
axis.min = threshold;
} else if (!defined(hardMax) && axis.max > threshold && axis.dataMax <= threshold) {
axis.max = threshold;
}
}
// get tickInterval
if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) {
axis.tickInterval = 1;
} else if (isLinked && !tickIntervalOption &&
tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) {
axis.tickInterval = tickIntervalOption = axis.linkedParent.tickInterval;
} else {
axis.tickInterval = pick(
tickIntervalOption,
this.tickAmount ? ((axis.max - axis.min) / Math.max(this.tickAmount - 1, 1)) : undefined,
categories ? // for categoried axis, 1 is default, for linear axis use tickPix
1 :
// don't let it be more than the data range
(axis.max - axis.min) * tickPixelIntervalOption / Math.max(axis.len, tickPixelIntervalOption)
);
}
// Now we're finished detecting min and max, crop and group series data. This
// is in turn needed in order to find tick positions in ordinal axes.
if (isXAxis && !secondPass) {
each(axis.series, function(series) {
series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax);
});
}
// set the translation factor used in translate function
axis.setAxisTranslation(true);
// hook for ordinal axes and radial axes
if (axis.beforeSetTickPositions) {
axis.beforeSetTickPositions();
}
// hook for extensions, used in Highstock ordinal axes
if (axis.postProcessTickInterval) {
axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval);
}
// In column-like charts, don't cramp in more ticks than there are points (#1943, #4184)
if (axis.pointRange && !tickIntervalOption) {
axis.tickInterval = Math.max(axis.pointRange, axis.tickInterval);
}
// Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined.
minTickInterval = pick(options.minTickInterval, axis.isDatetimeAxis && axis.closestPointRange);
if (!tickIntervalOption && axis.tickInterval < minTickInterval) {
axis.tickInterval = minTickInterval;
}
// for linear axes, get magnitude and normalize the interval
if (!isDatetimeAxis && !isLog && !tickIntervalOption) {
axis.tickInterval = normalizeTickInterval(
axis.tickInterval,
null,
getMagnitude(axis.tickInterval),
// If the tick interval is between 0.5 and 5 and the axis max is in the order of
// thousands, chances are we are dealing with years. Don't allow decimals. #3363.
pick(options.allowDecimals, !(axis.tickInterval > 0.5 && axis.tickInterval < 5 && axis.max > 1000 && axis.max < 9999)), !!this.tickAmount
);
}
// Prevent ticks from getting so close that we can't draw the labels
if (!this.tickAmount) {
axis.tickInterval = axis.unsquish();
}
this.setTickPositions();
},
/**
* Now we have computed the normalized tickInterval, get the tick positions
*/
setTickPositions: function() {
var options = this.options,
tickPositions,
tickPositionsOption = options.tickPositions,
tickPositioner = options.tickPositioner,
startOnTick = options.startOnTick,
endOnTick = options.endOnTick,
single;
// Set the tickmarkOffset
this.tickmarkOffset = (this.categories && options.tickmarkPlacement === 'between' &&
this.tickInterval === 1) ? 0.5 : 0; // #3202
// get minorTickInterval
this.minorTickInterval = options.minorTickInterval === 'auto' && this.tickInterval ?
this.tickInterval / 5 : options.minorTickInterval;
// Find the tick positions
this.tickPositions = tickPositions = tickPositionsOption && tickPositionsOption.slice(); // Work on a copy (#1565)
if (!tickPositions) {
if (this.isDatetimeAxis) {
tickPositions = this.getTimeTicks(
this.normalizeTimeTickInterval(this.tickInterval, options.units),
this.min,
this.max,
options.startOfWeek,
this.ordinalPositions,
this.closestPointRange,
true
);
} else if (this.isLog) {
tickPositions = this.getLogTickPositions(this.tickInterval, this.min, this.max);
} else {
tickPositions = this.getLinearTickPositions(this.tickInterval, this.min, this.max);
}
// Too dense ticks, keep only the first and last (#4477)
if (tickPositions.length > this.len) {
tickPositions = [tickPositions[0], tickPositions.pop()];
}
this.tickPositions = tickPositions;
// Run the tick positioner callback, that allows modifying auto tick positions.
if (tickPositioner) {
tickPositioner = tickPositioner.apply(this, [this.min, this.max]);
if (tickPositioner) {
this.tickPositions = tickPositions = tickPositioner;
}
}
}
if (!this.isLinked) {
// reset min/max or remove extremes based on start/end on tick
this.trimTicks(tickPositions, startOnTick, endOnTick);
// When there is only one point, or all points have the same value on this axis, then min
// and max are equal and tickPositions.length is 0 or 1. In this case, add some padding
// in order to center the point, but leave it with one tick. #1337.
if (this.min === this.max && defined(this.min) && !this.tickAmount) {
// Substract half a unit (#2619, #2846, #2515, #3390)
single = true;
this.min -= 0.5;
this.max += 0.5;
}
this.single = single;
if (!tickPositionsOption && !tickPositioner) {
this.adjustTickAmount();
}
}
},
/**
* Handle startOnTick and endOnTick by either adapting to padding min/max or rounded min/max
*/
trimTicks: function(tickPositions, startOnTick, endOnTick) {
var roundedMin = tickPositions[0],
roundedMax = tickPositions[tickPositions.length - 1],
minPointOffset = this.minPointOffset || 0;
if (startOnTick) {
this.min = roundedMin;
} else {
while (this.min - minPointOffset > tickPositions[0]) {
tickPositions.shift();
}
}
if (endOnTick) {
this.max = roundedMax;
} else {
while (this.max + minPointOffset < tickPositions[tickPositions.length - 1]) {
tickPositions.pop();
}
}
// If no tick are left, set one tick in the middle (#3195)
if (tickPositions.length === 0 && defined(roundedMin)) {
tickPositions.push((roundedMax + roundedMin) / 2);
}
},
/**
* Check if there are multiple axes in the same pane
* @returns {Boolean} There are other axes
*/
alignToOthers: function() {
var others = {}, // Whether there is another axis to pair with this one
hasOther,
options = this.options;
if (this.chart.options.chart.alignTicks !== false && options.alignTicks !== false) {
each(this.chart[this.coll], function(axis) {
var otherOptions = axis.options,
horiz = axis.horiz,
key = [
horiz ? otherOptions.left : otherOptions.top,
otherOptions.width,
otherOptions.height,
otherOptions.pane
].join(',');
if (axis.series.length) { // #4442
if (others[key]) {
hasOther = true; // #4201
} else {
others[key] = 1;
}
}
});
}
return hasOther;
},
/**
* Set the max ticks of either the x and y axis collection
*/
getTickAmount: function() {
var options = this.options,
tickAmount = options.tickAmount,
tickPixelInterval = options.tickPixelInterval;
if (!defined(options.tickInterval) && this.len < tickPixelInterval && !this.isRadial &&
!this.isLog && options.startOnTick && options.endOnTick) {
tickAmount = 2;
}
if (!tickAmount && this.alignToOthers()) {
// Add 1 because 4 tick intervals require 5 ticks (including first and last)
tickAmount = Math.ceil(this.len / tickPixelInterval) + 1;
}
// For tick amounts of 2 and 3, compute five ticks and remove the intermediate ones. This
// prevents the axis from adding ticks that are too far away from the data extremes.
if (tickAmount < 4) {
this.finalTickAmt = tickAmount;
tickAmount = 5;
}
this.tickAmount = tickAmount;
},
/**
* When using multiple axes, adjust the number of ticks to match the highest
* number of ticks in that group
*/
adjustTickAmount: function() {
var tickInterval = this.tickInterval,
tickPositions = this.tickPositions,
tickAmount = this.tickAmount,
finalTickAmt = this.finalTickAmt,
currentTickAmount = tickPositions && tickPositions.length,
i,
len;
if (currentTickAmount < tickAmount) {
while (tickPositions.length < tickAmount) {
tickPositions.push(correctFloat(
tickPositions[tickPositions.length - 1] + tickInterval
));
}
this.transA *= (currentTickAmount - 1) / (tickAmount - 1);
this.max = tickPositions[tickPositions.length - 1];
// We have too many ticks, run second pass to try to reduce ticks
} else if (currentTickAmount > tickAmount) {
this.tickInterval *= 2;
this.setTickPositions();
}
// The finalTickAmt property is set in getTickAmount
if (defined(finalTickAmt)) {
i = len = tickPositions.length;
while (i--) {
if (
(finalTickAmt === 3 && i % 2 === 1) || // Remove every other tick
(finalTickAmt <= 2 && i > 0 && i < len - 1) // Remove all but first and last
) {
tickPositions.splice(i, 1);
}
}
this.finalTickAmt = undefined;
}
},
/**
* Set the scale based on data min and max, user set min and max or options
*
*/
setScale: function() {
var axis = this,
isDirtyData,
isDirtyAxisLength;
axis.oldMin = axis.min;
axis.oldMax = axis.max;
axis.oldAxisLength = axis.len;
// set the new axisLength
axis.setAxisSize();
//axisLength = horiz ? axisWidth : axisHeight;
isDirtyAxisLength = axis.len !== axis.oldAxisLength;
// is there new data?
each(axis.series, function(series) {
if (series.isDirtyData || series.isDirty ||
series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well
isDirtyData = true;
}
});
// do we really need to go through all this?
if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw ||
axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax || axis.alignToOthers()) {
if (axis.resetStacks) {
axis.resetStacks();
}
axis.forceRedraw = false;
// get data extremes if needed
axis.getSeriesExtremes();
// get fixed positions based on tickInterval
axis.setTickInterval();
// record old values to decide whether a rescale is necessary later on (#540)
axis.oldUserMin = axis.userMin;
axis.oldUserMax = axis.userMax;
// Mark as dirty if it is not already set to dirty and extremes have changed. #595.
if (!axis.isDirty) {
axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax;
}
} else if (axis.cleanStacks) {
axis.cleanStacks();
}
},
/**
* Set the extremes and optionally redraw
* @param {Number} newMin
* @param {Number} newMax
* @param {Boolean} redraw
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
* @param {Object} eventArguments
*
*/
setExtremes: function(newMin, newMax, redraw, animation, eventArguments) {
var axis = this,
chart = axis.chart;
redraw = pick(redraw, true); // defaults to true
each(axis.series, function(serie) {
delete serie.kdTree;
});
// Extend the arguments with min and max
eventArguments = extend(eventArguments, {
min: newMin,
max: newMax
});
// Fire the event
fireEvent(axis, 'setExtremes', eventArguments, function() { // the default event handler
axis.userMin = newMin;
axis.userMax = newMax;
axis.eventArgs = eventArguments;
if (redraw) {
chart.redraw(animation);
}
});
},
/**
* Overridable method for zooming chart. Pulled out in a separate method to allow overriding
* in stock charts.
*/
zoom: function(newMin, newMax) {
var dataMin = this.dataMin,
dataMax = this.dataMax,
options = this.options,
min = Math.min(dataMin, pick(options.min, dataMin)),
max = Math.max(dataMax, pick(options.max, dataMax));
if (newMin !== this.min || newMax !== this.max) { // #5790
// Prevent pinch zooming out of range. Check for defined is for #1946. #1734.
if (!this.allowZoomOutside) {
if (defined(dataMin) && newMin <= min) {
newMin = min;
}
if (defined(dataMax) && newMax >= max) {
newMax = max;
}
}
// In full view, displaying the reset zoom button is not required
this.displayBtn = newMin !== undefined || newMax !== undefined;
// Do it
this.setExtremes(
newMin,
newMax,
false,
undefined, {
trigger: 'zoom'
}
);
}
return true;
},
/**
* Update the axis metrics
*/
setAxisSize: function() {
var chart = this.chart,
options = this.options,
offsetLeft = options.offsetLeft || 0,
offsetRight = options.offsetRight || 0,
horiz = this.horiz,
width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight),
height = pick(options.height, chart.plotHeight),
top = pick(options.top, chart.plotTop),
left = pick(options.left, chart.plotLeft + offsetLeft),
percentRegex = /%$/;
// Check for percentage based input values. Rounding fixes problems with
// column overflow and plot line filtering (#4898, #4899)
if (percentRegex.test(height)) {
height = Math.round(parseFloat(height) / 100 * chart.plotHeight);
}
if (percentRegex.test(top)) {
top = Math.round(parseFloat(top) / 100 * chart.plotHeight + chart.plotTop);
}
// Expose basic values to use in Series object and navigator
this.left = left;
this.top = top;
this.width = width;
this.height = height;
this.bottom = chart.chartHeight - height - top;
this.right = chart.chartWidth - width - left;
// Direction agnostic properties
this.len = Math.max(horiz ? width : height, 0); // Math.max fixes #905
this.pos = horiz ? left : top; // distance from SVG origin
},
/**
* Get the actual axis extremes
*/
getExtremes: function() {
var axis = this,
isLog = axis.isLog,
lin2log = axis.lin2log;
return {
min: isLog ? correctFloat(lin2log(axis.min)) : axis.min,
max: isLog ? correctFloat(lin2log(axis.max)) : axis.max,
dataMin: axis.dataMin,
dataMax: axis.dataMax,
userMin: axis.userMin,
userMax: axis.userMax
};
},
/**
* Get the zero plane either based on zero or on the min or max value.
* Used in bar and area plots
*/
getThreshold: function(threshold) {
var axis = this,
isLog = axis.isLog,
lin2log = axis.lin2log,
realMin = isLog ? lin2log(axis.min) : axis.min,
realMax = isLog ? lin2log(axis.max) : axis.max;
if (threshold === null) {
threshold = realMin;
} else if (realMin > threshold) {
threshold = realMin;
} else if (realMax < threshold) {
threshold = realMax;
}
return axis.translate(threshold, 0, 1, 0, 1);
},
/**
* Compute auto alignment for the axis label based on which side the axis is on
* and the given rotation for the label
*/
autoLabelAlign: function(rotation) {
var ret,
angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360;
if (angle > 15 && angle < 165) {
ret = 'right';
} else if (angle > 195 && angle < 345) {
ret = 'left';
} else {
ret = 'center';
}
return ret;
},
/**
* Get the tick length and width for the axis.
* @param {String} prefix 'tick' or 'minorTick'
* @returns {Array} An array of tickLength and tickWidth
*/
tickSize: function(prefix) {
var options = this.options,
tickLength = options[prefix + 'Length'],
tickWidth = pick(options[prefix + 'Width'], prefix === 'tick' && this.isXAxis ? 1 : 0); // X axis defaults to 1
if (tickWidth && tickLength) {
// Negate the length
if (options[prefix + 'Position'] === 'inside') {
tickLength = -tickLength;
}
return [tickLength, tickWidth];
}
},
/**
* Return the size of the labels
*/
labelMetrics: function() {
return this.chart.renderer.fontMetrics(
this.options.labels.style && this.options.labels.style.fontSize,
this.ticks[0] && this.ticks[0].label
);
},
/**
* Prevent the ticks from getting so close we can't draw the labels. On a horizontal
* axis, this is handled by rotating the labels, removing ticks and adding ellipsis.
* On a vertical axis remove ticks and add ellipsis.
*/
unsquish: function() {
var labelOptions = this.options.labels,
horiz = this.horiz,
tickInterval = this.tickInterval,
newTickInterval = tickInterval,
slotSize = this.len / (((this.categories ? 1 : 0) + this.max - this.min) / tickInterval),
rotation,
rotationOption = labelOptions.rotation,
labelMetrics = this.labelMetrics(),
step,
bestScore = Number.MAX_VALUE,
autoRotation,
// Return the multiple of tickInterval that is needed to avoid collision
getStep = function(spaceNeeded) {
var step = spaceNeeded / (slotSize || 1);
step = step > 1 ? Math.ceil(step) : 1;
return step * tickInterval;
};
if (horiz) {
autoRotation = !labelOptions.staggerLines && !labelOptions.step && ( // #3971
defined(rotationOption) ? [rotationOption] :
slotSize < pick(labelOptions.autoRotationLimit, 80) && labelOptions.autoRotation
);
if (autoRotation) {
// Loop over the given autoRotation options, and determine which gives the best score. The
// best score is that with the lowest number of steps and a rotation closest to horizontal.
each(autoRotation, function(rot) {
var score;
if (rot === rotationOption || (rot && rot >= -90 && rot <= 90)) { // #3891
step = getStep(Math.abs(labelMetrics.h / Math.sin(deg2rad * rot)));
score = step + Math.abs(rot / 360);
if (score < bestScore) {
bestScore = score;
rotation = rot;
newTickInterval = step;
}
}
});
}
} else if (!labelOptions.step) { // #4411
newTickInterval = getStep(labelMetrics.h);
}
this.autoRotation = autoRotation;
this.labelRotation = pick(rotation, rotationOption);
return newTickInterval;
},
/**
* Get the general slot width for this axis. This may change between the pre-render (from Axis.getOffset)
* and the final tick rendering and placement (#5086).
*/
getSlotWidth: function() {
var chart = this.chart,
horiz = this.horiz,
labelOptions = this.options.labels,
slotCount = Math.max(this.tickPositions.length - (this.categories ? 0 : 1), 1),
marginLeft = chart.margin[3];
return (horiz && (labelOptions.step || 0) < 2 && !labelOptions.rotation && // #4415
((this.staggerLines || 1) * chart.plotWidth) / slotCount) ||
(!horiz && ((marginLeft && (marginLeft - chart.spacing[3])) || chart.chartWidth * 0.33)); // #1580, #1931
},
/**
* Render the axis labels and determine whether ellipsis or rotation need to be applied
*/
renderUnsquish: function() {
var chart = this.chart,
renderer = chart.renderer,
tickPositions = this.tickPositions,
ticks = this.ticks,
labelOptions = this.options.labels,
horiz = this.horiz,
slotWidth = this.getSlotWidth(),
innerWidth = Math.max(1, Math.round(slotWidth - 2 * (labelOptions.padding || 5))),
attr = {},
labelMetrics = this.labelMetrics(),
textOverflowOption = labelOptions.style && labelOptions.style.textOverflow,
css,
maxLabelLength = 0,
label,
i,
pos;
// Set rotation option unless it is "auto", like in gauges
if (!isString(labelOptions.rotation)) {
attr.rotation = labelOptions.rotation || 0; // #4443
}
// Get the longest label length
each(tickPositions, function(tick) {
tick = ticks[tick];
if (tick && tick.labelLength > maxLabelLength) {
maxLabelLength = tick.labelLength;
}
});
this.maxLabelLength = maxLabelLength;
// Handle auto rotation on horizontal axis
if (this.autoRotation) {
// Apply rotation only if the label is too wide for the slot, and
// the label is wider than its height.
if (maxLabelLength > innerWidth && maxLabelLength > labelMetrics.h) {
attr.rotation = this.labelRotation;
} else {
this.labelRotation = 0;
}
// Handle word-wrap or ellipsis on vertical axis
} else if (slotWidth) {
// For word-wrap or ellipsis
css = {
width: innerWidth + 'px'
};
if (!textOverflowOption) {
css.textOverflow = 'clip';
// On vertical axis, only allow word wrap if there is room for more lines.
i = tickPositions.length;
while (!horiz && i--) {
pos = tickPositions[i];
label = ticks[pos].label;
if (label) {
// Reset ellipsis in order to get the correct bounding box (#4070)
if (label.styles && label.styles.textOverflow === 'ellipsis') {
label.css({
textOverflow: 'clip'
});
// Set the correct width in order to read the bounding box height (#4678, #5034)
} else if (ticks[pos].labelLength > slotWidth) {
label.css({
width: slotWidth + 'px'
});
}
if (label.getBBox().height > this.len / tickPositions.length - (labelMetrics.h - labelMetrics.f)) {
label.specCss = {
textOverflow: 'ellipsis'
};
}
}
}
}
}
// Add ellipsis if the label length is significantly longer than ideal
if (attr.rotation) {
css = {
width: (maxLabelLength > chart.chartHeight * 0.5 ? chart.chartHeight * 0.33 : chart.chartHeight) + 'px'
};
if (!textOverflowOption) {
css.textOverflow = 'ellipsis';
}
}
// Set the explicit or automatic label alignment
this.labelAlign = labelOptions.align || this.autoLabelAlign(this.labelRotation);
if (this.labelAlign) {
attr.align = this.labelAlign;
}
// Apply general and specific CSS
each(tickPositions, function(pos) {
var tick = ticks[pos],
label = tick && tick.label;
if (label) {
label.attr(attr); // This needs to go before the CSS in old IE (#4502)
if (css) {
label.css(merge(css, label.specCss));
}
delete label.specCss;
tick.rotation = attr.rotation;
}
});
// Note: Why is this not part of getLabelPosition?
this.tickRotCorr = renderer.rotCorr(labelMetrics.b, this.labelRotation || 0, this.side !== 0);
},
/**
* Return true if the axis has associated data
*/
hasData: function() {
return this.hasVisibleSeries || (defined(this.min) && defined(this.max) && !!this.tickPositions);
},
/**
* Render the tick labels to a preliminary position to get their sizes
*/
getOffset: function() {
var axis = this,
chart = axis.chart,
renderer = chart.renderer,
options = axis.options,
tickPositions = axis.tickPositions,
ticks = axis.ticks,
horiz = axis.horiz,
side = axis.side,
invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side,
hasData,
showAxis,
titleOffset = 0,
titleOffsetOption,
titleMargin = 0,
axisTitleOptions = options.title,
labelOptions = options.labels,
labelOffset = 0, // reset
labelOffsetPadded,
opposite = axis.opposite,
axisOffset = chart.axisOffset,
clipOffset = chart.clipOffset,
clip,
directionFactor = [-1, 1, 1, -1][side],
n,
className = options.className,
textAlign,
axisParent = axis.axisParent, // Used in color axis
lineHeightCorrection,
tickSize = this.tickSize('tick');
// For reuse in Axis.render
hasData = axis.hasData();
axis.showAxis = showAxis = hasData || pick(options.showEmpty, true);
// Set/reset staggerLines
axis.staggerLines = axis.horiz && labelOptions.staggerLines;
// Create the axisGroup and gridGroup elements on first iteration
if (!axis.axisGroup) {
axis.gridGroup = renderer.g('grid')
.attr({
zIndex: options.gridZIndex || 1
})
.addClass('highcharts-' + this.coll.toLowerCase() + '-grid ' + (className || ''))
.add(axisParent);
axis.axisGroup = renderer.g('axis')
.attr({
zIndex: options.zIndex || 2
})
.addClass('highcharts-' + this.coll.toLowerCase() + ' ' + (className || ''))
.add(axisParent);
axis.labelGroup = renderer.g('axis-labels')
.attr({
zIndex: labelOptions.zIndex || 7
})
.addClass('highcharts-' + axis.coll.toLowerCase() + '-labels ' + (className || ''))
.add(axisParent);
}
if (hasData || axis.isLinked) {
// Generate ticks
each(tickPositions, function(pos) {
if (!ticks[pos]) {
ticks[pos] = new Tick(axis, pos);
} else {
ticks[pos].addLabel(); // update labels depending on tick interval
}
});
axis.renderUnsquish();
// Left side must be align: right and right side must have align: left for labels
if (labelOptions.reserveSpace !== false && (side === 0 || side === 2 || {
1: 'left',
3: 'right'
}[side] === axis.labelAlign || axis.labelAlign === 'center')) {
each(tickPositions, function(pos) {
// get the highest offset
labelOffset = Math.max(
ticks[pos].getLabelSize(),
labelOffset
);
});
}
if (axis.staggerLines) {
labelOffset *= axis.staggerLines;
axis.labelOffset = labelOffset * (axis.opposite ? -1 : 1);
}
} else { // doesn't have data
for (n in ticks) {
ticks[n].destroy();
delete ticks[n];
}
}
if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) {
if (!axis.axisTitle) {
textAlign = axisTitleOptions.textAlign;
if (!textAlign) {
textAlign = (horiz ? {
low: 'left',
middle: 'center',
high: 'right'
} : {
low: opposite ? 'right' : 'left',
middle: 'center',
high: opposite ? 'left' : 'right'
})[axisTitleOptions.align];
}
axis.axisTitle = renderer.text(
axisTitleOptions.text,
0,
0,
axisTitleOptions.useHTML
)
.attr({
zIndex: 7,
rotation: axisTitleOptions.rotation || 0,
align: textAlign
})
.addClass('highcharts-axis-title')
.add(axis.axisGroup);
axis.axisTitle.isNew = true;
}
if (showAxis) {
titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width'];
titleOffsetOption = axisTitleOptions.offset;
titleMargin = defined(titleOffsetOption) ? 0 : pick(axisTitleOptions.margin, horiz ? 5 : 10);
}
// hide or show the title depending on whether showEmpty is set
axis.axisTitle[showAxis ? 'show' : 'hide'](true);
}
// Render the axis line
axis.renderLine();
// handle automatic or user set offset
axis.offset = directionFactor * pick(options.offset, axisOffset[side]);
axis.tickRotCorr = axis.tickRotCorr || {
x: 0,
y: 0
}; // polar
if (side === 0) {
lineHeightCorrection = -axis.labelMetrics().h;
} else if (side === 2) {
lineHeightCorrection = axis.tickRotCorr.y;
} else {
lineHeightCorrection = 0;
}
// Find the padded label offset
labelOffsetPadded = Math.abs(labelOffset) + titleMargin;
if (labelOffset) {
labelOffsetPadded -= lineHeightCorrection;
labelOffsetPadded += directionFactor * (horiz ? pick(labelOptions.y, axis.tickRotCorr.y + directionFactor * 8) : labelOptions.x);
}
axis.axisTitleMargin = pick(titleOffsetOption, labelOffsetPadded);
axisOffset[side] = Math.max(
axisOffset[side],
axis.axisTitleMargin + titleOffset + directionFactor * axis.offset,
labelOffsetPadded, // #3027
hasData && tickPositions.length && tickSize ? tickSize[0] : 0 // #4866
);
// Decide the clipping needed to keep the graph inside the plot area and axis lines
clip = options.offset ? 0 : Math.floor(axis.axisLine.strokeWidth() / 2) * 2; // #4308, #4371
clipOffset[invertedSide] = Math.max(clipOffset[invertedSide], clip);
},
/**
* Get the path for the axis line
*/
getLinePath: function(lineWidth) {
var chart = this.chart,
opposite = this.opposite,
offset = this.offset,
horiz = this.horiz,
lineLeft = this.left + (opposite ? this.width : 0) + offset,
lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset;
if (opposite) {
lineWidth *= -1; // crispify the other way - #1480, #1687
}
return chart.renderer
.crispLine([
'M',
horiz ?
this.left :
lineLeft,
horiz ?
lineTop :
this.top,
'L',
horiz ?
chart.chartWidth - this.right :
lineLeft,
horiz ?
lineTop :
chart.chartHeight - this.bottom
], lineWidth);
},
/**
* Render the axis line
* @returns {[type]} [description]
*/
renderLine: function() {
if (!this.axisLine) {
this.axisLine = this.chart.renderer.path()
.addClass('highcharts-axis-line')
.add(this.axisGroup);
}
},
/**
* Position the title
*/
getTitlePosition: function() {
// compute anchor points for each of the title align options
var horiz = this.horiz,
axisLeft = this.left,
axisTop = this.top,
axisLength = this.len,
axisTitleOptions = this.options.title,
margin = horiz ? axisLeft : axisTop,
opposite = this.opposite,
offset = this.offset,
xOption = axisTitleOptions.x || 0,
yOption = axisTitleOptions.y || 0,
fontSize = this.chart.renderer.fontMetrics(axisTitleOptions.style && axisTitleOptions.style.fontSize, this.axisTitle).f,
// the position in the length direction of the axis
alongAxis = {
low: margin + (horiz ? 0 : axisLength),
middle: margin + axisLength / 2,
high: margin + (horiz ? axisLength : 0)
}[axisTitleOptions.align],
// the position in the perpendicular direction of the axis
offAxis = (horiz ? axisTop + this.height : axisLeft) +
(horiz ? 1 : -1) * // horizontal axis reverses the margin
(opposite ? -1 : 1) * // so does opposite axes
this.axisTitleMargin +
(this.side === 2 ? fontSize : 0);
return {
x: horiz ?
alongAxis + xOption : offAxis + (opposite ? this.width : 0) + offset + xOption,
y: horiz ?
offAxis + yOption - (opposite ? this.height : 0) + offset : alongAxis + yOption
};
},
/**
* Render the axis
*/
render: function() {
var axis = this,
chart = axis.chart,
renderer = chart.renderer,
options = axis.options,
isLog = axis.isLog,
lin2log = axis.lin2log,
isLinked = axis.isLinked,
tickPositions = axis.tickPositions,
axisTitle = axis.axisTitle,
ticks = axis.ticks,
minorTicks = axis.minorTicks,
alternateBands = axis.alternateBands,
stackLabelOptions = options.stackLabels,
alternateGridColor = options.alternateGridColor,
tickmarkOffset = axis.tickmarkOffset,
axisLine = axis.axisLine,
hasRendered = chart.hasRendered,
slideInTicks = hasRendered && isNumber(axis.oldMin),
showAxis = axis.showAxis,
animation = animObject(renderer.globalAnimation),
from,
to;
// Reset
axis.labelEdge.length = 0;
//axis.justifyToPlot = overflow === 'justify';
axis.overlap = false;
// Mark all elements inActive before we go over and mark the active ones
each([ticks, minorTicks, alternateBands], function(coll) {
var pos;
for (pos in coll) {
coll[pos].isActive = false;
}
});
// If the series has data draw the ticks. Else only the line and title
if (axis.hasData() || isLinked) {
// minor ticks
if (axis.minorTickInterval && !axis.categories) {
each(axis.getMinorTickPositions(), function(pos) {
if (!minorTicks[pos]) {
minorTicks[pos] = new Tick(axis, pos, 'minor');
}
// render new ticks in old position
if (slideInTicks && minorTicks[pos].isNew) {
minorTicks[pos].render(null, true);
}
minorTicks[pos].render(null, false, 1);
});
}
// Major ticks. Pull out the first item and render it last so that
// we can get the position of the neighbour label. #808.
if (tickPositions.length) { // #1300
each(tickPositions, function(pos, i) {
// linked axes need an extra check to find out if
if (!isLinked || (pos >= axis.min && pos <= axis.max)) {
if (!ticks[pos]) {
ticks[pos] = new Tick(axis, pos);
}
// render new ticks in old position
if (slideInTicks && ticks[pos].isNew) {
ticks[pos].render(i, true, 0.1);
}
ticks[pos].render(i);
}
});
// In a categorized axis, the tick marks are displayed between labels. So
// we need to add a tick mark and grid line at the left edge of the X axis.
if (tickmarkOffset && (axis.min === 0 || axis.single)) {
if (!ticks[-1]) {
ticks[-1] = new Tick(axis, -1, null, true);
}
ticks[-1].render(-1);
}
}
// alternate grid color
if (alternateGridColor) {
each(tickPositions, function(pos, i) {
to = tickPositions[i + 1] !== undefined ? tickPositions[i + 1] + tickmarkOffset : axis.max - tickmarkOffset;
if (i % 2 === 0 && pos < axis.max && to <= axis.max + (chart.polar ? -tickmarkOffset : tickmarkOffset)) { // #2248, #4660
if (!alternateBands[pos]) {
alternateBands[pos] = new PlotLineOrBand(axis);
}
from = pos + tickmarkOffset; // #949
alternateBands[pos].options = {
from: isLog ? lin2log(from) : from,
to: isLog ? lin2log(to) : to,
color: alternateGridColor
};
alternateBands[pos].render();
alternateBands[pos].isActive = true;
}
});
}
// custom plot lines and bands
if (!axis._addedPlotLB) { // only first time
each((options.plotLines || []).concat(options.plotBands || []), function(plotLineOptions) {
axis.addPlotBandOrLine(plotLineOptions);
});
axis._addedPlotLB = true;
}
} // end if hasData
// Remove inactive ticks
each([ticks, minorTicks, alternateBands], function(coll) {
var pos,
i,
forDestruction = [],
delay = animation.duration,
destroyInactiveItems = function() {
i = forDestruction.length;
while (i--) {
// When resizing rapidly, the same items may be destroyed in different timeouts,
// or the may be reactivated
if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) {
coll[forDestruction[i]].destroy();
delete coll[forDestruction[i]];
}
}
};
for (pos in coll) {
if (!coll[pos].isActive) {
// Render to zero opacity
coll[pos].render(pos, false, 0);
coll[pos].isActive = false;
forDestruction.push(pos);
}
}
// When the objects are finished fading out, destroy them
syncTimeout(
destroyInactiveItems,
coll === alternateBands || !chart.hasRendered || !delay ? 0 : delay
);
});
// Set the axis line path
if (axisLine) {
axisLine[axisLine.isPlaced ? 'animate' : 'attr']({
d: this.getLinePath(axisLine.strokeWidth())
});
axisLine.isPlaced = true;
// Show or hide the line depending on options.showEmpty
axisLine[showAxis ? 'show' : 'hide'](true);
}
if (axisTitle && showAxis) {
axisTitle[axisTitle.isNew ? 'attr' : 'animate'](
axis.getTitlePosition()
);
axisTitle.isNew = false;
}
// Stacked totals:
if (stackLabelOptions && stackLabelOptions.enabled) {
axis.renderStackTotals();
}
// End stacked totals
axis.isDirty = false;
},
/**
* Redraw the axis to reflect changes in the data or axis extremes
*/
redraw: function() {
if (this.visible) {
// render the axis
this.render();
// move plot lines and bands
each(this.plotLinesAndBands, function(plotLine) {
plotLine.render();
});
}
// mark associated series as dirty and ready for redraw
each(this.series, function(series) {
series.isDirty = true;
});
},
/**
* Destroys an Axis instance.
*/
destroy: function(keepEvents) {
var axis = this,
stacks = axis.stacks,
stackKey,
plotLinesAndBands = axis.plotLinesAndBands,
i,
n,
keepProps;
// Remove the events
if (!keepEvents) {
removeEvent(axis);
}
// Destroy each stack total
for (stackKey in stacks) {
destroyObjectProperties(stacks[stackKey]);
stacks[stackKey] = null;
}
// Destroy collections
each([axis.ticks, axis.minorTicks, axis.alternateBands], function(coll) {
destroyObjectProperties(coll);
});
if (plotLinesAndBands) {
i = plotLinesAndBands.length;
while (i--) { // #1975
plotLinesAndBands[i].destroy();
}
}
// Destroy local variables
each(['stackTotalGroup', 'axisLine', 'axisTitle', 'axisGroup', 'gridGroup', 'labelGroup', 'cross'], function(prop) {
if (axis[prop]) {
axis[prop] = axis[prop].destroy();
}
});
// Delete all properties and fall back to the prototype.
// Preserve some properties, needed for Axis.update (#4317, #5773).
keepProps = ['extKey', 'hcEvents', 'names', 'series', 'userMax', 'userMin'];
for (n in axis) {
if (axis.hasOwnProperty(n) && inArray(n, keepProps) === -1) {
delete axis[n];
}
}
},
/**
* Draw the crosshair
*
* @param {Object} e The event arguments from the modified pointer event
* @param {Object} point The Point object
*/
drawCrosshair: function(e, point) {
var path,
options = this.crosshair,
snap = pick(options.snap, true),
pos,
categorized,
graphic = this.cross;
// Use last available event when updating non-snapped crosshairs without
// mouse interaction (#5287)
if (!e) {
e = this.cross && this.cross.e;
}
if (
// Disabled in options
!this.crosshair ||
// Snap
((defined(point) || !snap) === false)
) {
this.hideCrosshair();
} else {
// Get the path
if (!snap) {
pos = e && (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos);
} else if (defined(point)) {
pos = this.isXAxis ? point.plotX : this.len - point.plotY; // #3834
}
if (defined(pos)) {
path = this.getPlotLinePath(
// First argument, value, only used on radial
point && (this.isXAxis ? point.x : pick(point.stackY, point.y)),
null,
null,
null,
pos // Translated position
) || null; // #3189
}
if (!defined(path)) {
this.hideCrosshair();
return;
}
categorized = this.categories && !this.isRadial;
// Draw the cross
if (!graphic) {
this.cross = graphic = this.chart.renderer
.path()
.addClass('highcharts-crosshair highcharts-crosshair-' +
(categorized ? 'category ' : 'thin ') + options.className)
.attr({
zIndex: pick(options.zIndex, 2)
})
.add();
}
graphic.show().attr({
d: path
});
if (categorized && !options.width) {
graphic.attr({
'stroke-width': this.transA
});
}
this.cross.e = e;
}
},
/**
* Hide the crosshair.
*/
hideCrosshair: function() {
if (this.cross) {
this.cross.hide();
}
}
}; // end Axis
extend(H.Axis.prototype, AxisPlotLineOrBandExtension);
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Axis = H.Axis,
getMagnitude = H.getMagnitude,
map = H.map,
normalizeTickInterval = H.normalizeTickInterval,
pick = H.pick;
/**
* Methods defined on the Axis prototype
*/
/**
* Set the tick positions of a logarithmic axis
*/
Axis.prototype.getLogTickPositions = function(interval, min, max, minor) {
var axis = this,
options = axis.options,
axisLength = axis.len,
lin2log = axis.lin2log,
log2lin = axis.log2lin,
// Since we use this method for both major and minor ticks,
// use a local variable and return the result
positions = [];
// Reset
if (!minor) {
axis._minorAutoInterval = null;
}
// First case: All ticks fall on whole logarithms: 1, 10, 100 etc.
if (interval >= 0.5) {
interval = Math.round(interval);
positions = axis.getLinearTickPositions(interval, min, max);
// Second case: We need intermediary ticks. For example
// 1, 2, 4, 6, 8, 10, 20, 40 etc.
} else if (interval >= 0.08) {
var roundedMin = Math.floor(min),
intermediate,
i,
j,
len,
pos,
lastPos,
break2;
if (interval > 0.3) {
intermediate = [1, 2, 4];
} else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc
intermediate = [1, 2, 4, 6, 8];
} else { // 0.1 equals ten minor ticks per 1, 10, 100 etc
intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9];
}
for (i = roundedMin; i < max + 1 && !break2; i++) {
len = intermediate.length;
for (j = 0; j < len && !break2; j++) {
pos = log2lin(lin2log(i) * intermediate[j]);
if (pos > min && (!minor || lastPos <= max) && lastPos !== undefined) { // #1670, lastPos is #3113
positions.push(lastPos);
}
if (lastPos > max) {
break2 = true;
}
lastPos = pos;
}
}
// Third case: We are so deep in between whole logarithmic values that
// we might as well handle the tick positions like a linear axis. For
// example 1.01, 1.02, 1.03, 1.04.
} else {
var realMin = lin2log(min),
realMax = lin2log(max),
tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'],
filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption,
tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1),
totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength;
interval = pick(
filteredTickIntervalOption,
axis._minorAutoInterval,
(realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1)
);
interval = normalizeTickInterval(
interval,
null,
getMagnitude(interval)
);
positions = map(axis.getLinearTickPositions(
interval,
realMin,
realMax
), log2lin);
if (!minor) {
axis._minorAutoInterval = interval / 5;
}
}
// Set the axis-level tickInterval variable
if (!minor) {
axis.tickInterval = interval;
}
return positions;
};
Axis.prototype.log2lin = function(num) {
return Math.log(num) / Math.LN10;
};
Axis.prototype.lin2log = function(num) {
return Math.pow(10, num);
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var dateFormat = H.dateFormat,
each = H.each,
extend = H.extend,
format = H.format,
isNumber = H.isNumber,
map = H.map,
merge = H.merge,
pick = H.pick,
splat = H.splat,
stop = H.stop,
syncTimeout = H.syncTimeout,
timeUnits = H.timeUnits;
/**
* The tooltip object
* @param {Object} chart The chart instance
* @param {Object} options Tooltip options
*/
H.Tooltip = function() {
this.init.apply(this, arguments);
};
H.Tooltip.prototype = {
init: function(chart, options) {
// Save the chart and options
this.chart = chart;
this.options = options;
// Keep track of the current series
//this.currentSeries = undefined;
// List of crosshairs
this.crosshairs = [];
// Current values of x and y when animating
this.now = {
x: 0,
y: 0
};
// The tooltip is initially hidden
this.isHidden = true;
// Public property for getting the shared state.
this.split = options.split && !chart.inverted;
this.shared = options.shared || this.split;
},
/**
* Destroy the single tooltips in a split tooltip.
* If the tooltip is active then it is not destroyed, unless forced to.
* @param {boolean} force Force destroy all tooltips.
* @return {undefined}
*/
cleanSplit: function(force) {
each(this.chart.series, function(series) {
var tt = series && series.tt;
if (tt) {
if (!tt.isActive || force) {
series.tt = tt.destroy();
} else {
tt.isActive = false;
}
}
});
},
/**
* Create the Tooltip label element if it doesn't exist, then return the
* label.
*/
getLabel: function() {
var renderer = this.chart.renderer,
options = this.options;
if (!this.label) {
// Create the label
if (this.split) {
this.label = renderer.g('tooltip');
} else {
this.label = renderer.label(
'',
0,
0,
options.shape || 'callout',
null,
null,
options.useHTML,
null,
'tooltip'
)
.attr({
padding: options.padding,
r: options.borderRadius
});
}
this.label
.attr({
zIndex: 8
})
.add();
}
return this.label;
},
update: function(options) {
this.destroy();
this.init(this.chart, merge(true, this.options, options));
},
/**
* Destroy the tooltip and its elements.
*/
destroy: function() {
// Destroy and clear local variables
if (this.label) {
this.label = this.label.destroy();
}
if (this.split && this.tt) {
this.cleanSplit(this.chart, true);
this.tt = this.tt.destroy();
}
clearTimeout(this.hideTimer);
clearTimeout(this.tooltipTimeout);
},
/**
* Provide a soft movement for the tooltip
*
* @param {Number} x
* @param {Number} y
* @private
*/
move: function(x, y, anchorX, anchorY) {
var tooltip = this,
now = tooltip.now,
animate = tooltip.options.animation !== false && !tooltip.isHidden &&
// When we get close to the target position, abort animation and land on the right place (#3056)
(Math.abs(x - now.x) > 1 || Math.abs(y - now.y) > 1),
skipAnchor = tooltip.followPointer || tooltip.len > 1;
// Get intermediate values for animation
extend(now, {
x: animate ? (2 * now.x + x) / 3 : x,
y: animate ? (now.y + y) / 2 : y,
anchorX: skipAnchor ? undefined : animate ? (2 * now.anchorX + anchorX) / 3 : anchorX,
anchorY: skipAnchor ? undefined : animate ? (now.anchorY + anchorY) / 2 : anchorY
});
// Move to the intermediate value
tooltip.getLabel().attr(now);
// Run on next tick of the mouse tracker
if (animate) {
// Never allow two timeouts
clearTimeout(this.tooltipTimeout);
// Set the fixed interval ticking for the smooth tooltip
this.tooltipTimeout = setTimeout(function() {
// The interval function may still be running during destroy,
// so check that the chart is really there before calling.
if (tooltip) {
tooltip.move(x, y, anchorX, anchorY);
}
}, 32);
}
},
/**
* Hide the tooltip
*/
hide: function(delay) {
var tooltip = this;
clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766)
delay = pick(delay, this.options.hideDelay, 500);
if (!this.isHidden) {
this.hideTimer = syncTimeout(function() {
tooltip.getLabel()[delay ? 'fadeOut' : 'hide']();
tooltip.isHidden = true;
}, delay);
}
},
/**
* Extendable method to get the anchor position of the tooltip
* from a point or set of points
*/
getAnchor: function(points, mouseEvent) {
var ret,
chart = this.chart,
inverted = chart.inverted,
plotTop = chart.plotTop,
plotLeft = chart.plotLeft,
plotX = 0,
plotY = 0,
yAxis,
xAxis;
points = splat(points);
// Pie uses a special tooltipPos
ret = points[0].tooltipPos;
// When tooltip follows mouse, relate the position to the mouse
if (this.followPointer && mouseEvent) {
if (mouseEvent.chartX === undefined) {
mouseEvent = chart.pointer.normalize(mouseEvent);
}
ret = [
mouseEvent.chartX - chart.plotLeft,
mouseEvent.chartY - plotTop
];
}
// When shared, use the average position
if (!ret) {
each(points, function(point) {
yAxis = point.series.yAxis;
xAxis = point.series.xAxis;
plotX += point.plotX + (!inverted && xAxis ? xAxis.left - plotLeft : 0);
plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) +
(!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151
});
plotX /= points.length;
plotY /= points.length;
ret = [
inverted ? chart.plotWidth - plotY : plotX,
this.shared && !inverted && points.length > 1 && mouseEvent ?
mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424)
inverted ? chart.plotHeight - plotX : plotY
];
}
return map(ret, Math.round);
},
/**
* Place the tooltip in a chart without spilling over
* and not covering the point it self.
*/
getPosition: function(boxWidth, boxHeight, point) {
var chart = this.chart,
distance = this.distance,
ret = {},
h = point.h || 0, // #4117
swapped,
first = ['y', chart.chartHeight, boxHeight,
point.plotY + chart.plotTop, chart.plotTop,
chart.plotTop + chart.plotHeight
],
second = ['x', chart.chartWidth, boxWidth,
point.plotX + chart.plotLeft, chart.plotLeft,
chart.plotLeft + chart.plotWidth
],
// The far side is right or bottom
preferFarSide = !this.followPointer && pick(point.ttBelow, !chart.inverted === !!point.negative), // #4984
/**
* Handle the preferred dimension. When the preferred dimension is tooltip
* on top or bottom of the point, it will look for space there.
*/
firstDimension = function(dim, outerSize, innerSize, point, min, max) {
var roomLeft = innerSize < point - distance,
roomRight = point + distance + innerSize < outerSize,
alignedLeft = point - distance - innerSize,
alignedRight = point + distance;
if (preferFarSide && roomRight) {
ret[dim] = alignedRight;
} else if (!preferFarSide && roomLeft) {
ret[dim] = alignedLeft;
} else if (roomLeft) {
ret[dim] = Math.min(max - innerSize, alignedLeft - h < 0 ? alignedLeft : alignedLeft - h);
} else if (roomRight) {
ret[dim] = Math.max(
min,
alignedRight + h + innerSize > outerSize ?
alignedRight :
alignedRight + h
);
} else {
return false;
}
},
/**
* Handle the secondary dimension. If the preferred dimension is tooltip
* on top or bottom of the point, the second dimension is to align the tooltip
* above the point, trying to align center but allowing left or right
* align within the chart box.
*/
secondDimension = function(dim, outerSize, innerSize, point) {
var retVal;
// Too close to the edge, return false and swap dimensions
if (point < distance || point > outerSize - distance) {
retVal = false;
// Align left/top
} else if (point < innerSize / 2) {
ret[dim] = 1;
// Align right/bottom
} else if (point > outerSize - innerSize / 2) {
ret[dim] = outerSize - innerSize - 2;
// Align center
} else {
ret[dim] = point - innerSize / 2;
}
return retVal;
},
/**
* Swap the dimensions
*/
swap = function(count) {
var temp = first;
first = second;
second = temp;
swapped = count;
},
run = function() {
if (firstDimension.apply(0, first) !== false) {
if (secondDimension.apply(0, second) === false && !swapped) {
swap(true);
run();
}
} else if (!swapped) {
swap(true);
run();
} else {
ret.x = ret.y = 0;
}
};
// Under these conditions, prefer the tooltip on the side of the point
if (chart.inverted || this.len > 1) {
swap();
}
run();
return ret;
},
/**
* In case no user defined formatter is given, this will be used. Note that the context
* here is an object holding point, series, x, y etc.
*
* @returns {String|Array<String>}
*/
defaultFormatter: function(tooltip) {
var items = this.points || splat(this),
s;
// Build the header
s = [tooltip.tooltipFooterHeaderFormatter(items[0])];
// build the values
s = s.concat(tooltip.bodyFormatter(items));
// footer
s.push(tooltip.tooltipFooterHeaderFormatter(items[0], true));
return s;
},
/**
* Refresh the tooltip's text and position.
* @param {Object} point
*/
refresh: function(point, mouseEvent) {
var tooltip = this,
chart = tooltip.chart,
label = tooltip.getLabel(),
options = tooltip.options,
x,
y,
anchor,
textConfig = {},
text,
pointConfig = [],
formatter = options.formatter || tooltip.defaultFormatter,
hoverPoints = chart.hoverPoints,
shared = tooltip.shared,
currentSeries;
clearTimeout(this.hideTimer);
// get the reference point coordinates (pie charts use tooltipPos)
tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer;
anchor = tooltip.getAnchor(point, mouseEvent);
x = anchor[0];
y = anchor[1];
// shared tooltip, array is sent over
if (shared && !(point.series && point.series.noSharedTooltip)) {
// hide previous hoverPoints and set new
chart.hoverPoints = point;
if (hoverPoints) {
each(hoverPoints, function(point) {
point.setState();
});
}
each(point, function(item) {
item.setState('hover');
pointConfig.push(item.getLabelConfig());
});
textConfig = {
x: point[0].category,
y: point[0].y
};
textConfig.points = pointConfig;
this.len = pointConfig.length;
point = point[0];
// single point tooltip
} else {
textConfig = point.getLabelConfig();
}
text = formatter.call(textConfig, tooltip);
// register the current series
currentSeries = point.series;
this.distance = pick(currentSeries.tooltipOptions.distance, 16);
// update the inner HTML
if (text === false) {
this.hide();
} else {
// show it
if (tooltip.isHidden) {
stop(label);
label.attr({
opacity: 1
}).show();
}
// update text
if (tooltip.split) {
this.renderSplit(text, chart.hoverPoints);
} else {
label.attr({
text: text.join ? text.join('') : text
});
// Set the stroke color of the box to reflect the point
label.removeClass(/highcharts-color-[\d]+/g)
.addClass('highcharts-color-' + pick(point.colorIndex, currentSeries.colorIndex));
tooltip.updatePosition({
plotX: x,
plotY: y,
negative: point.negative,
ttBelow: point.ttBelow,
h: anchor[2] || 0
});
}
this.isHidden = false;
}
},
/**
* Render the split tooltip. Loops over each point's text and adds
* a label next to the point, then uses the distribute function to
* find best non-overlapping positions.
*/
renderSplit: function(labels, points) {
var tooltip = this,
boxes = [],
chart = this.chart,
ren = chart.renderer,
rightAligned = true,
options = this.options,
headerHeight,
tooltipLabel = this.getLabel();
// Create the individual labels
each(labels.slice(0, labels.length - 1), function(str, i) {
var point = points[i - 1] ||
// Item 0 is the header. Instead of this, we could also use the crosshair label
{
isHeader: true,
plotX: points[0].plotX
},
owner = point.series || tooltip,
tt = owner.tt,
series = point.series || {},
colorClass = 'highcharts-color-' + pick(point.colorIndex, series.colorIndex, 'none'),
target,
x,
bBox,
boxWidth;
// Store the tooltip referance on the series
if (!tt) {
owner.tt = tt = ren.label(null, null, null, point.isHeader && 'callout')
.addClass('highcharts-tooltip-box ' + colorClass)
.attr({
'padding': options.padding,
'r': options.borderRadius
})
.add(tooltipLabel);
// Add a connector back to the point
if (point.series) {
tt.connector = ren.path()
.addClass('highcharts-tooltip-connector ' + colorClass)
// Add it inside the label group so we will get hide and
// destroy for free
.add(tt);
}
}
tt.isActive = true;
tt.attr({
text: str
});
// Get X position now, so we can move all to the other side in case of overflow
bBox = tt.getBBox();
boxWidth = bBox.width + tt.strokeWidth();
if (point.isHeader) {
headerHeight = bBox.height;
x = Math.max(
0, // No left overflow
Math.min(
point.plotX + chart.plotLeft - boxWidth / 2,
chart.chartWidth - boxWidth // No right overflow (#5794)
)
);
} else {
x = point.plotX + chart.plotLeft - pick(options.distance, 16) -
boxWidth;
}
// If overflow left, we don't use this x in the next loop
if (x < 0) {
rightAligned = false;
}
// Prepare for distribution
target = (point.series && point.series.yAxis && point.series.yAxis.pos) + (point.plotY || 0);
target -= chart.plotTop;
boxes.push({
target: point.isHeader ? chart.plotHeight + headerHeight : target,
rank: point.isHeader ? 1 : 0,
size: owner.tt.getBBox().height + 1,
point: point,
x: x,
tt: tt
});
});
// Clean previous run (for missing points)
this.cleanSplit();
// Distribute and put in place
H.distribute(boxes, chart.plotHeight + headerHeight);
each(boxes, function(box) {
var point = box.point,
tt = box.tt,
attr;
// Put the label in place
attr = {
visibility: box.pos === undefined ? 'hidden' : 'inherit',
x: (rightAligned || point.isHeader ? box.x : point.plotX + chart.plotLeft + pick(options.distance, 16)),
y: box.pos + chart.plotTop
};
if (point.isHeader) {
attr.anchorX = point.plotX + chart.plotLeft;
attr.anchorY = attr.y - 100;
}
tt.attr(attr);
// Draw the connector to the point
if (!point.isHeader) {
tt.connector.attr({
d: [
'M',
point.plotX + chart.plotLeft - attr.x,
point.plotY + point.series.yAxis.pos - attr.y,
'L',
(rightAligned ? -1 : 1) * pick(options.distance, 16) +
point.plotX + chart.plotLeft - attr.x,
box.pos + chart.plotTop + tt.getBBox().height / 2 -
attr.y
]
});
}
});
},
/**
* Find the new position and perform the move
*/
updatePosition: function(point) {
var chart = this.chart,
label = this.getLabel(),
pos = (this.options.positioner || this.getPosition).call(
this,
label.width,
label.height,
point
);
// do the move
this.move(
Math.round(pos.x),
Math.round(pos.y || 0), // can be undefined (#3977)
point.plotX + chart.plotLeft,
point.plotY + chart.plotTop
);
},
/**
* Get the best X date format based on the closest point range on the axis.
*/
getXDateFormat: function(point, options, xAxis) {
var xDateFormat,
dateTimeLabelFormats = options.dateTimeLabelFormats,
closestPointRange = xAxis && xAxis.closestPointRange,
n,
blank = '01-01 00:00:00.000',
strpos = {
millisecond: 15,
second: 12,
minute: 9,
hour: 6,
day: 3
},
date,
lastN = 'millisecond'; // for sub-millisecond data, #4223
if (closestPointRange) {
date = dateFormat('%m-%d %H:%M:%S.%L', point.x);
for (n in timeUnits) {
// If the range is exactly one week and we're looking at a Sunday/Monday, go for the week format
if (closestPointRange === timeUnits.week && +dateFormat('%w', point.x) === xAxis.options.startOfWeek &&
date.substr(6) === blank.substr(6)) {
n = 'week';
break;
}
// The first format that is too great for the range
if (timeUnits[n] > closestPointRange) {
n = lastN;
break;
}
// If the point is placed every day at 23:59, we need to show
// the minutes as well. #2637.
if (strpos[n] && date.substr(strpos[n]) !== blank.substr(strpos[n])) {
break;
}
// Weeks are outside the hierarchy, only apply them on Mondays/Sundays like in the first condition
if (n !== 'week') {
lastN = n;
}
}
if (n) {
xDateFormat = dateTimeLabelFormats[n];
}
} else {
xDateFormat = dateTimeLabelFormats.day;
}
return xDateFormat || dateTimeLabelFormats.year; // #2546, 2581
},
/**
* Format the footer/header of the tooltip
* #3397: abstraction to enable formatting of footer and header
*/
tooltipFooterHeaderFormatter: function(labelConfig, isFooter) {
var footOrHead = isFooter ? 'footer' : 'header',
series = labelConfig.series,
tooltipOptions = series.tooltipOptions,
xDateFormat = tooltipOptions.xDateFormat,
xAxis = series.xAxis,
isDateTime = xAxis && xAxis.options.type === 'datetime' && isNumber(labelConfig.key),
formatString = tooltipOptions[footOrHead + 'Format'];
// Guess the best date format based on the closest point distance (#568, #3418)
if (isDateTime && !xDateFormat) {
xDateFormat = this.getXDateFormat(labelConfig, tooltipOptions, xAxis);
}
// Insert the footer date format if any
if (isDateTime && xDateFormat) {
formatString = formatString.replace('{point.key}', '{point.key:' + xDateFormat + '}');
}
return format(formatString, {
point: labelConfig,
series: series
});
},
/**
* Build the body (lines) of the tooltip by iterating over the items and returning one entry for each item,
* abstracting this functionality allows to easily overwrite and extend it.
*/
bodyFormatter: function(items) {
return map(items, function(item) {
var tooltipOptions = item.series.tooltipOptions;
return (tooltipOptions.pointFormatter || item.point.tooltipFormatter)
.call(item.point, tooltipOptions.pointFormat);
});
}
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
attr = H.attr,
charts = H.charts,
color = H.color,
css = H.css,
defined = H.defined,
doc = H.doc,
each = H.each,
extend = H.extend,
fireEvent = H.fireEvent,
offset = H.offset,
pick = H.pick,
removeEvent = H.removeEvent,
splat = H.splat,
Tooltip = H.Tooltip,
win = H.win;
/**
* The mouse tracker object. All methods starting with "on" are primary DOM event handlers.
* Subsequent methods should be named differently from what they are doing.
* @param {Object} chart The Chart instance
* @param {Object} options The root options object
*/
H.Pointer = function(chart, options) {
this.init(chart, options);
};
H.Pointer.prototype = {
/**
* Initialize Pointer
*/
init: function(chart, options) {
// Store references
this.options = options;
this.chart = chart;
// Do we need to handle click on a touch device?
this.runChartClick = options.chart.events && !!options.chart.events.click;
this.pinchDown = [];
this.lastValidTouch = {};
if (Tooltip && options.tooltip.enabled) {
chart.tooltip = new Tooltip(chart, options.tooltip);
this.followTouchMove = pick(options.tooltip.followTouchMove, true);
}
this.setDOMEvents();
},
/**
* Resolve the zoomType option
*/
zoomOption: function() {
var chart = this.chart,
zoomType = chart.options.chart.zoomType,
zoomX = /x/.test(zoomType),
zoomY = /y/.test(zoomType),
inverted = chart.inverted;
this.zoomX = zoomX;
this.zoomY = zoomY;
this.zoomHor = (zoomX && !inverted) || (zoomY && inverted);
this.zoomVert = (zoomY && !inverted) || (zoomX && inverted);
this.hasZoom = zoomX || zoomY;
},
/**
* Add crossbrowser support for chartX and chartY
* @param {Object} e The event object in standard browsers
*/
normalize: function(e, chartPosition) {
var chartX,
chartY,
ePos;
// IE normalizing
e = e || win.event;
if (!e.target) {
e.target = e.srcElement;
}
// iOS (#2757)
ePos = e.touches ? (e.touches.length ? e.touches.item(0) : e.changedTouches[0]) : e;
// Get mouse position
if (!chartPosition) {
this.chartPosition = chartPosition = offset(this.chart.container);
}
// chartX and chartY
if (ePos.pageX === undefined) { // IE < 9. #886.
chartX = Math.max(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is
// for IE10 quirks mode within framesets
chartY = e.y;
} else {
chartX = ePos.pageX - chartPosition.left;
chartY = ePos.pageY - chartPosition.top;
}
return extend(e, {
chartX: Math.round(chartX),
chartY: Math.round(chartY)
});
},
/**
* Get the click position in terms of axis values.
*
* @param {Object} e A pointer event
*/
getCoordinates: function(e) {
var coordinates = {
xAxis: [],
yAxis: []
};
each(this.chart.axes, function(axis) {
coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({
axis: axis,
value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY'])
});
});
return coordinates;
},
/**
* With line type charts with a single tracker, get the point closest to the mouse.
* Run Point.onMouseOver and display tooltip for the point or points.
*/
runPointActions: function(e) {
var pointer = this,
chart = pointer.chart,
series = chart.series,
tooltip = chart.tooltip,
shared = tooltip ? tooltip.shared : false,
followPointer,
updatePosition = true,
hoverPoint = chart.hoverPoint,
hoverSeries = chart.hoverSeries,
i,
anchor,
noSharedTooltip,
stickToHoverSeries,
directTouch,
kdpoints = [],
kdpointT;
// For hovering over the empty parts of the plot area (hoverSeries is undefined).
// If there is one series with point tracking (combo chart), don't go to nearest neighbour.
if (!shared && !hoverSeries) {
for (i = 0; i < series.length; i++) {
if (series[i].directTouch || !series[i].options.stickyTracking) {
series = [];
}
}
}
// If it has a hoverPoint and that series requires direct touch (like columns, #3899), or we're on
// a noSharedTooltip series among shared tooltip series (#4546), use the hoverPoint . Otherwise,
// search the k-d tree.
stickToHoverSeries = hoverSeries && (shared ? hoverSeries.noSharedTooltip : hoverSeries.directTouch);
if (stickToHoverSeries && hoverPoint) {
kdpoints = [hoverPoint];
// Handle shared tooltip or cases where a series is not yet hovered
} else {
// When we have non-shared tooltip and sticky tracking is disabled,
// search for the closest point only on hovered series: #5533, #5476
if (!shared && hoverSeries && !hoverSeries.options.stickyTracking) {
series = [hoverSeries];
}
// Find nearest points on all series
each(series, function(s) {
// Skip hidden series
noSharedTooltip = s.noSharedTooltip && shared;
directTouch = !shared && s.directTouch;
if (s.visible && !noSharedTooltip && !directTouch && pick(s.options.enableMouseTracking, true)) { // #3821
kdpointT = s.searchPoint(e, !noSharedTooltip && s.kdDimensions === 1); // #3828
if (kdpointT && kdpointT.series) { // Point.series becomes null when reset and before redraw (#5197)
kdpoints.push(kdpointT);
}
}
});
// Sort kdpoints by distance to mouse pointer
kdpoints.sort(function(p1, p2) {
var isCloserX = p1.distX - p2.distX,
isCloser = p1.dist - p2.dist,
isAbove = p1.series.group.zIndex > p2.series.group.zIndex ? -1 : 1;
// We have two points which are not in the same place on xAxis and shared tooltip:
if (isCloserX !== 0 && shared) { // #5721
return isCloserX;
}
// Points are not exactly in the same place on x/yAxis:
if (isCloser !== 0) {
return isCloser;
}
// The same xAxis and yAxis position, sort by z-index:
return isAbove;
});
}
// Remove points with different x-positions, required for shared tooltip and crosshairs (#4645):
if (shared) {
i = kdpoints.length;
while (i--) {
if (kdpoints[i].x !== kdpoints[0].x || kdpoints[i].series.noSharedTooltip) {
kdpoints.splice(i, 1);
}
}
}
// Refresh tooltip for kdpoint if new hover point or tooltip was hidden // #3926, #4200
if (kdpoints[0] && (kdpoints[0] !== this.prevKDPoint || (tooltip && tooltip.isHidden))) {
// Draw tooltip if necessary
if (shared && !kdpoints[0].series.noSharedTooltip) {
// Do mouseover on all points (#3919, #3985, #4410, #5622)
for (i = 0; i < kdpoints.length; i++) {
kdpoints[i].onMouseOver(e, kdpoints[i] !== ((hoverSeries && hoverSeries.directTouch && hoverPoint) || kdpoints[0]));
}
if (kdpoints.length && tooltip) {
// Keep the order of series in tooltip:
tooltip.refresh(kdpoints.sort(function(p1, p2) {
return p1.series.index - p2.series.index;
}), e);
}
} else {
if (tooltip) {
tooltip.refresh(kdpoints[0], e);
}
if (!hoverSeries || !hoverSeries.directTouch) { // #4448
kdpoints[0].onMouseOver(e);
}
}
this.prevKDPoint = kdpoints[0];
updatePosition = false;
}
// Update positions (regardless of kdpoint or hoverPoint)
if (updatePosition) {
followPointer = hoverSeries && hoverSeries.tooltipOptions.followPointer;
if (tooltip && followPointer && !tooltip.isHidden) {
anchor = tooltip.getAnchor([{}], e);
tooltip.updatePosition({
plotX: anchor[0],
plotY: anchor[1]
});
}
}
// Start the event listener to pick up the tooltip and crosshairs
if (!pointer._onDocumentMouseMove) {
pointer._onDocumentMouseMove = function(e) {
if (charts[H.hoverChartIndex]) {
charts[H.hoverChartIndex].pointer.onDocumentMouseMove(e);
}
};
addEvent(doc, 'mousemove', pointer._onDocumentMouseMove);
}
// Crosshair. For each hover point, loop over axes and draw cross if that point
// belongs to the axis (#4927).
each(shared ? kdpoints : [pick(hoverPoint, kdpoints[0])], function drawPointCrosshair(point) { // #5269
each(chart.axes, function drawAxisCrosshair(axis) {
// In case of snap = false, point is undefined, and we draw the crosshair anyway (#5066)
if (!point || point.series && point.series[axis.coll] === axis) { // #5658
axis.drawCrosshair(e, point);
}
});
});
},
/**
* Reset the tracking by hiding the tooltip, the hover series state and the hover point
*
* @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible
*/
reset: function(allowMove, delay) {
var pointer = this,
chart = pointer.chart,
hoverSeries = chart.hoverSeries,
hoverPoint = chart.hoverPoint,
hoverPoints = chart.hoverPoints,
tooltip = chart.tooltip,
tooltipPoints = tooltip && tooltip.shared ? hoverPoints : hoverPoint;
// Check if the points have moved outside the plot area (#1003, #4736, #5101)
if (allowMove && tooltipPoints) {
each(splat(tooltipPoints), function(point) {
if (point.series.isCartesian && point.plotX === undefined) {
allowMove = false;
}
});
}
// Just move the tooltip, #349
if (allowMove) {
if (tooltip && tooltipPoints) {
tooltip.refresh(tooltipPoints);
if (hoverPoint) { // #2500
hoverPoint.setState(hoverPoint.state, true);
each(chart.axes, function(axis) {
if (axis.crosshair) {
axis.drawCrosshair(null, hoverPoint);
}
});
}
}
// Full reset
} else {
if (hoverPoint) {
hoverPoint.onMouseOut();
}
if (hoverPoints) {
each(hoverPoints, function(point) {
point.setState();
});
}
if (hoverSeries) {
hoverSeries.onMouseOut();
}
if (tooltip) {
tooltip.hide(delay);
}
if (pointer._onDocumentMouseMove) {
removeEvent(doc, 'mousemove', pointer._onDocumentMouseMove);
pointer._onDocumentMouseMove = null;
}
// Remove crosshairs
each(chart.axes, function(axis) {
axis.hideCrosshair();
});
pointer.hoverX = pointer.prevKDPoint = chart.hoverPoints = chart.hoverPoint = null;
}
},
/**
* Scale series groups to a certain scale and translation
*/
scaleGroups: function(attribs, clip) {
var chart = this.chart,
seriesAttribs;
// Scale each series
each(chart.series, function(series) {
seriesAttribs = attribs || series.getPlotBox(); // #1701
if (series.xAxis && series.xAxis.zoomEnabled && series.group) {
series.group.attr(seriesAttribs);
if (series.markerGroup) {
series.markerGroup.attr(seriesAttribs);
series.markerGroup.clip(clip ? chart.clipRect : null);
}
if (series.dataLabelsGroup) {
series.dataLabelsGroup.attr(seriesAttribs);
}
}
});
// Clip
chart.clipRect.attr(clip || chart.clipBox);
},
/**
* Start a drag operation
*/
dragStart: function(e) {
var chart = this.chart;
// Record the start position
chart.mouseIsDown = e.type;
chart.cancelClick = false;
chart.mouseDownX = this.mouseDownX = e.chartX;
chart.mouseDownY = this.mouseDownY = e.chartY;
},
/**
* Perform a drag operation in response to a mousemove event while the mouse is down
*/
drag: function(e) {
var chart = this.chart,
chartOptions = chart.options.chart,
chartX = e.chartX,
chartY = e.chartY,
zoomHor = this.zoomHor,
zoomVert = this.zoomVert,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop,
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
clickedInside,
size,
selectionMarker = this.selectionMarker,
mouseDownX = this.mouseDownX,
mouseDownY = this.mouseDownY,
panKey = chartOptions.panKey && e[chartOptions.panKey + 'Key'];
// If the device supports both touch and mouse (like IE11), and we are touch-dragging
// inside the plot area, don't handle the mouse event. #4339.
if (selectionMarker && selectionMarker.touch) {
return;
}
// If the mouse is outside the plot area, adjust to cooordinates
// inside to prevent the selection marker from going outside
if (chartX < plotLeft) {
chartX = plotLeft;
} else if (chartX > plotLeft + plotWidth) {
chartX = plotLeft + plotWidth;
}
if (chartY < plotTop) {
chartY = plotTop;
} else if (chartY > plotTop + plotHeight) {
chartY = plotTop + plotHeight;
}
// determine if the mouse has moved more than 10px
this.hasDragged = Math.sqrt(
Math.pow(mouseDownX - chartX, 2) +
Math.pow(mouseDownY - chartY, 2)
);
if (this.hasDragged > 10) {
clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop);
// make a selection
if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside && !panKey) {
if (!selectionMarker) {
this.selectionMarker = selectionMarker = chart.renderer.rect(
plotLeft,
plotTop,
zoomHor ? 1 : plotWidth,
zoomVert ? 1 : plotHeight,
0
)
.attr({
'class': 'highcharts-selection-marker',
'zIndex': 7
})
.add();
}
}
// adjust the width of the selection marker
if (selectionMarker && zoomHor) {
size = chartX - mouseDownX;
selectionMarker.attr({
width: Math.abs(size),
x: (size > 0 ? 0 : size) + mouseDownX
});
}
// adjust the height of the selection marker
if (selectionMarker && zoomVert) {
size = chartY - mouseDownY;
selectionMarker.attr({
height: Math.abs(size),
y: (size > 0 ? 0 : size) + mouseDownY
});
}
// panning
if (clickedInside && !selectionMarker && chartOptions.panning) {
chart.pan(e, chartOptions.panning);
}
}
},
/**
* On mouse up or touch end across the entire document, drop the selection.
*/
drop: function(e) {
var pointer = this,
chart = this.chart,
hasPinched = this.hasPinched;
if (this.selectionMarker) {
var selectionData = {
originalEvent: e, // #4890
xAxis: [],
yAxis: []
},
selectionBox = this.selectionMarker,
selectionLeft = selectionBox.attr ? selectionBox.attr('x') : selectionBox.x,
selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y,
selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width,
selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height,
runZoom;
// a selection has been made
if (this.hasDragged || hasPinched) {
// record each axis' min and max
each(chart.axes, function(axis) {
if (axis.zoomEnabled && defined(axis.min) && (hasPinched || pointer[{
xAxis: 'zoomX',
yAxis: 'zoomY'
}[axis.coll]])) { // #859, #3569
var horiz = axis.horiz,
minPixelPadding = e.type === 'touchend' ? axis.minPixelPadding : 0, // #1207, #3075
selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding),
selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight) - minPixelPadding);
selectionData[axis.coll].push({
axis: axis,
min: Math.min(selectionMin, selectionMax), // for reversed axes
max: Math.max(selectionMin, selectionMax)
});
runZoom = true;
}
});
if (runZoom) {
fireEvent(chart, 'selection', selectionData, function(args) {
chart.zoom(extend(args, hasPinched ? {
animation: false
} : null));
});
}
}
this.selectionMarker = this.selectionMarker.destroy();
// Reset scaling preview
if (hasPinched) {
this.scaleGroups();
}
}
// Reset all
if (chart) { // it may be destroyed on mouse up - #877
css(chart.container, {
cursor: chart._cursor
});
chart.cancelClick = this.hasDragged > 10; // #370
chart.mouseIsDown = this.hasDragged = this.hasPinched = false;
this.pinchDown = [];
}
},
onContainerMouseDown: function(e) {
e = this.normalize(e);
this.zoomOption();
// issue #295, dragging not always working in Firefox
if (e.preventDefault) {
e.preventDefault();
}
this.dragStart(e);
},
onDocumentMouseUp: function(e) {
if (charts[H.hoverChartIndex]) {
charts[H.hoverChartIndex].pointer.drop(e);
}
},
/**
* Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea.
* Issue #149 workaround. The mouseleave event does not always fire.
*/
onDocumentMouseMove: function(e) {
var chart = this.chart,
chartPosition = this.chartPosition;
e = this.normalize(e, chartPosition);
// If we're outside, hide the tooltip
if (chartPosition && !this.inClass(e.target, 'highcharts-tracker') &&
!chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
this.reset();
}
},
/**
* When mouse leaves the container, hide the tooltip.
*/
onContainerMouseLeave: function(e) {
var chart = charts[H.hoverChartIndex];
if (chart && (e.relatedTarget || e.toElement)) { // #4886, MS Touch end fires mouseleave but with no related target
chart.pointer.reset();
chart.pointer.chartPosition = null; // also reset the chart position, used in #149 fix
}
},
// The mousemove, touchmove and touchstart event handler
onContainerMouseMove: function(e) {
var chart = this.chart;
if (!defined(H.hoverChartIndex) || !charts[H.hoverChartIndex] || !charts[H.hoverChartIndex].mouseIsDown) {
H.hoverChartIndex = chart.index;
}
e = this.normalize(e);
e.returnValue = false; // #2251, #3224
if (chart.mouseIsDown === 'mousedown') {
this.drag(e);
}
// Show the tooltip and run mouse over events (#977)
if ((this.inClass(e.target, 'highcharts-tracker') ||
chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) {
this.runPointActions(e);
}
},
/**
* Utility to detect whether an element has, or has a parent with, a specific
* class name. Used on detection of tracker objects and on deciding whether
* hovering the tooltip should cause the active series to mouse out.
*/
inClass: function(element, className) {
var elemClassName;
while (element) {
elemClassName = attr(element, 'class');
if (elemClassName) {
if (elemClassName.indexOf(className) !== -1) {
return true;
}
if (elemClassName.indexOf('highcharts-container') !== -1) {
return false;
}
}
element = element.parentNode;
}
},
onTrackerMouseOut: function(e) {
var series = this.chart.hoverSeries,
relatedTarget = e.relatedTarget || e.toElement;
if (series && relatedTarget && !series.options.stickyTracking &&
!this.inClass(relatedTarget, 'highcharts-tooltip') &&
(!this.inClass(relatedTarget, 'highcharts-series-' + series.index) || // #2499, #4465
!this.inClass(relatedTarget, 'highcharts-tracker') // #5553
)
) {
series.onMouseOut();
}
},
onContainerClick: function(e) {
var chart = this.chart,
hoverPoint = chart.hoverPoint,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop;
e = this.normalize(e);
if (!chart.cancelClick) {
// On tracker click, fire the series and point events. #783, #1583
if (hoverPoint && this.inClass(e.target, 'highcharts-tracker')) {
// the series click event
fireEvent(hoverPoint.series, 'click', extend(e, {
point: hoverPoint
}));
// the point click event
if (chart.hoverPoint) { // it may be destroyed (#1844)
hoverPoint.firePointEvent('click', e);
}
// When clicking outside a tracker, fire a chart event
} else {
extend(e, this.getCoordinates(e));
// fire a click event in the chart
if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) {
fireEvent(chart, 'click', e);
}
}
}
},
/**
* Set the JS DOM events on the container and document. This method should contain
* a one-to-one assignment between methods and their handlers. Any advanced logic should
* be moved to the handler reflecting the event's name.
*/
setDOMEvents: function() {
var pointer = this,
container = pointer.chart.container;
container.onmousedown = function(e) {
pointer.onContainerMouseDown(e);
};
container.onmousemove = function(e) {
pointer.onContainerMouseMove(e);
};
container.onclick = function(e) {
pointer.onContainerClick(e);
};
addEvent(container, 'mouseleave', pointer.onContainerMouseLeave);
if (H.chartCount === 1) {
addEvent(doc, 'mouseup', pointer.onDocumentMouseUp);
}
if (H.hasTouch) {
container.ontouchstart = function(e) {
pointer.onContainerTouchStart(e);
};
container.ontouchmove = function(e) {
pointer.onContainerTouchMove(e);
};
if (H.chartCount === 1) {
addEvent(doc, 'touchend', pointer.onDocumentTouchEnd);
}
}
},
/**
* Destroys the Pointer object and disconnects DOM events.
*/
destroy: function() {
var prop;
removeEvent(this.chart.container, 'mouseleave', this.onContainerMouseLeave);
if (!H.chartCount) {
removeEvent(doc, 'mouseup', this.onDocumentMouseUp);
removeEvent(doc, 'touchend', this.onDocumentTouchEnd);
}
// memory and CPU leak
clearInterval(this.tooltipTimeout);
for (prop in this) {
this[prop] = null;
}
}
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var charts = H.charts,
each = H.each,
extend = H.extend,
map = H.map,
noop = H.noop,
pick = H.pick,
Pointer = H.Pointer;
/* Support for touch devices */
extend(Pointer.prototype, {
/**
* Run translation operations
*/
pinchTranslate: function(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) {
if (this.zoomHor || this.pinchHor) {
this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
}
if (this.zoomVert || this.pinchVert) {
this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
}
},
/**
* Run translation operations for each direction (horizontal and vertical) independently
*/
pinchTranslateDirection: function(horiz, pinchDown, touches, transform,
selectionMarker, clip, lastValidTouch, forcedScale) {
var chart = this.chart,
xy = horiz ? 'x' : 'y',
XY = horiz ? 'X' : 'Y',
sChartXY = 'chart' + XY,
wh = horiz ? 'width' : 'height',
plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')],
selectionWH,
selectionXY,
clipXY,
scale = forcedScale || 1,
inverted = chart.inverted,
bounds = chart.bounds[horiz ? 'h' : 'v'],
singleTouch = pinchDown.length === 1,
touch0Start = pinchDown[0][sChartXY],
touch0Now = touches[0][sChartXY],
touch1Start = !singleTouch && pinchDown[1][sChartXY],
touch1Now = !singleTouch && touches[1][sChartXY],
outOfBounds,
transformScale,
scaleKey,
setScale = function() {
// Don't zoom if fingers are too close on this axis
if (!singleTouch && Math.abs(touch0Start - touch1Start) > 20) {
scale = forcedScale || Math.abs(touch0Now - touch1Now) / Math.abs(touch0Start - touch1Start);
}
clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start;
selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale;
};
// Set the scale, first pass
setScale();
selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not
// Out of bounds
if (selectionXY < bounds.min) {
selectionXY = bounds.min;
outOfBounds = true;
} else if (selectionXY + selectionWH > bounds.max) {
selectionXY = bounds.max - selectionWH;
outOfBounds = true;
}
// Is the chart dragged off its bounds, determined by dataMin and dataMax?
if (outOfBounds) {
// Modify the touchNow position in order to create an elastic drag movement. This indicates
// to the user that the chart is responsive but can't be dragged further.
touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]);
if (!singleTouch) {
touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]);
}
// Set the scale, second pass to adapt to the modified touchNow positions
setScale();
} else {
lastValidTouch[xy] = [touch0Now, touch1Now];
}
// Set geometry for clipping, selection and transformation
if (!inverted) {
clip[xy] = clipXY - plotLeftTop;
clip[wh] = selectionWH;
}
scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY;
transformScale = inverted ? 1 / scale : scale;
selectionMarker[wh] = selectionWH;
selectionMarker[xy] = selectionXY;
transform[scaleKey] = scale;
transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start));
},
/**
* Handle touch events with two touches
*/
pinch: function(e) {
var self = this,
chart = self.chart,
pinchDown = self.pinchDown,
touches = e.touches,
touchesLength = touches.length,
lastValidTouch = self.lastValidTouch,
hasZoom = self.hasZoom,
selectionMarker = self.selectionMarker,
transform = {},
fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, 'highcharts-tracker') &&
chart.runTrackerClick) || self.runChartClick),
clip = {};
// Don't initiate panning until the user has pinched. This prevents us from
// blocking page scrolling as users scroll down a long page (#4210).
if (touchesLength > 1) {
self.initiated = true;
}
// On touch devices, only proceed to trigger click if a handler is defined
if (hasZoom && self.initiated && !fireClickEvent) {
e.preventDefault();
}
// Normalize each touch
map(touches, function(e) {
return self.normalize(e);
});
// Register the touch start position
if (e.type === 'touchstart') {
each(touches, function(e, i) {
pinchDown[i] = {
chartX: e.chartX,
chartY: e.chartY
};
});
lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX];
lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY];
// Identify the data bounds in pixels
each(chart.axes, function(axis) {
if (axis.zoomEnabled) {
var bounds = chart.bounds[axis.horiz ? 'h' : 'v'],
minPixelPadding = axis.minPixelPadding,
min = axis.toPixels(pick(axis.options.min, axis.dataMin)),
max = axis.toPixels(pick(axis.options.max, axis.dataMax)),
absMin = Math.min(min, max),
absMax = Math.max(min, max);
// Store the bounds for use in the touchmove handler
bounds.min = Math.min(axis.pos, absMin - minPixelPadding);
bounds.max = Math.max(axis.pos + axis.len, absMax + minPixelPadding);
}
});
self.res = true; // reset on next move
// Event type is touchmove, handle panning and pinching
} else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first
// Set the marker
if (!selectionMarker) {
self.selectionMarker = selectionMarker = extend({
destroy: noop,
touch: true
}, chart.plotBox);
}
self.pinchTranslate(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
self.hasPinched = hasZoom;
// Scale and translate the groups to provide visual feedback during pinching
self.scaleGroups(transform, clip);
// Optionally move the tooltip on touchmove
if (!hasZoom && self.followTouchMove && touchesLength === 1) {
this.runPointActions(self.normalize(e));
} else if (self.res) {
self.res = false;
this.reset(false, 0);
}
}
},
/**
* General touch handler shared by touchstart and touchmove.
*/
touch: function(e, start) {
var chart = this.chart,
hasMoved,
pinchDown;
H.hoverChartIndex = chart.index;
if (e.touches.length === 1) {
e = this.normalize(e);
if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop) && !chart.openMenu) {
// Run mouse events and display tooltip etc
if (start) {
this.runPointActions(e);
}
// Android fires touchmove events after the touchstart even if the
// finger hasn't moved, or moved only a pixel or two. In iOS however,
// the touchmove doesn't fire unless the finger moves more than ~4px.
// So we emulate this behaviour in Android by checking how much it
// moved, and cancelling on small distances. #3450.
if (e.type === 'touchmove') {
pinchDown = this.pinchDown;
hasMoved = pinchDown[0] ? Math.sqrt( // #5266
Math.pow(pinchDown[0].chartX - e.chartX, 2) +
Math.pow(pinchDown[0].chartY - e.chartY, 2)
) >= 4 : false;
}
if (pick(hasMoved, true)) {
this.pinch(e);
}
} else if (start) {
// Hide the tooltip on touching outside the plot area (#1203)
this.reset();
}
} else if (e.touches.length === 2) {
this.pinch(e);
}
},
onContainerTouchStart: function(e) {
this.zoomOption();
this.touch(e, true);
},
onContainerTouchMove: function(e) {
this.touch(e);
},
onDocumentTouchEnd: function(e) {
if (charts[H.hoverChartIndex]) {
charts[H.hoverChartIndex].pointer.drop(e);
}
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
charts = H.charts,
css = H.css,
doc = H.doc,
extend = H.extend,
noop = H.noop,
Pointer = H.Pointer,
removeEvent = H.removeEvent,
win = H.win,
wrap = H.wrap;
if (win.PointerEvent || win.MSPointerEvent) {
// The touches object keeps track of the points being touched at all times
var touches = {},
hasPointerEvent = !!win.PointerEvent,
getWebkitTouches = function() {
var key,
fake = [];
fake.item = function(i) {
return this[i];
};
for (key in touches) {
if (touches.hasOwnProperty(key)) {
fake.push({
pageX: touches[key].pageX,
pageY: touches[key].pageY,
target: touches[key].target
});
}
}
return fake;
},
translateMSPointer = function(e, method, wktype, func) {
var p;
if ((e.pointerType === 'touch' || e.pointerType === e.MSPOINTER_TYPE_TOUCH) && charts[H.hoverChartIndex]) {
func(e);
p = charts[H.hoverChartIndex].pointer;
p[method]({
type: wktype,
target: e.currentTarget,
preventDefault: noop,
touches: getWebkitTouches()
});
}
};
/**
* Extend the Pointer prototype with methods for each event handler and more
*/
extend(Pointer.prototype, {
onContainerPointerDown: function(e) {
translateMSPointer(e, 'onContainerTouchStart', 'touchstart', function(e) {
touches[e.pointerId] = {
pageX: e.pageX,
pageY: e.pageY,
target: e.currentTarget
};
});
},
onContainerPointerMove: function(e) {
translateMSPointer(e, 'onContainerTouchMove', 'touchmove', function(e) {
touches[e.pointerId] = {
pageX: e.pageX,
pageY: e.pageY
};
if (!touches[e.pointerId].target) {
touches[e.pointerId].target = e.currentTarget;
}
});
},
onDocumentPointerUp: function(e) {
translateMSPointer(e, 'onDocumentTouchEnd', 'touchend', function(e) {
delete touches[e.pointerId];
});
},
/**
* Add or remove the MS Pointer specific events
*/
batchMSEvents: function(fn) {
fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown);
fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove);
fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp);
}
});
// Disable default IE actions for pinch and such on chart element
wrap(Pointer.prototype, 'init', function(proceed, chart, options) {
proceed.call(this, chart, options);
if (this.hasZoom) { // #4014
css(chart.container, {
'-ms-touch-action': 'none',
'touch-action': 'none'
});
}
});
// Add IE specific touch events to chart
wrap(Pointer.prototype, 'setDOMEvents', function(proceed) {
proceed.apply(this);
if (this.hasZoom || this.followTouchMove) {
this.batchMSEvents(addEvent);
}
});
// Destroy MS events also
wrap(Pointer.prototype, 'destroy', function(proceed) {
this.batchMSEvents(removeEvent);
proceed.call(this);
});
}
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Legend,
addEvent = H.addEvent,
css = H.css,
discardElement = H.discardElement,
defined = H.defined,
each = H.each,
extend = H.extend,
isFirefox = H.isFirefox,
marginNames = H.marginNames,
merge = H.merge,
pick = H.pick,
setAnimation = H.setAnimation,
stableSort = H.stableSort,
win = H.win,
wrap = H.wrap;
/**
* The overview of the chart's series
*/
Legend = H.Legend = function(chart, options) {
this.init(chart, options);
};
Legend.prototype = {
/**
* Initialize the legend
*/
init: function(chart, options) {
this.chart = chart;
this.setOptions(options);
if (options.enabled) {
// Render it
this.render();
// move checkboxes
addEvent(this.chart, 'endResize', function() {
this.legend.positionCheckboxes();
});
}
},
setOptions: function(options) {
var padding = pick(options.padding, 8);
this.options = options;
this.itemMarginTop = options.itemMarginTop || 0;
this.padding = padding;
this.initialItemX = padding;
this.initialItemY = padding - 5; // 5 is the number of pixels above the text
this.maxItemWidth = 0;
this.itemHeight = 0;
this.symbolWidth = pick(options.symbolWidth, 16);
this.pages = [];
},
/**
* Update the legend with new options. Equivalent to running chart.update with a legend
* configuration option.
* @param {Object} options Legend options
* @param {Boolean} redraw Whether to redraw the chart, defaults to true.
*/
update: function(options, redraw) {
var chart = this.chart;
this.setOptions(merge(true, this.options, options));
this.destroy();
chart.isDirtyLegend = chart.isDirtyBox = true;
if (pick(redraw, true)) {
chart.redraw();
}
},
/**
* Set the colors for the legend item
* @param {Object} item A Series or Point instance
* @param {Object} visible Dimmed or colored
*/
colorizeItem: function(item, visible) {
item.legendGroup[visible ? 'removeClass' : 'addClass']('highcharts-legend-item-hidden');
},
/**
* Position the legend item
* @param {Object} item A Series or Point instance
*/
positionItem: function(item) {
var legend = this,
options = legend.options,
symbolPadding = options.symbolPadding,
ltr = !options.rtl,
legendItemPos = item._legendItemPos,
itemX = legendItemPos[0],
itemY = legendItemPos[1],
checkbox = item.checkbox,
legendGroup = item.legendGroup;
if (legendGroup && legendGroup.element) {
legendGroup.translate(
ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4,
itemY
);
}
if (checkbox) {
checkbox.x = itemX;
checkbox.y = itemY;
}
},
/**
* Destroy a single legend item
* @param {Object} item The series or point
*/
destroyItem: function(item) {
var checkbox = item.checkbox;
// destroy SVG elements
each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function(key) {
if (item[key]) {
item[key] = item[key].destroy();
}
});
if (checkbox) {
discardElement(item.checkbox);
}
},
/**
* Destroys the legend.
*/
destroy: function() {
var legend = this,
legendGroup = legend.group,
box = legend.box;
if (box) {
legend.box = box.destroy();
}
// Destroy items
each(this.getAllItems(), function(item) {
each(['legendItem', 'legendGroup'], function(key) {
if (item[key]) {
item[key] = item[key].destroy();
}
});
});
if (legendGroup) {
legend.group = legendGroup.destroy();
}
},
/**
* Position the checkboxes after the width is determined
*/
positionCheckboxes: function(scrollOffset) {
var alignAttr = this.group.alignAttr,
translateY,
clipHeight = this.clipHeight || this.legendHeight,
titleHeight = this.titleHeight;
if (alignAttr) {
translateY = alignAttr.translateY;
each(this.allItems, function(item) {
var checkbox = item.checkbox,
top;
if (checkbox) {
top = translateY + titleHeight + checkbox.y + (scrollOffset || 0) + 3;
css(checkbox, {
left: (alignAttr.translateX + item.checkboxOffset + checkbox.x - 20) + 'px',
top: top + 'px',
display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : 'none'
});
}
});
}
},
/**
* Render the legend title on top of the legend
*/
renderTitle: function() {
var options = this.options,
padding = this.padding,
titleOptions = options.title,
titleHeight = 0,
bBox;
if (titleOptions.text) {
if (!this.title) {
this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title')
.attr({
zIndex: 1
})
.add(this.group);
}
bBox = this.title.getBBox();
titleHeight = bBox.height;
this.offsetWidth = bBox.width; // #1717
this.contentGroup.attr({
translateY: titleHeight
});
}
this.titleHeight = titleHeight;
},
/**
* Set the legend item text
*/
setText: function(item) {
var options = this.options;
item.legendItem.attr({
text: options.labelFormat ? H.format(options.labelFormat, item) : options.labelFormatter.call(item)
});
},
/**
* Render a single specific legend item
* @param {Object} item A series or point
*/
renderItem: function(item) {
var legend = this,
chart = legend.chart,
renderer = chart.renderer,
options = legend.options,
horizontal = options.layout === 'horizontal',
symbolWidth = legend.symbolWidth,
symbolPadding = options.symbolPadding,
padding = legend.padding,
itemDistance = horizontal ? pick(options.itemDistance, 20) : 0,
ltr = !options.rtl,
itemHeight,
widthOption = options.width,
itemMarginBottom = options.itemMarginBottom || 0,
itemMarginTop = legend.itemMarginTop,
initialItemX = legend.initialItemX,
bBox,
itemWidth,
li = item.legendItem,
isSeries = !item.series,
series = !isSeries && item.series.drawLegendSymbol ? item.series : item,
seriesOptions = series.options,
showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.showCheckbox,
useHTML = options.useHTML,
fontSize = 12;
if (!li) { // generate it once, later move it
// Generate the group box
// A group to hold the symbol and text. Text is to be appended in Legend class.
item.legendGroup = renderer.g('legend-item')
.addClass('highcharts-' + series.type + '-series highcharts-color-' + item.colorIndex + ' ' +
(item.options.className || '') +
(isSeries ? 'highcharts-series-' + item.index : '')
)
.attr({
zIndex: 1
})
.add(legend.scrollGroup);
// Generate the list item text and add it to the group
item.legendItem = li = renderer.text(
'',
ltr ? symbolWidth + symbolPadding : -symbolPadding,
legend.baseline || 0,
useHTML
)
.attr({
align: ltr ? 'left' : 'right',
zIndex: 2
})
.add(item.legendGroup);
// Get the baseline for the first item - the font size is equal for all
if (!legend.baseline) {
legend.fontMetrics = renderer.fontMetrics(
fontSize,
li
);
legend.baseline = legend.fontMetrics.f + 3 + itemMarginTop;
li.attr('y', legend.baseline);
}
// Draw the legend symbol inside the group box
series.drawLegendSymbol(legend, item);
if (legend.setItemEvents) {
legend.setItemEvents(item, li, useHTML);
}
// add the HTML checkbox on top
if (showCheckbox) {
legend.createCheckboxForItem(item);
}
}
// Colorize the items
legend.colorizeItem(item, item.visible);
// Always update the text
legend.setText(item);
// calculate the positions for the next line
bBox = li.getBBox();
itemWidth = item.checkboxOffset =
options.itemWidth ||
item.legendItemWidth ||
symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0);
legend.itemHeight = itemHeight = Math.round(item.legendItemHeight || bBox.height);
// if the item exceeds the width, start a new line
if (horizontal && legend.itemX - initialItemX + itemWidth >
(widthOption || (chart.chartWidth - 2 * padding - initialItemX - options.x))) {
legend.itemX = initialItemX;
legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom;
legend.lastLineHeight = 0; // reset for next line (#915, #3976)
}
// If the item exceeds the height, start a new column
/*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) {
legend.itemY = legend.initialItemY;
legend.itemX += legend.maxItemWidth;
legend.maxItemWidth = 0;
}*/
// Set the edge positions
legend.maxItemWidth = Math.max(legend.maxItemWidth, itemWidth);
legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom;
legend.lastLineHeight = Math.max(itemHeight, legend.lastLineHeight); // #915
// cache the position of the newly generated or reordered items
item._legendItemPos = [legend.itemX, legend.itemY];
// advance
if (horizontal) {
legend.itemX += itemWidth;
} else {
legend.itemY += itemMarginTop + itemHeight + itemMarginBottom;
legend.lastLineHeight = itemHeight;
}
// the width of the widest item
legend.offsetWidth = widthOption || Math.max(
(horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding,
legend.offsetWidth
);
},
/**
* Get all items, which is one item per series for normal series and one item per point
* for pie series.
*/
getAllItems: function() {
var allItems = [];
each(this.chart.series, function(series) {
var seriesOptions = series && series.options;
// Handle showInLegend. If the series is linked to another series, defaults to false.
if (series && pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? undefined : false, true)) {
// Use points or series for the legend item depending on legendType
allItems = allItems.concat(
series.legendItems ||
(seriesOptions.legendType === 'point' ?
series.data :
series)
);
}
});
return allItems;
},
/**
* Adjust the chart margins by reserving space for the legend on only one side
* of the chart. If the position is set to a corner, top or bottom is reserved
* for horizontal legends and left or right for vertical ones.
*/
adjustMargins: function(margin, spacing) {
var chart = this.chart,
options = this.options,
// Use the first letter of each alignment option in order to detect the side
alignment = options.align.charAt(0) + options.verticalAlign.charAt(0) + options.layout.charAt(0); // #4189 - use charAt(x) notation instead of [x] for IE7
if (!options.floating) {
each([
/(lth|ct|rth)/,
/(rtv|rm|rbv)/,
/(rbh|cb|lbh)/,
/(lbv|lm|ltv)/
], function(alignments, side) {
if (alignments.test(alignment) && !defined(margin[side])) {
// Now we have detected on which side of the chart we should reserve space for the legend
chart[marginNames[side]] = Math.max(
chart[marginNames[side]],
chart.legend[(side + 1) % 2 ? 'legendHeight' : 'legendWidth'] + [1, -1, -1, 1][side] * options[(side % 2) ? 'x' : 'y'] +
pick(options.margin, 12) +
spacing[side]
);
}
});
}
},
/**
* Render the legend. This method can be called both before and after
* chart.render. If called after, it will only rearrange items instead
* of creating new ones.
*/
render: function() {
var legend = this,
chart = legend.chart,
renderer = chart.renderer,
legendGroup = legend.group,
allItems,
display,
legendWidth,
legendHeight,
box = legend.box,
options = legend.options,
padding = legend.padding;
legend.itemX = legend.initialItemX;
legend.itemY = legend.initialItemY;
legend.offsetWidth = 0;
legend.lastItemY = 0;
if (!legendGroup) {
legend.group = legendGroup = renderer.g('legend')
.attr({
zIndex: 7
})
.add();
legend.contentGroup = renderer.g()
.attr({
zIndex: 1
}) // above background
.add(legendGroup);
legend.scrollGroup = renderer.g()
.add(legend.contentGroup);
}
legend.renderTitle();
// add each series or point
allItems = legend.getAllItems();
// sort by legendIndex
stableSort(allItems, function(a, b) {
return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0);
});
// reversed legend
if (options.reversed) {
allItems.reverse();
}
legend.allItems = allItems;
legend.display = display = !!allItems.length;
// render the items
legend.lastLineHeight = 0;
each(allItems, function(item) {
legend.renderItem(item);
});
// Get the box
legendWidth = (options.width || legend.offsetWidth) + padding;
legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight;
legendHeight = legend.handleOverflow(legendHeight);
legendHeight += padding;
// Draw the border and/or background
if (!box) {
legend.box = box = renderer.rect()
.addClass('highcharts-legend-box')
.attr({
r: options.borderRadius
})
.add(legendGroup);
box.isNew = true;
}
if (legendWidth > 0 && legendHeight > 0) {
box[box.isNew ? 'attr' : 'animate'](
box.crisp({
x: 0,
y: 0,
width: legendWidth,
height: legendHeight
}, box.strokeWidth())
);
box.isNew = false;
}
// hide the border if no items
box[display ? 'show' : 'hide']();
// Open for responsiveness
if (legendGroup.getStyle('display') === 'none') {
legendWidth = legendHeight = 0;
}
legend.legendWidth = legendWidth;
legend.legendHeight = legendHeight;
// Now that the legend width and height are established, put the items in the
// final position
each(allItems, function(item) {
legend.positionItem(item);
});
// 1.x compatibility: positioning based on style
/*var props = ['left', 'right', 'top', 'bottom'],
prop,
i = 4;
while (i--) {
prop = props[i];
if (options.style[prop] && options.style[prop] !== 'auto') {
options[i < 2 ? 'align' : 'verticalAlign'] = prop;
options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1);
}
}*/
if (display) {
legendGroup.align(extend({
width: legendWidth,
height: legendHeight
}, options), true, 'spacingBox');
}
if (!chart.isResizing) {
this.positionCheckboxes();
}
},
/**
* Set up the overflow handling by adding navigation with up and down arrows below the
* legend.
*/
handleOverflow: function(legendHeight) {
var legend = this,
chart = this.chart,
renderer = chart.renderer,
options = this.options,
optionsY = options.y,
alignTop = options.verticalAlign === 'top',
spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding,
maxHeight = options.maxHeight,
clipHeight,
clipRect = this.clipRect,
navOptions = options.navigation,
animation = pick(navOptions.animation, true),
arrowSize = navOptions.arrowSize || 12,
nav = this.nav,
pages = this.pages,
padding = this.padding,
lastY,
allItems = this.allItems,
clipToHeight = function(height) {
clipRect.attr({
height: height
});
// useHTML
if (legend.contentGroup.div) {
legend.contentGroup.div.style.clip = 'rect(' + padding + 'px,9999px,' + (padding + height) + 'px,0)';
}
};
// Adjust the height
if (options.layout === 'horizontal') {
spaceHeight /= 2;
}
if (maxHeight) {
spaceHeight = Math.min(spaceHeight, maxHeight);
}
// Reset the legend height and adjust the clipping rectangle
pages.length = 0;
if (legendHeight > spaceHeight && navOptions.enabled !== false) {
this.clipHeight = clipHeight = Math.max(spaceHeight - 20 - this.titleHeight - padding, 0);
this.currentPage = pick(this.currentPage, 1);
this.fullHeight = legendHeight;
// Fill pages with Y positions so that the top of each a legend item defines
// the scroll top for each page (#2098)
each(allItems, function(item, i) {
var y = item._legendItemPos[1],
h = Math.round(item.legendItem.getBBox().height),
len = pages.length;
if (!len || (y - pages[len - 1] > clipHeight && (lastY || y) !== pages[len - 1])) {
pages.push(lastY || y);
len++;
}
if (i === allItems.length - 1 && y + h - pages[len - 1] > clipHeight) {
pages.push(y);
}
if (y !== lastY) {
lastY = y;
}
});
// Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787)
if (!clipRect) {
clipRect = legend.clipRect = renderer.clipRect(0, padding, 9999, 0);
legend.contentGroup.clip(clipRect);
}
clipToHeight(clipHeight);
// Add navigation elements
if (!nav) {
this.nav = nav = renderer.g().attr({
zIndex: 1
}).add(this.group);
this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize)
.on('click', function() {
legend.scroll(-1, animation);
})
.add(nav);
this.pager = renderer.text('', 15, 10)
.addClass('highcharts-legend-navigation')
.add(nav);
this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize)
.on('click', function() {
legend.scroll(1, animation);
})
.add(nav);
}
// Set initial position
legend.scroll(0);
legendHeight = spaceHeight;
} else if (nav) {
clipToHeight(chart.chartHeight);
nav.hide();
this.scrollGroup.attr({
translateY: 1
});
this.clipHeight = 0; // #1379
}
return legendHeight;
},
/**
* Scroll the legend by a number of pages
* @param {Object} scrollBy
* @param {Object} animation
*/
scroll: function(scrollBy, animation) {
var pages = this.pages,
pageCount = pages.length,
currentPage = this.currentPage + scrollBy,
clipHeight = this.clipHeight,
navOptions = this.options.navigation,
pager = this.pager,
padding = this.padding,
scrollOffset;
// When resizing while looking at the last page
if (currentPage > pageCount) {
currentPage = pageCount;
}
if (currentPage > 0) {
if (animation !== undefined) {
setAnimation(animation, this.chart);
}
this.nav.attr({
translateX: padding,
translateY: clipHeight + this.padding + 7 + this.titleHeight,
visibility: 'visible'
});
this.up.attr({
'class': currentPage === 1 ? 'highcharts-legend-nav-inactive' : 'highcharts-legend-nav-active'
});
pager.attr({
text: currentPage + '/' + pageCount
});
this.down.attr({
'x': 18 + this.pager.getBBox().width, // adjust to text width
'class': currentPage === pageCount ? 'highcharts-legend-nav-inactive' : 'highcharts-legend-nav-active'
});
scrollOffset = -pages[currentPage - 1] + this.initialItemY;
this.scrollGroup.animate({
translateY: scrollOffset
});
this.currentPage = currentPage;
this.positionCheckboxes(scrollOffset);
}
}
};
/*
* LegendSymbolMixin
*/
H.LegendSymbolMixin = {
/**
* Get the series' symbol in the legend
*
* @param {Object} legend The legend object
* @param {Object} item The series (this) or point
*/
drawRectangle: function(legend, item) {
var options = legend.options,
symbolHeight = options.symbolHeight || legend.fontMetrics.f,
square = options.squareSymbol,
symbolWidth = square ? symbolHeight : legend.symbolWidth;
item.legendSymbol = this.chart.renderer.rect(
square ? (legend.symbolWidth - symbolHeight) / 2 : 0,
legend.baseline - symbolHeight + 1, // #3988
symbolWidth,
symbolHeight,
pick(legend.options.symbolRadius, symbolHeight / 2)
)
.addClass('highcharts-point')
.attr({
zIndex: 3
}).add(item.legendGroup);
},
/**
* Get the series' symbol in the legend. This method should be overridable to create custom
* symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols.
*
* @param {Object} legend The legend object
*/
drawLineMarker: function(legend) {
var options = this.options,
markerOptions = options.marker,
radius,
legendSymbol,
symbolWidth = legend.symbolWidth,
renderer = this.chart.renderer,
legendItemGroup = this.legendGroup,
verticalCenter = legend.baseline - Math.round(legend.fontMetrics.b * 0.3),
attr = {};
// Draw the line
this.legendLine = renderer.path([
'M',
0,
verticalCenter,
'L',
symbolWidth,
verticalCenter
])
.addClass('highcharts-graph')
.attr(attr)
.add(legendItemGroup);
// Draw the marker
if (markerOptions && markerOptions.enabled !== false) {
radius = this.symbol.indexOf('url') === 0 ? 0 : markerOptions.radius;
this.legendSymbol = legendSymbol = renderer.symbol(
this.symbol,
(symbolWidth / 2) - radius,
verticalCenter - radius,
2 * radius,
2 * radius,
markerOptions
)
.addClass('highcharts-point')
.add(legendItemGroup);
legendSymbol.isMarker = true;
}
}
};
// Workaround for #2030, horizontal legend items not displaying in IE11 Preview,
// and for #2580, a similar drawing flaw in Firefox 26.
// Explore if there's a general cause for this. The problem may be related
// to nested group elements, as the legend item texts are within 4 group elements.
if (/Trident\/7\.0/.test(win.navigator.userAgent) || isFirefox) {
wrap(Legend.prototype, 'positionItem', function(proceed, item) {
var legend = this,
runPositionItem = function() { // If chart destroyed in sync, this is undefined (#2030)
if (item._legendItemPos) {
proceed.call(legend, item);
}
};
// Do it now, for export and to get checkbox placement
runPositionItem();
// Do it after to work around the core issue
setTimeout(runPositionItem);
});
}
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
animate = H.animate,
animObject = H.animObject,
attr = H.attr,
doc = H.doc,
Axis = H.Axis, // @todo add as requirement
createElement = H.createElement,
defaultOptions = H.defaultOptions,
discardElement = H.discardElement,
charts = H.charts,
css = H.css,
defined = H.defined,
each = H.each,
error = H.error,
extend = H.extend,
fireEvent = H.fireEvent,
getStyle = H.getStyle,
grep = H.grep,
isNumber = H.isNumber,
isObject = H.isObject,
isString = H.isString,
Legend = H.Legend, // @todo add as requirement
marginNames = H.marginNames,
merge = H.merge,
Pointer = H.Pointer, // @todo add as requirement
pick = H.pick,
pInt = H.pInt,
removeEvent = H.removeEvent,
seriesTypes = H.seriesTypes,
splat = H.splat,
svg = H.svg,
syncTimeout = H.syncTimeout,
win = H.win,
Renderer = H.Renderer;
/**
* The Chart class
* @param {String|Object} renderTo The DOM element to render to, or its id
* @param {Object} options
* @param {Function} callback Function to run when the chart has loaded
*/
var Chart = H.Chart = function() {
this.getArgs.apply(this, arguments);
};
H.chart = function(a, b, c) {
return new Chart(a, b, c);
};
Chart.prototype = {
/**
* Hook for modules
*/
callbacks: [],
/**
* Handle the arguments passed to the constructor
* @returns {Array} Arguments without renderTo
*/
getArgs: function() {
var args = [].slice.call(arguments);
// Remove the optional first argument, renderTo, and
// set it on this.
if (isString(args[0]) || args[0].nodeName) {
this.renderTo = args.shift();
}
this.init(args[0], args[1]);
},
/**
* Initialize the chart
*/
init: function(userOptions, callback) {
// Handle regular options
var options,
seriesOptions = userOptions.series; // skip merging data points to increase performance
userOptions.series = null;
options = merge(defaultOptions, userOptions); // do the merge
options.series = userOptions.series = seriesOptions; // set back the series data
this.userOptions = userOptions;
this.respRules = [];
var optionsChart = options.chart;
var chartEvents = optionsChart.events;
this.margin = [];
this.spacing = [];
//this.runChartClick = chartEvents && !!chartEvents.click;
this.bounds = {
h: {},
v: {}
}; // Pixel data bounds for touch zoom
this.callback = callback;
this.isResizing = 0;
this.options = options;
//chartTitleOptions = undefined;
//chartSubtitleOptions = undefined;
this.axes = [];
this.series = [];
this.hasCartesianSeries = optionsChart.showAxes;
//this.axisOffset = undefined;
//this.inverted = undefined;
//this.loadingShown = undefined;
//this.container = undefined;
//this.chartWidth = undefined;
//this.chartHeight = undefined;
//this.marginRight = undefined;
//this.marginBottom = undefined;
//this.containerWidth = undefined;
//this.containerHeight = undefined;
//this.oldChartWidth = undefined;
//this.oldChartHeight = undefined;
//this.renderTo = undefined;
//this.renderToClone = undefined;
//this.spacingBox = undefined
//this.legend = undefined;
// Elements
//this.chartBackground = undefined;
//this.plotBackground = undefined;
//this.plotBGImage = undefined;
//this.plotBorder = undefined;
//this.loadingDiv = undefined;
//this.loadingSpan = undefined;
var chart = this,
eventType;
// Add the chart to the global lookup
chart.index = charts.length;
charts.push(chart);
H.chartCount++;
// Chart event handlers
if (chartEvents) {
for (eventType in chartEvents) {
addEvent(chart, eventType, chartEvents[eventType]);
}
}
chart.xAxis = [];
chart.yAxis = [];
chart.pointCount = chart.colorCounter = chart.symbolCounter = 0;
chart.firstRender();
},
/**
* Initialize an individual series, called internally before render time
*/
initSeries: function(options) {
var chart = this,
optionsChart = chart.options.chart,
type = options.type || optionsChart.type || optionsChart.defaultSeriesType,
series,
Constr = seriesTypes[type];
// No such series type
if (!Constr) {
error(17, true);
}
series = new Constr();
series.init(this, options);
return series;
},
/**
* Check whether a given point is within the plot area
*
* @param {Number} plotX Pixel x relative to the plot area
* @param {Number} plotY Pixel y relative to the plot area
* @param {Boolean} inverted Whether the chart is inverted
*/
isInsidePlot: function(plotX, plotY, inverted) {
var x = inverted ? plotY : plotX,
y = inverted ? plotX : plotY;
return x >= 0 &&
x <= this.plotWidth &&
y >= 0 &&
y <= this.plotHeight;
},
/**
* Redraw legend, axes or series based on updated data
*
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
redraw: function(animation) {
var chart = this,
axes = chart.axes,
series = chart.series,
pointer = chart.pointer,
legend = chart.legend,
redrawLegend = chart.isDirtyLegend,
hasStackedSeries,
hasDirtyStacks,
hasCartesianSeries = chart.hasCartesianSeries,
isDirtyBox = chart.isDirtyBox,
seriesLength = series.length,
i = seriesLength,
serie,
renderer = chart.renderer,
isHiddenChart = renderer.isHidden(),
afterRedraw = [];
H.setAnimation(animation, chart);
if (isHiddenChart) {
chart.cloneRenderTo();
}
// Adjust title layout (reflow multiline text)
chart.layOutTitles();
// link stacked series
while (i--) {
serie = series[i];
if (serie.options.stacking) {
hasStackedSeries = true;
if (serie.isDirty) {
hasDirtyStacks = true;
break;
}
}
}
if (hasDirtyStacks) { // mark others as dirty
i = seriesLength;
while (i--) {
serie = series[i];
if (serie.options.stacking) {
serie.isDirty = true;
}
}
}
// Handle updated data in the series
each(series, function(serie) {
if (serie.isDirty) {
if (serie.options.legendType === 'point') {
if (serie.updateTotals) {
serie.updateTotals();
}
redrawLegend = true;
}
}
if (serie.isDirtyData) {
fireEvent(serie, 'updatedData');
}
});
// handle added or removed series
if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed
// draw legend graphics
legend.render();
chart.isDirtyLegend = false;
}
// reset stacks
if (hasStackedSeries) {
chart.getStacks();
}
if (hasCartesianSeries) {
// set axes scales
each(axes, function(axis) {
axis.updateNames();
axis.setScale();
});
}
chart.getMargins(); // #3098
if (hasCartesianSeries) {
// If one axis is dirty, all axes must be redrawn (#792, #2169)
each(axes, function(axis) {
if (axis.isDirty) {
isDirtyBox = true;
}
});
// redraw axes
each(axes, function(axis) {
// Fire 'afterSetExtremes' only if extremes are set
var key = axis.min + ',' + axis.max;
if (axis.extKey !== key) { // #821, #4452
axis.extKey = key;
afterRedraw.push(function() { // prevent a recursive call to chart.redraw() (#1119)
fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751
delete axis.eventArgs;
});
}
if (isDirtyBox || hasStackedSeries) {
axis.redraw();
}
});
}
// the plot areas size has changed
if (isDirtyBox) {
chart.drawChartBox();
}
// redraw affected series
each(series, function(serie) {
if ((isDirtyBox || serie.isDirty) && serie.visible) {
serie.redraw();
}
});
// move tooltip or reset
if (pointer) {
pointer.reset(true);
}
// redraw if canvas
renderer.draw();
// fire the event
fireEvent(chart, 'redraw');
if (isHiddenChart) {
chart.cloneRenderTo(true);
}
// Fire callbacks that are put on hold until after the redraw
each(afterRedraw, function(callback) {
callback.call();
});
},
/**
* Get an axis, series or point object by id.
* @param id {String} The id as given in the configuration options
*/
get: function(id) {
var chart = this,
axes = chart.axes,
series = chart.series;
var i,
j,
points;
// search axes
for (i = 0; i < axes.length; i++) {
if (axes[i].options.id === id) {
return axes[i];
}
}
// search series
for (i = 0; i < series.length; i++) {
if (series[i].options.id === id) {
return series[i];
}
}
// search points
for (i = 0; i < series.length; i++) {
points = series[i].points || [];
for (j = 0; j < points.length; j++) {
if (points[j].id === id) {
return points[j];
}
}
}
return null;
},
/**
* Create the Axis instances based on the config options
*/
getAxes: function() {
var chart = this,
options = this.options,
xAxisOptions = options.xAxis = splat(options.xAxis || {}),
yAxisOptions = options.yAxis = splat(options.yAxis || {}),
optionsArray;
// make sure the options are arrays and add some members
each(xAxisOptions, function(axis, i) {
axis.index = i;
axis.isX = true;
});
each(yAxisOptions, function(axis, i) {
axis.index = i;
});
// concatenate all axis options into one array
optionsArray = xAxisOptions.concat(yAxisOptions);
each(optionsArray, function(axisOptions) {
new Axis(chart, axisOptions); // eslint-disable-line no-new
});
},
/**
* Get the currently selected points from all series
*/
getSelectedPoints: function() {
var points = [];
each(this.series, function(serie) {
points = points.concat(grep(serie.points || [], function(point) {
return point.selected;
}));
});
return points;
},
/**
* Get the currently selected series
*/
getSelectedSeries: function() {
return grep(this.series, function(serie) {
return serie.selected;
});
},
/**
* Show the title and subtitle of the chart
*
* @param titleOptions {Object} New title options
* @param subtitleOptions {Object} New subtitle options
*
*/
setTitle: function(titleOptions, subtitleOptions, redraw) {
var chart = this,
options = chart.options,
chartTitleOptions,
chartSubtitleOptions;
chartTitleOptions = options.title = merge(options.title, titleOptions);
chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions);
// add title and subtitle
each([
['title', titleOptions, chartTitleOptions],
['subtitle', subtitleOptions, chartSubtitleOptions]
], function(arr, i) {
var name = arr[0],
title = chart[name],
titleOptions = arr[1],
chartTitleOptions = arr[2];
if (title && titleOptions) {
chart[name] = title = title.destroy(); // remove old
}
if (chartTitleOptions && chartTitleOptions.text && !title) {
chart[name] = chart.renderer.text(
chartTitleOptions.text,
0,
0,
chartTitleOptions.useHTML
)
.attr({
align: chartTitleOptions.align,
'class': 'highcharts-' + name,
zIndex: chartTitleOptions.zIndex || 4
})
.add();
// Update methods, shortcut to Chart.setTitle
chart[name].update = function(o) {
chart.setTitle(!i && o, i && o);
};
}
});
chart.layOutTitles(redraw);
},
/**
* Lay out the chart titles and cache the full offset height for use in getMargins
*/
layOutTitles: function(redraw) {
var titleOffset = 0,
requiresDirtyBox,
renderer = this.renderer,
spacingBox = this.spacingBox;
// Lay out the title and the subtitle respectively
each(['title', 'subtitle'], function(key) {
var title = this[key],
titleOptions = this.options[key],
titleSize;
if (title) {
titleSize = renderer.fontMetrics(titleSize, title).b;
title
.css({
width: (titleOptions.width || spacingBox.width + titleOptions.widthAdjust) + 'px'
})
.align(extend({
y: titleOffset + titleSize + (key === 'title' ? -3 : 2)
}, titleOptions), false, 'spacingBox');
if (!titleOptions.floating && !titleOptions.verticalAlign) {
titleOffset = Math.ceil(titleOffset + title.getBBox().height);
}
}
}, this);
requiresDirtyBox = this.titleOffset !== titleOffset;
this.titleOffset = titleOffset; // used in getMargins
if (!this.isDirtyBox && requiresDirtyBox) {
this.isDirtyBox = requiresDirtyBox;
// Redraw if necessary (#2719, #2744)
if (this.hasRendered && pick(redraw, true) && this.isDirtyBox) {
this.redraw();
}
}
},
/**
* Get chart width and height according to options and container size
*/
getChartSize: function() {
var chart = this,
optionsChart = chart.options.chart,
widthOption = optionsChart.width,
heightOption = optionsChart.height,
renderTo = chart.renderToClone || chart.renderTo;
// Get inner width and height
if (!defined(widthOption)) {
chart.containerWidth = getStyle(renderTo, 'width');
}
if (!defined(heightOption)) {
chart.containerHeight = getStyle(renderTo, 'height');
}
chart.chartWidth = Math.max(0, widthOption || chart.containerWidth || 600); // #1393, 1460
chart.chartHeight = Math.max(0, pick(heightOption,
// the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7:
chart.containerHeight > 19 ? chart.containerHeight : 400));
},
/**
* Create a clone of the chart's renderTo div and place it outside the viewport to allow
* size computation on chart.render and chart.redraw
*/
cloneRenderTo: function(revert) {
var clone = this.renderToClone,
container = this.container;
// Destroy the clone and bring the container back to the real renderTo div
if (revert) {
if (clone) {
while (clone.childNodes.length) { // #5231
this.renderTo.appendChild(clone.firstChild);
}
discardElement(clone);
delete this.renderToClone;
}
// Set up the clone
} else {
if (container && container.parentNode === this.renderTo) {
this.renderTo.removeChild(container); // do not clone this
}
this.renderToClone = clone = this.renderTo.cloneNode(0);
css(clone, {
position: 'absolute',
top: '-9999px',
display: 'block' // #833
});
if (clone.style.setProperty) { // #2631
clone.style.setProperty('display', 'block', 'important');
}
doc.body.appendChild(clone);
if (container) {
clone.appendChild(container);
}
}
},
/**
* Setter for the chart class name
*/
setClassName: function(className) {
this.container.className = 'highcharts-container ' + (className || '');
},
/**
* Get the containing element, determine the size and create the inner container
* div to hold the chart
*/
getContainer: function() {
var chart = this,
container,
options = chart.options,
optionsChart = options.chart,
chartWidth,
chartHeight,
renderTo = chart.renderTo,
indexAttrName = 'data-highcharts-chart',
oldChartIndex,
Ren,
containerId = 'highcharts-' + H.idCounter++,
containerStyle,
key;
if (!renderTo) {
chart.renderTo = renderTo = optionsChart.renderTo;
}
if (isString(renderTo)) {
chart.renderTo = renderTo = doc.getElementById(renderTo);
}
// Display an error if the renderTo is wrong
if (!renderTo) {
error(13, true);
}
// If the container already holds a chart, destroy it. The check for hasRendered is there
// because web pages that are saved to disk from the browser, will preserve the data-highcharts-chart
// attribute and the SVG contents, but not an interactive chart. So in this case,
// charts[oldChartIndex] will point to the wrong chart if any (#2609).
oldChartIndex = pInt(attr(renderTo, indexAttrName));
if (isNumber(oldChartIndex) && charts[oldChartIndex] && charts[oldChartIndex].hasRendered) {
charts[oldChartIndex].destroy();
}
// Make a reference to the chart from the div
attr(renderTo, indexAttrName, chart.index);
// remove previous chart
renderTo.innerHTML = '';
// If the container doesn't have an offsetWidth, it has or is a child of a node
// that has display:none. We need to temporarily move it out to a visible
// state to determine the size, else the legend and tooltips won't render
// properly. The allowClone option is used in sparklines as a micro optimization,
// saving about 1-2 ms each chart.
if (!optionsChart.skipClone && !renderTo.offsetWidth) {
chart.cloneRenderTo();
}
// get the width and height
chart.getChartSize();
chartWidth = chart.chartWidth;
chartHeight = chart.chartHeight;
// Create the inner container
chart.container = container = createElement(
'div', {
id: containerId
},
containerStyle,
chart.renderToClone || renderTo
);
// cache the cursor (#1650)
chart._cursor = container.style.cursor;
// Initialize the renderer
Ren = H[optionsChart.renderer] || Renderer;
chart.renderer = new Ren(
container,
chartWidth,
chartHeight,
null,
optionsChart.forExport,
options.exporting && options.exporting.allowHTML
);
chart.setClassName(optionsChart.className);
// Initialize definitions
for (key in options.defs) {
this.renderer.definition(options.defs[key]);
}
// Add a reference to the charts index
chart.renderer.chartIndex = chart.index;
},
/**
* Calculate margins by rendering axis labels in a preliminary position. Title,
* subtitle and legend have already been rendered at this stage, but will be
* moved into their final positions
*/
getMargins: function(skipAxes) {
var chart = this,
spacing = chart.spacing,
margin = chart.margin,
titleOffset = chart.titleOffset;
chart.resetMargins();
// Adjust for title and subtitle
if (titleOffset && !defined(margin[0])) {
chart.plotTop = Math.max(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]);
}
// Adjust for legend
if (chart.legend.display) {
chart.legend.adjustMargins(margin, spacing);
}
// adjust for scroller
if (chart.extraBottomMargin) {
chart.marginBottom += chart.extraBottomMargin;
}
if (chart.extraTopMargin) {
chart.plotTop += chart.extraTopMargin;
}
if (!skipAxes) {
this.getAxisMargins();
}
},
getAxisMargins: function() {
var chart = this,
axisOffset = chart.axisOffset = [0, 0, 0, 0], // top, right, bottom, left
margin = chart.margin;
// pre-render axes to get labels offset width
if (chart.hasCartesianSeries) {
each(chart.axes, function(axis) {
if (axis.visible) {
axis.getOffset();
}
});
}
// Add the axis offsets
each(marginNames, function(m, side) {
if (!defined(margin[side])) {
chart[m] += axisOffset[side];
}
});
chart.setChartSize();
},
/**
* Resize the chart to its container if size is not explicitly set
*/
reflow: function(e) {
var chart = this,
optionsChart = chart.options.chart,
renderTo = chart.renderTo,
hasUserWidth = defined(optionsChart.width),
width = optionsChart.width || getStyle(renderTo, 'width'),
height = optionsChart.height || getStyle(renderTo, 'height'),
target = e ? e.target : win;
// Width and height checks for display:none. Target is doc in IE8 and Opera,
// win in Firefox, Chrome and IE9.
if (!hasUserWidth && !chart.isPrinting && width && height && (target === win || target === doc)) { // #1093
if (width !== chart.containerWidth || height !== chart.containerHeight) {
clearTimeout(chart.reflowTimeout);
// When called from window.resize, e is set, else it's called directly (#2224)
chart.reflowTimeout = syncTimeout(function() {
if (chart.container) { // It may have been destroyed in the meantime (#1257)
chart.setSize(undefined, undefined, false);
}
}, e ? 100 : 0);
}
chart.containerWidth = width;
chart.containerHeight = height;
}
},
/**
* Add the event handlers necessary for auto resizing
*/
initReflow: function() {
var chart = this,
reflow = function(e) {
chart.reflow(e);
};
addEvent(win, 'resize', reflow);
addEvent(chart, 'destroy', function() {
removeEvent(win, 'resize', reflow);
});
// The following will add listeners to re-fit the chart before and after
// printing (#2284). However it only works in WebKit. Should have worked
// in Firefox, but not supported in IE.
/*
if (win.matchMedia) {
win.matchMedia('print').addListener(function reflow() {
chart.reflow();
});
}
*/
},
/**
* Resize the chart to a given width and height
* @param {Number} width
* @param {Number} height
* @param {Object|Boolean} animation
*/
setSize: function(width, height, animation) {
var chart = this,
renderer = chart.renderer,
globalAnimation;
// Handle the isResizing counter
chart.isResizing += 1;
// set the animation for the current process
H.setAnimation(animation, chart);
chart.oldChartHeight = chart.chartHeight;
chart.oldChartWidth = chart.chartWidth;
if (width !== undefined) {
chart.options.chart.width = width;
}
if (height !== undefined) {
chart.options.chart.height = height;
}
chart.getChartSize();
// Resize the container with the global animation applied if enabled (#2503)
chart.setChartSize(true);
renderer.setSize(chart.chartWidth, chart.chartHeight, animation);
// handle axes
each(chart.axes, function(axis) {
axis.isDirty = true;
axis.setScale();
});
chart.isDirtyLegend = true; // force legend redraw
chart.isDirtyBox = true; // force redraw of plot and chart border
chart.layOutTitles(); // #2857
chart.getMargins();
if (chart.setResponsive) {
chart.setResponsive(false);
}
chart.redraw(animation);
chart.oldChartHeight = null;
fireEvent(chart, 'resize');
// Fire endResize and set isResizing back. If animation is disabled, fire without delay
syncTimeout(function() {
if (chart) {
fireEvent(chart, 'endResize', null, function() {
chart.isResizing -= 1;
});
}
}, animObject(globalAnimation).duration);
},
/**
* Set the public chart properties. This is done before and after the pre-render
* to determine margin sizes
*/
setChartSize: function(skipAxes) {
var chart = this,
inverted = chart.inverted,
renderer = chart.renderer,
chartWidth = chart.chartWidth,
chartHeight = chart.chartHeight,
optionsChart = chart.options.chart,
spacing = chart.spacing,
clipOffset = chart.clipOffset,
clipX,
clipY,
plotLeft,
plotTop,
plotWidth,
plotHeight,
plotBorderWidth;
chart.plotLeft = plotLeft = Math.round(chart.plotLeft);
chart.plotTop = plotTop = Math.round(chart.plotTop);
chart.plotWidth = plotWidth = Math.max(0, Math.round(chartWidth - plotLeft - chart.marginRight));
chart.plotHeight = plotHeight = Math.max(0, Math.round(chartHeight - plotTop - chart.marginBottom));
chart.plotSizeX = inverted ? plotHeight : plotWidth;
chart.plotSizeY = inverted ? plotWidth : plotHeight;
chart.plotBorderWidth = optionsChart.plotBorderWidth || 0;
// Set boxes used for alignment
chart.spacingBox = renderer.spacingBox = {
x: spacing[3],
y: spacing[0],
width: chartWidth - spacing[3] - spacing[1],
height: chartHeight - spacing[0] - spacing[2]
};
chart.plotBox = renderer.plotBox = {
x: plotLeft,
y: plotTop,
width: plotWidth,
height: plotHeight
};
plotBorderWidth = 2 * Math.floor(chart.plotBorderWidth / 2);
clipX = Math.ceil(Math.max(plotBorderWidth, clipOffset[3]) / 2);
clipY = Math.ceil(Math.max(plotBorderWidth, clipOffset[0]) / 2);
chart.clipBox = {
x: clipX,
y: clipY,
width: Math.floor(chart.plotSizeX - Math.max(plotBorderWidth, clipOffset[1]) / 2 - clipX),
height: Math.max(0, Math.floor(chart.plotSizeY - Math.max(plotBorderWidth, clipOffset[2]) / 2 - clipY))
};
if (!skipAxes) {
each(chart.axes, function(axis) {
axis.setAxisSize();
axis.setAxisTranslation();
});
}
},
/**
* Initial margins before auto size margins are applied
*/
resetMargins: function() {
var chart = this,
chartOptions = chart.options.chart;
// Create margin and spacing array
each(['margin', 'spacing'], function splashArrays(target) {
var value = chartOptions[target],
values = isObject(value) ? value : [value, value, value, value];
each(['Top', 'Right', 'Bottom', 'Left'], function(sideName, side) {
chart[target][side] = pick(chartOptions[target + sideName], values[side]);
});
});
// Set margin names like chart.plotTop, chart.plotLeft, chart.marginRight, chart.marginBottom.
each(marginNames, function(m, side) {
chart[m] = pick(chart.margin[side], chart.spacing[side]);
});
chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left
chart.clipOffset = [0, 0, 0, 0];
},
/**
* Draw the borders and backgrounds for chart and plot area
*/
drawChartBox: function() {
var chart = this,
optionsChart = chart.options.chart,
renderer = chart.renderer,
chartWidth = chart.chartWidth,
chartHeight = chart.chartHeight,
chartBackground = chart.chartBackground,
plotBackground = chart.plotBackground,
plotBorder = chart.plotBorder,
chartBorderWidth,
mgn,
bgAttr,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop,
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
plotBox = chart.plotBox,
clipRect = chart.clipRect,
clipBox = chart.clipBox,
verb = 'animate';
// Chart area
if (!chartBackground) {
chart.chartBackground = chartBackground = renderer.rect()
.addClass('highcharts-background')
.add();
verb = 'attr';
}
chartBorderWidth = mgn = chartBackground.strokeWidth();
chartBackground[verb]({
x: mgn / 2,
y: mgn / 2,
width: chartWidth - mgn - chartBorderWidth % 2,
height: chartHeight - mgn - chartBorderWidth % 2,
r: optionsChart.borderRadius
});
// Plot background
verb = 'animate';
if (!plotBackground) {
verb = 'attr';
chart.plotBackground = plotBackground = renderer.rect()
.addClass('highcharts-plot-background')
.add();
}
plotBackground[verb](plotBox);
// Plot clip
if (!clipRect) {
chart.clipRect = renderer.clipRect(clipBox);
} else {
clipRect.animate({
width: clipBox.width,
height: clipBox.height
});
}
// Plot area border
verb = 'animate';
if (!plotBorder) {
verb = 'attr';
chart.plotBorder = plotBorder = renderer.rect()
.addClass('highcharts-plot-border')
.attr({
zIndex: 1 // Above the grid
})
.add();
}
plotBorder[verb](plotBorder.crisp({
x: plotLeft,
y: plotTop,
width: plotWidth,
height: plotHeight
}, -plotBorder.strokeWidth())); //#3282 plotBorder should be negative;
// reset
chart.isDirtyBox = false;
},
/**
* Detect whether a certain chart property is needed based on inspecting its options
* and series. This mainly applies to the chart.inverted property, and in extensions to
* the chart.angular and chart.polar properties.
*/
propFromSeries: function() {
var chart = this,
optionsChart = chart.options.chart,
klass,
seriesOptions = chart.options.series,
i,
value;
each(['inverted', 'angular', 'polar'], function(key) {
// The default series type's class
klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType];
// Get the value from available chart-wide properties
value =
optionsChart[key] || // It is set in the options
(klass && klass.prototype[key]); // The default series class requires it
// 4. Check if any the chart's series require it
i = seriesOptions && seriesOptions.length;
while (!value && i--) {
klass = seriesTypes[seriesOptions[i].type];
if (klass && klass.prototype[key]) {
value = true;
}
}
// Set the chart property
chart[key] = value;
});
},
/**
* Link two or more series together. This is done initially from Chart.render,
* and after Chart.addSeries and Series.remove.
*/
linkSeries: function() {
var chart = this,
chartSeries = chart.series;
// Reset links
each(chartSeries, function(series) {
series.linkedSeries.length = 0;
});
// Apply new links
each(chartSeries, function(series) {
var linkedTo = series.options.linkedTo;
if (isString(linkedTo)) {
if (linkedTo === ':previous') {
linkedTo = chart.series[series.index - 1];
} else {
linkedTo = chart.get(linkedTo);
}
if (linkedTo && linkedTo.linkedParent !== series) { // #3341 avoid mutual linking
linkedTo.linkedSeries.push(series);
series.linkedParent = linkedTo;
series.visible = pick(series.options.visible, linkedTo.options.visible, series.visible); // #3879
}
}
});
},
/**
* Render series for the chart
*/
renderSeries: function() {
each(this.series, function(serie) {
serie.translate();
serie.render();
});
},
/**
* Render labels for the chart
*/
renderLabels: function() {
var chart = this,
labels = chart.options.labels;
if (labels.items) {
each(labels.items, function(label) {
var style = extend(labels.style, label.style),
x = pInt(style.left) + chart.plotLeft,
y = pInt(style.top) + chart.plotTop + 12;
// delete to prevent rewriting in IE
delete style.left;
delete style.top;
chart.renderer.text(
label.html,
x,
y
)
.attr({
zIndex: 2
})
.css(style)
.add();
});
}
},
/**
* Render all graphics for the chart
*/
render: function() {
var chart = this,
axes = chart.axes,
renderer = chart.renderer,
options = chart.options,
tempWidth,
tempHeight,
redoHorizontal,
redoVertical;
// Title
chart.setTitle();
// Legend
chart.legend = new Legend(chart, options.legend);
// Get stacks
if (chart.getStacks) {
chart.getStacks();
}
// Get chart margins
chart.getMargins(true);
chart.setChartSize();
// Record preliminary dimensions for later comparison
tempWidth = chart.plotWidth;
tempHeight = chart.plotHeight = chart.plotHeight - 21; // 21 is the most common correction for X axis labels
// Get margins by pre-rendering axes
each(axes, function(axis) {
axis.setScale();
});
chart.getAxisMargins();
// If the plot area size has changed significantly, calculate tick positions again
redoHorizontal = tempWidth / chart.plotWidth > 1.1;
redoVertical = tempHeight / chart.plotHeight > 1.05; // Height is more sensitive
if (redoHorizontal || redoVertical) {
each(axes, function(axis) {
if ((axis.horiz && redoHorizontal) || (!axis.horiz && redoVertical)) {
axis.setTickInterval(true); // update to reflect the new margins
}
});
chart.getMargins(); // second pass to check for new labels
}
// Draw the borders and backgrounds
chart.drawChartBox();
// Axes
if (chart.hasCartesianSeries) {
each(axes, function(axis) {
if (axis.visible) {
axis.render();
}
});
}
// The series
if (!chart.seriesGroup) {
chart.seriesGroup = renderer.g('series-group')
.attr({
zIndex: 3
})
.add();
}
chart.renderSeries();
// Labels
chart.renderLabels();
// Credits
chart.addCredits();
// Handle responsiveness
if (chart.setResponsive) {
chart.setResponsive();
}
// Set flag
chart.hasRendered = true;
},
/**
* Show chart credits based on config options
*/
addCredits: function(credits) {
var chart = this;
credits = merge(true, this.options.credits, credits);
if (credits.enabled && !this.credits) {
this.credits = this.renderer.text(
credits.text + (this.mapCredits || ''),
0,
0
)
.addClass('highcharts-credits')
.on('click', function() {
if (credits.href) {
win.location.href = credits.href;
}
})
.attr({
align: credits.position.align,
zIndex: 8
})
.add()
.align(credits.position);
// Dynamically update
this.credits.update = function(options) {
chart.credits = chart.credits.destroy();
chart.addCredits(options);
};
}
},
/**
* Clean up memory usage
*/
destroy: function() {
var chart = this,
axes = chart.axes,
series = chart.series,
container = chart.container,
i,
parentNode = container && container.parentNode;
// fire the chart.destoy event
fireEvent(chart, 'destroy');
// Delete the chart from charts lookup array
charts[chart.index] = undefined;
H.chartCount--;
chart.renderTo.removeAttribute('data-highcharts-chart');
// remove events
removeEvent(chart);
// ==== Destroy collections:
// Destroy axes
i = axes.length;
while (i--) {
axes[i] = axes[i].destroy();
}
// Destroy scroller & scroller series before destroying base series
if (this.scroller && this.scroller.destroy) {
this.scroller.destroy();
}
// Destroy each series
i = series.length;
while (i--) {
series[i] = series[i].destroy();
}
// ==== Destroy chart properties:
each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage',
'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer',
'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'
], function(name) {
var prop = chart[name];
if (prop && prop.destroy) {
chart[name] = prop.destroy();
}
});
// remove container and all SVG
if (container) { // can break in IE when destroyed before finished loading
container.innerHTML = '';
removeEvent(container);
if (parentNode) {
discardElement(container);
}
}
// clean it all up
for (i in chart) {
delete chart[i];
}
},
/**
* VML namespaces can't be added until after complete. Listening
* for Perini's doScroll hack is not enough.
*/
isReadyToRender: function() {
var chart = this;
// Note: win == win.top is required
if ((!svg && (win == win.top && doc.readyState !== 'complete'))) { // eslint-disable-line eqeqeq
doc.attachEvent('onreadystatechange', function() {
doc.detachEvent('onreadystatechange', chart.firstRender);
if (doc.readyState === 'complete') {
chart.firstRender();
}
});
return false;
}
return true;
},
/**
* Prepare for first rendering after all data are loaded
*/
firstRender: function() {
var chart = this,
options = chart.options;
// Check whether the chart is ready to render
if (!chart.isReadyToRender()) {
return;
}
// Create the container
chart.getContainer();
// Run an early event after the container and renderer are established
fireEvent(chart, 'init');
chart.resetMargins();
chart.setChartSize();
// Set the common chart properties (mainly invert) from the given series
chart.propFromSeries();
// get axes
chart.getAxes();
// Initialize the series
each(options.series || [], function(serieOptions) {
chart.initSeries(serieOptions);
});
chart.linkSeries();
// Run an event after axes and series are initialized, but before render. At this stage,
// the series data is indexed and cached in the xData and yData arrays, so we can access
// those before rendering. Used in Highstock.
fireEvent(chart, 'beforeRender');
// depends on inverted and on margins being set
if (Pointer) {
chart.pointer = new Pointer(chart, options);
}
chart.render();
// add canvas
chart.renderer.draw();
// Fire the load event if there are no external images
if (!chart.renderer.imgCount && chart.onload) {
chart.onload();
}
// If the chart was rendered outside the top container, put it back in (#3679)
chart.cloneRenderTo(true);
},
/**
* On chart load
*/
onload: function() {
// Run callbacks
each([this.callback].concat(this.callbacks), function(fn) {
if (fn && this.index !== undefined) { // Chart destroyed in its own callback (#3600)
fn.apply(this, [this]);
}
}, this);
fireEvent(this, 'load');
// Set up auto resize
if (this.options.chart.reflow !== false) {
this.initReflow();
}
// Don't run again
this.onload = null;
}
}; // end Chart
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Point,
each = H.each,
extend = H.extend,
erase = H.erase,
fireEvent = H.fireEvent,
format = H.format,
isArray = H.isArray,
isNumber = H.isNumber,
pick = H.pick,
removeEvent = H.removeEvent;
/**
* The Point object and prototype. Inheritable and used as base for PiePoint
*/
Point = H.Point = function() {};
Point.prototype = {
/**
* Initialize the point
* @param {Object} series The series object containing this point
* @param {Object} options The data in either number, array or object format
*/
init: function(series, options, x) {
var point = this,
colors,
colorCount = series.chart.options.chart.colorCount,
colorIndex;
point.series = series;
point.applyOptions(options, x);
if (series.options.colorByPoint) {
colorIndex = series.colorCounter;
series.colorCounter++;
// loop back to zero
if (series.colorCounter === colorCount) {
series.colorCounter = 0;
}
} else {
colorIndex = series.colorIndex;
}
point.colorIndex = pick(point.colorIndex, colorIndex);
series.chart.pointCount++;
return point;
},
/**
* Apply the options containing the x and y data and possible some extra properties.
* This is called on point init or from point.update.
*
* @param {Object} options
*/
applyOptions: function(options, x) {
var point = this,
series = point.series,
pointValKey = series.options.pointValKey || series.pointValKey;
options = Point.prototype.optionsToObject.call(this, options);
// copy options directly to point
extend(point, options);
point.options = point.options ? extend(point.options, options) : options;
// Since options are copied into the Point instance, some accidental options must be shielded (#5681)
if (options.group) {
delete point.group;
}
// For higher dimension series types. For instance, for ranges, point.y is mapped to point.low.
if (pointValKey) {
point.y = point[pointValKey];
}
point.isNull = pick(
point.isValid && !point.isValid(),
point.x === null || !isNumber(point.y, true)
); // #3571, check for NaN
// The point is initially selected by options (#5777)
if (point.selected) {
point.state = 'select';
}
// If no x is set by now, get auto incremented value. All points must have an
// x value, however the y value can be null to create a gap in the series
if ('name' in point && x === undefined && series.xAxis && series.xAxis.hasNames) {
point.x = series.xAxis.nameToX(point);
}
if (point.x === undefined && series) {
if (x === undefined) {
point.x = series.autoIncrement(point);
} else {
point.x = x;
}
}
return point;
},
/**
* Transform number or array configs into objects
*/
optionsToObject: function(options) {
var ret = {},
series = this.series,
keys = series.options.keys,
pointArrayMap = keys || series.pointArrayMap || ['y'],
valueCount = pointArrayMap.length,
firstItemType,
i = 0,
j = 0;
if (isNumber(options) || options === null) {
ret[pointArrayMap[0]] = options;
} else if (isArray(options)) {
// with leading x value
if (!keys && options.length > valueCount) {
firstItemType = typeof options[0];
if (firstItemType === 'string') {
ret.name = options[0];
} else if (firstItemType === 'number') {
ret.x = options[0];
}
i++;
}
while (j < valueCount) {
if (!keys || options[i] !== undefined) { // Skip undefined positions for keys
ret[pointArrayMap[j]] = options[i];
}
i++;
j++;
}
} else if (typeof options === 'object') {
ret = options;
// This is the fastest way to detect if there are individual point dataLabels that need
// to be considered in drawDataLabels. These can only occur in object configs.
if (options.dataLabels) {
series._hasPointLabels = true;
}
// Same approach as above for markers
if (options.marker) {
series._hasPointMarkers = true;
}
}
return ret;
},
/**
* Get the CSS class names for individual points
* @returns {String} The class name
*/
getClassName: function() {
return 'highcharts-point' +
(this.selected ? ' highcharts-point-select' : '') +
(this.negative ? ' highcharts-negative' : '') +
(this.isNull ? ' highcharts-null-point' : '') +
(this.colorIndex !== undefined ? ' highcharts-color-' + this.colorIndex : '') +
(this.options.className ? ' ' + this.options.className : '');
},
/**
* Return the zone that the point belongs to
*/
getZone: function() {
var series = this.series,
zones = series.zones,
zoneAxis = series.zoneAxis || 'y',
i = 0,
zone;
zone = zones[i];
while (this[zoneAxis] >= zone.value) {
zone = zones[++i];
}
if (zone && zone.color && !this.options.color) {
this.color = zone.color;
}
return zone;
},
/**
* Destroy a point to clear memory. Its reference still stays in series.data.
*/
destroy: function() {
var point = this,
series = point.series,
chart = series.chart,
hoverPoints = chart.hoverPoints,
prop;
chart.pointCount--;
if (hoverPoints) {
point.setState();
erase(hoverPoints, point);
if (!hoverPoints.length) {
chart.hoverPoints = null;
}
}
if (point === chart.hoverPoint) {
point.onMouseOut();
}
// remove all events
if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive
removeEvent(point);
point.destroyElements();
}
if (point.legendItem) { // pies have legend items
chart.legend.destroyItem(point);
}
for (prop in point) {
point[prop] = null;
}
},
/**
* Destroy SVG elements associated with the point
*/
destroyElements: function() {
var point = this,
props = ['graphic', 'dataLabel', 'dataLabelUpper', 'connector', 'shadowGroup'],
prop,
i = 6;
while (i--) {
prop = props[i];
if (point[prop]) {
point[prop] = point[prop].destroy();
}
}
},
/**
* Return the configuration hash needed for the data label and tooltip formatters
*/
getLabelConfig: function() {
return {
x: this.category,
y: this.y,
color: this.color,
key: this.name || this.category,
series: this.series,
point: this,
percentage: this.percentage,
total: this.total || this.stackTotal
};
},
/**
* Extendable method for formatting each point's tooltip line
*
* @return {String} A string to be concatenated in to the common tooltip text
*/
tooltipFormatter: function(pointFormat) {
// Insert options for valueDecimals, valuePrefix, and valueSuffix
var series = this.series,
seriesTooltipOptions = series.tooltipOptions,
valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''),
valuePrefix = seriesTooltipOptions.valuePrefix || '',
valueSuffix = seriesTooltipOptions.valueSuffix || '';
// Loop over the point array map and replace unformatted values with sprintf formatting markup
each(series.pointArrayMap || ['y'], function(key) {
key = '{point.' + key; // without the closing bracket
if (valuePrefix || valueSuffix) {
pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix);
}
pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}');
});
return format(pointFormat, {
point: this,
series: this.series
});
},
/**
* Fire an event on the Point object.
* @param {String} eventType
* @param {Object} eventArgs Additional event arguments
* @param {Function} defaultFunction Default event handler
*/
firePointEvent: function(eventType, eventArgs, defaultFunction) {
var point = this,
series = this.series,
seriesOptions = series.options;
// load event handlers on demand to save time on mouseover/out
if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) {
this.importEvents();
}
// add default handler if in selection mode
if (eventType === 'click' && seriesOptions.allowPointSelect) {
defaultFunction = function(event) {
// Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera
if (point.select) { // Could be destroyed by prior event handlers (#2911)
point.select(null, event.ctrlKey || event.metaKey || event.shiftKey);
}
};
}
fireEvent(this, eventType, eventArgs, defaultFunction);
},
visible: true
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
animObject = H.animObject,
arrayMax = H.arrayMax,
arrayMin = H.arrayMin,
correctFloat = H.correctFloat,
Date = H.Date,
defaultOptions = H.defaultOptions,
defaultPlotOptions = H.defaultPlotOptions,
defined = H.defined,
each = H.each,
erase = H.erase,
error = H.error,
extend = H.extend,
fireEvent = H.fireEvent,
grep = H.grep,
isArray = H.isArray,
isNumber = H.isNumber,
isString = H.isString,
LegendSymbolMixin = H.LegendSymbolMixin, // @todo add as a requirement
merge = H.merge,
pick = H.pick,
Point = H.Point, // @todo add as a requirement
removeEvent = H.removeEvent,
splat = H.splat,
stableSort = H.stableSort,
SVGElement = H.SVGElement,
syncTimeout = H.syncTimeout,
win = H.win;
/**
* @classDescription The base function which all other series types inherit from. The data in the series is stored
* in various arrays.
*
* - First, series.options.data contains all the original config options for
* each point whether added by options or methods like series.addPoint.
* - Next, series.data contains those values converted to points, but in case the series data length
* exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It
* only contains the points that have been created on demand.
* - Then there's series.points that contains all currently visible point objects. In case of cropping,
* the cropped-away points are not part of this array. The series.points array starts at series.cropStart
* compared to series.data and series.options.data. If however the series data is grouped, these can't
* be correlated one to one.
* - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points.
* - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points.
*
* @param {Object} chart
* @param {Object} options
*/
H.Series = H.seriesType('line', null, { // base series options
allowPointSelect: false,
showCheckbox: false,
animation: {
duration: 1000
},
//clip: true,
//connectNulls: false,
//enableMouseTracking: true,
events: {},
//legendIndex: 0,
// stacking: null,
marker: {
//enabled: true,
//symbol: null,
radius: 4,
states: { // states for a single point
hover: {
animation: {
duration: 50
},
enabled: true,
radiusPlus: 2
}
}
},
point: {
events: {}
},
dataLabels: {
align: 'center',
// defer: true,
// enabled: false,
formatter: function() {
return this.y === null ? '' : H.numberFormat(this.y, -1);
},
/*style: {
color: 'contrast',
textShadow: '0 0 6px contrast, 0 0 3px contrast'
},*/
verticalAlign: 'bottom', // above singular point
x: 0,
y: 0,
// borderRadius: undefined,
padding: 5
},
cropThreshold: 300, // draw points outside the plot area when the number of points is less than this
pointRange: 0,
//pointStart: 0,
//pointInterval: 1,
//showInLegend: null, // auto: true for standalone series, false for linked series
softThreshold: true,
states: { // states for the entire series
hover: {
//enabled: false,
lineWidthPlus: 1,
marker: {
// lineWidth: base + 1,
// radius: base + 1
},
halo: {
size: 10
}
},
select: {
marker: {}
}
},
stickyTracking: true,
//tooltip: {
//pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b>'
//valueDecimals: null,
//xDateFormat: '%A, %b %e, %Y',
//valuePrefix: '',
//ySuffix: ''
//}
turboThreshold: 1000
// zIndex: null
// Prototype properties
}, {
isCartesian: true,
pointClass: Point,
sorted: true, // requires the data to be sorted
requireSorting: true,
directTouch: false,
axisTypes: ['xAxis', 'yAxis'],
colorCounter: 0,
parallelArrays: ['x', 'y'], // each point's x and y values are stored in this.xData and this.yData
coll: 'series',
init: function(chart, options) {
var series = this,
eventType,
events,
chartSeries = chart.series,
sortByIndex = function(a, b) {
return pick(a.options.index, a._i) - pick(b.options.index, b._i);
};
series.chart = chart;
series.options = options = series.setOptions(options); // merge with plotOptions
series.linkedSeries = [];
// bind the axes
series.bindAxes();
// set some variables
extend(series, {
name: options.name,
state: '',
visible: options.visible !== false, // true by default
selected: options.selected === true // false by default
});
// register event listeners
events = options.events;
for (eventType in events) {
addEvent(series, eventType, events[eventType]);
}
if (
(events && events.click) ||
(options.point && options.point.events && options.point.events.click) ||
options.allowPointSelect
) {
chart.runTrackerClick = true;
}
series.getColor();
series.getSymbol();
// Set the data
each(series.parallelArrays, function(key) {
series[key + 'Data'] = [];
});
series.setData(options.data, false);
// Mark cartesian
if (series.isCartesian) {
chart.hasCartesianSeries = true;
}
// Register it in the chart
chartSeries.push(series);
series._i = chartSeries.length - 1;
// Sort series according to index option (#248, #1123, #2456)
stableSort(chartSeries, sortByIndex);
if (this.yAxis) {
stableSort(this.yAxis.series, sortByIndex);
}
each(chartSeries, function(series, i) {
series.index = i;
series.name = series.name || 'Series ' + (i + 1);
});
},
/**
* Set the xAxis and yAxis properties of cartesian series, and register the series
* in the axis.series array
*/
bindAxes: function() {
var series = this,
seriesOptions = series.options,
chart = series.chart,
axisOptions;
each(series.axisTypes || [], function(AXIS) { // repeat for xAxis and yAxis
each(chart[AXIS], function(axis) { // loop through the chart's axis objects
axisOptions = axis.options;
// apply if the series xAxis or yAxis option mathches the number of the
// axis, or if undefined, use the first axis
if ((seriesOptions[AXIS] === axisOptions.index) ||
(seriesOptions[AXIS] !== undefined && seriesOptions[AXIS] === axisOptions.id) ||
(seriesOptions[AXIS] === undefined && axisOptions.index === 0)) {
// register this series in the axis.series lookup
axis.series.push(series);
// set this series.xAxis or series.yAxis reference
series[AXIS] = axis;
// mark dirty for redraw
axis.isDirty = true;
}
});
// The series needs an X and an Y axis
if (!series[AXIS] && series.optionalAxis !== AXIS) {
error(18, true);
}
});
},
/**
* For simple series types like line and column, the data values are held in arrays like
* xData and yData for quick lookup to find extremes and more. For multidimensional series
* like bubble and map, this can be extended with arrays like zData and valueData by
* adding to the series.parallelArrays array.
*/
updateParallelArrays: function(point, i) {
var series = point.series,
args = arguments,
fn = isNumber(i) ?
// Insert the value in the given position
function(key) {
var val = key === 'y' && series.toYData ? series.toYData(point) : point[key];
series[key + 'Data'][i] = val;
} :
// Apply the method specified in i with the following arguments as arguments
function(key) {
Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2));
};
each(series.parallelArrays, fn);
},
/**
* Return an auto incremented x value based on the pointStart and pointInterval options.
* This is only used if an x value is not given for the point that calls autoIncrement.
*/
autoIncrement: function() {
var options = this.options,
xIncrement = this.xIncrement,
date,
pointInterval,
pointIntervalUnit = options.pointIntervalUnit;
xIncrement = pick(xIncrement, options.pointStart, 0);
this.pointInterval = pointInterval = pick(this.pointInterval, options.pointInterval, 1);
// Added code for pointInterval strings
if (pointIntervalUnit) {
date = new Date(xIncrement);
if (pointIntervalUnit === 'day') {
date = +date[Date.hcSetDate](date[Date.hcGetDate]() + pointInterval);
} else if (pointIntervalUnit === 'month') {
date = +date[Date.hcSetMonth](date[Date.hcGetMonth]() + pointInterval);
} else if (pointIntervalUnit === 'year') {
date = +date[Date.hcSetFullYear](date[Date.hcGetFullYear]() + pointInterval);
}
pointInterval = date - xIncrement;
}
this.xIncrement = xIncrement + pointInterval;
return xIncrement;
},
/**
* Set the series options by merging from the options tree
* @param {Object} itemOptions
*/
setOptions: function(itemOptions) {
var chart = this.chart,
chartOptions = chart.options,
plotOptions = chartOptions.plotOptions,
userOptions = chart.userOptions || {},
userPlotOptions = userOptions.plotOptions || {},
typeOptions = plotOptions[this.type],
options,
zones;
this.userOptions = itemOptions;
// General series options take precedence over type options because otherwise, default
// type options like column.animation would be overwritten by the general option.
// But issues have been raised here (#3881), and the solution may be to distinguish
// between default option and userOptions like in the tooltip below.
options = merge(
typeOptions,
plotOptions.series,
itemOptions
);
// The tooltip options are merged between global and series specific options
this.tooltipOptions = merge(
defaultOptions.tooltip,
defaultOptions.plotOptions[this.type].tooltip,
userOptions.tooltip,
userPlotOptions.series && userPlotOptions.series.tooltip,
userPlotOptions[this.type] && userPlotOptions[this.type].tooltip,
itemOptions.tooltip
);
// Delete marker object if not allowed (#1125)
if (typeOptions.marker === null) {
delete options.marker;
}
// Handle color zones
this.zoneAxis = options.zoneAxis;
zones = this.zones = (options.zones || []).slice();
if ((options.negativeColor || options.negativeFillColor) && !options.zones) {
zones.push({
value: options[this.zoneAxis + 'Threshold'] || options.threshold || 0,
className: 'highcharts-negative'
});
}
if (zones.length) { // Push one extra zone for the rest
if (defined(zones[zones.length - 1].value)) {
zones.push({
});
}
}
return options;
},
getCyclic: function(prop, value, defaults) {
var i,
userOptions = this.userOptions,
indexName = prop + 'Index',
counterName = prop + 'Counter',
len = defaults ? defaults.length : pick(this.chart.options.chart[prop + 'Count'], this.chart[prop + 'Count']),
setting;
if (!value) {
// Pick up either the colorIndex option, or the _colorIndex after Series.update()
setting = pick(userOptions[indexName], userOptions['_' + indexName]);
if (defined(setting)) { // after Series.update()
i = setting;
} else {
userOptions['_' + indexName] = i = this.chart[counterName] % len;
this.chart[counterName] += 1;
}
if (defaults) {
value = defaults[i];
}
}
// Set the colorIndex
if (i !== undefined) {
this[indexName] = i;
}
this[prop] = value;
},
/**
* Get the series' color
*/
getColor: function() {
this.getCyclic('color');
},
/**
* Get the series' symbol
*/
getSymbol: function() {
var seriesMarkerOption = this.options.marker;
this.getCyclic('symbol', seriesMarkerOption.symbol, this.chart.options.symbols);
},
drawLegendSymbol: LegendSymbolMixin.drawLineMarker,
/**
* Replace the series data with a new set of data
* @param {Object} data
* @param {Object} redraw
*/
setData: function(data, redraw, animation, updatePoints) {
var series = this,
oldData = series.points,
oldDataLength = (oldData && oldData.length) || 0,
dataLength,
options = series.options,
chart = series.chart,
firstPoint = null,
xAxis = series.xAxis,
i,
turboThreshold = options.turboThreshold,
pt,
xData = this.xData,
yData = this.yData,
pointArrayMap = series.pointArrayMap,
valueCount = pointArrayMap && pointArrayMap.length;
data = data || [];
dataLength = data.length;
redraw = pick(redraw, true);
// If the point count is the same as is was, just run Point.update which is
// cheaper, allows animation, and keeps references to points.
if (updatePoints !== false && dataLength && oldDataLength === dataLength && !series.cropped && !series.hasGroupedData && series.visible) {
each(data, function(point, i) {
// .update doesn't exist on a linked, hidden series (#3709)
if (oldData[i].update && point !== options.data[i]) {
oldData[i].update(point, false, null, false);
}
});
} else {
// Reset properties
series.xIncrement = null;
series.colorCounter = 0; // for series with colorByPoint (#1547)
// Update parallel arrays
each(this.parallelArrays, function(key) {
series[key + 'Data'].length = 0;
});
// In turbo mode, only one- or twodimensional arrays of numbers are allowed. The
// first value is tested, and we assume that all the rest are defined the same
// way. Although the 'for' loops are similar, they are repeated inside each
// if-else conditional for max performance.
if (turboThreshold && dataLength > turboThreshold) {
// find the first non-null point
i = 0;
while (firstPoint === null && i < dataLength) {
firstPoint = data[i];
i++;
}
if (isNumber(firstPoint)) { // assume all points are numbers
for (i = 0; i < dataLength; i++) {
xData[i] = this.autoIncrement();
yData[i] = data[i];
}
} else if (isArray(firstPoint)) { // assume all points are arrays
if (valueCount) { // [x, low, high] or [x, o, h, l, c]
for (i = 0; i < dataLength; i++) {
pt = data[i];
xData[i] = pt[0];
yData[i] = pt.slice(1, valueCount + 1);
}
} else { // [x, y]
for (i = 0; i < dataLength; i++) {
pt = data[i];
xData[i] = pt[0];
yData[i] = pt[1];
}
}
} else {
error(12); // Highcharts expects configs to be numbers or arrays in turbo mode
}
} else {
for (i = 0; i < dataLength; i++) {
if (data[i] !== undefined) { // stray commas in oldIE
pt = {
series: series
};
series.pointClass.prototype.applyOptions.apply(pt, [data[i]]);
series.updateParallelArrays(pt, i);
}
}
}
// Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON
if (isString(yData[0])) {
error(14, true);
}
series.data = [];
series.options.data = series.userOptions.data = data;
// destroy old points
i = oldDataLength;
while (i--) {
if (oldData[i] && oldData[i].destroy) {
oldData[i].destroy();
}
}
// reset minRange (#878)
if (xAxis) {
xAxis.minRange = xAxis.userMinRange;
}
// redraw
series.isDirty = chart.isDirtyBox = true;
series.isDirtyData = !!oldData;
animation = false;
}
// Typically for pie series, points need to be processed and generated
// prior to rendering the legend
if (options.legendType === 'point') {
this.processData();
this.generatePoints();
}
if (redraw) {
chart.redraw(animation);
}
},
/**
* Process the data by cropping away unused data points if the series is longer
* than the crop threshold. This saves computing time for lage series.
*/
processData: function(force) {
var series = this,
processedXData = series.xData, // copied during slice operation below
processedYData = series.yData,
dataLength = processedXData.length,
croppedData,
cropStart = 0,
cropped,
distance,
closestPointRange,
xAxis = series.xAxis,
i, // loop variable
options = series.options,
cropThreshold = options.cropThreshold,
getExtremesFromAll = series.getExtremesFromAll || options.getExtremesFromAll, // #4599
isCartesian = series.isCartesian,
xExtremes,
val2lin = xAxis && xAxis.val2lin,
isLog = xAxis && xAxis.isLog,
min,
max;
// If the series data or axes haven't changed, don't go through this. Return false to pass
// the message on to override methods like in data grouping.
if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) {
return false;
}
if (xAxis) {
xExtremes = xAxis.getExtremes(); // corrected for log axis (#3053)
min = xExtremes.min;
max = xExtremes.max;
}
// optionally filter out points outside the plot area
if (isCartesian && series.sorted && !getExtremesFromAll && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) {
// it's outside current extremes
if (processedXData[dataLength - 1] < min || processedXData[0] > max) {
processedXData = [];
processedYData = [];
// only crop if it's actually spilling out
} else if (processedXData[0] < min || processedXData[dataLength - 1] > max) {
croppedData = this.cropData(series.xData, series.yData, min, max);
processedXData = croppedData.xData;
processedYData = croppedData.yData;
cropStart = croppedData.start;
cropped = true;
}
}
// Find the closest distance between processed points
i = processedXData.length || 1;
while (--i) {
distance = isLog ?
val2lin(processedXData[i]) - val2lin(processedXData[i - 1]) :
processedXData[i] - processedXData[i - 1];
if (distance > 0 && (closestPointRange === undefined || distance < closestPointRange)) {
closestPointRange = distance;
// Unsorted data is not supported by the line tooltip, as well as data grouping and
// navigation in Stock charts (#725) and width calculation of columns (#1900)
} else if (distance < 0 && series.requireSorting) {
error(15);
}
}
// Record the properties
series.cropped = cropped; // undefined or true
series.cropStart = cropStart;
series.processedXData = processedXData;
series.processedYData = processedYData;
series.closestPointRange = closestPointRange;
},
/**
* Iterate over xData and crop values between min and max. Returns object containing crop start/end
* cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range
*/
cropData: function(xData, yData, min, max) {
var dataLength = xData.length,
cropStart = 0,
cropEnd = dataLength,
cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside
i,
j;
// iterate up to find slice start
for (i = 0; i < dataLength; i++) {
if (xData[i] >= min) {
cropStart = Math.max(0, i - cropShoulder);
break;
}
}
// proceed to find slice end
for (j = i; j < dataLength; j++) {
if (xData[j] > max) {
cropEnd = j + cropShoulder;
break;
}
}
return {
xData: xData.slice(cropStart, cropEnd),
yData: yData.slice(cropStart, cropEnd),
start: cropStart,
end: cropEnd
};
},
/**
* Generate the data point after the data has been processed by cropping away
* unused points and optionally grouped in Highcharts Stock.
*/
generatePoints: function() {
var series = this,
options = series.options,
dataOptions = options.data,
data = series.data,
dataLength,
processedXData = series.processedXData,
processedYData = series.processedYData,
PointClass = series.pointClass,
processedDataLength = processedXData.length,
cropStart = series.cropStart || 0,
cursor,
hasGroupedData = series.hasGroupedData,
point,
points = [],
i;
if (!data && !hasGroupedData) {
var arr = [];
arr.length = dataOptions.length;
data = series.data = arr;
}
for (i = 0; i < processedDataLength; i++) {
cursor = cropStart + i;
if (!hasGroupedData) {
if (data[cursor]) {
point = data[cursor];
} else if (dataOptions[cursor] !== undefined) { // #970
data[cursor] = point = (new PointClass()).init(series, dataOptions[cursor], processedXData[i]);
}
points[i] = point;
} else {
// splat the y data in case of ohlc data array
points[i] = (new PointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i])));
points[i].dataGroup = series.groupMap[i];
}
points[i].index = cursor; // For faster access in Point.update
}
// Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when
// swithching view from non-grouped data to grouped data (#637)
if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) {
for (i = 0; i < dataLength; i++) {
if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points
i += processedDataLength;
}
if (data[i]) {
data[i].destroyElements();
data[i].plotX = undefined; // #1003
}
}
}
series.data = data;
series.points = points;
},
/**
* Calculate Y extremes for visible data
*/
getExtremes: function(yData) {
var xAxis = this.xAxis,
yAxis = this.yAxis,
xData = this.processedXData,
yDataLength,
activeYData = [],
activeCounter = 0,
xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis
xMin = xExtremes.min,
xMax = xExtremes.max,
validValue,
withinRange,
x,
y,
i,
j;
yData = yData || this.stackedYData || this.processedYData || [];
yDataLength = yData.length;
for (i = 0; i < yDataLength; i++) {
x = xData[i];
y = yData[i];
// For points within the visible range, including the first point outside the
// visible range, consider y extremes
validValue = (isNumber(y, true) || isArray(y)) && (!yAxis.isLog || (y.length || y > 0));
withinRange = this.getExtremesFromAll || this.options.getExtremesFromAll || this.cropped ||
((xData[i + 1] || x) >= xMin && (xData[i - 1] || x) <= xMax);
if (validValue && withinRange) {
j = y.length;
if (j) { // array, like ohlc or range data
while (j--) {
if (y[j] !== null) {
activeYData[activeCounter++] = y[j];
}
}
} else {
activeYData[activeCounter++] = y;
}
}
}
this.dataMin = arrayMin(activeYData);
this.dataMax = arrayMax(activeYData);
},
/**
* Translate data points from raw data values to chart specific positioning data
* needed later in drawPoints, drawGraph and drawTracker.
*/
translate: function() {
if (!this.processedXData) { // hidden series
this.processData();
}
this.generatePoints();
var series = this,
options = series.options,
stacking = options.stacking,
xAxis = series.xAxis,
categories = xAxis.categories,
yAxis = series.yAxis,
points = series.points,
dataLength = points.length,
hasModifyValue = !!series.modifyValue,
i,
pointPlacement = options.pointPlacement,
dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement),
threshold = options.threshold,
stackThreshold = options.startFromThreshold ? threshold : 0,
plotX,
plotY,
lastPlotX,
stackIndicator,
closestPointRangePx = Number.MAX_VALUE;
// Translate each point
for (i = 0; i < dataLength; i++) {
var point = points[i],
xValue = point.x,
yValue = point.y,
yBottom = point.low,
stack = stacking && yAxis.stacks[(series.negStacks && yValue < (stackThreshold ? 0 : threshold) ? '-' : '') + series.stackKey],
pointStack,
stackValues;
// Discard disallowed y values for log axes (#3434)
if (yAxis.isLog && yValue !== null && yValue <= 0) {
point.isNull = true;
}
// Get the plotX translation
point.plotX = plotX = correctFloat( // #5236
Math.min(Math.max(-1e5, xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags')), 1e5) // #3923
);
// Calculate the bottom y value for stacked series
if (stacking && series.visible && !point.isNull && stack && stack[xValue]) {
stackIndicator = series.getStackIndicator(stackIndicator, xValue, series.index);
pointStack = stack[xValue];
stackValues = pointStack.points[stackIndicator.key];
yBottom = stackValues[0];
yValue = stackValues[1];
if (yBottom === stackThreshold && stackIndicator.key === stack[xValue].base) {
yBottom = pick(threshold, yAxis.min);
}
if (yAxis.isLog && yBottom <= 0) { // #1200, #1232
yBottom = null;
}
point.total = point.stackTotal = pointStack.total;
point.percentage = pointStack.total && (point.y / pointStack.total * 100);
point.stackY = yValue;
// Place the stack label
pointStack.setOffset(series.pointXOffset || 0, series.barW || 0);
}
// Set translated yBottom or remove it
point.yBottom = defined(yBottom) ?
yAxis.translate(yBottom, 0, 1, 0, 1) :
null;
// general hook, used for Highstock compare mode
if (hasModifyValue) {
yValue = series.modifyValue(yValue, point);
}
// Set the the plotY value, reset it for redraws
point.plotY = plotY = (typeof yValue === 'number' && yValue !== Infinity) ?
Math.min(Math.max(-1e5, yAxis.translate(yValue, 0, 1, 0, 1)), 1e5) : // #3201
undefined;
point.isInside = plotY !== undefined && plotY >= 0 && plotY <= yAxis.len && // #3519
plotX >= 0 && plotX <= xAxis.len;
// Set client related positions for mouse tracking
point.clientX = dynamicallyPlaced ? correctFloat(xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement)) : plotX; // #1514, #5383, #5518
point.negative = point.y < (threshold || 0);
// some API data
point.category = categories && categories[point.x] !== undefined ?
categories[point.x] : point.x;
// Determine auto enabling of markers (#3635, #5099)
if (!point.isNull) {
if (lastPlotX !== undefined) {
closestPointRangePx = Math.min(closestPointRangePx, Math.abs(plotX - lastPlotX));
}
lastPlotX = plotX;
}
}
series.closestPointRangePx = closestPointRangePx;
},
/**
* Return the series points with null points filtered out
*/
getValidPoints: function(points, insideOnly) {
var chart = this.chart;
return grep(points || this.points || [], function isValidPoint(point) { // #3916, #5029
if (insideOnly && !chart.isInsidePlot(point.plotX, point.plotY, chart.inverted)) { // #5085
return false;
}
return !point.isNull;
});
},
/**
* Set the clipping for the series. For animated series it is called twice, first to initiate
* animating the clip then the second time without the animation to set the final clip.
*/
setClip: function(animation) {
var chart = this.chart,
options = this.options,
renderer = chart.renderer,
inverted = chart.inverted,
seriesClipBox = this.clipBox,
clipBox = seriesClipBox || chart.clipBox,
sharedClipKey = this.sharedClipKey || ['_sharedClip', animation && animation.duration, animation && animation.easing, clipBox.height, options.xAxis, options.yAxis].join(','), // #4526
clipRect = chart[sharedClipKey],
markerClipRect = chart[sharedClipKey + 'm'];
// If a clipping rectangle with the same properties is currently present in the chart, use that.
if (!clipRect) {
// When animation is set, prepare the initial positions
if (animation) {
clipBox.width = 0;
chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect(-99, // include the width of the first marker
inverted ? -chart.plotLeft : -chart.plotTop,
99,
inverted ? chart.chartWidth : chart.chartHeight
);
}
chart[sharedClipKey] = clipRect = renderer.clipRect(clipBox);
// Create hashmap for series indexes
clipRect.count = {
length: 0
};
}
if (animation) {
if (!clipRect.count[this.index]) {
clipRect.count[this.index] = true;
clipRect.count.length += 1;
}
}
if (options.clip !== false) {
this.group.clip(animation || seriesClipBox ? clipRect : chart.clipRect);
this.markerGroup.clip(markerClipRect);
this.sharedClipKey = sharedClipKey;
}
// Remove the shared clipping rectangle when all series are shown
if (!animation) {
if (clipRect.count[this.index]) {
delete clipRect.count[this.index];
clipRect.count.length -= 1;
}
if (clipRect.count.length === 0 && sharedClipKey && chart[sharedClipKey]) {
if (!seriesClipBox) {
chart[sharedClipKey] = chart[sharedClipKey].destroy();
}
if (chart[sharedClipKey + 'm']) {
chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy();
}
}
}
},
/**
* Animate in the series
*/
animate: function(init) {
var series = this,
chart = series.chart,
clipRect,
animation = animObject(series.options.animation),
sharedClipKey;
// Initialize the animation. Set up the clipping rectangle.
if (init) {
series.setClip(animation);
// Run the animation
} else {
sharedClipKey = this.sharedClipKey;
clipRect = chart[sharedClipKey];
if (clipRect) {
clipRect.animate({
width: chart.plotSizeX
}, animation);
}
if (chart[sharedClipKey + 'm']) {
chart[sharedClipKey + 'm'].animate({
width: chart.plotSizeX + 99
}, animation);
}
// Delete this function to allow it only once
series.animate = null;
}
},
/**
* This runs after animation to land on the final plot clipping
*/
afterAnimate: function() {
this.setClip();
fireEvent(this, 'afterAnimate');
},
/**
* Draw the markers
*/
drawPoints: function() {
var series = this,
points = series.points,
chart = series.chart,
plotY,
i,
point,
symbol,
graphic,
options = series.options,
seriesMarkerOptions = options.marker,
pointMarkerOptions,
hasPointMarker,
enabled,
isInside,
markerGroup = series.markerGroup,
xAxis = series.xAxis,
markerAttribs,
globallyEnabled = pick(
seriesMarkerOptions.enabled,
xAxis.isRadial ? true : null,
series.closestPointRangePx > 2 * seriesMarkerOptions.radius
);
if (seriesMarkerOptions.enabled !== false || series._hasPointMarkers) {
i = points.length;
while (i--) {
point = points[i];
plotY = point.plotY;
graphic = point.graphic;
pointMarkerOptions = point.marker || {};
hasPointMarker = !!point.marker;
enabled = (globallyEnabled && pointMarkerOptions.enabled === undefined) || pointMarkerOptions.enabled;
isInside = point.isInside;
// only draw the point if y is defined
if (enabled && isNumber(plotY) && point.y !== null) {
// Shortcuts
symbol = pick(pointMarkerOptions.symbol, series.symbol);
point.hasImage = symbol.indexOf('url') === 0;
markerAttribs = series.markerAttribs(
point,
point.selected && 'select'
);
if (graphic) { // update
graphic[isInside ? 'show' : 'hide'](true) // Since the marker group isn't clipped, each individual marker must be toggled
.animate(markerAttribs);
} else if (isInside && (markerAttribs.width > 0 || point.hasImage)) {
point.graphic = graphic = chart.renderer.symbol(
symbol,
markerAttribs.x,
markerAttribs.y,
markerAttribs.width,
markerAttribs.height,
hasPointMarker ? pointMarkerOptions : seriesMarkerOptions
)
.add(markerGroup);
}
if (graphic) {
graphic.addClass(point.getClassName(), true);
}
} else if (graphic) {
point.graphic = graphic.destroy(); // #1269
}
}
}
},
/**
* Get non-presentational attributes for the point.
*/
markerAttribs: function(point, state) {
var seriesMarkerOptions = this.options.marker,
seriesStateOptions,
pointOptions = point && point.options,
pointMarkerOptions = (pointOptions && pointOptions.marker) || {},
pointStateOptions,
radius = pick(
pointMarkerOptions.radius,
seriesMarkerOptions.radius
),
attribs;
// Handle hover and select states
if (state) {
seriesStateOptions = seriesMarkerOptions.states[state];
pointStateOptions = pointMarkerOptions.states &&
pointMarkerOptions.states[state];
radius = pick(
pointStateOptions && pointStateOptions.radius,
seriesStateOptions && seriesStateOptions.radius,
radius + (seriesStateOptions && seriesStateOptions.radiusPlus || 0)
);
}
if (point.hasImage) {
radius = 0; // and subsequently width and height is not set
}
attribs = {
x: Math.floor(point.plotX) - radius, // Math.floor for #1843
y: point.plotY - radius
};
if (radius) {
attribs.width = attribs.height = 2 * radius;
}
return attribs;
},
/**
* Clear DOM objects and free up memory
*/
destroy: function() {
var series = this,
chart = series.chart,
issue134 = /AppleWebKit\/533/.test(win.navigator.userAgent),
destroy,
i,
data = series.data || [],
point,
prop,
axis;
// add event hook
fireEvent(series, 'destroy');
// remove all events
removeEvent(series);
// erase from axes
each(series.axisTypes || [], function(AXIS) {
axis = series[AXIS];
if (axis && axis.series) {
erase(axis.series, series);
axis.isDirty = axis.forceRedraw = true;
}
});
// remove legend items
if (series.legendItem) {
series.chart.legend.destroyItem(series);
}
// destroy all points with their elements
i = data.length;
while (i--) {
point = data[i];
if (point && point.destroy) {
point.destroy();
}
}
series.points = null;
// Clear the animation timeout if we are destroying the series during initial animation
clearTimeout(series.animationTimeout);
// Destroy all SVGElements associated to the series
for (prop in series) {
if (series[prop] instanceof SVGElement && !series[prop].survive) { // Survive provides a hook for not destroying
// issue 134 workaround
destroy = issue134 && prop === 'group' ?
'hide' :
'destroy';
series[prop][destroy]();
}
}
// remove from hoverSeries
if (chart.hoverSeries === series) {
chart.hoverSeries = null;
}
erase(chart.series, series);
// clear all members
for (prop in series) {
delete series[prop];
}
},
/**
* Get the graph path
*/
getGraphPath: function(points, nullsAsZeroes, connectCliffs) {
var series = this,
options = series.options,
step = options.step,
reversed,
graphPath = [],
xMap = [],
gap;
points = points || series.points;
// Bottom of a stack is reversed
reversed = points.reversed;
if (reversed) {
points.reverse();
}
// Reverse the steps (#5004)
step = {
right: 1,
center: 2
}[step] || (step && 3);
if (step && reversed) {
step = 4 - step;
}
// Remove invalid points, especially in spline (#5015)
if (options.connectNulls && !nullsAsZeroes && !connectCliffs) {
points = this.getValidPoints(points);
}
// Build the line
each(points, function(point, i) {
var plotX = point.plotX,
plotY = point.plotY,
lastPoint = points[i - 1],
pathToPoint; // the path to this point from the previous
if ((point.leftCliff || (lastPoint && lastPoint.rightCliff)) && !connectCliffs) {
gap = true; // ... and continue
}
// Line series, nullsAsZeroes is not handled
if (point.isNull && !defined(nullsAsZeroes) && i > 0) {
gap = !options.connectNulls;
// Area series, nullsAsZeroes is set
} else if (point.isNull && !nullsAsZeroes) {
gap = true;
} else {
if (i === 0 || gap) {
pathToPoint = ['M', point.plotX, point.plotY];
} else if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object
pathToPoint = series.getPointSpline(points, point, i);
} else if (step) {
if (step === 1) { // right
pathToPoint = [
'L',
lastPoint.plotX,
plotY
];
} else if (step === 2) { // center
pathToPoint = [
'L',
(lastPoint.plotX + plotX) / 2,
lastPoint.plotY,
'L',
(lastPoint.plotX + plotX) / 2,
plotY
];
} else {
pathToPoint = [
'L',
plotX,
lastPoint.plotY
];
}
pathToPoint.push('L', plotX, plotY);
} else {
// normal line to next point
pathToPoint = [
'L',
plotX,
plotY
];
}
// Prepare for animation. When step is enabled, there are two path nodes for each x value.
xMap.push(point.x);
if (step) {
xMap.push(point.x);
}
graphPath.push.apply(graphPath, pathToPoint);
gap = false;
}
});
graphPath.xMap = xMap;
series.graphPath = graphPath;
return graphPath;
},
/**
* Draw the actual graph
*/
drawGraph: function() {
var series = this,
options = this.options,
graphPath = (this.gappedPath || this.getGraphPath).call(this),
props = [
[
'graph',
'highcharts-graph'
]
];
// Add the zone properties if any
each(this.zones, function(zone, i) {
props.push([
'zone-graph-' + i,
'highcharts-graph highcharts-zone-graph-' + i + ' ' + (zone.className || '')
]);
});
// Draw the graph
each(props, function(prop, i) {
var graphKey = prop[0],
graph = series[graphKey],
attribs;
if (graph) {
graph.endX = graphPath.xMap;
graph.animate({
d: graphPath
});
} else if (graphPath.length) { // #1487
series[graphKey] = series.chart.renderer.path(graphPath)
.addClass(prop[1])
.attr({
zIndex: 1
}) // #1069
.add(series.group);
}
// Helpers for animation
if (graph) {
graph.startX = graphPath.xMap;
//graph.shiftUnit = options.step ? 2 : 1;
graph.isArea = graphPath.isArea; // For arearange animation
}
});
},
/**
* Clip the graphs into the positive and negative coloured graphs
*/
applyZones: function() {
var series = this,
chart = this.chart,
renderer = chart.renderer,
zones = this.zones,
translatedFrom,
translatedTo,
clips = this.clips || [],
clipAttr,
graph = this.graph,
area = this.area,
chartSizeMax = Math.max(chart.chartWidth, chart.chartHeight),
axis = this[(this.zoneAxis || 'y') + 'Axis'],
extremes,
reversed,
inverted = chart.inverted,
horiz,
pxRange,
pxPosMin,
pxPosMax,
ignoreZones = false;
if (zones.length && (graph || area) && axis && axis.min !== undefined) {
reversed = axis.reversed;
horiz = axis.horiz;
// The use of the Color Threshold assumes there are no gaps
// so it is safe to hide the original graph and area
if (graph) {
graph.hide();
}
if (area) {
area.hide();
}
// Create the clips
extremes = axis.getExtremes();
each(zones, function(threshold, i) {
translatedFrom = reversed ?
(horiz ? chart.plotWidth : 0) :
(horiz ? 0 : axis.toPixels(extremes.min));
translatedFrom = Math.min(Math.max(pick(translatedTo, translatedFrom), 0), chartSizeMax);
translatedTo = Math.min(Math.max(Math.round(axis.toPixels(pick(threshold.value, extremes.max), true)), 0), chartSizeMax);
if (ignoreZones) {
translatedFrom = translatedTo = axis.toPixels(extremes.max);
}
pxRange = Math.abs(translatedFrom - translatedTo);
pxPosMin = Math.min(translatedFrom, translatedTo);
pxPosMax = Math.max(translatedFrom, translatedTo);
if (axis.isXAxis) {
clipAttr = {
x: inverted ? pxPosMax : pxPosMin,
y: 0,
width: pxRange,
height: chartSizeMax
};
if (!horiz) {
clipAttr.x = chart.plotHeight - clipAttr.x;
}
} else {
clipAttr = {
x: 0,
y: inverted ? pxPosMax : pxPosMin,
width: chartSizeMax,
height: pxRange
};
if (horiz) {
clipAttr.y = chart.plotWidth - clipAttr.y;
}
}
if (clips[i]) {
clips[i].animate(clipAttr);
} else {
clips[i] = renderer.clipRect(clipAttr);
if (graph) {
series['zone-graph-' + i].clip(clips[i]);
}
if (area) {
series['zone-area-' + i].clip(clips[i]);
}
}
// if this zone extends out of the axis, ignore the others
ignoreZones = threshold.value > extremes.max;
});
this.clips = clips;
}
},
/**
* Initialize and perform group inversion on series.group and series.markerGroup
*/
invertGroups: function(inverted) {
var series = this,
chart = series.chart;
// Pie, go away (#1736)
if (!series.xAxis) {
return;
}
// A fixed size is needed for inversion to work
function setInvert() {
var size = {
width: series.yAxis.len,
height: series.xAxis.len
};
each(['group', 'markerGroup'], function(groupName) {
if (series[groupName]) {
series[groupName].attr(size).invert(inverted);
}
});
}
addEvent(chart, 'resize', setInvert); // do it on resize
addEvent(series, 'destroy', function() {
removeEvent(chart, 'resize', setInvert);
});
// Do it now
setInvert(inverted); // do it now
// On subsequent render and redraw, just do setInvert without setting up events again
series.invertGroups = setInvert;
},
/**
* General abstraction for creating plot groups like series.group, series.dataLabelsGroup and
* series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size.
*/
plotGroup: function(prop, name, visibility, zIndex, parent) {
var group = this[prop],
isNew = !group;
// Generate it on first call
if (isNew) {
this[prop] = group = this.chart.renderer.g(name)
.attr({
zIndex: zIndex || 0.1 // IE8 and pointer logic use this
})
.add(parent);
group.addClass('highcharts-series-' + this.index + ' highcharts-' + this.type + '-series highcharts-color-' + this.colorIndex +
' ' + (this.options.className || ''));
}
// Place it on first and subsequent (redraw) calls
group.attr({
visibility: visibility
})[isNew ? 'attr' : 'animate'](this.getPlotBox());
return group;
},
/**
* Get the translation and scale for the plot area of this series
*/
getPlotBox: function() {
var chart = this.chart,
xAxis = this.xAxis,
yAxis = this.yAxis;
// Swap axes for inverted (#2339)
if (chart.inverted) {
xAxis = yAxis;
yAxis = this.xAxis;
}
return {
translateX: xAxis ? xAxis.left : chart.plotLeft,
translateY: yAxis ? yAxis.top : chart.plotTop,
scaleX: 1, // #1623
scaleY: 1
};
},
/**
* Render the graph and markers
*/
render: function() {
var series = this,
chart = series.chart,
group,
options = series.options,
// Animation doesn't work in IE8 quirks when the group div is hidden,
// and looks bad in other oldIE
animDuration = !!series.animate && chart.renderer.isSVG && animObject(options.animation).duration,
visibility = series.visible ? 'inherit' : 'hidden', // #2597
zIndex = options.zIndex,
hasRendered = series.hasRendered,
chartSeriesGroup = chart.seriesGroup,
inverted = chart.inverted;
// the group
group = series.plotGroup(
'group',
'series',
visibility,
zIndex,
chartSeriesGroup
);
series.markerGroup = series.plotGroup(
'markerGroup',
'markers',
visibility,
zIndex,
chartSeriesGroup
);
// initiate the animation
if (animDuration) {
series.animate(true);
}
// SVGRenderer needs to know this before drawing elements (#1089, #1795)
group.inverted = series.isCartesian ? inverted : false;
// draw the graph if any
if (series.drawGraph) {
series.drawGraph();
series.applyZones();
}
/* each(series.points, function (point) {
if (point.redraw) {
point.redraw();
}
});*/
// draw the data labels (inn pies they go before the points)
if (series.drawDataLabels) {
series.drawDataLabels();
}
// draw the points
if (series.visible) {
series.drawPoints();
}
// draw the mouse tracking area
if (series.drawTracker && series.options.enableMouseTracking !== false) {
series.drawTracker();
}
// Handle inverted series and tracker groups
series.invertGroups(inverted);
// Initial clipping, must be defined after inverting groups for VML. Applies to columns etc. (#3839).
if (options.clip !== false && !series.sharedClipKey && !hasRendered) {
group.clip(chart.clipRect);
}
// Run the animation
if (animDuration) {
series.animate();
}
// Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option
// which should be available to the user).
if (!hasRendered) {
series.animationTimeout = syncTimeout(function() {
series.afterAnimate();
}, animDuration);
}
series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
// (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
series.hasRendered = true;
},
/**
* Redraw the series after an update in the axes.
*/
redraw: function() {
var series = this,
chart = series.chart,
wasDirty = series.isDirty || series.isDirtyData, // cache it here as it is set to false in render, but used after
group = series.group,
xAxis = series.xAxis,
yAxis = series.yAxis;
// reposition on resize
if (group) {
if (chart.inverted) {
group.attr({
width: chart.plotWidth,
height: chart.plotHeight
});
}
group.animate({
translateX: pick(xAxis && xAxis.left, chart.plotLeft),
translateY: pick(yAxis && yAxis.top, chart.plotTop)
});
}
series.translate();
series.render();
if (wasDirty) { // #3868, #3945
delete this.kdTree;
}
},
/**
* KD Tree && PointSearching Implementation
*/
kdDimensions: 1,
kdAxisArray: ['clientX', 'plotY'],
searchPoint: function(e, compareX) {
var series = this,
xAxis = series.xAxis,
yAxis = series.yAxis,
inverted = series.chart.inverted;
return this.searchKDTree({
clientX: inverted ? xAxis.len - e.chartY + xAxis.pos : e.chartX - xAxis.pos,
plotY: inverted ? yAxis.len - e.chartX + yAxis.pos : e.chartY - yAxis.pos
}, compareX);
},
buildKDTree: function() {
var series = this,
dimensions = series.kdDimensions;
// Internal function
function _kdtree(points, depth, dimensions) {
var axis,
median,
length = points && points.length;
if (length) {
// alternate between the axis
axis = series.kdAxisArray[depth % dimensions];
// sort point array
points.sort(function(a, b) {
return a[axis] - b[axis];
});
median = Math.floor(length / 2);
// build and return nod
return {
point: points[median],
left: _kdtree(points.slice(0, median), depth + 1, dimensions),
right: _kdtree(points.slice(median + 1), depth + 1, dimensions)
};
}
}
// Start the recursive build process with a clone of the points array and null points filtered out (#3873)
function startRecursive() {
series.kdTree = _kdtree(
series.getValidPoints(
null, !series.directTouch // For line-type series restrict to plot area, but column-type series not (#3916, #4511)
),
dimensions,
dimensions
);
}
delete series.kdTree;
// For testing tooltips, don't build async
syncTimeout(startRecursive, series.options.kdNow ? 0 : 1);
},
searchKDTree: function(point, compareX) {
var series = this,
kdX = this.kdAxisArray[0],
kdY = this.kdAxisArray[1],
kdComparer = compareX ? 'distX' : 'dist';
// Set the one and two dimensional distance on the point object
function setDistance(p1, p2) {
var x = (defined(p1[kdX]) && defined(p2[kdX])) ? Math.pow(p1[kdX] - p2[kdX], 2) : null,
y = (defined(p1[kdY]) && defined(p2[kdY])) ? Math.pow(p1[kdY] - p2[kdY], 2) : null,
r = (x || 0) + (y || 0);
p2.dist = defined(r) ? Math.sqrt(r) : Number.MAX_VALUE;
p2.distX = defined(x) ? Math.sqrt(x) : Number.MAX_VALUE;
}
function _search(search, tree, depth, dimensions) {
var point = tree.point,
axis = series.kdAxisArray[depth % dimensions],
tdist,
sideA,
sideB,
ret = point,
nPoint1,
nPoint2;
setDistance(search, point);
// Pick side based on distance to splitting point
tdist = search[axis] - point[axis];
sideA = tdist < 0 ? 'left' : 'right';
sideB = tdist < 0 ? 'right' : 'left';
// End of tree
if (tree[sideA]) {
nPoint1 = _search(search, tree[sideA], depth + 1, dimensions);
ret = (nPoint1[kdComparer] < ret[kdComparer] ? nPoint1 : point);
}
if (tree[sideB]) {
// compare distance to current best to splitting point to decide wether to check side B or not
if (Math.sqrt(tdist * tdist) < ret[kdComparer]) {
nPoint2 = _search(search, tree[sideB], depth + 1, dimensions);
ret = (nPoint2[kdComparer] < ret[kdComparer] ? nPoint2 : ret);
}
}
return ret;
}
if (!this.kdTree) {
this.buildKDTree();
}
if (this.kdTree) {
return _search(point,
this.kdTree, this.kdDimensions, this.kdDimensions);
}
}
}); // end Series prototype
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
animate = H.animate,
Axis = H.Axis,
Chart = H.Chart,
createElement = H.createElement,
css = H.css,
defined = H.defined,
each = H.each,
erase = H.erase,
extend = H.extend,
fireEvent = H.fireEvent,
inArray = H.inArray,
isNumber = H.isNumber,
isObject = H.isObject,
merge = H.merge,
pick = H.pick,
Point = H.Point,
Series = H.Series,
seriesTypes = H.seriesTypes,
setAnimation = H.setAnimation,
splat = H.splat;
// Extend the Chart prototype for dynamic methods
extend(Chart.prototype, {
/**
* Add a series dynamically after time
*
* @param {Object} options The config options
* @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true.
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*
* @return {Object} series The newly created series object
*/
addSeries: function(options, redraw, animation) {
var series,
chart = this;
if (options) {
redraw = pick(redraw, true); // defaults to true
fireEvent(chart, 'addSeries', {
options: options
}, function() {
series = chart.initSeries(options);
chart.isDirtyLegend = true; // the series array is out of sync with the display
chart.linkSeries();
if (redraw) {
chart.redraw(animation);
}
});
}
return series;
},
/**
* Add an axis to the chart
* @param {Object} options The axis option
* @param {Boolean} isX Whether it is an X axis or a value axis
*/
addAxis: function(options, isX, redraw, animation) {
var key = isX ? 'xAxis' : 'yAxis',
chartOptions = this.options,
userOptions = merge(options, {
index: this[key].length,
isX: isX
});
new Axis(this, userOptions); // eslint-disable-line no-new
// Push the new axis options to the chart options
chartOptions[key] = splat(chartOptions[key] || {});
chartOptions[key].push(userOptions);
if (pick(redraw, true)) {
this.redraw(animation);
}
},
/**
* Dim the chart and show a loading text or symbol
* @param {String} str An optional text to show in the loading label instead of the default one
*/
showLoading: function(str) {
var chart = this,
options = chart.options,
loadingDiv = chart.loadingDiv,
loadingOptions = options.loading,
setLoadingSize = function() {
if (loadingDiv) {
css(loadingDiv, {
left: chart.plotLeft + 'px',
top: chart.plotTop + 'px',
width: chart.plotWidth + 'px',
height: chart.plotHeight + 'px'
});
}
};
// create the layer at the first call
if (!loadingDiv) {
chart.loadingDiv = loadingDiv = createElement('div', {
className: 'highcharts-loading highcharts-loading-hidden'
}, null, chart.container);
chart.loadingSpan = createElement(
'span', {
className: 'highcharts-loading-inner'
},
null,
loadingDiv
);
addEvent(chart, 'redraw', setLoadingSize); // #1080
}
loadingDiv.className = 'highcharts-loading';
// Update text
chart.loadingSpan.innerHTML = str || options.lang.loading;
chart.loadingShown = true;
setLoadingSize();
},
/**
* Hide the loading layer
*/
hideLoading: function() {
var options = this.options,
loadingDiv = this.loadingDiv;
if (loadingDiv) {
loadingDiv.className = 'highcharts-loading highcharts-loading-hidden';
}
this.loadingShown = false;
},
/**
* These properties cause isDirtyBox to be set to true when updating. Can be extended from plugins.
*/
propsRequireDirtyBox: ['backgroundColor', 'borderColor', 'borderWidth', 'margin', 'marginTop', 'marginRight',
'marginBottom', 'marginLeft', 'spacing', 'spacingTop', 'spacingRight', 'spacingBottom', 'spacingLeft',
'borderRadius', 'plotBackgroundColor', 'plotBackgroundImage', 'plotBorderColor', 'plotBorderWidth',
'plotShadow', 'shadow'
],
/**
* These properties cause all series to be updated when updating. Can be extended from plugins.
*/
propsRequireUpdateSeries: ['chart.polar', 'chart.ignoreHiddenSeries', 'chart.type', 'colors', 'plotOptions'],
/**
* Chart.update function that takes the whole options stucture.
*/
update: function(options, redraw) {
var key,
adders = {
credits: 'addCredits',
title: 'setTitle',
subtitle: 'setSubtitle'
},
optionsChart = options.chart,
updateAllAxes,
updateAllSeries,
newWidth,
newHeight;
// If the top-level chart option is present, some special updates are required
if (optionsChart) {
merge(true, this.options.chart, optionsChart);
// Setter function
if ('className' in optionsChart) {
this.setClassName(optionsChart.className);
}
if ('inverted' in optionsChart || 'polar' in optionsChart) {
this.propFromSeries(); // Parses options.chart.inverted and options.chart.polar together with the available series
updateAllAxes = true;
}
for (key in optionsChart) {
if (optionsChart.hasOwnProperty(key)) {
if (inArray('chart.' + key, this.propsRequireUpdateSeries) !== -1) {
updateAllSeries = true;
}
// Only dirty box
if (inArray(key, this.propsRequireDirtyBox) !== -1) {
this.isDirtyBox = true;
}
}
}
}
// Some option stuctures correspond one-to-one to chart objects that have
// update methods, for example
// options.credits => chart.credits
// options.legend => chart.legend
// options.title => chart.title
// options.tooltip => chart.tooltip
// options.subtitle => chart.subtitle
// options.navigator => chart.navigator
// options.scrollbar => chart.scrollbar
for (key in options) {
if (this[key] && typeof this[key].update === 'function') {
this[key].update(options[key], false);
// If a one-to-one object does not exist, look for an adder function
} else if (typeof this[adders[key]] === 'function') {
this[adders[key]](options[key]);
}
if (key !== 'chart' && inArray(key, this.propsRequireUpdateSeries) !== -1) {
updateAllSeries = true;
}
}
if (options.plotOptions) {
merge(true, this.options.plotOptions, options.plotOptions);
}
// Setters for collections. For axes and series, each item is referred by an id. If the
// id is not found, it defaults to the first item in the collection, so setting series
// without an id, will update the first series in the chart.
each(['xAxis', 'yAxis', 'series'], function(coll) {
if (options[coll]) {
each(splat(options[coll]), function(newOptions) {
var item = (defined(newOptions.id) && this.get(newOptions.id)) || this[coll][0];
if (item && item.coll === coll) {
item.update(newOptions, false);
}
}, this);
}
}, this);
if (updateAllAxes) {
each(this.axes, function(axis) {
axis.update({}, false);
});
}
// Certain options require the whole series structure to be thrown away
// and rebuilt
if (updateAllSeries) {
each(this.series, function(series) {
series.update({}, false);
});
}
// For loading, just update the options, do not redraw
if (options.loading) {
merge(true, this.options.loading, options.loading);
}
// Update size. Redraw is forced.
newWidth = optionsChart && optionsChart.width;
newHeight = optionsChart && optionsChart.height;
if ((isNumber(newWidth) && newWidth !== this.chartWidth) ||
(isNumber(newHeight) && newHeight !== this.chartHeight)) {
this.setSize(newWidth, newHeight);
} else if (pick(redraw, true)) {
this.redraw();
}
},
/**
* Setter function to allow use from chart.update
*/
setSubtitle: function(options) {
this.setTitle(undefined, options);
}
});
// extend the Point prototype for dynamic methods
extend(Point.prototype, {
/**
* Point.update with new options (typically x/y data) and optionally redraw the series.
*
* @param {Object} options Point options as defined in the series.data array
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
update: function(options, redraw, animation, runEvent) {
var point = this,
series = point.series,
graphic = point.graphic,
i,
chart = series.chart,
seriesOptions = series.options;
redraw = pick(redraw, true);
function update() {
point.applyOptions(options);
// Update visuals
if (point.y === null && graphic) { // #4146
point.graphic = graphic.destroy();
}
if (isObject(options, true)) {
// Destroy so we can get new elements
if (graphic && graphic.element) {
if (options && options.marker && options.marker.symbol) {
point.graphic = graphic.destroy();
}
}
if (options && options.dataLabels && point.dataLabel) { // #2468
point.dataLabel = point.dataLabel.destroy();
}
}
// record changes in the parallel arrays
i = point.index;
series.updateParallelArrays(point, i);
// Record the options to options.data. If there is an object from before,
// use point options, otherwise use raw options. (#4701)
seriesOptions.data[i] = isObject(seriesOptions.data[i], true) ? point.options : options;
// redraw
series.isDirty = series.isDirtyData = true;
if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320
chart.isDirtyBox = true;
}
if (seriesOptions.legendType === 'point') { // #1831, #1885
chart.isDirtyLegend = true;
}
if (redraw) {
chart.redraw(animation);
}
}
// Fire the event with a default handler of doing the update
if (runEvent === false) { // When called from setData
update();
} else {
point.firePointEvent('update', {
options: options
}, update);
}
},
/**
* Remove a point and optionally redraw the series and if necessary the axes
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
remove: function(redraw, animation) {
this.series.removePoint(inArray(this, this.series.data), redraw, animation);
}
});
// Extend the series prototype for dynamic methods
extend(Series.prototype, {
/**
* Add a point dynamically after chart load time
* @param {Object} options Point options as given in series.data
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean} shift If shift is true, a point is shifted off the start
* of the series as one is appended to the end.
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
addPoint: function(options, redraw, shift, animation) {
var series = this,
seriesOptions = series.options,
data = series.data,
chart = series.chart,
names = series.xAxis && series.xAxis.names,
dataOptions = seriesOptions.data,
point,
isInTheMiddle,
xData = series.xData,
i,
x;
// Optional redraw, defaults to true
redraw = pick(redraw, true);
// Get options and push the point to xData, yData and series.options. In series.generatePoints
// the Point instance will be created on demand and pushed to the series.data array.
point = {
series: series
};
series.pointClass.prototype.applyOptions.apply(point, [options]);
x = point.x;
// Get the insertion point
i = xData.length;
if (series.requireSorting && x < xData[i - 1]) {
isInTheMiddle = true;
while (i && xData[i - 1] > x) {
i--;
}
}
series.updateParallelArrays(point, 'splice', i, 0, 0); // insert undefined item
series.updateParallelArrays(point, i); // update it
if (names && point.name) {
names[x] = point.name;
}
dataOptions.splice(i, 0, options);
if (isInTheMiddle) {
series.data.splice(i, 0, null);
series.processData();
}
// Generate points to be added to the legend (#1329)
if (seriesOptions.legendType === 'point') {
series.generatePoints();
}
// Shift the first point off the parallel arrays
if (shift) {
if (data[0] && data[0].remove) {
data[0].remove(false);
} else {
data.shift();
series.updateParallelArrays(point, 'shift');
dataOptions.shift();
}
}
// redraw
series.isDirty = true;
series.isDirtyData = true;
if (redraw) {
chart.redraw(animation); // Animation is set anyway on redraw, #5665
}
},
/**
* Remove a point (rendered or not), by index
*/
removePoint: function(i, redraw, animation) {
var series = this,
data = series.data,
point = data[i],
points = series.points,
chart = series.chart,
remove = function() {
if (points && points.length === data.length) { // #4935
points.splice(i, 1);
}
data.splice(i, 1);
series.options.data.splice(i, 1);
series.updateParallelArrays(point || {
series: series
}, 'splice', i, 1);
if (point) {
point.destroy();
}
// redraw
series.isDirty = true;
series.isDirtyData = true;
if (redraw) {
chart.redraw();
}
};
setAnimation(animation, chart);
redraw = pick(redraw, true);
// Fire the event with a default handler of removing the point
if (point) {
point.firePointEvent('remove', null, remove);
} else {
remove();
}
},
/**
* Remove a series and optionally redraw the chart
*
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
remove: function(redraw, animation, withEvent) {
var series = this,
chart = series.chart;
function remove() {
// Destroy elements
series.destroy();
// Redraw
chart.isDirtyLegend = chart.isDirtyBox = true;
chart.linkSeries();
if (pick(redraw, true)) {
chart.redraw(animation);
}
}
// Fire the event with a default handler of removing the point
if (withEvent !== false) {
fireEvent(series, 'remove', null, remove);
} else {
remove();
}
},
/**
* Series.update with a new set of options
*/
update: function(newOptions, redraw) {
var series = this,
chart = this.chart,
// must use user options when changing type because this.options is merged
// in with type specific plotOptions
oldOptions = this.userOptions,
oldType = this.type,
newType = newOptions.type || oldOptions.type || chart.options.chart.type,
proto = seriesTypes[oldType].prototype,
preserve = ['group', 'markerGroup', 'dataLabelsGroup'],
n;
// If we're changing type or zIndex, create new groups (#3380, #3404)
if ((newType && newType !== oldType) || newOptions.zIndex !== undefined) {
preserve.length = 0;
}
// Make sure groups are not destroyed (#3094)
each(preserve, function(prop) {
preserve[prop] = series[prop];
delete series[prop];
});
// Do the merge, with some forced options
newOptions = merge(oldOptions, {
animation: false,
index: this.index,
pointStart: this.xData[0] // when updating after addPoint
}, {
data: this.options.data
}, newOptions);
// Destroy the series and delete all properties. Reinsert all methods
// and properties from the new type prototype (#2270, #3719)
this.remove(false, null, false);
for (n in proto) {
this[n] = undefined;
}
extend(this, seriesTypes[newType || oldType].prototype);
// Re-register groups (#3094)
each(preserve, function(prop) {
series[prop] = preserve[prop];
});
this.init(chart, newOptions);
chart.linkSeries(); // Links are lost in this.remove (#3028)
if (pick(redraw, true)) {
chart.redraw(false);
}
}
});
// Extend the Axis.prototype for dynamic methods
extend(Axis.prototype, {
/**
* Axis.update with a new options structure
*/
update: function(newOptions, redraw) {
var chart = this.chart;
newOptions = chart.options[this.coll][this.options.index] = merge(this.userOptions, newOptions);
this.destroy(true);
this.init(chart, extend(newOptions, {
events: undefined
}));
chart.isDirtyBox = true;
if (pick(redraw, true)) {
chart.redraw();
}
},
/**
* Remove the axis from the chart
*/
remove: function(redraw) {
var chart = this.chart,
key = this.coll, // xAxis or yAxis
axisSeries = this.series,
i = axisSeries.length;
// Remove associated series (#2687)
while (i--) {
if (axisSeries[i]) {
axisSeries[i].remove(false);
}
}
// Remove the axis
erase(chart.axes, this);
erase(chart[key], this);
chart.options[key].splice(this.options.index, 1);
each(chart[key], function(axis, i) { // Re-index, #1706
axis.options.index = i;
});
this.destroy();
chart.isDirtyBox = true;
if (pick(redraw, true)) {
chart.redraw();
}
},
/**
* Update the axis title by options
*/
setTitle: function(newTitleOptions, redraw) {
this.update({
title: newTitleOptions
}, redraw);
},
/**
* Set new axis categories and optionally redraw
* @param {Array} categories
* @param {Boolean} redraw
*/
setCategories: function(categories, redraw) {
this.update({
categories: categories
}, redraw);
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var animObject = H.animObject,
color = H.color,
each = H.each,
extend = H.extend,
isNumber = H.isNumber,
LegendSymbolMixin = H.LegendSymbolMixin,
merge = H.merge,
noop = H.noop,
pick = H.pick,
Series = H.Series,
seriesType = H.seriesType,
stop = H.stop,
svg = H.svg;
/**
* The column series type
*/
seriesType('column', 'line', {
borderRadius: 0,
//colorByPoint: undefined,
groupPadding: 0.2,
//grouping: true,
marker: null, // point options are specified in the base options
pointPadding: 0.1,
//pointWidth: null,
minPointLength: 0,
cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes
pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories
states: {
hover: {
halo: false
}
},
dataLabels: {
align: null, // auto
verticalAlign: null, // auto
y: null
},
softThreshold: false,
startFromThreshold: true, // false doesn't work well: http://jsfiddle.net/highcharts/hz8fopan/14/
stickyTracking: false,
tooltip: {
distance: 6
},
threshold: 0,
// Prototype members
}, {
cropShoulder: 0,
directTouch: true, // When tooltip is not shared, this series (and derivatives) requires direct touch/hover. KD-tree does not apply.
trackerGroups: ['group', 'dataLabelsGroup'],
negStacks: true, // use separate negative stacks, unlike area stacks where a negative
// point is substracted from previous (#1910)
/**
* Initialize the series
*/
init: function() {
Series.prototype.init.apply(this, arguments);
var series = this,
chart = series.chart;
// if the series is added dynamically, force redraw of other
// series affected by a new column
if (chart.hasRendered) {
each(chart.series, function(otherSeries) {
if (otherSeries.type === series.type) {
otherSeries.isDirty = true;
}
});
}
},
/**
* Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding,
* pointWidth etc.
*/
getColumnMetrics: function() {
var series = this,
options = series.options,
xAxis = series.xAxis,
yAxis = series.yAxis,
reversedXAxis = xAxis.reversed,
stackKey,
stackGroups = {},
columnCount = 0;
// Get the total number of column type series.
// This is called on every series. Consider moving this logic to a
// chart.orderStacks() function and call it on init, addSeries and removeSeries
if (options.grouping === false) {
columnCount = 1;
} else {
each(series.chart.series, function(otherSeries) {
var otherOptions = otherSeries.options,
otherYAxis = otherSeries.yAxis,
columnIndex;
if (otherSeries.type === series.type && otherSeries.visible &&
yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086
if (otherOptions.stacking) {
stackKey = otherSeries.stackKey;
if (stackGroups[stackKey] === undefined) {
stackGroups[stackKey] = columnCount++;
}
columnIndex = stackGroups[stackKey];
} else if (otherOptions.grouping !== false) { // #1162
columnIndex = columnCount++;
}
otherSeries.columnIndex = columnIndex;
}
});
}
var categoryWidth = Math.min(
Math.abs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || xAxis.tickInterval || 1), // #2610
xAxis.len // #1535
),
groupPadding = categoryWidth * options.groupPadding,
groupWidth = categoryWidth - 2 * groupPadding,
pointOffsetWidth = groupWidth / columnCount,
pointWidth = Math.min(
options.maxPointWidth || xAxis.len,
pick(options.pointWidth, pointOffsetWidth * (1 - 2 * options.pointPadding))
),
pointPadding = (pointOffsetWidth - pointWidth) / 2,
colIndex = (series.columnIndex || 0) + (reversedXAxis ? 1 : 0), // #1251, #3737
pointXOffset = pointPadding + (groupPadding + colIndex *
pointOffsetWidth - (categoryWidth / 2)) *
(reversedXAxis ? -1 : 1);
// Save it for reading in linked series (Error bars particularly)
series.columnMetrics = {
width: pointWidth,
offset: pointXOffset
};
return series.columnMetrics;
},
/**
* Make the columns crisp. The edges are rounded to the nearest full pixel.
*/
crispCol: function(x, y, w, h) {
var chart = this.chart,
borderWidth = this.borderWidth,
xCrisp = -(borderWidth % 2 ? 0.5 : 0),
yCrisp = borderWidth % 2 ? 0.5 : 1,
right,
bottom,
fromTop;
if (chart.inverted && chart.renderer.isVML) {
yCrisp += 1;
}
// Horizontal. We need to first compute the exact right edge, then round it
// and compute the width from there.
right = Math.round(x + w) + xCrisp;
x = Math.round(x) + xCrisp;
w = right - x;
// Vertical
bottom = Math.round(y + h) + yCrisp;
fromTop = Math.abs(y) <= 0.5 && bottom > 0.5; // #4504, #4656
y = Math.round(y) + yCrisp;
h = bottom - y;
// Top edges are exceptions
if (fromTop && h) { // #5146
y -= 1;
h += 1;
}
return {
x: x,
y: y,
width: w,
height: h
};
},
/**
* Translate each point to the plot area coordinate system and find shape positions
*/
translate: function() {
var series = this,
chart = series.chart,
options = series.options,
dense = series.dense = series.closestPointRange * series.xAxis.transA < 2,
borderWidth = series.borderWidth = pick(
options.borderWidth,
dense ? 0 : 1 // #3635
),
yAxis = series.yAxis,
threshold = options.threshold,
translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold),
minPointLength = pick(options.minPointLength, 5),
metrics = series.getColumnMetrics(),
pointWidth = metrics.width,
seriesBarW = series.barW = Math.max(pointWidth, 1 + 2 * borderWidth), // postprocessed for border width
pointXOffset = series.pointXOffset = metrics.offset;
if (chart.inverted) {
translatedThreshold -= 0.5; // #3355
}
// When the pointPadding is 0, we want the columns to be packed tightly, so we allow individual
// columns to have individual sizes. When pointPadding is greater, we strive for equal-width
// columns (#2694).
if (options.pointPadding) {
seriesBarW = Math.ceil(seriesBarW);
}
Series.prototype.translate.apply(series);
// Record the new values
each(series.points, function(point) {
var yBottom = pick(point.yBottom, translatedThreshold),
safeDistance = 999 + Math.abs(yBottom),
plotY = Math.min(Math.max(-safeDistance, point.plotY), yAxis.len + safeDistance), // Don't draw too far outside plot area (#1303, #2241, #4264)
barX = point.plotX + pointXOffset,
barW = seriesBarW,
barY = Math.min(plotY, yBottom),
up,
barH = Math.max(plotY, yBottom) - barY;
// Handle options.minPointLength
if (Math.abs(barH) < minPointLength) {
if (minPointLength) {
barH = minPointLength;
up = (!yAxis.reversed && !point.negative) || (yAxis.reversed && point.negative);
barY = Math.abs(barY - translatedThreshold) > minPointLength ? // stacked
yBottom - minPointLength : // keep position
translatedThreshold - (up ? minPointLength : 0); // #1485, #4051
}
}
// Cache for access in polar
point.barX = barX;
point.pointWidth = pointWidth;
// Fix the tooltip on center of grouped columns (#1216, #424, #3648)
point.tooltipPos = chart.inverted ? [yAxis.len + yAxis.pos - chart.plotLeft - plotY, series.xAxis.len - barX - barW / 2, barH] : [barX + barW / 2, plotY + yAxis.pos - chart.plotTop, barH];
// Register shape type and arguments to be used in drawPoints
point.shapeType = 'rect';
point.shapeArgs = series.crispCol.apply(
series,
point.isNull ? [point.plotX, yAxis.len / 2, 0, 0] : // #3169, drilldown from null must have a position to work from
[barX, barY, barW, barH]
);
});
},
getSymbol: noop,
/**
* Use a solid rectangle like the area series types
*/
drawLegendSymbol: LegendSymbolMixin.drawRectangle,
/**
* Columns have no graph
*/
drawGraph: function() {
this.group[this.dense ? 'addClass' : 'removeClass']('highcharts-dense-data');
},
/**
* Draw the columns. For bars, the series.group is rotated, so the same coordinates
* apply for columns and bars. This method is inherited by scatter series.
*
*/
drawPoints: function() {
var series = this,
chart = this.chart,
options = series.options,
renderer = chart.renderer,
animationLimit = options.animationLimit || 250,
shapeArgs;
// draw the columns
each(series.points, function(point) {
var plotY = point.plotY,
graphic = point.graphic;
if (isNumber(plotY) && point.y !== null) {
shapeArgs = point.shapeArgs;
if (graphic) { // update
stop(graphic);
graphic[chart.pointCount < animationLimit ? 'animate' : 'attr'](
merge(shapeArgs)
);
} else {
point.graphic = graphic = renderer[point.shapeType](shapeArgs)
.attr({
'class': point.getClassName()
})
.add(point.group || series.group);
}
} else if (graphic) {
point.graphic = graphic.destroy(); // #1269
}
});
},
/**
* Animate the column heights one by one from zero
* @param {Boolean} init Whether to initialize the animation or run it
*/
animate: function(init) {
var series = this,
yAxis = this.yAxis,
options = series.options,
inverted = this.chart.inverted,
attr = {},
translatedThreshold;
if (svg) { // VML is too slow anyway
if (init) {
attr.scaleY = 0.001;
translatedThreshold = Math.min(yAxis.pos + yAxis.len, Math.max(yAxis.pos, yAxis.toPixels(options.threshold)));
if (inverted) {
attr.translateX = translatedThreshold - yAxis.len;
} else {
attr.translateY = translatedThreshold;
}
series.group.attr(attr);
} else { // run the animation
attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos;
series.group.animate(attr, extend(animObject(series.options.animation), {
// Do the scale synchronously to ensure smooth updating (#5030)
step: function(val, fx) {
series.group.attr({
scaleY: Math.max(0.001, fx.pos) // #5250
});
}
}));
// delete this function to allow it only once
series.animate = null;
}
}
},
/**
* Remove this series from the chart
*/
remove: function() {
var series = this,
chart = series.chart;
// column and bar series affects other series of the same type
// as they are either stacked or grouped
if (chart.hasRendered) {
each(chart.series, function(otherSeries) {
if (otherSeries.type === series.type) {
otherSeries.isDirty = true;
}
});
}
Series.prototype.remove.apply(series, arguments);
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Series = H.Series,
seriesType = H.seriesType;
/**
* The scatter series type
*/
seriesType('scatter', 'line', {
lineWidth: 0,
marker: {
enabled: true // Overrides auto-enabling in line series (#3647)
},
tooltip: {
headerFormat: '<span style="color:{point.color}">\u25CF</span> <span style="font-size: 0.85em"> {series.name}</span><br/>',
pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>'
}
// Prototype members
}, {
sorted: false,
requireSorting: false,
noSharedTooltip: true,
trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'],
takeOrdinalPosition: false, // #2342
kdDimensions: 2,
drawGraph: function() {
if (this.options.lineWidth) {
Series.prototype.drawGraph.call(this);
}
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
arrayMax = H.arrayMax,
defined = H.defined,
each = H.each,
extend = H.extend,
format = H.format,
map = H.map,
merge = H.merge,
noop = H.noop,
pick = H.pick,
relativeLength = H.relativeLength,
Series = H.Series,
seriesTypes = H.seriesTypes,
stableSort = H.stableSort,
stop = H.stop;
/**
* Generatl distribution algorithm for distributing labels of differing size along a
* confined length in two dimensions. The algorithm takes an array of objects containing
* a size, a target and a rank. It will place the labels as close as possible to their
* targets, skipping the lowest ranked labels if necessary.
*/
H.distribute = function(boxes, len) {
var i,
overlapping = true,
origBoxes = boxes, // Original array will be altered with added .pos
restBoxes = [], // The outranked overshoot
box,
target,
total = 0;
function sortByTarget(a, b) {
return a.target - b.target;
}
// If the total size exceeds the len, remove those boxes with the lowest rank
i = boxes.length;
while (i--) {
total += boxes[i].size;
}
// Sort by rank, then slice away overshoot
if (total > len) {
stableSort(boxes, function(a, b) {
return (b.rank || 0) - (a.rank || 0);
});
i = 0;
total = 0;
while (total <= len) {
total += boxes[i].size;
i++;
}
restBoxes = boxes.splice(i - 1, boxes.length);
}
// Order by target
stableSort(boxes, sortByTarget);
// So far we have been mutating the original array. Now
// create a copy with target arrays
boxes = map(boxes, function(box) {
return {
size: box.size,
targets: [box.target]
};
});
while (overlapping) {
// Initial positions: target centered in box
i = boxes.length;
while (i--) {
box = boxes[i];
// Composite box, average of targets
target = (Math.min.apply(0, box.targets) + Math.max.apply(0, box.targets)) / 2;
box.pos = Math.min(Math.max(0, target - box.size / 2), len - box.size);
}
// Detect overlap and join boxes
i = boxes.length;
overlapping = false;
while (i--) {
if (i > 0 && boxes[i - 1].pos + boxes[i - 1].size > boxes[i].pos) { // Overlap
boxes[i - 1].size += boxes[i].size; // Add this size to the previous box
boxes[i - 1].targets = boxes[i - 1].targets.concat(boxes[i].targets);
// Overlapping right, push left
if (boxes[i - 1].pos + boxes[i - 1].size > len) {
boxes[i - 1].pos = len - boxes[i - 1].size;
}
boxes.splice(i, 1); // Remove this item
overlapping = true;
}
}
}
// Now the composite boxes are placed, we need to put the original boxes within them
i = 0;
each(boxes, function(box) {
var posInCompositeBox = 0;
each(box.targets, function() {
origBoxes[i].pos = box.pos + posInCompositeBox;
posInCompositeBox += origBoxes[i].size;
i++;
});
});
// Add the rest (hidden) boxes and sort by target
origBoxes.push.apply(origBoxes, restBoxes);
stableSort(origBoxes, sortByTarget);
};
/**
* Draw the data labels
*/
Series.prototype.drawDataLabels = function() {
var series = this,
seriesOptions = series.options,
options = seriesOptions.dataLabels,
points = series.points,
pointOptions,
generalOptions,
hasRendered = series.hasRendered || 0,
str,
dataLabelsGroup,
defer = pick(options.defer, true),
renderer = series.chart.renderer;
if (options.enabled || series._hasPointLabels) {
// Process default alignment of data labels for columns
if (series.dlProcessOptions) {
series.dlProcessOptions(options);
}
// Create a separate group for the data labels to avoid rotation
dataLabelsGroup = series.plotGroup(
'dataLabelsGroup',
'data-labels',
defer && !hasRendered ? 'hidden' : 'visible', // #5133
options.zIndex || 6
);
if (defer) {
dataLabelsGroup.attr({
opacity: +hasRendered
}); // #3300
if (!hasRendered) {
addEvent(series, 'afterAnimate', function() {
if (series.visible) { // #2597, #3023, #3024
dataLabelsGroup.show(true);
}
dataLabelsGroup[seriesOptions.animation ? 'animate' : 'attr']({
opacity: 1
}, {
duration: 200
});
});
}
}
// Make the labels for each point
generalOptions = options;
each(points, function(point) {
var enabled,
dataLabel = point.dataLabel,
labelConfig,
attr,
name,
rotation,
connector = point.connector,
isNew = true,
style,
moreStyle = {};
// Determine if each data label is enabled
pointOptions = point.dlOptions || (point.options && point.options.dataLabels); // dlOptions is used in treemaps
enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled) && point.y !== null; // #2282, #4641
// If the point is outside the plot area, destroy it. #678, #820
if (dataLabel && !enabled) {
point.dataLabel = dataLabel.destroy();
// Individual labels are disabled if the are explicitly disabled
// in the point options, or if they fall outside the plot area.
} else if (enabled) {
// Create individual options structure that can be extended without
// affecting others
options = merge(generalOptions, pointOptions);
style = options.style;
rotation = options.rotation;
// Get the string
labelConfig = point.getLabelConfig();
str = options.format ?
format(options.format, labelConfig) :
options.formatter.call(labelConfig, options);
// update existing label
if (dataLabel) {
if (defined(str)) {
dataLabel
.attr({
text: str
});
isNew = false;
} else { // #1437 - the label is shown conditionally
point.dataLabel = dataLabel = dataLabel.destroy();
if (connector) {
point.connector = connector.destroy();
}
}
// create new label
} else if (defined(str)) {
attr = {
//align: align,
r: options.borderRadius || 0,
rotation: rotation,
padding: options.padding,
zIndex: 1
};
// Remove unused attributes (#947)
for (name in attr) {
if (attr[name] === undefined) {
delete attr[name];
}
}
dataLabel = point.dataLabel = renderer[rotation ? 'text' : 'label']( // labels don't support rotation
str,
0, -9999,
options.shape,
null,
null,
options.useHTML,
null,
'data-label'
)
.attr(attr);
dataLabel.addClass('highcharts-data-label-color-' + point.colorIndex + ' ' + (options.className || ''));
dataLabel.add(dataLabelsGroup);
}
if (dataLabel) {
// Now the data label is created and placed at 0,0, so we need to align it
series.alignDataLabel(point, dataLabel, options, null, isNew);
}
}
});
}
};
/**
* Align each individual data label
*/
Series.prototype.alignDataLabel = function(point, dataLabel, options, alignTo, isNew) {
var chart = this.chart,
inverted = chart.inverted,
plotX = pick(point.plotX, -9999),
plotY = pick(point.plotY, -9999),
bBox = dataLabel.getBBox(),
fontSize,
baseline,
rotation = options.rotation,
normRotation,
negRotation,
align = options.align,
rotCorr, // rotation correction
// Math.round for rounding errors (#2683), alignTo to allow column labels (#2700)
visible = this.visible && (point.series.forceDL || chart.isInsidePlot(plotX, Math.round(plotY), inverted) ||
(alignTo && chart.isInsidePlot(plotX, inverted ? alignTo.x + 1 : alignTo.y + alignTo.height - 1, inverted))),
alignAttr, // the final position;
justify = pick(options.overflow, 'justify') === 'justify';
if (visible) {
baseline = chart.renderer.fontMetrics(fontSize, dataLabel).b;
// The alignment box is a singular point
alignTo = extend({
x: inverted ? chart.plotWidth - plotY : plotX,
y: Math.round(inverted ? chart.plotHeight - plotX : plotY),
width: 0,
height: 0
}, alignTo);
// Add the text size for alignment calculation
extend(options, {
width: bBox.width,
height: bBox.height
});
// Allow a hook for changing alignment in the last moment, then do the alignment
if (rotation) {
justify = false; // Not supported for rotated text
rotCorr = chart.renderer.rotCorr(baseline, rotation); // #3723
alignAttr = {
x: alignTo.x + options.x + alignTo.width / 2 + rotCorr.x,
y: alignTo.y + options.y + {
top: 0,
middle: 0.5,
bottom: 1
}[options.verticalAlign] * alignTo.height
};
dataLabel[isNew ? 'attr' : 'animate'](alignAttr)
.attr({ // #3003
align: align
});
// Compensate for the rotated label sticking out on the sides
normRotation = (rotation + 720) % 360;
negRotation = normRotation > 180 && normRotation < 360;
if (align === 'left') {
alignAttr.y -= negRotation ? bBox.height : 0;
} else if (align === 'center') {
alignAttr.x -= bBox.width / 2;
alignAttr.y -= bBox.height / 2;
} else if (align === 'right') {
alignAttr.x -= bBox.width;
alignAttr.y -= negRotation ? 0 : bBox.height;
}
} else {
dataLabel.align(options, null, alignTo);
alignAttr = dataLabel.alignAttr;
}
// Handle justify or crop
if (justify) {
this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew);
// Now check that the data label is within the plot area
} else if (pick(options.crop, true)) {
visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height);
}
// When we're using a shape, make it possible with a connector or an arrow pointing to thie point
if (options.shape && !rotation) {
dataLabel.attr({
anchorX: point.plotX,
anchorY: point.plotY
});
}
}
// Show or hide based on the final aligned position
if (!visible) {
stop(dataLabel);
dataLabel.attr({
y: -9999
});
dataLabel.placed = false; // don't animate back in
}
};
/**
* If data labels fall partly outside the plot area, align them back in, in a way that
* doesn't hide the point.
*/
Series.prototype.justifyDataLabel = function(dataLabel, options, alignAttr, bBox, alignTo, isNew) {
var chart = this.chart,
align = options.align,
verticalAlign = options.verticalAlign,
off,
justified,
padding = dataLabel.box ? 0 : (dataLabel.padding || 0);
// Off left
off = alignAttr.x + padding;
if (off < 0) {
if (align === 'right') {
options.align = 'left';
} else {
options.x = -off;
}
justified = true;
}
// Off right
off = alignAttr.x + bBox.width - padding;
if (off > chart.plotWidth) {
if (align === 'left') {
options.align = 'right';
} else {
options.x = chart.plotWidth - off;
}
justified = true;
}
// Off top
off = alignAttr.y + padding;
if (off < 0) {
if (verticalAlign === 'bottom') {
options.verticalAlign = 'top';
} else {
options.y = -off;
}
justified = true;
}
// Off bottom
off = alignAttr.y + bBox.height - padding;
if (off > chart.plotHeight) {
if (verticalAlign === 'top') {
options.verticalAlign = 'bottom';
} else {
options.y = chart.plotHeight - off;
}
justified = true;
}
if (justified) {
dataLabel.placed = !isNew;
dataLabel.align(options, null, alignTo);
}
};
/**
* Override the base drawDataLabels method by pie specific functionality
*/
if (seriesTypes.pie) {
seriesTypes.pie.prototype.drawDataLabels = function() {
var series = this,
data = series.data,
point,
chart = series.chart,
options = series.options.dataLabels,
connectorPadding = pick(options.connectorPadding, 10),
connectorWidth = pick(options.connectorWidth, 1),
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
connector,
distanceOption = options.distance,
seriesCenter = series.center,
radius = seriesCenter[2] / 2,
centerY = seriesCenter[1],
outside = distanceOption > 0,
dataLabel,
dataLabelWidth,
labelPos,
labelHeight,
halves = [ // divide the points into right and left halves for anti collision
[], // right
[] // left
],
x,
y,
visibility,
j,
overflow = [0, 0, 0, 0]; // top, right, bottom, left
// get out if not enabled
if (!series.visible || (!options.enabled && !series._hasPointLabels)) {
return;
}
// run parent method
Series.prototype.drawDataLabels.apply(series);
each(data, function(point) {
if (point.dataLabel && point.visible) { // #407, #2510
// Arrange points for detection collision
halves[point.half].push(point);
// Reset positions (#4905)
point.dataLabel._pos = null;
}
});
/* Loop over the points in each half, starting from the top and bottom
* of the pie to detect overlapping labels.
*/
each(halves, function(points, i) {
var top,
bottom,
length = points.length,
positions,
naturalY,
size;
if (!length) {
return;
}
// Sort by angle
series.sortByAngle(points, i - 0.5);
// Only do anti-collision when we are outside the pie and have connectors (#856)
if (distanceOption > 0) {
top = Math.max(0, centerY - radius - distanceOption);
bottom = Math.min(centerY + radius + distanceOption, chart.plotHeight);
positions = map(points, function(point) {
if (point.dataLabel) {
size = point.dataLabel.getBBox().height || 21;
return {
target: point.labelPos[1] - top + size / 2,
size: size,
rank: point.y
};
}
});
H.distribute(positions, bottom + size - top);
}
// now the used slots are sorted, fill them up sequentially
for (j = 0; j < length; j++) {
point = points[j];
labelPos = point.labelPos;
dataLabel = point.dataLabel;
visibility = point.visible === false ? 'hidden' : 'inherit';
naturalY = labelPos[1];
if (positions) {
if (positions[j].pos === undefined) {
visibility = 'hidden';
} else {
labelHeight = positions[j].size;
y = top + positions[j].pos;
}
} else {
y = naturalY;
}
// get the x - use the natural x position for labels near the top and bottom, to prevent the top
// and botton slice connectors from touching each other on either side
if (options.justify) {
x = seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption);
} else {
x = series.getX(y < top + 2 || y > bottom - 2 ? naturalY : y, i);
}
// Record the placement and visibility
dataLabel._attr = {
visibility: visibility,
align: labelPos[6]
};
dataLabel._pos = {
x: x + options.x +
({
left: connectorPadding,
right: -connectorPadding
}[labelPos[6]] || 0),
y: y + options.y - 10 // 10 is for the baseline (label vs text)
};
labelPos.x = x;
labelPos.y = y;
// Detect overflowing data labels
if (series.options.size === null) {
dataLabelWidth = dataLabel.width;
// Overflow left
if (x - dataLabelWidth < connectorPadding) {
overflow[3] = Math.max(Math.round(dataLabelWidth - x + connectorPadding), overflow[3]);
// Overflow right
} else if (x + dataLabelWidth > plotWidth - connectorPadding) {
overflow[1] = Math.max(Math.round(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]);
}
// Overflow top
if (y - labelHeight / 2 < 0) {
overflow[0] = Math.max(Math.round(-y + labelHeight / 2), overflow[0]);
// Overflow left
} else if (y + labelHeight / 2 > plotHeight) {
overflow[2] = Math.max(Math.round(y + labelHeight / 2 - plotHeight), overflow[2]);
}
}
} // for each point
}); // for each half
// Do not apply the final placement and draw the connectors until we have verified
// that labels are not spilling over.
if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) {
// Place the labels in the final position
this.placeDataLabels();
// Draw the connectors
if (outside && connectorWidth) {
each(this.points, function(point) {
var isNew;
connector = point.connector;
dataLabel = point.dataLabel;
if (dataLabel && dataLabel._pos && point.visible) {
visibility = dataLabel._attr.visibility;
isNew = !connector;
if (isNew) {
point.connector = connector = chart.renderer.path()
.addClass('highcharts-data-label-connector highcharts-color-' + point.colorIndex)
.add(series.dataLabelsGroup);
}
connector[isNew ? 'attr' : 'animate']({
d: series.connectorPath(point.labelPos)
});
connector.attr('visibility', visibility);
} else if (connector) {
point.connector = connector.destroy();
}
});
}
}
};
/**
* Extendable method for getting the path of the connector between the data label
* and the pie slice.
*/
seriesTypes.pie.prototype.connectorPath = function(labelPos) {
var x = labelPos.x,
y = labelPos.y;
return pick(this.options.softConnector, true) ? [
'M',
x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
'C',
x, y, // first break, next to the label
2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5],
labelPos[2], labelPos[3], // second break
'L',
labelPos[4], labelPos[5] // base
] : [
'M',
x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
'L',
labelPos[2], labelPos[3], // second break
'L',
labelPos[4], labelPos[5] // base
];
};
/**
* Perform the final placement of the data labels after we have verified that they
* fall within the plot area.
*/
seriesTypes.pie.prototype.placeDataLabels = function() {
each(this.points, function(point) {
var dataLabel = point.dataLabel,
_pos;
if (dataLabel && point.visible) {
_pos = dataLabel._pos;
if (_pos) {
dataLabel.attr(dataLabel._attr);
dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos);
dataLabel.moved = true;
} else if (dataLabel) {
dataLabel.attr({
y: -9999
});
}
}
});
};
seriesTypes.pie.prototype.alignDataLabel = noop;
/**
* Verify whether the data labels are allowed to draw, or we should run more translation and data
* label positioning to keep them inside the plot area. Returns true when data labels are ready
* to draw.
*/
seriesTypes.pie.prototype.verifyDataLabelOverflow = function(overflow) {
var center = this.center,
options = this.options,
centerOption = options.center,
minSize = options.minSize || 80,
newSize = minSize,
ret;
// Handle horizontal size and center
if (centerOption[0] !== null) { // Fixed center
newSize = Math.max(center[2] - Math.max(overflow[1], overflow[3]), minSize);
} else { // Auto center
newSize = Math.max(
center[2] - overflow[1] - overflow[3], // horizontal overflow
minSize
);
center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center
}
// Handle vertical size and center
if (centerOption[1] !== null) { // Fixed center
newSize = Math.max(Math.min(newSize, center[2] - Math.max(overflow[0], overflow[2])), minSize);
} else { // Auto center
newSize = Math.max(
Math.min(
newSize,
center[2] - overflow[0] - overflow[2] // vertical overflow
),
minSize
);
center[1] += (overflow[0] - overflow[2]) / 2; // vertical center
}
// If the size must be decreased, we need to run translate and drawDataLabels again
if (newSize < center[2]) {
center[2] = newSize;
center[3] = Math.min(relativeLength(options.innerSize || 0, newSize), newSize); // #3632
this.translate(center);
if (this.drawDataLabels) {
this.drawDataLabels();
}
// Else, return true to indicate that the pie and its labels is within the plot area
} else {
ret = true;
}
return ret;
};
}
if (seriesTypes.column) {
/**
* Override the basic data label alignment by adjusting for the position of the column
*/
seriesTypes.column.prototype.alignDataLabel = function(point, dataLabel, options, alignTo, isNew) {
var inverted = this.chart.inverted,
series = point.series,
dlBox = point.dlBox || point.shapeArgs, // data label box for alignment
below = pick(point.below, point.plotY > pick(this.translatedThreshold, series.yAxis.len)), // point.below is used in range series
inside = pick(options.inside, !!this.options.stacking), // draw it inside the box?
overshoot;
// Align to the column itself, or the top of it
if (dlBox) { // Area range uses this method but not alignTo
alignTo = merge(dlBox);
if (alignTo.y < 0) {
alignTo.height += alignTo.y;
alignTo.y = 0;
}
overshoot = alignTo.y + alignTo.height - series.yAxis.len;
if (overshoot > 0) {
alignTo.height -= overshoot;
}
if (inverted) {
alignTo = {
x: series.yAxis.len - alignTo.y - alignTo.height,
y: series.xAxis.len - alignTo.x - alignTo.width,
width: alignTo.height,
height: alignTo.width
};
}
// Compute the alignment box
if (!inside) {
if (inverted) {
alignTo.x += below ? 0 : alignTo.width;
alignTo.width = 0;
} else {
alignTo.y += below ? alignTo.height : 0;
alignTo.height = 0;
}
}
}
// When alignment is undefined (typically columns and bars), display the individual
// point below or above the point depending on the threshold
options.align = pick(
options.align, !inverted || inside ? 'center' : below ? 'right' : 'left'
);
options.verticalAlign = pick(
options.verticalAlign,
inverted || inside ? 'middle' : below ? 'top' : 'bottom'
);
// Call the parent method
Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew);
};
}
}(Highcharts));
(function(H) {
/**
* (c) 2009-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
/**
* Highcharts module to hide overlapping data labels. This module is included in Highcharts.
*/
var Chart = H.Chart,
each = H.each,
pick = H.pick,
addEvent = H.addEvent;
// Collect potensial overlapping data labels. Stack labels probably don't need to be
// considered because they are usually accompanied by data labels that lie inside the columns.
Chart.prototype.callbacks.push(function(chart) {
function collectAndHide() {
var labels = [];
each(chart.series, function(series) {
var dlOptions = series.options.dataLabels,
collections = series.dataLabelCollections || ['dataLabel']; // Range series have two collections
if ((dlOptions.enabled || series._hasPointLabels) && !dlOptions.allowOverlap && series.visible) { // #3866
each(collections, function(coll) {
each(series.points, function(point) {
if (point[coll]) {
point[coll].labelrank = pick(point.labelrank, point.shapeArgs && point.shapeArgs.height); // #4118
labels.push(point[coll]);
}
});
});
}
});
chart.hideOverlappingLabels(labels);
}
// Do it now ...
collectAndHide();
// ... and after each chart redraw
addEvent(chart, 'redraw', collectAndHide);
});
/**
* Hide overlapping labels. Labels are moved and faded in and out on zoom to provide a smooth
* visual imression.
*/
Chart.prototype.hideOverlappingLabels = function(labels) {
var len = labels.length,
label,
i,
j,
label1,
label2,
isIntersecting,
pos1,
pos2,
parent1,
parent2,
padding,
intersectRect = function(x1, y1, w1, h1, x2, y2, w2, h2) {
return !(
x2 > x1 + w1 ||
x2 + w2 < x1 ||
y2 > y1 + h1 ||
y2 + h2 < y1
);
};
// Mark with initial opacity
for (i = 0; i < len; i++) {
label = labels[i];
if (label) {
label.oldOpacity = label.opacity;
label.newOpacity = 1;
}
}
// Prevent a situation in a gradually rising slope, that each label
// will hide the previous one because the previous one always has
// lower rank.
labels.sort(function(a, b) {
return (b.labelrank || 0) - (a.labelrank || 0);
});
// Detect overlapping labels
for (i = 0; i < len; i++) {
label1 = labels[i];
for (j = i + 1; j < len; ++j) {
label2 = labels[j];
if (label1 && label2 && label1.placed && label2.placed && label1.newOpacity !== 0 && label2.newOpacity !== 0) {
pos1 = label1.alignAttr;
pos2 = label2.alignAttr;
parent1 = label1.parentGroup; // Different panes have different positions
parent2 = label2.parentGroup;
padding = 2 * (label1.box ? 0 : label1.padding); // Substract the padding if no background or border (#4333)
isIntersecting = intersectRect(
pos1.x + parent1.translateX,
pos1.y + parent1.translateY,
label1.width - padding,
label1.height - padding,
pos2.x + parent2.translateX,
pos2.y + parent2.translateY,
label2.width - padding,
label2.height - padding
);
if (isIntersecting) {
(label1.labelrank < label2.labelrank ? label1 : label2).newOpacity = 0;
}
}
}
}
// Hide or show
each(labels, function(label) {
var complete,
newOpacity;
if (label) {
newOpacity = label.newOpacity;
if (label.oldOpacity !== newOpacity && label.placed) {
// Make sure the label is completely hidden to avoid catching clicks (#4362)
if (newOpacity) {
label.show(true);
} else {
complete = function() {
label.hide();
};
}
// Animate or set the opacity
label.alignAttr.opacity = newOpacity;
label[label.isOld ? 'animate' : 'attr'](label.alignAttr, null, complete);
}
label.isOld = true;
}
});
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Axis = H.Axis,
each = H.each,
pick = H.pick,
wrap = H.wrap;
/**
* Override to use the extreme coordinates from the SVG shape, not the
* data values
*/
wrap(Axis.prototype, 'getSeriesExtremes', function(proceed) {
var isXAxis = this.isXAxis,
dataMin,
dataMax,
xData = [],
useMapGeometry;
// Remove the xData array and cache it locally so that the proceed method doesn't use it
if (isXAxis) {
each(this.series, function(series, i) {
if (series.useMapGeometry) {
xData[i] = series.xData;
series.xData = [];
}
});
}
// Call base to reach normal cartesian series (like mappoint)
proceed.call(this);
// Run extremes logic for map and mapline
if (isXAxis) {
dataMin = pick(this.dataMin, Number.MAX_VALUE);
dataMax = pick(this.dataMax, -Number.MAX_VALUE);
each(this.series, function(series, i) {
if (series.useMapGeometry) {
dataMin = Math.min(dataMin, pick(series.minX, dataMin));
dataMax = Math.max(dataMax, pick(series.maxX, dataMin));
series.xData = xData[i]; // Reset xData array
useMapGeometry = true;
}
});
if (useMapGeometry) {
this.dataMin = dataMin;
this.dataMax = dataMax;
}
}
});
/**
* Override axis translation to make sure the aspect ratio is always kept
*/
wrap(Axis.prototype, 'setAxisTranslation', function(proceed) {
var chart = this.chart,
mapRatio,
plotRatio = chart.plotWidth / chart.plotHeight,
adjustedAxisLength,
xAxis = chart.xAxis[0],
padAxis,
fixTo,
fixDiff,
preserveAspectRatio;
// Run the parent method
proceed.call(this);
// Check for map-like series
if (this.coll === 'yAxis' && xAxis.transA !== undefined) {
each(this.series, function(series) {
if (series.preserveAspectRatio) {
preserveAspectRatio = true;
}
});
}
// On Y axis, handle both
if (preserveAspectRatio) {
// Use the same translation for both axes
this.transA = xAxis.transA = Math.min(this.transA, xAxis.transA);
mapRatio = plotRatio / ((xAxis.max - xAxis.min) / (this.max - this.min));
// What axis to pad to put the map in the middle
padAxis = mapRatio < 1 ? this : xAxis;
// Pad it
adjustedAxisLength = (padAxis.max - padAxis.min) * padAxis.transA;
padAxis.pixelPadding = padAxis.len - adjustedAxisLength;
padAxis.minPixelPadding = padAxis.pixelPadding / 2;
fixTo = padAxis.fixTo;
if (fixTo) {
fixDiff = fixTo[1] - padAxis.toValue(fixTo[0], true);
fixDiff *= padAxis.transA;
if (Math.abs(fixDiff) > padAxis.minPixelPadding || (padAxis.min === padAxis.dataMin && padAxis.max === padAxis.dataMax)) { // zooming out again, keep within restricted area
fixDiff = 0;
}
padAxis.minPixelPadding -= fixDiff;
}
}
});
/**
* Override Axis.render in order to delete the fixTo prop
*/
wrap(Axis.prototype, 'render', function(proceed) {
proceed.call(this);
this.fixTo = null;
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Axis = H.Axis,
Chart = H.Chart,
color = H.color,
ColorAxis,
each = H.each,
extend = H.extend,
isNumber = H.isNumber,
Legend = H.Legend,
LegendSymbolMixin = H.LegendSymbolMixin,
noop = H.noop,
merge = H.merge,
pick = H.pick,
wrap = H.wrap;
/**
* The ColorAxis object for inclusion in gradient legends
*/
ColorAxis = H.ColorAxis = function() {
this.init.apply(this, arguments);
};
extend(ColorAxis.prototype, Axis.prototype);
extend(ColorAxis.prototype, {
defaultColorAxisOptions: {
lineWidth: 0,
minPadding: 0,
maxPadding: 0,
gridLineWidth: 1,
tickPixelInterval: 72,
startOnTick: true,
endOnTick: true,
offset: 0,
marker: {
animation: {
duration: 50
},
width: 0.01
},
labels: {
overflow: 'justify'
},
minColor: '#e6ebf5',
maxColor: '#003399',
tickLength: 5,
showInLegend: true
},
init: function(chart, userOptions) {
var horiz = chart.options.legend.layout !== 'vertical',
options;
this.coll = 'colorAxis';
// Build the options
options = merge(this.defaultColorAxisOptions, {
side: horiz ? 2 : 1,
reversed: !horiz
}, userOptions, {
opposite: !horiz,
showEmpty: false,
title: null
});
Axis.prototype.init.call(this, chart, options);
// Base init() pushes it to the xAxis array, now pop it again
//chart[this.isXAxis ? 'xAxis' : 'yAxis'].pop();
// Prepare data classes
if (userOptions.dataClasses) {
this.initDataClasses(userOptions);
}
this.initStops(userOptions);
// Override original axis properties
this.horiz = horiz;
this.zoomEnabled = false;
// Add default values
this.defaultLegendLength = 200;
},
/*
* Return an intermediate color between two colors, according to pos where 0
* is the from color and 1 is the to color.
* NOTE: Changes here should be copied
* to the same function in drilldown.src.js and solid-gauge-src.js.
*/
tweenColors: function(from, to, pos) {
// Check for has alpha, because rgba colors perform worse due to lack of
// support in WebKit.
var hasAlpha,
ret;
// Unsupported color, return to-color (#3920)
if (!to.rgba.length || !from.rgba.length) {
ret = to.input || 'none';
// Interpolate
} else {
from = from.rgba;
to = to.rgba;
hasAlpha = (to[3] !== 1 || from[3] !== 1);
ret = (hasAlpha ? 'rgba(' : 'rgb(') +
Math.round(to[0] + (from[0] - to[0]) * (1 - pos)) + ',' +
Math.round(to[1] + (from[1] - to[1]) * (1 - pos)) + ',' +
Math.round(to[2] + (from[2] - to[2]) * (1 - pos)) +
(hasAlpha ? (',' + (to[3] + (from[3] - to[3]) * (1 - pos))) : '') + ')';
}
return ret;
},
initDataClasses: function(userOptions) {
var axis = this,
chart = this.chart,
dataClasses,
colorCounter = 0,
colorCount = chart.options.chart.colorCount,
options = this.options,
len = userOptions.dataClasses.length;
this.dataClasses = dataClasses = [];
this.legendItems = [];
each(userOptions.dataClasses, function(dataClass, i) {
var colors;
dataClass = merge(dataClass);
dataClasses.push(dataClass);
if (!dataClass.color) {
if (options.dataClassColor === 'category') {
dataClass.colorIndex = colorCounter;
// increase and loop back to zero
colorCounter++;
if (colorCounter === colorCount) {
colorCounter = 0;
}
} else {
dataClass.color = axis.tweenColors(
color(options.minColor),
color(options.maxColor),
len < 2 ? 0.5 : i / (len - 1) // #3219
);
}
}
});
},
initStops: function(userOptions) {
this.stops = userOptions.stops || [
[0, this.options.minColor],
[1, this.options.maxColor]
];
each(this.stops, function(stop) {
stop.color = color(stop[1]);
});
},
/**
* Extend the setOptions method to process extreme colors and color
* stops.
*/
setOptions: function(userOptions) {
Axis.prototype.setOptions.call(this, userOptions);
this.options.crosshair = this.options.marker;
},
setAxisSize: function() {
var symbol = this.legendSymbol,
chart = this.chart,
legendOptions = chart.options.legend || {},
x,
y,
width,
height;
if (symbol) {
this.left = x = symbol.attr('x');
this.top = y = symbol.attr('y');
this.width = width = symbol.attr('width');
this.height = height = symbol.attr('height');
this.right = chart.chartWidth - x - width;
this.bottom = chart.chartHeight - y - height;
this.len = this.horiz ? width : height;
this.pos = this.horiz ? x : y;
} else {
// Fake length for disabled legend to avoid tick issues and such (#5205)
this.len = (this.horiz ? legendOptions.symbolWidth : legendOptions.symbolHeight) || this.defaultLegendLength;
}
},
/**
* Translate from a value to a color
*/
toColor: function(value, point) {
var pos,
stops = this.stops,
from,
to,
color,
dataClasses = this.dataClasses,
dataClass,
i;
if (dataClasses) {
i = dataClasses.length;
while (i--) {
dataClass = dataClasses[i];
from = dataClass.from;
to = dataClass.to;
if ((from === undefined || value >= from) && (to === undefined || value <= to)) {
color = dataClass.color;
if (point) {
point.dataClass = i;
point.colorIndex = dataClass.colorIndex;
}
break;
}
}
} else {
if (this.isLog) {
value = this.val2lin(value);
}
pos = 1 - ((this.max - value) / ((this.max - this.min) || 1));
i = stops.length;
while (i--) {
if (pos > stops[i][0]) {
break;
}
}
from = stops[i] || stops[i + 1];
to = stops[i + 1] || from;
// The position within the gradient
pos = 1 - (to[0] - pos) / ((to[0] - from[0]) || 1);
color = this.tweenColors(
from.color,
to.color,
pos
);
}
return color;
},
/**
* Override the getOffset method to add the whole axis groups inside the legend.
*/
getOffset: function() {
var group = this.legendGroup,
sideOffset = this.chart.axisOffset[this.side];
if (group) {
// Hook for the getOffset method to add groups to this parent group
this.axisParent = group;
// Call the base
Axis.prototype.getOffset.call(this);
// First time only
if (!this.added) {
this.added = true;
this.labelLeft = 0;
this.labelRight = this.width;
}
// Reset it to avoid color axis reserving space
this.chart.axisOffset[this.side] = sideOffset;
}
},
/**
* Create the color gradient
*/
setLegendColor: function() {
var grad,
horiz = this.horiz,
options = this.options,
reversed = this.reversed,
one = reversed ? 1 : 0,
zero = reversed ? 0 : 1;
grad = horiz ? [one, 0, zero, 0] : [0, zero, 0, one]; // #3190
this.legendColor = {
linearGradient: {
x1: grad[0],
y1: grad[1],
x2: grad[2],
y2: grad[3]
},
stops: options.stops || [
[0, options.minColor],
[1, options.maxColor]
]
};
},
/**
* The color axis appears inside the legend and has its own legend symbol
*/
drawLegendSymbol: function(legend, item) {
var padding = legend.padding,
legendOptions = legend.options,
horiz = this.horiz,
width = pick(legendOptions.symbolWidth, horiz ? this.defaultLegendLength : 12),
height = pick(legendOptions.symbolHeight, horiz ? 12 : this.defaultLegendLength),
labelPadding = pick(legendOptions.labelPadding, horiz ? 16 : 30),
itemDistance = pick(legendOptions.itemDistance, 10);
this.setLegendColor();
// Create the gradient
item.legendSymbol = this.chart.renderer.rect(
0,
legend.baseline - 11,
width,
height
).attr({
zIndex: 1
}).add(item.legendGroup);
// Set how much space this legend item takes up
this.legendItemWidth = width + padding + (horiz ? itemDistance : labelPadding);
this.legendItemHeight = height + padding + (horiz ? labelPadding : 0);
},
/**
* Fool the legend
*/
setState: noop,
visible: true,
setVisible: noop,
getSeriesExtremes: function() {
var series;
if (this.series.length) {
series = this.series[0];
this.dataMin = series.valueMin;
this.dataMax = series.valueMax;
}
},
drawCrosshair: function(e, point) {
var plotX = point && point.plotX,
plotY = point && point.plotY,
crossPos,
axisPos = this.pos,
axisLen = this.len;
if (point) {
crossPos = this.toPixels(point[point.series.colorKey]);
if (crossPos < axisPos) {
crossPos = axisPos - 2;
} else if (crossPos > axisPos + axisLen) {
crossPos = axisPos + axisLen + 2;
}
point.plotX = crossPos;
point.plotY = this.len - crossPos;
Axis.prototype.drawCrosshair.call(this, e, point);
point.plotX = plotX;
point.plotY = plotY;
if (this.cross) {
this.cross
.addClass('highcharts-coloraxis-marker')
.add(this.legendGroup);
}
}
},
getPlotLinePath: function(a, b, c, d, pos) {
return isNumber(pos) ? // crosshairs only // #3969 pos can be 0 !!
(this.horiz ? ['M', pos - 4, this.top - 6, 'L', pos + 4, this.top - 6, pos, this.top, 'Z'] : ['M', this.left, pos, 'L', this.left - 6, pos + 6, this.left - 6, pos - 6, 'Z']) :
Axis.prototype.getPlotLinePath.call(this, a, b, c, d);
},
update: function(newOptions, redraw) {
var chart = this.chart,
legend = chart.legend;
each(this.series, function(series) {
series.isDirtyData = true; // Needed for Axis.update when choropleth colors change
});
// When updating data classes, destroy old items and make sure new ones are created (#3207)
if (newOptions.dataClasses && legend.allItems) {
each(legend.allItems, function(item) {
if (item.isDataClass) {
item.legendGroup.destroy();
}
});
chart.isDirtyLegend = true;
}
// Keep the options structure updated for export. Unlike xAxis and yAxis, the colorAxis is
// not an array. (#3207)
chart.options[this.coll] = merge(this.userOptions, newOptions);
Axis.prototype.update.call(this, newOptions, redraw);
if (this.legendItem) {
this.setLegendColor();
legend.colorizeItem(this, true);
}
},
/**
* Get the legend item symbols for data classes
*/
getDataClassLegendSymbols: function() {
var axis = this,
chart = this.chart,
legendItems = this.legendItems,
legendOptions = chart.options.legend,
valueDecimals = legendOptions.valueDecimals,
valueSuffix = legendOptions.valueSuffix || '',
name;
if (!legendItems.length) {
each(this.dataClasses, function(dataClass, i) {
var vis = true,
from = dataClass.from,
to = dataClass.to;
// Assemble the default name. This can be overridden by legend.options.labelFormatter
name = '';
if (from === undefined) {
name = '< ';
} else if (to === undefined) {
name = '> ';
}
if (from !== undefined) {
name += H.numberFormat(from, valueDecimals) + valueSuffix;
}
if (from !== undefined && to !== undefined) {
name += ' - ';
}
if (to !== undefined) {
name += H.numberFormat(to, valueDecimals) + valueSuffix;
}
// Add a mock object to the legend items
legendItems.push(extend({
chart: chart,
name: name,
options: {},
drawLegendSymbol: LegendSymbolMixin.drawRectangle,
visible: true,
setState: noop,
isDataClass: true,
setVisible: function() {
vis = this.visible = !vis;
each(axis.series, function(series) {
each(series.points, function(point) {
if (point.dataClass === i) {
point.setVisible(vis);
}
});
});
chart.legend.colorizeItem(this, vis);
}
}, dataClass));
});
}
return legendItems;
},
name: '' // Prevents 'undefined' in legend in IE8
});
/**
* Handle animation of the color attributes directly
*/
each(['fill', 'stroke'], function(prop) {
H.Fx.prototype[prop + 'Setter'] = function() {
this.elem.attr(prop, ColorAxis.prototype.tweenColors(color(this.start), color(this.end), this.pos));
};
});
/**
* Extend the chart getAxes method to also get the color axis
*/
wrap(Chart.prototype, 'getAxes', function(proceed) {
var options = this.options,
colorAxisOptions = options.colorAxis;
proceed.call(this);
this.colorAxis = [];
if (colorAxisOptions) {
new ColorAxis(this, colorAxisOptions); // eslint-disable-line no-new
}
});
/**
* Wrap the legend getAllItems method to add the color axis. This also removes the
* axis' own series to prevent them from showing up individually.
*/
wrap(Legend.prototype, 'getAllItems', function(proceed) {
var allItems = [],
colorAxis = this.chart.colorAxis[0];
if (colorAxis && colorAxis.options) {
if (colorAxis.options.showInLegend) {
// Data classes
if (colorAxis.options.dataClasses) {
allItems = allItems.concat(colorAxis.getDataClassLegendSymbols());
// Gradient legend
} else {
// Add this axis on top
allItems.push(colorAxis);
}
}
// Don't add the color axis' series
each(colorAxis.series, function(series) {
series.options.showInLegend = false;
});
}
return allItems.concat(proceed.call(this));
});
wrap(Legend.prototype, 'colorizeItem', function(proceed, item, visible) {
proceed.call(this, item, visible);
if (visible && item.legendColor) {
item.legendSymbol.attr({
fill: item.legendColor
});
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var defined = H.defined,
each = H.each,
noop = H.noop,
seriesTypes = H.seriesTypes;
/**
* Mixin for maps and heatmaps
*/
H.colorPointMixin = {
/**
* Color points have a value option that determines whether or not it is a null point
*/
isValid: function() {
return this.value !== null;
},
/**
* Set the visibility of a single point
*/
setVisible: function(vis) {
var point = this,
method = vis ? 'show' : 'hide';
// Show and hide associated elements
each(['graphic', 'dataLabel'], function(key) {
if (point[key]) {
point[key][method]();
}
});
}
};
H.colorSeriesMixin = {
pointArrayMap: ['value'],
axisTypes: ['xAxis', 'yAxis', 'colorAxis'],
optionalAxis: 'colorAxis',
trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'],
getSymbol: noop,
parallelArrays: ['x', 'y', 'value'],
colorKey: 'value',
/**
* In choropleth maps, the color is a result of the value, so this needs translation too
*/
translateColors: function() {
var series = this,
nullColor = this.options.nullColor,
colorAxis = this.colorAxis,
colorKey = this.colorKey;
each(this.data, function(point) {
var value = point[colorKey],
color;
color = point.options.color ||
(point.isNull ? nullColor : (colorAxis && value !== undefined) ? colorAxis.toColor(value, point) : point.color || series.color);
if (color) {
point.color = color;
}
});
},
/**
* Get the color attibutes to apply on the graphic
*/
colorAttribs: function(point) {
var ret = {};
if (defined(point.color)) {
ret[this.colorProp || 'fill'] = point.color;
}
return ret;
}
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var color = H.color,
ColorAxis = H.ColorAxis,
colorPointMixin = H.colorPointMixin,
colorSeriesMixin = H.colorSeriesMixin,
doc = H.doc,
each = H.each,
extend = H.extend,
isNumber = H.isNumber,
LegendSymbolMixin = H.LegendSymbolMixin,
map = H.map,
merge = H.merge,
noop = H.noop,
pick = H.pick,
isArray = H.isArray,
Point = H.Point,
Series = H.Series,
seriesType = H.seriesType,
seriesTypes = H.seriesTypes,
splat = H.splat;
// The vector-effect attribute is not supported in IE <= 11 (at least), so we need
// diffent logic (#3218)
var supportsVectorEffect = doc.documentElement.style.vectorEffect !== undefined;
/**
* The MapAreaPoint object
*/
/**
* Add the map series type
*/
seriesType('map', 'scatter', {
allAreas: true,
animation: false, // makes the complex shapes slow
nullColor: '#f7f7f7',
borderColor: '#cccccc',
borderWidth: 1,
marker: null,
stickyTracking: false,
joinBy: 'hc-key',
dataLabels: {
formatter: function() { // #2945
return this.point.value;
},
inside: true, // for the color
verticalAlign: 'middle',
crop: false,
overflow: false,
padding: 0
},
turboThreshold: 0,
tooltip: {
followPointer: true,
pointFormat: '{point.name}: {point.value}<br/>'
},
states: {
normal: {
animation: true
},
hover: {
brightness: 0.2,
halo: null
},
select: {
color: '#cccccc'
}
}
// Prototype members
}, merge(colorSeriesMixin, {
type: 'map',
supportsDrilldown: true,
getExtremesFromAll: true,
useMapGeometry: true, // get axis extremes from paths, not values
forceDL: true,
searchPoint: noop,
directTouch: true, // When tooltip is not shared, this series (and derivatives) requires direct touch/hover. KD-tree does not apply.
preserveAspectRatio: true, // X axis and Y axis must have same translation slope
pointArrayMap: ['value'],
/**
* Get the bounding box of all paths in the map combined.
*/
getBox: function(paths) {
var MAX_VALUE = Number.MAX_VALUE,
maxX = -MAX_VALUE,
minX = MAX_VALUE,
maxY = -MAX_VALUE,
minY = MAX_VALUE,
minRange = MAX_VALUE,
xAxis = this.xAxis,
yAxis = this.yAxis,
hasBox;
// Find the bounding box
each(paths || [], function(point) {
if (point.path) {
if (typeof point.path === 'string') {
point.path = H.splitPath(point.path);
}
var path = point.path || [],
i = path.length,
even = false, // while loop reads from the end
pointMaxX = -MAX_VALUE,
pointMinX = MAX_VALUE,
pointMaxY = -MAX_VALUE,
pointMinY = MAX_VALUE,
properties = point.properties;
// The first time a map point is used, analyze its box
if (!point._foundBox) {
while (i--) {
if (isNumber(path[i])) {
if (even) { // even = x
pointMaxX = Math.max(pointMaxX, path[i]);
pointMinX = Math.min(pointMinX, path[i]);
} else { // odd = Y
pointMaxY = Math.max(pointMaxY, path[i]);
pointMinY = Math.min(pointMinY, path[i]);
}
even = !even;
}
}
// Cache point bounding box for use to position data labels, bubbles etc
point._midX = pointMinX + (pointMaxX - pointMinX) *
(point.middleX || (properties && properties['hc-middle-x']) || 0.5); // pick is slower and very marginally needed
point._midY = pointMinY + (pointMaxY - pointMinY) *
(point.middleY || (properties && properties['hc-middle-y']) || 0.5);
point._maxX = pointMaxX;
point._minX = pointMinX;
point._maxY = pointMaxY;
point._minY = pointMinY;
point.labelrank = pick(point.labelrank, (pointMaxX - pointMinX) * (pointMaxY - pointMinY));
point._foundBox = true;
}
maxX = Math.max(maxX, point._maxX);
minX = Math.min(minX, point._minX);
maxY = Math.max(maxY, point._maxY);
minY = Math.min(minY, point._minY);
minRange = Math.min(point._maxX - point._minX, point._maxY - point._minY, minRange);
hasBox = true;
}
});
// Set the box for the whole series
if (hasBox) {
this.minY = Math.min(minY, pick(this.minY, MAX_VALUE));
this.maxY = Math.max(maxY, pick(this.maxY, -MAX_VALUE));
this.minX = Math.min(minX, pick(this.minX, MAX_VALUE));
this.maxX = Math.max(maxX, pick(this.maxX, -MAX_VALUE));
// If no minRange option is set, set the default minimum zooming range to 5 times the
// size of the smallest element
if (xAxis && xAxis.options.minRange === undefined) {
xAxis.minRange = Math.min(5 * minRange, (this.maxX - this.minX) / 5, xAxis.minRange || MAX_VALUE);
}
if (yAxis && yAxis.options.minRange === undefined) {
yAxis.minRange = Math.min(5 * minRange, (this.maxY - this.minY) / 5, yAxis.minRange || MAX_VALUE);
}
}
},
getExtremes: function() {
// Get the actual value extremes for colors
Series.prototype.getExtremes.call(this, this.valueData);
// Recalculate box on updated data
if (this.chart.hasRendered && this.isDirtyData) {
this.getBox(this.options.data);
}
this.valueMin = this.dataMin;
this.valueMax = this.dataMax;
// Extremes for the mock Y axis
this.dataMin = this.minY;
this.dataMax = this.maxY;
},
/**
* Translate the path so that it automatically fits into the plot area box
* @param {Object} path
*/
translatePath: function(path) {
var series = this,
even = false, // while loop reads from the end
xAxis = series.xAxis,
yAxis = series.yAxis,
xMin = xAxis.min,
xTransA = xAxis.transA,
xMinPixelPadding = xAxis.minPixelPadding,
yMin = yAxis.min,
yTransA = yAxis.transA,
yMinPixelPadding = yAxis.minPixelPadding,
i,
ret = []; // Preserve the original
// Do the translation
if (path) {
i = path.length;
while (i--) {
if (isNumber(path[i])) {
ret[i] = even ?
(path[i] - xMin) * xTransA + xMinPixelPadding :
(path[i] - yMin) * yTransA + yMinPixelPadding;
even = !even;
} else {
ret[i] = path[i];
}
}
}
return ret;
},
/**
* Extend setData to join in mapData. If the allAreas option is true, all areas
* from the mapData are used, and those that don't correspond to a data value
* are given null values.
*/
setData: function(data, redraw, animation, updatePoints) {
var options = this.options,
chartOptions = this.chart.options.chart,
globalMapData = chartOptions && chartOptions.map,
mapData = options.mapData,
joinBy = options.joinBy,
joinByNull = joinBy === null,
pointArrayMap = options.keys || this.pointArrayMap,
dataUsed = [],
mapMap = {},
mapPoint,
transform,
mapTransforms = this.chart.mapTransforms,
props,
i;
// Collect mapData from chart options if not defined on series
if (!mapData && globalMapData) {
mapData = typeof globalMapData === 'string' ? H.maps[globalMapData] : globalMapData;
}
if (joinByNull) {
joinBy = '_i';
}
joinBy = this.joinBy = splat(joinBy);
if (!joinBy[1]) {
joinBy[1] = joinBy[0];
}
// Pick up numeric values, add index
// Convert Array point definitions to objects using pointArrayMap
if (data) {
each(data, function(val, i) {
var ix = 0;
if (isNumber(val)) {
data[i] = {
value: val
};
} else if (isArray(val)) {
data[i] = {};
// Automatically copy first item to hc-key if there is an extra leading string
if (!options.keys && val.length > pointArrayMap.length && typeof val[0] === 'string') {
data[i]['hc-key'] = val[0];
++ix;
}
// Run through pointArrayMap and what's left of the point data array in parallel, copying over the values
for (var j = 0; j < pointArrayMap.length; ++j, ++ix) {
if (pointArrayMap[j]) {
data[i][pointArrayMap[j]] = val[ix];
}
}
}
if (joinByNull) {
data[i]._i = i;
}
});
}
this.getBox(data);
// Pick up transform definitions for chart
this.chart.mapTransforms = mapTransforms = chartOptions && chartOptions.mapTransforms || mapData && mapData['hc-transform'] || mapTransforms;
// Cache cos/sin of transform rotation angle
if (mapTransforms) {
for (transform in mapTransforms) {
if (mapTransforms.hasOwnProperty(transform) && transform.rotation) {
transform.cosAngle = Math.cos(transform.rotation);
transform.sinAngle = Math.sin(transform.rotation);
}
}
}
if (mapData) {
if (mapData.type === 'FeatureCollection') {
this.mapTitle = mapData.title;
mapData = H.geojson(mapData, this.type, this);
}
this.mapData = mapData;
this.mapMap = {};
for (i = 0; i < mapData.length; i++) {
mapPoint = mapData[i];
props = mapPoint.properties;
mapPoint._i = i;
// Copy the property over to root for faster access
if (joinBy[0] && props && props[joinBy[0]]) {
mapPoint[joinBy[0]] = props[joinBy[0]];
}
mapMap[mapPoint[joinBy[0]]] = mapPoint;
}
this.mapMap = mapMap;
// Registered the point codes that actually hold data
if (data && joinBy[1]) {
each(data, function(point) {
if (mapMap[point[joinBy[1]]]) {
dataUsed.push(mapMap[point[joinBy[1]]]);
}
});
}
if (options.allAreas) {
this.getBox(mapData);
data = data || [];
// Registered the point codes that actually hold data
if (joinBy[1]) {
each(data, function(point) {
dataUsed.push(point[joinBy[1]]);
});
}
// Add those map points that don't correspond to data, which will be drawn as null points
dataUsed = '|' + map(dataUsed, function(point) {
return point && point[joinBy[0]];
}).join('|') + '|'; // String search is faster than array.indexOf
each(mapData, function(mapPoint) {
if (!joinBy[0] || dataUsed.indexOf('|' + mapPoint[joinBy[0]] + '|') === -1) {
data.push(merge(mapPoint, {
value: null
}));
updatePoints = false; // #5050 - adding all areas causes the update optimization of setData to kick in, even though the point order has changed
}
});
} else {
this.getBox(dataUsed); // Issue #4784
}
}
Series.prototype.setData.call(this, data, redraw, animation, updatePoints);
},
/**
* No graph for the map series
*/
drawGraph: noop,
/**
* We need the points' bounding boxes in order to draw the data labels, so
* we skip it now and call it from drawPoints instead.
*/
drawDataLabels: noop,
/**
* Allow a quick redraw by just translating the area group. Used for zooming and panning
* in capable browsers.
*/
doFullTranslate: function() {
return this.isDirtyData || this.chart.isResizing || this.chart.renderer.isVML || !this.baseTrans;
},
/**
* Add the path option for data points. Find the max value for color calculation.
*/
translate: function() {
var series = this,
xAxis = series.xAxis,
yAxis = series.yAxis,
doFullTranslate = series.doFullTranslate();
series.generatePoints();
each(series.data, function(point) {
// Record the middle point (loosely based on centroid), determined
// by the middleX and middleY options.
point.plotX = xAxis.toPixels(point._midX, true);
point.plotY = yAxis.toPixels(point._midY, true);
if (doFullTranslate) {
point.shapeType = 'path';
point.shapeArgs = {
d: series.translatePath(point.path)
};
}
});
series.translateColors();
},
/**
* Get presentational attributes
*/
pointAttribs: function(point, state) {
var attr = seriesTypes.column.prototype.pointAttribs.call(this, point, state);
// Prevent flickering whan called from setState
if (point.isFading) {
delete attr.fill;
}
// If vector-effect is not supported, we set the stroke-width on the group element
// and let all point graphics inherit. That way we don't have to iterate over all
// points to update the stroke-width on zooming. TODO: Check unstyled
if (supportsVectorEffect) {
attr['vector-effect'] = 'non-scaling-stroke';
} else {
attr['stroke-width'] = 'inherit';
}
return attr;
},
/**
* Use the drawPoints method of column, that is able to handle simple shapeArgs.
* Extend it by assigning the tooltip position.
*/
drawPoints: function() {
var series = this,
xAxis = series.xAxis,
yAxis = series.yAxis,
group = series.group,
chart = series.chart,
renderer = chart.renderer,
scaleX,
scaleY,
translateX,
translateY,
baseTrans = this.baseTrans;
// Set a group that handles transform during zooming and panning in order to preserve clipping
// on series.group
if (!series.transformGroup) {
series.transformGroup = renderer.g()
.attr({
scaleX: 1,
scaleY: 1
})
.add(group);
series.transformGroup.survive = true;
}
// Draw the shapes again
if (series.doFullTranslate()) {
// Individual point actions. TODO: Check unstyled.
// Draw them in transformGroup
series.group = series.transformGroup;
seriesTypes.column.prototype.drawPoints.apply(series);
series.group = group; // Reset
// Add class names
each(series.points, function(point) {
if (point.graphic) {
if (point.name) {
point.graphic.addClass('highcharts-name-' + point.name.replace(/ /g, '-').toLowerCase());
}
if (point.properties && point.properties['hc-key']) {
point.graphic.addClass('highcharts-key-' + point.properties['hc-key'].toLowerCase());
}
}
});
// Set the base for later scale-zooming. The originX and originY properties are the
// axis values in the plot area's upper left corner.
this.baseTrans = {
originX: xAxis.min - xAxis.minPixelPadding / xAxis.transA,
originY: yAxis.min - yAxis.minPixelPadding / yAxis.transA + (yAxis.reversed ? 0 : yAxis.len / yAxis.transA),
transAX: xAxis.transA,
transAY: yAxis.transA
};
// Reset transformation in case we're doing a full translate (#3789)
this.transformGroup.animate({
translateX: 0,
translateY: 0,
scaleX: 1,
scaleY: 1
});
// Just update the scale and transform for better performance
} else {
scaleX = xAxis.transA / baseTrans.transAX;
scaleY = yAxis.transA / baseTrans.transAY;
translateX = xAxis.toPixels(baseTrans.originX, true);
translateY = yAxis.toPixels(baseTrans.originY, true);
// Handle rounding errors in normal view (#3789)
if (scaleX > 0.99 && scaleX < 1.01 && scaleY > 0.99 && scaleY < 1.01) {
scaleX = 1;
scaleY = 1;
translateX = Math.round(translateX);
translateY = Math.round(translateY);
}
this.transformGroup.animate({
translateX: translateX,
translateY: translateY,
scaleX: scaleX,
scaleY: scaleY
});
}
// Set the stroke-width directly on the group element so the children inherit it. We need to use
// setAttribute directly, because the stroke-widthSetter method expects a stroke color also to be
// set.
if (!supportsVectorEffect) {
series.group.element.setAttribute(
'stroke-width',
series.options[
(series.pointAttrToOptions && series.pointAttrToOptions['stroke-width']) || 'borderWidth'
] / (scaleX || 1)
);
}
this.drawMapDataLabels();
},
/**
* Draw the data labels. Special for maps is the time that the data labels are drawn (after points),
* and the clipping of the dataLabelsGroup.
*/
drawMapDataLabels: function() {
Series.prototype.drawDataLabels.call(this);
if (this.dataLabelsGroup) {
this.dataLabelsGroup.clip(this.chart.clipRect);
}
},
/**
* Override render to throw in an async call in IE8. Otherwise it chokes on the US counties demo.
*/
render: function() {
var series = this,
render = Series.prototype.render;
// Give IE8 some time to breathe.
if (series.chart.renderer.isVML && series.data.length > 3000) {
setTimeout(function() {
render.call(series);
});
} else {
render.call(series);
}
},
/**
* The initial animation for the map series. By default, animation is disabled.
* Animation of map shapes is not at all supported in VML browsers.
*/
animate: function(init) {
var chart = this.chart,
animation = this.options.animation,
group = this.group,
xAxis = this.xAxis,
yAxis = this.yAxis,
left = xAxis.pos,
top = yAxis.pos;
if (chart.renderer.isSVG) {
if (animation === true) {
animation = {
duration: 1000
};
}
// Initialize the animation
if (init) {
// Scale down the group and place it in the center
group.attr({
translateX: left + xAxis.len / 2,
translateY: top + yAxis.len / 2,
scaleX: 0.001, // #1499
scaleY: 0.001
});
// Run the animation
} else {
group.animate({
translateX: left,
translateY: top,
scaleX: 1,
scaleY: 1
}, animation);
// Delete this function to allow it only once
this.animate = null;
}
}
},
/**
* Animate in the new series from the clicked point in the old series.
* Depends on the drilldown.js module
*/
animateDrilldown: function(init) {
var toBox = this.chart.plotBox,
level = this.chart.drilldownLevels[this.chart.drilldownLevels.length - 1],
fromBox = level.bBox,
animationOptions = this.chart.options.drilldown.animation,
scale;
if (!init) {
scale = Math.min(fromBox.width / toBox.width, fromBox.height / toBox.height);
level.shapeArgs = {
scaleX: scale,
scaleY: scale,
translateX: fromBox.x,
translateY: fromBox.y
};
each(this.points, function(point) {
if (point.graphic) {
point.graphic
.attr(level.shapeArgs)
.animate({
scaleX: 1,
scaleY: 1,
translateX: 0,
translateY: 0
}, animationOptions);
}
});
this.animate = null;
}
},
drawLegendSymbol: LegendSymbolMixin.drawRectangle,
/**
* When drilling up, pull out the individual point graphics from the lower series
* and animate them into the origin point in the upper series.
*/
animateDrillupFrom: function(level) {
seriesTypes.column.prototype.animateDrillupFrom.call(this, level);
},
/**
* When drilling up, keep the upper series invisible until the lower series has
* moved into place
*/
animateDrillupTo: function(init) {
seriesTypes.column.prototype.animateDrillupTo.call(this, init);
}
// Point class
}), extend({
/**
* Extend the Point object to split paths
*/
applyOptions: function(options, x) {
var point = Point.prototype.applyOptions.call(this, options, x),
series = this.series,
joinBy = series.joinBy,
mapPoint;
if (series.mapData) {
mapPoint = point[joinBy[1]] !== undefined && series.mapMap[point[joinBy[1]]];
if (mapPoint) {
// This applies only to bubbles
if (series.xyFromShape) {
point.x = mapPoint._midX;
point.y = mapPoint._midY;
}
extend(point, mapPoint); // copy over properties
} else {
point.value = point.value || null;
}
}
return point;
},
/**
* Stop the fade-out
*/
onMouseOver: function(e) {
clearTimeout(this.colorInterval);
if (this.value !== null) {
Point.prototype.onMouseOver.call(this, e);
} else { //#3401 Tooltip doesn't hide when hovering over null points
this.series.onMouseOut(e);
}
},
/**
* Zoom the chart to view a specific area point
*/
zoomTo: function() {
var point = this,
series = point.series;
series.xAxis.setExtremes(
point._minX,
point._maxX,
false
);
series.yAxis.setExtremes(
point._minY,
point._maxY,
false
);
series.chart.redraw();
}
}, colorPointMixin));
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
Chart = H.Chart,
doc = H.doc,
each = H.each,
extend = H.extend,
merge = H.merge,
pick = H.pick,
wrap = H.wrap;
function stopEvent(e) {
if (e) {
if (e.preventDefault) {
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
e.cancelBubble = true;
}
}
// Add events to the Chart object itself
extend(Chart.prototype, {
renderMapNavigation: function() {
var chart = this,
options = this.options.mapNavigation,
buttons = options.buttons,
n,
button,
buttonOptions,
attr,
states,
hoverStates,
selectStates,
outerHandler = function(e) {
this.handler.call(chart, e);
stopEvent(e); // Stop default click event (#4444)
};
if (pick(options.enableButtons, options.enabled) && !chart.renderer.forExport) {
chart.mapNavButtons = [];
for (n in buttons) {
if (buttons.hasOwnProperty(n)) {
buttonOptions = merge(options.buttonOptions, buttons[n]);
button = chart.renderer.button(
buttonOptions.text,
0,
0,
outerHandler,
attr,
hoverStates,
selectStates,
0,
n === 'zoomIn' ? 'topbutton' : 'bottombutton'
)
.addClass('highcharts-map-navigation')
.attr({
width: buttonOptions.width,
height: buttonOptions.height,
title: chart.options.lang[n],
padding: buttonOptions.padding,
zIndex: 5
})
.add();
button.handler = buttonOptions.onclick;
button.align(extend(buttonOptions, {
width: button.width,
height: 2 * button.height
}), null, buttonOptions.alignTo);
addEvent(button.element, 'dblclick', stopEvent); // Stop double click event (#4444)
chart.mapNavButtons.push(button);
}
}
}
},
/**
* Fit an inner box to an outer. If the inner box overflows left or right, align it to the sides of the
* outer. If it overflows both sides, fit it within the outer. This is a pattern that occurs more places
* in Highcharts, perhaps it should be elevated to a common utility function.
*/
fitToBox: function(inner, outer) {
each([
['x', 'width'],
['y', 'height']
], function(dim) {
var pos = dim[0],
size = dim[1];
if (inner[pos] + inner[size] > outer[pos] + outer[size]) { // right overflow
if (inner[size] > outer[size]) { // the general size is greater, fit fully to outer
inner[size] = outer[size];
inner[pos] = outer[pos];
} else { // align right
inner[pos] = outer[pos] + outer[size] - inner[size];
}
}
if (inner[size] > outer[size]) {
inner[size] = outer[size];
}
if (inner[pos] < outer[pos]) {
inner[pos] = outer[pos];
}
});
return inner;
},
/**
* Zoom the map in or out by a certain amount. Less than 1 zooms in, greater than 1 zooms out.
*/
mapZoom: function(howMuch, centerXArg, centerYArg, mouseX, mouseY) {
/*if (this.isMapZooming) {
this.mapZoomQueue = arguments;
return;
}*/
var chart = this,
xAxis = chart.xAxis[0],
xRange = xAxis.max - xAxis.min,
centerX = pick(centerXArg, xAxis.min + xRange / 2),
newXRange = xRange * howMuch,
yAxis = chart.yAxis[0],
yRange = yAxis.max - yAxis.min,
centerY = pick(centerYArg, yAxis.min + yRange / 2),
newYRange = yRange * howMuch,
fixToX = mouseX ? ((mouseX - xAxis.pos) / xAxis.len) : 0.5,
fixToY = mouseY ? ((mouseY - yAxis.pos) / yAxis.len) : 0.5,
newXMin = centerX - newXRange * fixToX,
newYMin = centerY - newYRange * fixToY,
newExt = chart.fitToBox({
x: newXMin,
y: newYMin,
width: newXRange,
height: newYRange
}, {
x: xAxis.dataMin,
y: yAxis.dataMin,
width: xAxis.dataMax - xAxis.dataMin,
height: yAxis.dataMax - yAxis.dataMin
}),
zoomOut = newExt.x <= xAxis.dataMin &&
newExt.width >= xAxis.dataMax - xAxis.dataMin &&
newExt.y <= yAxis.dataMin &&
newExt.height >= yAxis.dataMax - yAxis.dataMin;
// When mousewheel zooming, fix the point under the mouse
if (mouseX) {
xAxis.fixTo = [mouseX - xAxis.pos, centerXArg];
}
if (mouseY) {
yAxis.fixTo = [mouseY - yAxis.pos, centerYArg];
}
// Zoom
if (howMuch !== undefined && !zoomOut) {
xAxis.setExtremes(newExt.x, newExt.x + newExt.width, false);
yAxis.setExtremes(newExt.y, newExt.y + newExt.height, false);
// Reset zoom
} else {
xAxis.setExtremes(undefined, undefined, false);
yAxis.setExtremes(undefined, undefined, false);
}
// Prevent zooming until this one is finished animating
/*chart.holdMapZoom = true;
setTimeout(function () {
chart.holdMapZoom = false;
}, 200);*/
/*delay = animation ? animation.duration || 500 : 0;
if (delay) {
chart.isMapZooming = true;
setTimeout(function () {
chart.isMapZooming = false;
if (chart.mapZoomQueue) {
chart.mapZoom.apply(chart, chart.mapZoomQueue);
}
chart.mapZoomQueue = null;
}, delay);
}*/
chart.redraw();
}
});
/**
* Extend the Chart.render method to add zooming and panning
*/
wrap(Chart.prototype, 'render', function(proceed) {
var chart = this,
mapNavigation = chart.options.mapNavigation;
// Render the plus and minus buttons. Doing this before the shapes makes getBBox much quicker, at least in Chrome.
chart.renderMapNavigation();
proceed.call(chart);
// Add the double click event
if (pick(mapNavigation.enableDoubleClickZoom, mapNavigation.enabled) || mapNavigation.enableDoubleClickZoomTo) {
addEvent(chart.container, 'dblclick', function(e) {
chart.pointer.onContainerDblClick(e);
});
}
// Add the mousewheel event
if (pick(mapNavigation.enableMouseWheelZoom, mapNavigation.enabled)) {
addEvent(chart.container, doc.onmousewheel === undefined ? 'DOMMouseScroll' : 'mousewheel', function(e) {
chart.pointer.onContainerMouseWheel(e);
stopEvent(e); // Issue #5011, returning false from non-jQuery event does not prevent default
return false;
});
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var extend = H.extend,
pick = H.pick,
Pointer = H.Pointer,
wrap = H.wrap;
// Extend the Pointer
extend(Pointer.prototype, {
/**
* The event handler for the doubleclick event
*/
onContainerDblClick: function(e) {
var chart = this.chart;
e = this.normalize(e);
if (chart.options.mapNavigation.enableDoubleClickZoomTo) {
if (chart.pointer.inClass(e.target, 'highcharts-tracker') && chart.hoverPoint) {
chart.hoverPoint.zoomTo();
}
} else if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
chart.mapZoom(
0.5,
chart.xAxis[0].toValue(e.chartX),
chart.yAxis[0].toValue(e.chartY),
e.chartX,
e.chartY
);
}
},
/**
* The event handler for the mouse scroll event
*/
onContainerMouseWheel: function(e) {
var chart = this.chart,
delta;
e = this.normalize(e);
// Firefox uses e.detail, WebKit and IE uses wheelDelta
delta = e.detail || -(e.wheelDelta / 120);
if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
chart.mapZoom(
Math.pow(chart.options.mapNavigation.mouseWheelSensitivity, delta),
chart.xAxis[0].toValue(e.chartX),
chart.yAxis[0].toValue(e.chartY),
e.chartX,
e.chartY
);
}
}
});
// Implement the pinchType option
wrap(Pointer.prototype, 'zoomOption', function(proceed) {
var mapNavigation = this.chart.options.mapNavigation;
proceed.apply(this, [].slice.call(arguments, 1));
// Pinch status
if (pick(mapNavigation.enableTouchZoom, mapNavigation.enabled)) {
this.pinchX = this.pinchHor = this.pinchY = this.pinchVert = this.hasZoom = true;
}
});
// Extend the pinchTranslate method to preserve fixed ratio when zooming
wrap(Pointer.prototype, 'pinchTranslate', function(proceed, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) {
var xBigger;
proceed.call(this, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
// Keep ratio
if (this.chart.options.chart.type === 'map' && this.hasZoom) {
xBigger = transform.scaleX > transform.scaleY;
this.pinchTranslateDirection(!xBigger,
pinchDown,
touches,
transform,
selectionMarker,
clip,
lastValidTouch,
xBigger ? transform.scaleX : transform.scaleY
);
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var seriesType = H.seriesType,
seriesTypes = H.seriesTypes;
// The mapline series type
seriesType('mapline', 'map', {
}, {
type: 'mapline',
colorProp: 'stroke',
drawLegendSymbol: seriesTypes.line.prototype.drawLegendSymbol
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var merge = H.merge,
Point = H.Point,
seriesType = H.seriesType;
// The mappoint series type
seriesType('mappoint', 'scatter', {
dataLabels: {
enabled: true,
formatter: function() { // #2945
return this.point.name;
},
crop: false,
defer: false,
overflow: false,
style: {
color: '#000000'
}
}
// Prototype members
}, {
type: 'mappoint',
forceDL: true
// Point class
}, {
applyOptions: function(options, x) {
var mergedOptions = options.lat !== undefined && options.lon !== undefined ? merge(options, this.series.chart.fromLatLonToPoint(options)) : options;
return Point.prototype.applyOptions.call(this, mergedOptions, x);
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var arrayMax = H.arrayMax,
arrayMin = H.arrayMin,
Axis = H.Axis,
color = H.color,
each = H.each,
isNumber = H.isNumber,
noop = H.noop,
pick = H.pick,
pInt = H.pInt,
Point = H.Point,
Series = H.Series,
seriesType = H.seriesType,
seriesTypes = H.seriesTypes;
/* ****************************************************************************
* Start Bubble series code *
*****************************************************************************/
seriesType('bubble', 'scatter', {
dataLabels: {
formatter: function() { // #2945
return this.point.z;
},
inside: true,
verticalAlign: 'middle'
},
// displayNegative: true,
marker: {
// Avoid offset in Point.setState
radius: null,
states: {
hover: {
radiusPlus: 0
}
}
},
minSize: 8,
maxSize: '20%',
// negativeColor: null,
// sizeBy: 'area'
softThreshold: false,
states: {
hover: {
halo: {
size: 5
}
}
},
tooltip: {
pointFormat: '({point.x}, {point.y}), Size: {point.z}'
},
turboThreshold: 0,
zThreshold: 0,
zoneAxis: 'z'
// Prototype members
}, {
pointArrayMap: ['y', 'z'],
parallelArrays: ['x', 'y', 'z'],
trackerGroups: ['group', 'dataLabelsGroup'],
bubblePadding: true,
zoneAxis: 'z',
/**
* Get the radius for each point based on the minSize, maxSize and each point's Z value. This
* must be done prior to Series.translate because the axis needs to add padding in
* accordance with the point sizes.
*/
getRadii: function(zMin, zMax, minSize, maxSize) {
var len,
i,
pos,
zData = this.zData,
radii = [],
options = this.options,
sizeByArea = options.sizeBy !== 'width',
zThreshold = options.zThreshold,
zRange = zMax - zMin,
value,
radius;
// Set the shape type and arguments to be picked up in drawPoints
for (i = 0, len = zData.length; i < len; i++) {
value = zData[i];
// When sizing by threshold, the absolute value of z determines the size
// of the bubble.
if (options.sizeByAbsoluteValue && value !== null) {
value = Math.abs(value - zThreshold);
zMax = Math.max(zMax - zThreshold, Math.abs(zMin - zThreshold));
zMin = 0;
}
if (value === null) {
radius = null;
// Issue #4419 - if value is less than zMin, push a radius that's always smaller than the minimum size
} else if (value < zMin) {
radius = minSize / 2 - 1;
} else {
// Relative size, a number between 0 and 1
pos = zRange > 0 ? (value - zMin) / zRange : 0.5;
if (sizeByArea && pos >= 0) {
pos = Math.sqrt(pos);
}
radius = Math.ceil(minSize + pos * (maxSize - minSize)) / 2;
}
radii.push(radius);
}
this.radii = radii;
},
/**
* Perform animation on the bubbles
*/
animate: function(init) {
var animation = this.options.animation;
if (!init) { // run the animation
each(this.points, function(point) {
var graphic = point.graphic,
shapeArgs = point.shapeArgs;
if (graphic && shapeArgs) {
// start values
graphic.attr('r', 1);
// animate
graphic.animate({
r: shapeArgs.r
}, animation);
}
});
// delete this function to allow it only once
this.animate = null;
}
},
/**
* Extend the base translate method to handle bubble size
*/
translate: function() {
var i,
data = this.data,
point,
radius,
radii = this.radii;
// Run the parent method
seriesTypes.scatter.prototype.translate.call(this);
// Set the shape type and arguments to be picked up in drawPoints
i = data.length;
while (i--) {
point = data[i];
radius = radii ? radii[i] : 0; // #1737
if (isNumber(radius) && radius >= this.minPxSize / 2) {
// Shape arguments
point.shapeType = 'circle';
point.shapeArgs = {
x: point.plotX,
y: point.plotY,
r: radius
};
// Alignment box for the data label
point.dlBox = {
x: point.plotX - radius,
y: point.plotY - radius,
width: 2 * radius,
height: 2 * radius
};
} else { // below zThreshold
point.shapeArgs = point.plotY = point.dlBox = undefined; // #1691
}
}
},
/**
* Get the series' symbol in the legend
*
* @param {Object} legend The legend object
* @param {Object} item The series (this) or point
*/
drawLegendSymbol: function(legend, item) {
var renderer = this.chart.renderer,
radius = renderer.fontMetrics(legend.itemStyle.fontSize).f / 2;
item.legendSymbol = renderer.circle(
radius,
legend.baseline - radius,
radius
).attr({
zIndex: 3
}).add(item.legendGroup);
item.legendSymbol.isMarker = true;
},
drawPoints: seriesTypes.column.prototype.drawPoints,
alignDataLabel: seriesTypes.column.prototype.alignDataLabel,
buildKDTree: noop,
applyZones: noop
// Point class
}, {
haloPath: function() {
return Point.prototype.haloPath.call(this, this.shapeArgs.r + this.series.options.states.hover.halo.size);
},
ttBelow: false
});
/**
* Add logic to pad each axis with the amount of pixels
* necessary to avoid the bubbles to overflow.
*/
Axis.prototype.beforePadding = function() {
var axis = this,
axisLength = this.len,
chart = this.chart,
pxMin = 0,
pxMax = axisLength,
isXAxis = this.isXAxis,
dataKey = isXAxis ? 'xData' : 'yData',
min = this.min,
extremes = {},
smallestSize = Math.min(chart.plotWidth, chart.plotHeight),
zMin = Number.MAX_VALUE,
zMax = -Number.MAX_VALUE,
range = this.max - min,
transA = axisLength / range,
activeSeries = [];
// Handle padding on the second pass, or on redraw
each(this.series, function(series) {
var seriesOptions = series.options,
zData;
if (series.bubblePadding && (series.visible || !chart.options.chart.ignoreHiddenSeries)) {
// Correction for #1673
axis.allowZoomOutside = true;
// Cache it
activeSeries.push(series);
if (isXAxis) { // because X axis is evaluated first
// For each series, translate the size extremes to pixel values
each(['minSize', 'maxSize'], function(prop) {
var length = seriesOptions[prop],
isPercent = /%$/.test(length);
length = pInt(length);
extremes[prop] = isPercent ?
smallestSize * length / 100 :
length;
});
series.minPxSize = extremes.minSize;
series.maxPxSize = extremes.maxSize;
// Find the min and max Z
zData = series.zData;
if (zData.length) { // #1735
zMin = pick(seriesOptions.zMin, Math.min(
zMin,
Math.max(
arrayMin(zData),
seriesOptions.displayNegative === false ? seriesOptions.zThreshold : -Number.MAX_VALUE
)
));
zMax = pick(seriesOptions.zMax, Math.max(zMax, arrayMax(zData)));
}
}
}
});
each(activeSeries, function(series) {
var data = series[dataKey],
i = data.length,
radius;
if (isXAxis) {
series.getRadii(zMin, zMax, series.minPxSize, series.maxPxSize);
}
if (range > 0) {
while (i--) {
if (isNumber(data[i]) && axis.dataMin <= data[i] && data[i] <= axis.dataMax) {
radius = series.radii[i];
pxMin = Math.min(((data[i] - min) * transA) - radius, pxMin);
pxMax = Math.max(((data[i] - min) * transA) + radius, pxMax);
}
}
}
});
if (activeSeries.length && range > 0 && !this.isLog) {
pxMax -= axisLength;
transA *= (axisLength + pxMin - pxMax) / axisLength;
each([
['min', 'userMin', pxMin],
['max', 'userMax', pxMax]
], function(keys) {
if (pick(axis.options[keys[0]], axis[keys[1]]) === undefined) {
axis[keys[0]] += keys[2] / transA;
}
});
}
};
/* ****************************************************************************
* End Bubble series code *
*****************************************************************************/
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var merge = H.merge,
Point = H.Point,
seriesType = H.seriesType,
seriesTypes = H.seriesTypes;
// The mapbubble series type
if (seriesTypes.bubble) {
seriesType('mapbubble', 'bubble', {
animationLimit: 500,
tooltip: {
pointFormat: '{point.name}: {point.z}'
}
// Prototype members
}, {
xyFromShape: true,
type: 'mapbubble',
pointArrayMap: ['z'], // If one single value is passed, it is interpreted as z
/**
* Return the map area identified by the dataJoinBy option
*/
getMapData: seriesTypes.map.prototype.getMapData,
getBox: seriesTypes.map.prototype.getBox,
setData: seriesTypes.map.prototype.setData
// Point class
}, {
applyOptions: function(options, x) {
var point;
if (options && options.lat !== undefined && options.lon !== undefined) {
point = Point.prototype.applyOptions.call(
this,
merge(options, this.series.chart.fromLatLonToPoint(options)),
x
);
} else {
point = seriesTypes.map.prototype.pointClass.prototype.applyOptions.call(this, options, x);
}
return point;
},
ttBelow: false
});
}
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Chart = H.Chart,
each = H.each,
extend = H.extend,
error = H.error,
format = H.format,
merge = H.merge,
win = H.win,
wrap = H.wrap;
/**
* Test for point in polygon. Polygon defined as array of [x,y] points.
*/
function pointInPolygon(point, polygon) {
var i,
j,
rel1,
rel2,
c = false,
x = point.x,
y = point.y;
for (i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
rel1 = polygon[i][1] > y;
rel2 = polygon[j][1] > y;
if (rel1 !== rel2 && (x < (polygon[j][0] - polygon[i][0]) * (y - polygon[i][1]) / (polygon[j][1] - polygon[i][1]) + polygon[i][0])) {
c = !c;
}
}
return c;
}
/**
* Get point from latLon using specified transform definition
*/
Chart.prototype.transformFromLatLon = function(latLon, transform) {
if (win.proj4 === undefined) {
error(21);
return {
x: 0,
y: null
};
}
var projected = win.proj4(transform.crs, [latLon.lon, latLon.lat]),
cosAngle = transform.cosAngle || (transform.rotation && Math.cos(transform.rotation)),
sinAngle = transform.sinAngle || (transform.rotation && Math.sin(transform.rotation)),
rotated = transform.rotation ? [projected[0] * cosAngle + projected[1] * sinAngle, -projected[0] * sinAngle + projected[1] * cosAngle] : projected;
return {
x: ((rotated[0] - (transform.xoffset || 0)) * (transform.scale || 1) + (transform.xpan || 0)) * (transform.jsonres || 1) + (transform.jsonmarginX || 0),
y: (((transform.yoffset || 0) - rotated[1]) * (transform.scale || 1) + (transform.ypan || 0)) * (transform.jsonres || 1) - (transform.jsonmarginY || 0)
};
};
/**
* Get latLon from point using specified transform definition
*/
Chart.prototype.transformToLatLon = function(point, transform) {
if (win.proj4 === undefined) {
error(21);
return;
}
var normalized = {
x: ((point.x - (transform.jsonmarginX || 0)) / (transform.jsonres || 1) - (transform.xpan || 0)) / (transform.scale || 1) + (transform.xoffset || 0),
y: ((-point.y - (transform.jsonmarginY || 0)) / (transform.jsonres || 1) + (transform.ypan || 0)) / (transform.scale || 1) + (transform.yoffset || 0)
},
cosAngle = transform.cosAngle || (transform.rotation && Math.cos(transform.rotation)),
sinAngle = transform.sinAngle || (transform.rotation && Math.sin(transform.rotation)),
// Note: Inverted sinAngle to reverse rotation direction
projected = win.proj4(transform.crs, 'WGS84', transform.rotation ? {
x: normalized.x * cosAngle + normalized.y * -sinAngle,
y: normalized.x * sinAngle + normalized.y * cosAngle
} : normalized);
return {
lat: projected.y,
lon: projected.x
};
};
Chart.prototype.fromPointToLatLon = function(point) {
var transforms = this.mapTransforms,
transform;
if (!transforms) {
error(22);
return;
}
for (transform in transforms) {
if (transforms.hasOwnProperty(transform) && transforms[transform].hitZone &&
pointInPolygon({
x: point.x,
y: -point.y
}, transforms[transform].hitZone.coordinates[0])) {
return this.transformToLatLon(point, transforms[transform]);
}
}
return this.transformToLatLon(point, transforms['default']); // eslint-disable-line dot-notation
};
Chart.prototype.fromLatLonToPoint = function(latLon) {
var transforms = this.mapTransforms,
transform,
coords;
if (!transforms) {
error(22);
return {
x: 0,
y: null
};
}
for (transform in transforms) {
if (transforms.hasOwnProperty(transform) && transforms[transform].hitZone) {
coords = this.transformFromLatLon(latLon, transforms[transform]);
if (pointInPolygon({
x: coords.x,
y: -coords.y
}, transforms[transform].hitZone.coordinates[0])) {
return coords;
}
}
}
return this.transformFromLatLon(latLon, transforms['default']); // eslint-disable-line dot-notation
};
/**
* Convert a geojson object to map data of a given Highcharts type (map, mappoint or mapline).
*/
H.geojson = function(geojson, hType, series) {
var mapData = [],
path = [],
polygonToPath = function(polygon) {
var i,
len = polygon.length;
path.push('M');
for (i = 0; i < len; i++) {
if (i === 1) {
path.push('L');
}
path.push(polygon[i][0], -polygon[i][1]);
}
};
hType = hType || 'map';
each(geojson.features, function(feature) {
var geometry = feature.geometry,
type = geometry.type,
coordinates = geometry.coordinates,
properties = feature.properties,
point;
path = [];
if (hType === 'map' || hType === 'mapbubble') {
if (type === 'Polygon') {
each(coordinates, polygonToPath);
path.push('Z');
} else if (type === 'MultiPolygon') {
each(coordinates, function(items) {
each(items, polygonToPath);
});
path.push('Z');
}
if (path.length) {
point = {
path: path
};
}
} else if (hType === 'mapline') {
if (type === 'LineString') {
polygonToPath(coordinates);
} else if (type === 'MultiLineString') {
each(coordinates, polygonToPath);
}
if (path.length) {
point = {
path: path
};
}
} else if (hType === 'mappoint') {
if (type === 'Point') {
point = {
x: coordinates[0],
y: -coordinates[1]
};
}
}
if (point) {
mapData.push(extend(point, {
name: properties.name || properties.NAME,
properties: properties
}));
}
});
// Create a credits text that includes map source, to be picked up in Chart.addCredits
if (series && geojson.copyrightShort) {
series.chart.mapCredits = format(series.chart.options.credits.mapText, {
geojson: geojson
});
series.chart.mapCreditsFull = format(series.chart.options.credits.mapTextFull, {
geojson: geojson
});
}
return mapData;
};
/**
* Override addCredits to include map source by default
*/
wrap(Chart.prototype, 'addCredits', function(proceed, credits) {
credits = merge(true, this.options.credits, credits);
// Disable credits link if map credits enabled. This to allow for in-text anchors.
if (this.mapCredits) {
credits.href = null;
}
proceed.call(this, credits);
// Add full map credits to hover
if (this.credits && this.mapCreditsFull) {
this.credits.attr({
title: this.mapCreditsFull
});
}
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Chart = H.Chart,
defaultOptions = H.defaultOptions,
each = H.each,
extend = H.extend,
merge = H.merge,
pick = H.pick,
Renderer = H.Renderer,
SVGRenderer = H.SVGRenderer,
VMLRenderer = H.VMLRenderer;
// Add language
extend(defaultOptions.lang, {
zoomIn: 'Zoom in',
zoomOut: 'Zoom out'
});
// Set the default map navigation options
defaultOptions.mapNavigation = {
buttonOptions: {
alignTo: 'plotBox',
align: 'left',
verticalAlign: 'top',
x: 0,
width: 18,
height: 18,
padding: 5
},
buttons: {
zoomIn: {
onclick: function() {
this.mapZoom(0.5);
},
text: '+',
y: 0
},
zoomOut: {
onclick: function() {
this.mapZoom(2);
},
text: '-',
y: 28
}
},
mouseWheelSensitivity: 1.1
// enabled: false,
// enableButtons: null, // inherit from enabled
// enableTouchZoom: null, // inherit from enabled
// enableDoubleClickZoom: null, // inherit from enabled
// enableDoubleClickZoomTo: false
// enableMouseWheelZoom: null, // inherit from enabled
};
/**
* Utility for reading SVG paths directly.
*/
H.splitPath = function(path) {
var i;
// Move letters apart
path = path.replace(/([A-Za-z])/g, ' $1 ');
// Trim
path = path.replace(/^\s*/, '').replace(/\s*$/, '');
// Split on spaces and commas
path = path.split(/[ ,]+/); // Extra comma to escape gulp.scripts task
// Parse numbers
for (i = 0; i < path.length; i++) {
if (!/[a-zA-Z]/.test(path[i])) {
path[i] = parseFloat(path[i]);
}
}
return path;
};
// A placeholder for map definitions
H.maps = {};
// Create symbols for the zoom buttons
function selectiveRoundedRect(x, y, w, h, rTopLeft, rTopRight, rBottomRight, rBottomLeft) {
return ['M', x + rTopLeft, y,
// top side
'L', x + w - rTopRight, y,
// top right corner
'C', x + w - rTopRight / 2, y, x + w, y + rTopRight / 2, x + w, y + rTopRight,
// right side
'L', x + w, y + h - rBottomRight,
// bottom right corner
'C', x + w, y + h - rBottomRight / 2, x + w - rBottomRight / 2, y + h, x + w - rBottomRight, y + h,
// bottom side
'L', x + rBottomLeft, y + h,
// bottom left corner
'C', x + rBottomLeft / 2, y + h, x, y + h - rBottomLeft / 2, x, y + h - rBottomLeft,
// left side
'L', x, y + rTopLeft,
// top left corner
'C', x, y + rTopLeft / 2, x + rTopLeft / 2, y, x + rTopLeft, y,
'Z'
];
}
SVGRenderer.prototype.symbols.topbutton = function(x, y, w, h, attr) {
return selectiveRoundedRect(x - 1, y - 1, w, h, attr.r, attr.r, 0, 0);
};
SVGRenderer.prototype.symbols.bottombutton = function(x, y, w, h, attr) {
return selectiveRoundedRect(x - 1, y - 1, w, h, 0, 0, attr.r, attr.r);
};
// The symbol callbacks are generated on the SVGRenderer object in all browsers. Even
// VML browsers need this in order to generate shapes in export. Now share
// them with the VMLRenderer.
if (Renderer === VMLRenderer) {
each(['topbutton', 'bottombutton'], function(shape) {
VMLRenderer.prototype.symbols[shape] = SVGRenderer.prototype.symbols[shape];
});
}
/**
* A wrapper for Chart with all the default values for a Map
*/
H.Map = H.mapChart = function(a, b, c) {
var hasRenderToArg = typeof a === 'string' || a.nodeName,
options = arguments[hasRenderToArg ? 1 : 0],
hiddenAxis = {
endOnTick: false,
visible: false,
minPadding: 0,
maxPadding: 0,
startOnTick: false
},
seriesOptions,
defaultCreditsOptions = H.getOptions().credits;
/* For visual testing
hiddenAxis.gridLineWidth = 1;
hiddenAxis.gridZIndex = 10;
hiddenAxis.tickPositions = undefined;
// */
// Don't merge the data
seriesOptions = options.series;
options.series = null;
options = merge({
chart: {
panning: 'xy',
type: 'map'
},
credits: {
mapText: pick(defaultCreditsOptions.mapText, ' \u00a9 <a href="{geojson.copyrightUrl}">{geojson.copyrightShort}</a>'),
mapTextFull: pick(defaultCreditsOptions.mapTextFull, '{geojson.copyright}')
},
xAxis: hiddenAxis,
yAxis: merge(hiddenAxis, {
reversed: true
})
},
options, // user's options
{ // forced options
chart: {
inverted: false,
alignTicks: false
}
}
);
options.series = seriesOptions;
return hasRenderToArg ?
new Chart(a, options, c) :
new Chart(options, b);
};
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var colorPointMixin = H.colorPointMixin,
colorSeriesMixin = H.colorSeriesMixin,
each = H.each,
LegendSymbolMixin = H.LegendSymbolMixin,
merge = H.merge,
noop = H.noop,
pick = H.pick,
Series = H.Series,
seriesType = H.seriesType,
seriesTypes = H.seriesTypes;
// The Heatmap series type
seriesType('heatmap', 'scatter', {
animation: false,
borderWidth: 0,
dataLabels: {
formatter: function() { // #2945
return this.point.value;
},
inside: true,
verticalAlign: 'middle',
crop: false,
overflow: false,
padding: 0 // #3837
},
marker: null,
pointRange: null, // dynamically set to colsize by default
tooltip: {
pointFormat: '{point.x}, {point.y}: {point.value}<br/>'
},
states: {
normal: {
animation: true
},
hover: {
halo: false, // #3406, halo is not required on heatmaps
brightness: 0.2
}
}
}, merge(colorSeriesMixin, {
pointArrayMap: ['y', 'value'],
hasPointSpecificOptions: true,
supportsDrilldown: true,
getExtremesFromAll: true,
directTouch: true,
/**
* Override the init method to add point ranges on both axes.
*/
init: function() {
var options;
seriesTypes.scatter.prototype.init.apply(this, arguments);
options = this.options;
options.pointRange = pick(options.pointRange, options.colsize || 1); // #3758, prevent resetting in setData
this.yAxis.axisPointRange = options.rowsize || 1; // general point range
},
translate: function() {
var series = this,
options = series.options,
xAxis = series.xAxis,
yAxis = series.yAxis,
between = function(x, a, b) {
return Math.min(Math.max(a, x), b);
};
series.generatePoints();
each(series.points, function(point) {
var xPad = (options.colsize || 1) / 2,
yPad = (options.rowsize || 1) / 2,
x1 = between(Math.round(xAxis.len - xAxis.translate(point.x - xPad, 0, 1, 0, 1)), -xAxis.len, 2 * xAxis.len),
x2 = between(Math.round(xAxis.len - xAxis.translate(point.x + xPad, 0, 1, 0, 1)), -xAxis.len, 2 * xAxis.len),
y1 = between(Math.round(yAxis.translate(point.y - yPad, 0, 1, 0, 1)), -yAxis.len, 2 * yAxis.len),
y2 = between(Math.round(yAxis.translate(point.y + yPad, 0, 1, 0, 1)), -yAxis.len, 2 * yAxis.len);
// Set plotX and plotY for use in K-D-Tree and more
point.plotX = point.clientX = (x1 + x2) / 2;
point.plotY = (y1 + y2) / 2;
point.shapeType = 'rect';
point.shapeArgs = {
x: Math.min(x1, x2),
y: Math.min(y1, y2),
width: Math.abs(x2 - x1),
height: Math.abs(y2 - y1)
};
});
series.translateColors();
},
drawPoints: function() {
seriesTypes.column.prototype.drawPoints.call(this);
each(this.points, function(point) {
point.graphic.attr(this.colorAttribs(point, point.state));
}, this);
},
animate: noop,
getBox: noop,
drawLegendSymbol: LegendSymbolMixin.drawRectangle,
alignDataLabel: seriesTypes.column.prototype.alignDataLabel,
getExtremes: function() {
// Get the extremes from the value data
Series.prototype.getExtremes.call(this, this.valueData);
this.valueMin = this.dataMin;
this.valueMax = this.dataMax;
// Get the extremes from the y data
Series.prototype.getExtremes.call(this);
}
}), colorPointMixin);
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var addEvent = H.addEvent,
Chart = H.Chart,
createElement = H.createElement,
css = H.css,
defaultOptions = H.defaultOptions,
defaultPlotOptions = H.defaultPlotOptions,
each = H.each,
extend = H.extend,
fireEvent = H.fireEvent,
hasTouch = H.hasTouch,
inArray = H.inArray,
isObject = H.isObject,
Legend = H.Legend,
merge = H.merge,
pick = H.pick,
Point = H.Point,
Series = H.Series,
seriesTypes = H.seriesTypes,
svg = H.svg,
TrackerMixin;
/**
* TrackerMixin for points and graphs
*/
TrackerMixin = H.TrackerMixin = {
drawTrackerPoint: function() {
var series = this,
chart = series.chart,
pointer = chart.pointer,
onMouseOver = function(e) {
var target = e.target,
point;
while (target && !point) {
point = target.point;
target = target.parentNode;
}
if (point !== undefined && point !== chart.hoverPoint) { // undefined on graph in scatterchart
point.onMouseOver(e);
}
};
// Add reference to the point
each(series.points, function(point) {
if (point.graphic) {
point.graphic.element.point = point;
}
if (point.dataLabel) {
point.dataLabel.element.point = point;
}
});
// Add the event listeners, we need to do this only once
if (!series._hasTracking) {
each(series.trackerGroups, function(key) {
if (series[key]) { // we don't always have dataLabelsGroup
series[key]
.addClass('highcharts-tracker')
.on('mouseover', onMouseOver)
.on('mouseout', function(e) {
pointer.onTrackerMouseOut(e);
});
if (hasTouch) {
series[key].on('touchstart', onMouseOver);
}
}
});
series._hasTracking = true;
}
},
/**
* Draw the tracker object that sits above all data labels and markers to
* track mouse events on the graph or points. For the line type charts
* the tracker uses the same graphPath, but with a greater stroke width
* for better control.
*/
drawTrackerGraph: function() {
var series = this,
options = series.options,
trackByArea = options.trackByArea,
trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath),
trackerPathLength = trackerPath.length,
chart = series.chart,
pointer = chart.pointer,
renderer = chart.renderer,
snap = chart.options.tooltip.snap,
tracker = series.tracker,
i,
onMouseOver = function() {
if (chart.hoverSeries !== series) {
series.onMouseOver();
}
},
/*
* Empirical lowest possible opacities for TRACKER_FILL for an element to stay invisible but clickable
* IE6: 0.002
* IE7: 0.002
* IE8: 0.002
* IE9: 0.00000000001 (unlimited)
* IE10: 0.0001 (exporting only)
* FF: 0.00000000001 (unlimited)
* Chrome: 0.000001
* Safari: 0.000001
* Opera: 0.00000000001 (unlimited)
*/
TRACKER_FILL = 'rgba(192,192,192,' + (svg ? 0.0001 : 0.002) + ')';
// Extend end points. A better way would be to use round linecaps,
// but those are not clickable in VML.
if (trackerPathLength && !trackByArea) {
i = trackerPathLength + 1;
while (i--) {
if (trackerPath[i] === 'M') { // extend left side
trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], 'L');
}
if ((i && trackerPath[i] === 'M') || i === trackerPathLength) { // extend right side
trackerPath.splice(i, 0, 'L', trackerPath[i - 2] + snap, trackerPath[i - 1]);
}
}
}
// handle single points
/*for (i = 0; i < singlePoints.length; i++) {
singlePoint = singlePoints[i];
trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY,
L, singlePoint.plotX + snap, singlePoint.plotY);
}*/
// draw the tracker
if (tracker) {
tracker.attr({
d: trackerPath
});
} else if (series.graph) { // create
series.tracker = renderer.path(trackerPath)
.attr({
'stroke-linejoin': 'round', // #1225
visibility: series.visible ? 'visible' : 'hidden',
stroke: TRACKER_FILL,
fill: trackByArea ? TRACKER_FILL : 'none',
'stroke-width': series.graph.strokeWidth() + (trackByArea ? 0 : 2 * snap),
zIndex: 2
})
.add(series.group);
// The tracker is added to the series group, which is clipped, but is covered
// by the marker group. So the marker group also needs to capture events.
each([series.tracker, series.markerGroup], function(tracker) {
tracker.addClass('highcharts-tracker')
.on('mouseover', onMouseOver)
.on('mouseout', function(e) {
pointer.onTrackerMouseOut(e);
});
if (hasTouch) {
tracker.on('touchstart', onMouseOver);
}
});
}
}
};
/* End TrackerMixin */
/**
* Add tracking event listener to the series group, so the point graphics
* themselves act as trackers
*/
if (seriesTypes.column) {
seriesTypes.column.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
}
if (seriesTypes.pie) {
seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
}
if (seriesTypes.scatter) {
seriesTypes.scatter.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
}
/*
* Extend Legend for item events
*/
extend(Legend.prototype, {
setItemEvents: function(item, legendItem, useHTML) {
var legend = this,
chart = legend.chart,
activeClass = 'highcharts-legend-' + (item.series ? 'point' : 'series') + '-active';
// Set the events on the item group, or in case of useHTML, the item itself (#1249)
(useHTML ? legendItem : item.legendGroup).on('mouseover', function() {
item.setState('hover');
// A CSS class to dim or hide other than the hovered series
chart.seriesGroup.addClass(activeClass);
})
.on('mouseout', function() {
// A CSS class to dim or hide other than the hovered series
chart.seriesGroup.removeClass(activeClass);
item.setState();
})
.on('click', function(event) {
var strLegendItemClick = 'legendItemClick',
fnLegendItemClick = function() {
if (item.setVisible) {
item.setVisible();
}
};
// Pass over the click/touch event. #4.
event = {
browserEvent: event
};
// click the name or symbol
if (item.firePointEvent) { // point
item.firePointEvent(strLegendItemClick, event, fnLegendItemClick);
} else {
fireEvent(item, strLegendItemClick, event, fnLegendItemClick);
}
});
},
createCheckboxForItem: function(item) {
var legend = this;
item.checkbox = createElement('input', {
type: 'checkbox',
checked: item.selected,
defaultChecked: item.selected // required by IE7
}, legend.options.itemCheckboxStyle, legend.chart.container);
addEvent(item.checkbox, 'click', function(event) {
var target = event.target;
fireEvent(
item.series || item,
'checkboxClick', { // #3712
checked: target.checked,
item: item
},
function() {
item.select();
}
);
});
}
});
/*
* Extend the Chart object with interaction
*/
extend(Chart.prototype, {
/**
* Display the zoom button
*/
showResetZoom: function() {
var chart = this,
lang = defaultOptions.lang,
btnOptions = chart.options.chart.resetZoomButton,
theme = btnOptions.theme,
states = theme.states,
alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox';
function zoomOut() {
chart.zoomOut();
}
this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, zoomOut, theme, states && states.hover)
.attr({
align: btnOptions.position.align,
title: lang.resetZoomTitle
})
.addClass('highcharts-reset-zoom')
.add()
.align(btnOptions.position, false, alignTo);
},
/**
* Zoom out to 1:1
*/
zoomOut: function() {
var chart = this;
fireEvent(chart, 'selection', {
resetSelection: true
}, function() {
chart.zoom();
});
},
/**
* Zoom into a given portion of the chart given by axis coordinates
* @param {Object} event
*/
zoom: function(event) {
var chart = this,
hasZoomed,
pointer = chart.pointer,
displayButton = false,
resetZoomButton;
// If zoom is called with no arguments, reset the axes
if (!event || event.resetSelection) {
each(chart.axes, function(axis) {
hasZoomed = axis.zoom();
});
} else { // else, zoom in on all axes
each(event.xAxis.concat(event.yAxis), function(axisData) {
var axis = axisData.axis,
isXAxis = axis.isXAxis;
// don't zoom more than minRange
if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) {
hasZoomed = axis.zoom(axisData.min, axisData.max);
if (axis.displayBtn) {
displayButton = true;
}
}
});
}
// Show or hide the Reset zoom button
resetZoomButton = chart.resetZoomButton;
if (displayButton && !resetZoomButton) {
chart.showResetZoom();
} else if (!displayButton && isObject(resetZoomButton)) {
chart.resetZoomButton = resetZoomButton.destroy();
}
// Redraw
if (hasZoomed) {
chart.redraw(
pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation
);
}
},
/**
* Pan the chart by dragging the mouse across the pane. This function is called
* on mouse move, and the distance to pan is computed from chartX compared to
* the first chartX position in the dragging operation.
*/
pan: function(e, panning) {
var chart = this,
hoverPoints = chart.hoverPoints,
doRedraw;
// remove active points for shared tooltip
if (hoverPoints) {
each(hoverPoints, function(point) {
point.setState();
});
}
each(panning === 'xy' ? [1, 0] : [1], function(isX) { // xy is used in maps
var axis = chart[isX ? 'xAxis' : 'yAxis'][0],
horiz = axis.horiz,
mousePos = e[horiz ? 'chartX' : 'chartY'],
mouseDown = horiz ? 'mouseDownX' : 'mouseDownY',
startPos = chart[mouseDown],
halfPointRange = (axis.pointRange || 0) / 2,
extremes = axis.getExtremes(),
newMin = axis.toValue(startPos - mousePos, true) + halfPointRange,
newMax = axis.toValue(startPos + axis.len - mousePos, true) - halfPointRange,
goingLeft = startPos > mousePos; // #3613
if (axis.series.length &&
(goingLeft || newMin > Math.min(extremes.dataMin, extremes.min)) &&
(!goingLeft || newMax < Math.max(extremes.dataMax, extremes.max))) {
axis.setExtremes(newMin, newMax, false, false, {
trigger: 'pan'
});
doRedraw = true;
}
chart[mouseDown] = mousePos; // set new reference for next run
});
if (doRedraw) {
chart.redraw(false);
}
css(chart.container, {
cursor: 'move'
});
}
});
/*
* Extend the Point object with interaction
*/
extend(Point.prototype, {
/**
* Toggle the selection status of a point
* @param {Boolean} selected Whether to select or unselect the point.
* @param {Boolean} accumulate Whether to add to the previous selection. By default,
* this happens if the control key (Cmd on Mac) was pressed during clicking.
*/
select: function(selected, accumulate) {
var point = this,
series = point.series,
chart = series.chart;
selected = pick(selected, !point.selected);
// fire the event with the default handler
point.firePointEvent(selected ? 'select' : 'unselect', {
accumulate: accumulate
}, function() {
point.selected = point.options.selected = selected;
series.options.data[inArray(point, series.data)] = point.options;
point.setState(selected && 'select');
// unselect all other points unless Ctrl or Cmd + click
if (!accumulate) {
each(chart.getSelectedPoints(), function(loopPoint) {
if (loopPoint.selected && loopPoint !== point) {
loopPoint.selected = loopPoint.options.selected = false;
series.options.data[inArray(loopPoint, series.data)] = loopPoint.options;
loopPoint.setState('');
loopPoint.firePointEvent('unselect');
}
});
}
});
},
/**
* Runs on mouse over the point
*
* @param {Object} e The event arguments
* @param {Boolean} byProximity Falsy for kd points that are closest to the mouse, or to
* actually hovered points. True for other points in shared tooltip.
*/
onMouseOver: function(e, byProximity) {
var point = this,
series = point.series,
chart = series.chart,
tooltip = chart.tooltip,
hoverPoint = chart.hoverPoint;
if (point.series) { // It may have been destroyed, #4130
// In shared tooltip, call mouse over when point/series is actually hovered: (#5766)
if (!byProximity) {
// set normal state to previous series
if (hoverPoint && hoverPoint !== point) {
hoverPoint.onMouseOut();
}
if (chart.hoverSeries !== series) {
series.onMouseOver();
}
chart.hoverPoint = point;
}
// update the tooltip
if (tooltip && (!tooltip.shared || series.noSharedTooltip)) {
// hover point only for non shared points: (#5766)
point.setState('hover');
tooltip.refresh(point, e);
} else if (!tooltip) {
point.setState('hover');
}
// trigger the event
point.firePointEvent('mouseOver');
}
},
/**
* Runs on mouse out from the point
*/
onMouseOut: function() {
var chart = this.series.chart,
hoverPoints = chart.hoverPoints;
this.firePointEvent('mouseOut');
if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887, #2240
this.setState();
chart.hoverPoint = null;
}
},
/**
* Import events from the series' and point's options. Only do it on
* demand, to save processing time on hovering.
*/
importEvents: function() {
if (!this.hasImportedEvents) {
var point = this,
options = merge(point.series.options.point, point.options),
events = options.events,
eventType;
point.events = events;
for (eventType in events) {
addEvent(point, eventType, events[eventType]);
}
this.hasImportedEvents = true;
}
},
/**
* Set the point's state
* @param {String} state
*/
setState: function(state, move) {
var point = this,
plotX = Math.floor(point.plotX), // #4586
plotY = point.plotY,
series = point.series,
stateOptions = series.options.states[state] || {},
markerOptions = defaultPlotOptions[series.type].marker &&
series.options.marker,
normalDisabled = markerOptions && markerOptions.enabled === false,
markerStateOptions = (markerOptions && markerOptions.states &&
markerOptions.states[state]) || {},
stateDisabled = markerStateOptions.enabled === false,
stateMarkerGraphic = series.stateMarkerGraphic,
pointMarker = point.marker || {},
chart = series.chart,
halo = series.halo,
haloOptions,
markerAttribs,
newSymbol;
state = state || ''; // empty string
if (
// already has this state
(state === point.state && !move) ||
// selected points don't respond to hover
(point.selected && state !== 'select') ||
// series' state options is disabled
(stateOptions.enabled === false) ||
// general point marker's state options is disabled
(state && (stateDisabled || (normalDisabled && markerStateOptions.enabled === false))) ||
// individual point marker's state options is disabled
(state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610
) {
return;
}
if (markerOptions) {
markerAttribs = series.markerAttribs(point, state);
}
// Apply hover styles to the existing point
if (point.graphic) {
if (point.state) {
point.graphic.removeClass('highcharts-point-' + point.state);
}
if (state) {
point.graphic.addClass('highcharts-point-' + state);
}
/*attribs = radius ? { // new symbol attributes (#507, #612)
x: plotX - radius,
y: plotY - radius,
width: 2 * radius,
height: 2 * radius
} : {};*/
if (markerAttribs) {
point.graphic.animate(
markerAttribs,
pick(
chart.options.chart.animation, // Turn off globally
markerStateOptions.animation,
markerOptions.animation
)
);
}
// Zooming in from a range with no markers to a range with markers
if (stateMarkerGraphic) {
stateMarkerGraphic.hide();
}
} else {
// if a graphic is not applied to each point in the normal state, create a shared
// graphic for the hover state
if (state && markerStateOptions) {
newSymbol = pointMarker.symbol || series.symbol;
// If the point has another symbol than the previous one, throw away the
// state marker graphic and force a new one (#1459)
if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) {
stateMarkerGraphic = stateMarkerGraphic.destroy();
}
// Add a new state marker graphic
if (!stateMarkerGraphic) {
if (newSymbol) {
series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol(
newSymbol,
markerAttribs.x,
markerAttribs.y,
markerAttribs.width,
markerAttribs.height
)
.add(series.markerGroup);
stateMarkerGraphic.currentSymbol = newSymbol;
}
// Move the existing graphic
} else {
stateMarkerGraphic[move ? 'animate' : 'attr']({ // #1054
x: markerAttribs.x,
y: markerAttribs.y
});
}
}
if (stateMarkerGraphic) {
stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY, chart.inverted) ? 'show' : 'hide'](); // #2450
stateMarkerGraphic.element.point = point; // #4310
}
}
// Show me your halo
haloOptions = stateOptions.halo;
if (haloOptions && haloOptions.size) {
if (!halo) {
series.halo = halo = chart.renderer.path()
.add(series.markerGroup || series.group);
}
H.stop(halo);
halo[move ? 'animate' : 'attr']({
d: point.haloPath(haloOptions.size)
});
halo.attr({
'class': 'highcharts-halo highcharts-color-' + pick(point.colorIndex, series.colorIndex)
});
} else if (halo) {
halo.animate({
d: point.haloPath(0)
}); // Hide
}
point.state = state;
},
/**
* Get the circular path definition for the halo
* @param {Number} size The radius of the circular halo
* @returns {Array} The path definition
*/
haloPath: function(size) {
var series = this.series,
chart = series.chart,
inverted = chart.inverted,
plotX = Math.floor(this.plotX);
return chart.renderer.symbols.circle(
(inverted ? series.yAxis.len - this.plotY : plotX) - size,
(inverted ? series.xAxis.len - plotX : this.plotY) - size,
size * 2,
size * 2
);
}
});
/*
* Extend the Series object with interaction
*/
extend(Series.prototype, {
/**
* Series mouse over handler
*/
onMouseOver: function() {
var series = this,
chart = series.chart,
hoverSeries = chart.hoverSeries;
// set normal state to previous series
if (hoverSeries && hoverSeries !== series) {
hoverSeries.onMouseOut();
}
// trigger the event, but to save processing time,
// only if defined
if (series.options.events.mouseOver) {
fireEvent(series, 'mouseOver');
}
// hover this
series.setState('hover');
chart.hoverSeries = series;
},
/**
* Series mouse out handler
*/
onMouseOut: function() {
// trigger the event only if listeners exist
var series = this,
options = series.options,
chart = series.chart,
tooltip = chart.tooltip,
hoverPoint = chart.hoverPoint;
chart.hoverSeries = null; // #182, set to null before the mouseOut event fires
// trigger mouse out on the point, which must be in this series
if (hoverPoint) {
hoverPoint.onMouseOut();
}
// fire the mouse out event
if (series && options.events.mouseOut) {
fireEvent(series, 'mouseOut');
}
// hide the tooltip
if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) {
tooltip.hide();
}
// set normal state
series.setState();
},
/**
* Set the state of the graph
*/
setState: function(state) {
var series = this,
options = series.options,
graph = series.graph,
stateOptions = options.states,
lineWidth = options.lineWidth,
attribs,
i = 0;
state = state || '';
if (series.state !== state) {
// Toggle class names
each([series.group, series.markerGroup], function(group) {
if (group) {
// Old state
if (series.state) {
group.removeClass('highcharts-series-' + series.state);
}
// New state
if (state) {
group.addClass('highcharts-series-' + state);
}
}
});
series.state = state;
}
},
/**
* Set the visibility of the graph
*
* @param vis {Boolean} True to show the series, false to hide. If undefined,
* the visibility is toggled.
*/
setVisible: function(vis, redraw) {
var series = this,
chart = series.chart,
legendItem = series.legendItem,
showOrHide,
ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries,
oldVisibility = series.visible;
// if called without an argument, toggle visibility
series.visible = vis = series.options.visible = series.userOptions.visible = vis === undefined ? !oldVisibility : vis; // #5618
showOrHide = vis ? 'show' : 'hide';
// show or hide elements
each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker', 'tt'], function(key) {
if (series[key]) {
series[key][showOrHide]();
}
});
// hide tooltip (#1361)
if (chart.hoverSeries === series || (chart.hoverPoint && chart.hoverPoint.series) === series) {
series.onMouseOut();
}
if (legendItem) {
chart.legend.colorizeItem(series, vis);
}
// rescale or adapt to resized chart
series.isDirty = true;
// in a stack, all other series are affected
if (series.options.stacking) {
each(chart.series, function(otherSeries) {
if (otherSeries.options.stacking && otherSeries.visible) {
otherSeries.isDirty = true;
}
});
}
// show or hide linked series
each(series.linkedSeries, function(otherSeries) {
otherSeries.setVisible(vis, false);
});
if (ignoreHiddenSeries) {
chart.isDirtyBox = true;
}
if (redraw !== false) {
chart.redraw();
}
fireEvent(series, showOrHide);
},
/**
* Show the graph
*/
show: function() {
this.setVisible(true);
},
/**
* Hide the graph
*/
hide: function() {
this.setVisible(false);
},
/**
* Set the selected state of the graph
*
* @param selected {Boolean} True to select the series, false to unselect. If
* undefined, the selection state is toggled.
*/
select: function(selected) {
var series = this;
// if called without an argument, toggle
series.selected = selected = (selected === undefined) ? !series.selected : selected;
if (series.checkbox) {
series.checkbox.checked = selected;
}
fireEvent(series, selected ? 'select' : 'unselect');
},
drawTracker: TrackerMixin.drawTrackerGraph
});
}(Highcharts));
(function(H) {
/**
* (c) 2010-2016 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
var Chart = H.Chart,
each = H.each,
inArray = H.inArray,
isObject = H.isObject,
pick = H.pick,
splat = H.splat;
/**
* Update the chart based on the current chart/document size and options for responsiveness
*/
Chart.prototype.setResponsive = function(redraw) {
var options = this.options.responsive;
if (options && options.rules) {
each(options.rules, function(rule) {
this.matchResponsiveRule(rule, redraw);
}, this);
}
};
/**
* Handle a single responsiveness rule
*/
Chart.prototype.matchResponsiveRule = function(rule, redraw) {
var respRules = this.respRules,
condition = rule.condition,
matches,
fn = rule.callback || function() {
return this.chartWidth <= pick(condition.maxWidth, Number.MAX_VALUE) &&
this.chartHeight <= pick(condition.maxHeight, Number.MAX_VALUE) &&
this.chartWidth >= pick(condition.minWidth, 0) &&
this.chartHeight >= pick(condition.minHeight, 0);
};
if (rule._id === undefined) {
rule._id = H.idCounter++;
}
matches = fn.call(this);
// Apply a rule
if (!respRules[rule._id] && matches) {
// Store the current state of the options
if (rule.chartOptions) {
respRules[rule._id] = this.currentOptions(rule.chartOptions);
this.update(rule.chartOptions, redraw);
}
// Unapply a rule based on the previous options before the rule
// was applied
} else if (respRules[rule._id] && !matches) {
this.update(respRules[rule._id], redraw);
delete respRules[rule._id];
}
};
/**
* Get the current values for a given set of options. Used before we update
* the chart with a new responsiveness rule.
* TODO: Restore axis options (by id?)
*/
Chart.prototype.currentOptions = function(options) {
var ret = {};
/**
* Recurse over a set of options and its current values,
* and store the current values in the ret object.
*/
function getCurrent(options, curr, ret) {
var key, i;
for (key in options) {
if (inArray(key, ['series', 'xAxis', 'yAxis']) > -1) {
options[key] = splat(options[key]);
ret[key] = [];
for (i = 0; i < options[key].length; i++) {
ret[key][i] = {};
getCurrent(options[key][i], curr[key][i], ret[key][i]);
}
} else if (isObject(options[key])) {
ret[key] = {};
getCurrent(options[key], curr[key] || {}, ret[key]);
} else {
ret[key] = curr[key] || null;
}
}
}
getCurrent(options, this.options, ret);
return ret;
};
}(Highcharts));
return Highcharts
}));
|
app/javascript/mastodon/components/extended_video_player.js | palon7/mastodon | import React from 'react';
import PropTypes from 'prop-types';
export default class ExtendedVideoPlayer extends React.PureComponent {
static propTypes = {
src: PropTypes.string.isRequired,
width: PropTypes.number,
height: PropTypes.number,
time: PropTypes.number,
controls: PropTypes.bool.isRequired,
muted: PropTypes.bool.isRequired,
};
handleLoadedData = () => {
if (this.props.time) {
this.video.currentTime = this.props.time;
}
}
componentDidMount () {
this.video.addEventListener('loadeddata', this.handleLoadedData);
}
componentWillUnmount () {
this.video.removeEventListener('loadeddata', this.handleLoadedData);
}
setRef = (c) => {
this.video = c;
}
render () {
return (
<div className='extended-video-player'>
<video
ref={this.setRef}
src={this.props.src}
autoPlay
muted={this.props.muted}
controls={this.props.controls}
loop={!this.props.controls}
/>
</div>
);
}
}
|
src/svg-icons/action/view-array.js | xmityaz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionViewArray = (props) => (
<SvgIcon {...props}>
<path d="M4 18h3V5H4v13zM18 5v13h3V5h-3zM8 18h9V5H8v13z"/>
</SvgIcon>
);
ActionViewArray = pure(ActionViewArray);
ActionViewArray.displayName = 'ActionViewArray';
ActionViewArray.muiName = 'SvgIcon';
export default ActionViewArray;
|
src/pages/app/login.js | getinsomnia/insomnia.rest | import React from 'react';
import * as session from '../../lib/session';
import App from '../../lib/app-wrapper';
import Link from '../../components/link';
class Login extends React.Component {
state = {
loading: false,
email: '',
password: '',
error: ''
};
_handleUpdateInput(e) {
this.setState({ [e.target.name]: e.target.value, error: '' });
}
async _handleSubmit(e) {
e.preventDefault();
this.setState({ loading: true });
try {
await session.login(this.state.email, this.state.password);
const nextUrl = localStorage.getItem('login.next') || '/app/account/';
localStorage.removeItem('login.next');
window.location = nextUrl;
} catch (err) {
this.setState({ error: err.message, loading: false });
}
}
render() {
const { loading, error } = this.state;
return (
<form onSubmit={this._handleSubmit.bind(this)} method="POST">
<div className="form-control">
<label>
Email Address
<input
type="email"
name="email"
placeholder="[email protected]"
onChange={this._handleUpdateInput.bind(this)}
autoFocus
required
/>
</label>
</div>
<div className="form-control">
<label>
Password
<input
type="password"
name="password"
onChange={this._handleUpdateInput.bind(this)}
placeholder="•••••••••••••"
required
/>
</label>
</div>
{error ? (
<small className="form-control error">** {error}</small>
) : null}
<div className="form-row padding-top-sm">
<div className="form-control">
Or, <Link to="/app/signup">Sign Up</Link>
</div>
<div className="form-control right">
{loading ? (
<button type="button" disabled className="button">
Logging In...
</button>
) : (
<button type="submit" className="button">
Log In
</button>
)}
</div>
</div>
<hr className="hr--skinny" />
<p className="center text-sm">
<Link
to="https://support.insomnia.rest/article/56-forgot-password"
target="_blank">
Forgot your password?
</Link>
</p>
</form>
);
}
}
Login.propTypes = {};
export default () => (
<App noAuth title="Login" subTitle="Access your account 😀" hideFooter={true}>
{props => <Login {...props} />}
</App>
);
|
newclient/scripts/components/admin/detail-view/upload-attachments-panel/index.js | kuali/research-coi | /*
The Conflict of Interest (COI) module of Kuali Research
Copyright © 2005-2016 Kuali, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
import styles from './style';
import React from 'react';
import {AdminActions} from '../../../../actions/admin-actions';
import {FileUpload} from '../../../file-upload';
import classNames from 'classnames';
export default function UploadAttachmentsPanel(props) {
return (
<div name='Upload Attachments Panel' className={classNames(styles.container, props.className)}>
<div className={styles.header}>
<span className={styles.close} onClick={AdminActions.hideUploadAttachmentsPanel}>
<i className="fa fa-times" style={{fontSize: 23}} /> CLOSE
</span>
<span className={styles.title}>UPLOAD ATTACHMENTS</span>
</div>
<FileUpload
fileType='Admin'
readonly={props.readonly}
onDrop={AdminActions.addAdminAttachment}
delete={AdminActions.deleteAdminAttachment}
files={props.files}
multiple={true}
className={`${styles.override} ${styles.fileUploadStyles}`}
>
<div>Drag and drop or upload your attachments</div>
<div style={{fontSize: 10, marginTop: 2}}>Acceptable Formats: .pdf, .png, .doc, .jpeg</div>
</FileUpload>
</div>
);
}
|
news/routes/Featured/Featured.js | MiloATH/FreeCodeCamp | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router-dom';
import { Image } from 'react-bootstrap';
import Helmet from 'react-helmet';
import { getFeaturedList } from '../../utils/ajax';
import { Loader, Spacer } from '../../../common/app/helperComponents';
import BannerWide from '../../components/BannerWide';
import ArticleMeta from '../../components/ArticleMeta';
const propTypes = {
history: PropTypes.shape({
push: PropTypes.func.isRequired
})
};
const styles = `
.featured-list {
list-style: none;
padding-left: 0;
margin-top: 40px;
}
.featured-list-item {
padding-bottom: 20px;
}
.featured-list-item .title {
color: #333;
padding-bottom: 20px;
}
.featured-list-item a {
padding-top: 5px;
}
.featured-list-image {
margin: 0 auto;
}
.featured-list-item a:hover,
.featured-list-item a:focus {
text-decoration: none;
text-decoration-line: none;
text-decoration-color: transparaent;
}
.featured-list-item a:hover > .meta-wrapper,
.featured-list-item a:focus > .meta-wrapper {
color: #006400;
}
`;
class Featured extends Component {
constructor(props) {
super(props);
this.state = {
fetchState: {
pending: false,
complete: false,
errored: false,
error: null
},
featuredList: []
};
this.fetchFeaturedList = this.fetchFeaturedList.bind(this);
}
componentDidMount() {
return this.fetchFeaturedList();
}
fetchFeaturedList() {
return this.setState(
{
fetchState: { pending: true, complete: false, errored: false }
},
() =>
getFeaturedList().then(({ data }) =>
this.setState({
featuredList: data,
fetchState: {
pending: false,
complete: true,
errored: false,
error: null
}
})
)
);
}
createHandleArticleClick(slug, article) {
const { history } = this.props;
return e => {
e.preventDefault();
return history.push({ pathname: slug, state: { article } });
};
}
renderFeatured(articles) {
return articles.map(article => {
const slug = `/${article.author.username}/`.concat(
article.slugPart,
'--',
article.shortId
);
const { featureImage, shortId, title } = article;
return (
<li className='featured-list-item' key={shortId}>
<a
href={'/news' + slug}
onClick={this.createHandleArticleClick(slug, article)}
>
<h3 className='title'>{title}</h3>
{featureImage && featureImage.src ? (
<Image
className='featured-list-image'
responsive={true}
src={featureImage.src}
/>
) : (
<BannerWide />
)}
<ArticleMeta article={article} />
</a>
<Spacer />
</li>
);
});
}
render() {
const {
fetchState: { pending, complete, errored },
featuredList
} = this.state;
if (pending || !complete) {
return (
<div className='full-size' style={{ position: 'fixed', left: 0 }}>
<Loader />
</div>
);
}
if (complete && errored) {
return <h2>Oh noes!! Something went wrong!</h2>;
}
return (
<div>
<Helmet>
<style>{styles}</style>
</Helmet>
<ul className='featured-list'>{this.renderFeatured(featuredList)}</ul>
</div>
);
}
}
Featured.displayName = 'Featured';
Featured.propTypes = propTypes;
export default withRouter(Featured);
|
docs/src/app/components/pages/components/Dialog/ExampleCustomWidth.js | verdan/material-ui | import React from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
const customContentStyle = {
width: '100%',
maxWidth: 'none',
};
/**
* The dialog width has been set to occupy the full width of browser through the `contentStyle` property.
*/
export default class DialogExampleCustomWidth extends React.Component {
state = {
open: false,
};
handleOpen = () => {
this.setState({open: true});
};
handleClose = () => {
this.setState({open: false});
};
render() {
const actions = [
<FlatButton
label="Cancel"
primary={true}
onTouchTap={this.handleClose}
/>,
<FlatButton
label="Submit"
primary={true}
onTouchTap={this.handleClose}
/>,
];
return (
<div>
<RaisedButton label="Dialog With Custom Width" onTouchTap={this.handleOpen} />
<Dialog
title="Dialog With Custom Width"
actions={actions}
modal={true}
contentStyle={customContentStyle}
open={this.state.open}
>
This dialog spans the entire width of the screen.
</Dialog>
</div>
);
}
}
|
src/components/Header/Header.js | KantanGroup/zuzu-sites | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Header.css';
import Link from '../Link';
import Navigation from '../Navigation';
import logoUrl from './logo-small.png';
import logoUrl2x from './[email protected]';
class Header extends React.Component {
render() {
return (
<div className={s.root}>
<div className={s.container}>
<Navigation />
<Link className={s.brand} to="/">
<img src={logoUrl} srcSet={`${logoUrl2x} 2x`} width="38" height="38" alt="React" />
<span className={s.brandTxt}>Your Company</span>
</Link>
<div className={s.banner}>
<h1 className={s.bannerTitle}>React</h1>
<p className={s.bannerDesc}>Complex web apps made easy</p>
</div>
</div>
</div>
);
}
}
export default withStyles(s)(Header);
|
packages/material-ui-icons/src/ToggleOnRounded.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0z" /><path d="M17 7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h10c2.76 0 5-2.24 5-5s-2.24-5-5-5zm0 8c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3z" /></React.Fragment>
, 'ToggleOnRounded');
|
clients/packages/admin-client/src/mobilizations/widgets/__plugins__/form/components/input.spec.js | nossas/bonde-client | import React from 'react';
import sinon from 'sinon';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import { Input } from '../../../../../mobilizations/widgets/__plugins__/form/components';
describe('client/mobilizations/widgets/__plugins__/form/components/input', () => {
describe('when render form edit input settings', () => {
let props = {
uid: '',
initializeEditing: true,
editable: true,
configurable: true,
mobilization: {
body_font: '',
},
};
it('should call renderForm when initialize editable', () => {
sinon.spy(Input.prototype, 'renderForm');
shallow(<Input {...props} />);
expect(Input.prototype.renderForm.calledOnce).to.equal(true);
});
});
describe('when render input form', () => {
let props = {
uid: '',
initializeEditing: false,
editable: true,
configurable: true,
mobilization: {
body_font: '',
},
};
it('should call renderInput, renderInstructions, renderFieldKind when not initialize editable', () => {
props.field = {};
sinon.spy(Input.prototype, 'renderInput');
sinon.spy(Input.prototype, 'renderInstructions');
sinon.spy(Input.prototype, 'renderFieldKind');
shallow(<Input {...props} />);
expect(Input.prototype.renderInput.calledOnce).to.equal(true);
expect(Input.prototype.renderInstructions.calledOnce).to.equal(true);
expect(Input.prototype.renderFieldKind.calledOnce).to.equal(true);
});
it('should render a select input when field kind equals dropdown', () => {
props.field = { kind: 'dropdown', placeholder: '1,2,3' };
let wrapper = shallow(<Input {...props} />);
expect(wrapper.find('select')).to.have.length(1);
});
it('should render a input text when field kind not equals dropdown or greetings', () => {
props.field = { kind: 'dummy', placeholder: '' };
let wrapper = shallow(<Input {...props} />);
expect(wrapper.find('input')).to.have.length(1);
});
it('should render success message when field kind equals greetings', () => {
props.field = { kind: 'greetings', placeholder: 'new message' };
let wrapper = shallow(<Input {...props} />);
expect(wrapper.find('p')).to.have.length(1);
let node = wrapper.find('p').at(0);
expect(node.text()).to.have.string(props.field.placeholder);
});
it('should change hasMouseOver state for render link edit when mouseOver', () => {
let wrapper = shallow(<Input {...props} />);
wrapper.simulate('mouseEnter');
expect(wrapper.state('hasMouseOver')).to.equals(true);
wrapper.simulate('mouseLeave');
expect(wrapper.state('hasMouseOver')).to.equals(false);
});
it('should editMode when click on block', () => {
let wrapper = shallow(<Input {...props} />);
wrapper.simulate('click');
expect(wrapper.state('editing')).to.equals(true);
});
it('should not click to go edit mode when configurable is False', () => {
props.configurable = false;
let wrapper = shallow(<Input {...props} />);
wrapper.simulate('click');
expect(wrapper.state('editing')).to.equals(false);
});
});
});
|
src/app/main.js | toxzilla/app | import React from 'react';
import {render} from 'react-dom';
import {Controller} from 'cerebral';
import {Container} from 'cerebral-view-react';
import Forms from 'cerebral-module-forms';
import ViewPort from './ViewPort';
import Authenticate from './modules/Authenticate';
import Chat from './modules/Chat';
import Friends from './modules/Friends';
import FTE from './modules/FTE';
import {HeaderBar} from './modules/HeaderBar';
import Notifications from './modules/Notifications';
import Network, {networkRules} from './modules/Network';
import Preferences from './modules/Preferences';
import Profile from './modules/Profile';
import MainView from './views/MainView';
import Store, {model, defaultRules} from './store';
// Initialize the controller
const controller = Controller(model);
// Add the controller modules
controller.addModules({
store: Store({
portName: 'app'
}),
authenticate: Authenticate(),
chat: Chat(),
friends: Friends(),
fte: FTE(),
notifications: Notifications(),
network: Network(),
preferences: Preferences(),
profile: Profile(),
forms: Forms({
rules: {...defaultRules, ...networkRules}
})
});
render(
<Container controller={controller}>
<ViewPort className='main'>
<HeaderBar/>
<MainView/>
</ViewPort>
</Container>, document.getElementById('root'));
|
docs/app/Examples/collections/Grid/Variations/GridExampleTextAlignmentMixed.js | aabustamante/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
|
apps/mk-app-portal/apps/mk-app-portal-about/action.js | ziaochina/mk-demo | import React from 'react'
import { action as MetaAction, AppLoader } from 'mk-meta-engine'
import config from './config'
class action {
constructor(option) {
this.metaAction = option.metaAction
this.config = config.current
}
onInit = ({ component, injections }) => {
this.component = component
this.injections = injections
injections.reduce('init')
}
}
export default function creator(option) {
const metaAction = new MetaAction(option),
o = new action({ ...option, metaAction }),
ret = { ...metaAction, ...o }
metaAction.config({ metaHandlers: ret })
return ret
} |
src/containers/DevTools/DevTools.js | anorudes/react-redux-universal-hot-example | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor toggleVisibilityKey="H"
changePositionKey="Q">
<LogMonitor />
</DockMonitor>
);
|
src/svg-icons/file/folder-shared.js | ichiohta/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let FileFolderShared = (props) => (
<SvgIcon {...props}>
<path d="M20 6h-8l-2-2H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-5 3c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm4 8h-8v-1c0-1.33 2.67-2 4-2s4 .67 4 2v1z"/>
</SvgIcon>
);
FileFolderShared = pure(FileFolderShared);
FileFolderShared.displayName = 'FileFolderShared';
FileFolderShared.muiName = 'SvgIcon';
export default FileFolderShared;
|
admin/client/App/screens/List/components/ItemsTable/ItemsTableDragDropZone.js | matthieugayon/keystone | /**
* THIS IS ORPHANED AND ISN'T RENDERED AT THE MOMENT
* THIS WAS DONE TO FINISH THE REDUX INTEGRATION, WILL REWRITE SOON
* - @mxstbr
*/
import React from 'react';
import DropZoneTarget from './ItemsTableDragDropZoneTarget';
import classnames from 'classnames';
var ItemsTableDragDropZone = React.createClass({
displayName: 'ItemsTableDragDropZone',
propTypes: {
columns: React.PropTypes.array,
connectDropTarget: React.PropTypes.func,
items: React.PropTypes.object,
list: React.PropTypes.object,
},
renderPageDrops () {
const { items, currentPage, pageSize } = this.props;
const totalPages = Math.ceil(items.count / pageSize);
const style = { display: totalPages > 1 ? null : 'none' };
const pages = [];
for (let i = 0; i < totalPages; i++) {
const page = i + 1;
const pageItems = '' + (page * pageSize - (pageSize - 1)) + ' - ' + (page * pageSize);
const current = (page === currentPage);
const className = classnames('ItemList__dropzone--page', {
'is-active': current,
});
pages.push(
<DropZoneTarget
key={'page_' + page}
page={page}
className={className}
pageItems={pageItems}
pageSize={pageSize}
currentPage={currentPage}
drag={this.props.drag}
dispatch={this.props.dispatch}
/>
);
}
let cols = this.props.columns.length;
if (this.props.list.sortable) cols++;
if (!this.props.list.nodelete) cols++;
return (
<tr style={style}>
<td colSpan={cols} >
<div className="ItemList__dropzone" >
{pages}
<div className="clearfix" />
</div>
</td>
</tr>
);
},
render () {
return this.renderPageDrops();
},
});
module.exports = ItemsTableDragDropZone;
|
src/components/Loader/Circle.js | strues/react-universal-boiler | import React from 'react';
import PropTypes from 'prop-types';
import styled, { keyframes } from 'styled-components';
const circleFadeDelay = keyframes`
0%,
39%,
100% {
opacity: 0;
}
40% {
opacity: 1;
}
`;
const Circle = props => {
const CirclePrimitive = styled.div`
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
${props.rotate &&
`
-webkit-transform: rotate(${props.rotate}deg);
-ms-transform: rotate(${props.rotate}deg);
transform: rotate(${props.rotate}deg);
`} &:before {
content: '';
display: block;
margin: 0 auto;
width: 15%;
height: 15%;
background-color: #999;
border-radius: 100%;
animation: ${circleFadeDelay} 1.2s infinite ease-in-out both;
${props.delay &&
`
-webkit-animation-delay: ${props.delay}s;
animation-delay: ${props.delay}s;
`};
}
`;
return <CirclePrimitive />;
};
Circle.propTypes = {
delay: PropTypes.number,
rotate: PropTypes.number,
};
export default Circle;
|
packages/react-dom/src/events/__tests__/SyntheticMouseEvent-test.js | dilidili/react | /**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
let React;
let ReactDOM;
describe('SyntheticMouseEvent', () => {
let container;
beforeEach(() => {
React = require('react');
ReactDOM = require('react-dom');
// The container has to be attached for events to fire.
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
container = null;
});
it('should only use values from movementX/Y when event type is mousemove', () => {
const events = [];
const onMouseMove = event => {
events.push(event.movementX);
};
const onMouseDown = event => {
events.push(event.movementX);
};
const node = ReactDOM.render(
<div onMouseMove={onMouseMove} onMouseDown={onMouseDown} />,
container,
);
let event = new MouseEvent('mousemove', {
relatedTarget: null,
bubbles: true,
screenX: 2,
screenY: 2,
});
node.dispatchEvent(event);
event = new MouseEvent('mousemove', {
relatedTarget: null,
bubbles: true,
screenX: 8,
screenY: 8,
});
node.dispatchEvent(event);
// Now trigger a mousedown event to see if movementX has changed back to 0
event = new MouseEvent('mousedown', {
relatedTarget: null,
bubbles: true,
screenX: 25,
screenY: 65,
});
node.dispatchEvent(event);
expect(events.length).toBe(3);
expect(events[0]).toBe(0);
expect(events[1]).toBe(6);
expect(events[2]).toBe(0); // mousedown event should have movementX at 0
});
});
|
demo/src/App.js | dhunninghake/resuite | import React, { Component } from 'react';
import { render } from 'react-dom';
import {
Svg,
Arrow,
Button,
Text,
Image,
} from '../../src';
const style = {
fontFamily: 'monospace'
};
class App extends Component {
doSomething(e) {
e.preventDefault();
alert('cool!');
}
render() {
return (
<div style={style}>
<h1>{'RESUITE'}</h1>
<h3>{'<Svg>'}</h3>
<Svg width={100} height={100}>
<circle cx='50' cy='50' r='40' stroke='black' strokeWidth='4' fill='white' />
</Svg>
<h3>{'<Arrow />'}</h3>
<Arrow
width={30}
height={30}
direction={'right'}
strokeWidth={5}
rounded />
<h3>{'<Button />'}</h3>
<form onSubmit={this.doSomething}>
<Button
text={'I’m a button!'}
size={'small'}
rounding={90}
submit />
</form>
<h3>{'<Text>'}</h3>
<Text tag={'h1'} sm={'h6'} md={'h0'} lg={64}>
{'This is an h1'}
</Text>
<h3>{'<Image>'}</h3>
<Image
src='https://cdn.eso.org/images/large/eso1322a.jpg'
loadingIndicator={<h3>LOADING</h3>}
errorNotice={<h3>ERROR</h3>}
width={'25%'} />
</div>
);
}
}
render(
<App />,
document.getElementById('app')
);
|
src/components/Button.js | wdavidw/node-csv-docs | import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { css } from 'glamor'
const riple_styles = {
ripple: {
top: 0,
left: 0,
width: '100%',
height: '100%',
display: 'block',
position: 'absolute',
overflow: 'hidden',
zIndex: 0,
pointerEvents: 'none',
},
child: {
transform: 'scale(.0)',
opacity: 0.5,
display: 'block',
width: '100%',
height: '100%',
borderRadius: '50%',
backgroundColor: '#000',
},
active: {
transform: 'scale(1)',
transition: 'transform 150ms cubic-bezier(0.4, 0, 0.2, 1)',
},
}
class Ripple extends Component {
state = {
active: false,
}
start(event) {
this.child.current.classList.add(css(riple_styles.active).toString())
this.startTimer = setTimeout(() => {
if(this.child.current){ // node may be destructed on timeout
this.child.current.classList.remove(css(riple_styles.active).toString())
}
}, 200)
}
stop(event, callback) {
this.child.current.classList.remove(css(riple_styles.active).toString())
if (callback) callback()
}
constructor(props) {
super(props)
this.child = React.createRef()
this.start = this.start.bind(this)
this.stop = this.stop.bind(this)
}
render() {
const styles = riple_styles
return (
<span css={[styles.ripple, this.state.active && styles.active]}>
<span ref={this.child} css={styles.child} />
</span>
)
}
}
const styles = {
base: {
display: 'inline-flex',
position: 'relative',
alignItems: 'center',
verticalAlign: 'middle',
justifyContent: 'center',
flex: '0 0 auto',
padding: 0,
fontSize: '1.5rem',
textAlign: 'center',
textDecoration: 'none',
backgroundColor: 'transparent',
},
button: {
cursor: 'pointer',
':disabled': {
cursor: 'default',
},
border: 0,
margin: 0,
':focus': {
outline: 'none',
},
},
link: {
},
label: {
width: '100%',
display: 'flex',
alignItems: 'inherit',
justifyContent: 'inherit',
},
}
class Button extends Component {
handleBlur(event) {}
handleFocus(event) {}
handleKeyDown(event) {}
handleKeyUp(event) {
const key = event.key
if (key === 'space' || key === 'enter') {
event.persist()
const {ripple} = this.props
if(ripple){
this.ripple.current.stop(event, () => {
this.ripple.current.start(event)
})
}
}
}
handleMouseDown(event) {
event.persist()
const {ripple} = this.props
if(ripple){
this.ripple.current.stop(event, () => {
this.ripple.current.start(event)
})
}
}
handleMouseLeave(event) {}
handleMouseUp(event) {}
handleTouchMove(event) {}
handleTouchEnd(event) {}
handleTouchStart(event) {
event.persist()
const {ripple} = this.props
if(ripple){
this.ripple.current.stop(event, () => {
this.ripple.current.start(event)
})
}
}
constructor(props) {
super(props)
this.state = { isMobile: false }
this.ripple = React.createRef()
}
componentDidMount() {
if (window.innerWidth < this.props.breakpoint) {
this.setState({ isMobile: true })
}
}
render() {
const {
children,
disabled,
title,
tabIndex,
href,
role,
className,
ripple,
userStyles,
...props
} = this.props
userStyles.base = { ...styles.base, ...userStyles.base }
userStyles.button = { ...styles.button, ...userStyles.button }
userStyles.link = { ...styles.link, ...userStyles.link }
userStyles.label = { ...styles.label, ...userStyles.label }
const Component = href ? 'a' : 'button'
const componentProps = {
title: title,
tabIndex: tabIndex,
}
if (href) {
componentProps.href = href
componentProps.role = role
} else {
componentProps.type = 'button'
componentProps.disabled = disabled
}
return (
<Component
onBlur={this.handleBlur.bind(this)}
onFocus={this.handleFocus.bind(this)}
onKeyDown={this.handleKeyDown.bind(this)}
onKeyUp={this.handleKeyUp.bind(this)}
onMouseDown={this.handleMouseDown.bind(this)}
onMouseLeave={this.handleMouseLeave.bind(this)}
onMouseUp={this.handleMouseUp.bind(this)}
onTouchEnd={this.handleTouchEnd.bind(this)}
onTouchMove={this.handleTouchMove.bind(this)}
onTouchStart={this.handleTouchStart.bind(this)}
css={[userStyles.base, href ? userStyles.link : userStyles.button]}
className={className}
{...componentProps}
{...props}
>
<span css={userStyles.label}>{children}</span>
{ripple && <Ripple ref={this.ripple} />}
</Component>
)
}
}
Button.propTypes = {
// disabled: PropTypes.boolean,
role: PropTypes.string,
tabIndex: PropTypes.number,
}
Button.defaultProps = {
role: 'button',
tabIndex: 0,
userStyles: {},
// disabled: false,
}
export default Button
|
example/pages/[name].js | Wildhoney/ReactShadow | import React from 'react';
import Layout from '../components/Layout';
import * as api from '../api';
import * as utils from '../utils';
export default function City(props) {
return <Layout {...props} />;
}
City.getInitialProps = async ({ query }) => {
const place = api.places.find(
({ city }) => utils.toSlug(city) === query.name,
);
return place
? {
name: place.city,
cities: api.places.map(({ city }) => city),
weather: await api.fetch(`${place.city}, ${place.country}`),
}
: { name: query.name };
};
|
src/components/Navigation/Navigation.js | kevinchau321/TReactr | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import cx from 'classnames';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Navigation.css';
import Link from '../Link';
class Navigation extends React.Component {
render() {
return (
<div className={s.root} role="navigation">
<Link className={s.link} to="/about">About</Link>
<Link className={s.link} to="/contact">Contact</Link>
<a className={s.link} href="https://www.github.com/kevin-chau/TReactr">GitHub</a>
<span className={s.spacer}> | </span>
<Link className={s.link} to="/login">Log in</Link>
<span className={s.spacer}>or</span>
<Link className={cx(s.link, s.highlight)} to="/register">Sign up</Link>
</div>
);
}
}
export default withStyles(s)(Navigation);
|
src/components/hoc/OnKeyDownHOC.js | f0zze/rosemary-ui | import React from 'react';
import ReactDOM from 'react-dom';
import {KEY_DOWN} from '../../constant/events';
import {isFunction} from '../../util/utils';
export function enhanceWithKeyDown(ParentClass) {
class Enhance extends ParentClass {
static get displayName() {
return ParentClass.displayName || ParentClass.name;
}
constructor() {
super(...arguments);
this.handleKeyDown = this.handleKeyDown.bind(this);
}
componentDidMount() {
if (super.componentDidMount) {
super.componentDidMount(...arguments);
}
document.addEventListener(KEY_DOWN, this.handleKeyDown);
}
componentWillUnmount() {
if (super.componentWillUnmount) {
super.componentWillUnmount(...arguments);
}
document.removeEventListener(KEY_DOWN, this.handleKeyDown);
}
handleKeyDown({keyCode}) {
if (isFunction(super.handleKeyDown)) {
super.handleKeyDown(keyCode);
}
}
}
Enhance.propTypes = ParentClass.propTypes;
Enhance.defaultProps = ParentClass.defaultProps;
Enhance.childContextTypes = ParentClass.childContextTypes;
Enhance.contextTypes = ParentClass.contextTypes;
return Enhance;
}
|
src/components/issues.js | JakeGinnivan/Drone | import React from 'react'
import { connect } from 'react-redux'
import { getAllIssues } from 'services/api'
export default class Issues extends React.Component {
constructor(props) {
super(props)
}
componentWillMount() {
if (!this.props.issues) {
this.props.dispatch({type: 'LOADING_ISSUES'})
getAllIssues()
.then(issues => {
this.props.dispatch({type: 'ISSUES_LOADED', issues})
})
}
}
componentWillUnmount() {
this.props.dispatch({type: 'UNLOAD_ISSUES'})
}
render() {
if (this.props.issuesLoading)
return <div>Loading...</div>
let issues = (this.props.issues|| [])
return (
<div>
<p>{issues.length} in list</p>
<ul>
{issues.map(i => {
return (
<li key={`${i.repoId}+${i.issueNumber}`}>
{i.repoName} - <a href={i.issueUrl} target='_blank'>#{i.issueNumber}</a> ({i.issueType}) - {i.issueTitle}
{i.labels.map(l => <div key={l.name} style={{backgroundColor: '#'+l.color, display: 'inline', margin: '2px', padding: '2px'}}>{l.name}</div>)}
</li>
)
})}
</ul>
</div>
)
}
}
Issues.preloadStore = store => {
var state = store.getState()
var userId = state.drone.userId
if (!userId) return Promise.resolve([])
var promise = getAllIssues(userId)
return promise.then(issues => {
store.dispatch({type: 'ISSUES_LOADED', issues })
})
}
Issues.propTypes = {
issues: React.PropTypes.arrayOf(React.PropTypes.shape({
number: React.PropTypes.number,
title: React.PropTypes.string
}))
}
export default connect(s => ({
issues: s.drone.issues,
issuesLoading: s.drone.issuesLoading
}))(Issues)
|
docs/src/section.js | ricsv/react-leonardo-ui | import React from 'react';
const Section = (props) => (
<section>
<h2 id={props.title}>
<a href={`#${props.title}`}>{props.title}</a>
</h2>
{props.children}
</section>
);
export default Section;
|
app/components/Hypno/index.js | brainsandspace/ship | /**
*
* Hypno
*
*/
import React from 'react';
import styled from 'styled-components';
const Wrapper = styled.div`
overflow: hidden;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: center;
-ms-flex-pack: center;
// height: 100vh;
.circle {
position: absolute;
height: 20vmin;
width: 20vmin;
border-radius: 50%;
opacity: 1;
background: black;
}
#c1 {
-webkit-transform-origin: center 46%;
transform-origin: center 46%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #edebe9;
-webkit-animation: circleAn1 10s infinite linear;
animation: circleAn1 10s infinite linear;
}
@-webkit-keyframes circleAn1 {
50% {
background: #edede9;
}
to {
background: #edebe9;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn1 {
50% {
background: #edede9;
}
to {
background: #edebe9;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c2 {
-webkit-transform-origin: center 47%;
transform-origin: center 47%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #dcdcd4;
-webkit-animation: circleAn2 10s infinite linear;
animation: circleAn2 10s infinite linear;
}
@-webkit-keyframes circleAn2 {
50% {
background: #d8dcd4;
}
to {
background: #dcdcd4;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn2 {
50% {
background: #d8dcd4;
}
to {
background: #dcdcd4;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c3 {
-webkit-transform-origin: center 48%;
transform-origin: center 48%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #c4cabe;
-webkit-animation: circleAn3 10s infinite linear;
animation: circleAn3 10s infinite linear;
}
@-webkit-keyframes circleAn3 {
50% {
background: #becabe;
}
to {
background: #c4cabe;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn3 {
50% {
background: #becabe;
}
to {
background: #c4cabe;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c4 {
-webkit-transform-origin: center 49%;
transform-origin: center 49%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #a9b8a9;
-webkit-animation: circleAn4 10s infinite linear;
animation: circleAn4 10s infinite linear;
}
@-webkit-keyframes circleAn4 {
50% {
background: #a9b8b1;
}
to {
background: #a9b8a9;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn4 {
50% {
background: #a9b8b1;
}
to {
background: #a9b8a9;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c5 {
-webkit-transform-origin: center 50%;
transform-origin: center 50%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #93a79d;
-webkit-animation: circleAn5 10s infinite linear;
animation: circleAn5 10s infinite linear;
}
@-webkit-keyframes circleAn5 {
50% {
background: #93a7a7;
}
to {
background: #93a79d;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn5 {
50% {
background: #93a7a7;
}
to {
background: #93a79d;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c6 {
-webkit-transform-origin: center 51%;
transform-origin: center 51%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #7e9595;
-webkit-animation: circleAn6 10s infinite linear;
animation: circleAn6 10s infinite linear;
}
@-webkit-keyframes circleAn6 {
50% {
background: #7e8995;
}
to {
background: #7e9595;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn6 {
50% {
background: #7e8995;
}
to {
background: #7e9595;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c7 {
-webkit-transform-origin: center 52%;
transform-origin: center 52%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #6a7681;
-webkit-animation: circleAn7 10s infinite linear;
animation: circleAn7 10s infinite linear;
}
@-webkit-keyframes circleAn7 {
50% {
background: #6a6a81;
}
to {
background: #6a7681;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn7 {
50% {
background: #6a6a81;
}
to {
background: #6a7681;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c8 {
-webkit-transform-origin: center 53%;
transform-origin: center 53%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #58586c;
-webkit-animation: circleAn8 10s infinite linear;
animation: circleAn8 10s infinite linear;
}
@-webkit-keyframes circleAn8 {
50% {
background: #62586c;
}
to {
background: #58586c;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn8 {
50% {
background: #62586c;
}
to {
background: #58586c;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c9 {
-webkit-transform-origin: center 54%;
transform-origin: center 54%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #4e4756;
-webkit-animation: circleAn9 10s infinite linear;
animation: circleAn9 10s infinite linear;
}
@-webkit-keyframes circleAn9 {
50% {
background: #564756;
}
to {
background: #4e4756;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn9 {
50% {
background: #564756;
}
to {
background: #4e4756;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c10 {
-webkit-transform-origin: center 55%;
transform-origin: center 55%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #413541;
-webkit-animation: circleAn10 10s infinite linear;
animation: circleAn10 10s infinite linear;
}
@-webkit-keyframes circleAn10 {
50% {
background: #41353b;
}
to {
background: #413541;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn10 {
50% {
background: #41353b;
}
to {
background: #413541;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c11 {
-webkit-transform-origin: center 56%;
transform-origin: center 56%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #2b2327;
-webkit-animation: circleAn11 10s infinite linear;
animation: circleAn11 10s infinite linear;
}
@-webkit-keyframes circleAn11 {
50% {
background: #2b2323;
}
to {
background: #2b2327;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn11 {
50% {
background: #2b2323;
}
to {
background: #2b2327;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c12 {
-webkit-transform-origin: center 57%;
transform-origin: center 57%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: #161212;
-webkit-animation: circleAn12 10s infinite linear;
animation: circleAn12 10s infinite linear;
}
@-webkit-keyframes circleAn12 {
50% {
background: #161412;
}
to {
background: #161212;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn12 {
50% {
background: #161412;
}
to {
background: #161212;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
#c13 {
-webkit-transform-origin: center 58%;
transform-origin: center 58%;
-webkit-transform: scale(0.8) rotate(0deg);
transform: scale(0.8) rotate(0deg);
background: black;
-webkit-animation: circleAn13 10s infinite linear;
animation: circleAn13 10s infinite linear;
}
@-webkit-keyframes circleAn13 {
50% {
background: black;
}
to {
background: black;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
@keyframes circleAn13 {
50% {
background: black;
}
to {
background: black;
-webkit-transform: scale(0.8) rotate(360deg);
transform: scale(0.8) rotate(360deg);
}
}
`;
function Hypno() {
return (
<Wrapper>
<div className="circle" id="c1">
<div className="circle" id="c2">
<div className="circle" id="c3">
<div className="circle" id="c4">
<div className="circle" id="c5">
<div className="circle" id="c6">
<div className="circle" id="c7">
<div className="circle" id="c8">
<div className="circle" id="c9">
<div className="circle" id="c10">
<div className="circle" id="c11">
<div className="circle" id="c12">
<div className="circle" id="c13"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</Wrapper>
);
}
Hypno.propTypes = {
};
export default Hypno;
|
components/grid.js | wulkano/kap-website | import React from 'react'
import screenSizes from '../lib/screen-sizes'
export const Column = ({ children }) => (
<div className="column">
{children}
<style jsx>{`
.column:last-child {
width: 368px;
}
@media only screen and (max-width: ${screenSizes.laptop}) {
.column:last-child {
width: 40%;
}
}
@media only screen and (max-width: ${screenSizes.tablet}) {
.column,
.column:last-child {
width: 100%;
margin-top: 50px;
}
}
`}</style>
</div>
)
const Grid = ({ children, style }) => (
<div className="grid" style={style}>
{children}
<style jsx>{`
.grid {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: flex-start;
max-width: 1168px;
width: 100%;
margin-bottom: 128px;
margin-top: 64px;
margin-right: 32px;
margin-left: 32px;
}
@media only screen and (max-width: ${screenSizes.tablet}) {
.grid {
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 64px;
margin-top: 32px;
overflow: hidden;
margin-right: 16px;
margin-left: 16px;
}
}
`}</style>
</div>
)
export default Grid
|
test/ButtonSpec.js | JimiHFord/react-bootstrap | import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Button from '../src/Button';
describe('Button', function () {
it('Should output a button', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button>
Title
</Button>
);
assert.equal(React.findDOMNode(instance).nodeName, 'BUTTON');
});
it('Should have type=button by default', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button>
Title
</Button>
);
assert.equal(React.findDOMNode(instance).getAttribute('type'), 'button');
});
it('Should show the type if passed one', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button type='submit'>
Title
</Button>
);
assert.equal(React.findDOMNode(instance).getAttribute('type'), 'submit');
});
it('Should output an anchor if called with a href', function () {
let href = '/url';
let instance = ReactTestUtils.renderIntoDocument(
<Button href={href}>
Title
</Button>
);
assert.equal(React.findDOMNode(instance).nodeName, 'A');
assert.equal(React.findDOMNode(instance).getAttribute('href'), href);
});
it('Should output an anchor if called with a target', function () {
let target = '_blank';
let instance = ReactTestUtils.renderIntoDocument(
<Button target={target}>
Title
</Button>
);
assert.equal(React.findDOMNode(instance).nodeName, 'A');
assert.equal(React.findDOMNode(instance).getAttribute('target'), target);
});
it('Should call onClick callback', function (done) {
let doneOp = function () {
done();
};
let instance = ReactTestUtils.renderIntoDocument(
<Button onClick={doneOp}>
Title
</Button>
);
ReactTestUtils.Simulate.click(React.findDOMNode(instance));
});
it('Should be disabled', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button disabled>
Title
</Button>
);
assert.ok(React.findDOMNode(instance).disabled);
});
it('Should be disabled link', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button disabled href='#'>
Title
</Button>
);
assert.ok(React.findDOMNode(instance).className.match(/\bdisabled\b/));
});
it('Should have block class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button block>
Title
</Button>
);
assert.ok(React.findDOMNode(instance).className.match(/\bbtn-block\b/));
});
it('Should apply bsStyle class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button bsStyle='danger'>
Title
</Button>
);
assert.ok(React.findDOMNode(instance).className.match(/\bbtn-danger\b/));
});
it('Should honour additional classes passed in, adding not overriding', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button className="bob" bsStyle="danger">
Title
</Button>
);
assert.ok(React.findDOMNode(instance).className.match(/\bbob\b/));
assert.ok(React.findDOMNode(instance).className.match(/\bbtn-danger\b/));
});
it('Should default to bsStyle="default"', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button bsStyle='default'>
Title
</Button>
);
assert.equal(instance.props.bsStyle, 'default');
});
it('Should be active', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button active>
Title
</Button>
);
assert.ok(React.findDOMNode(instance).className.match(/\bactive\b/));
});
it('Should render an anchor in a list item when in a nav', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button navItem active>
Title
</Button>
);
let li = React.findDOMNode(instance);
let anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a');
assert.equal(li.nodeName, 'LI');
assert.ok(li.className.match(/\bactive\b/));
assert.ok(anchor.props.href, '#');
});
it('Should render an anchor when in a navDropdown', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button navDropdown>
Title
</Button>
);
let anchor = React.findDOMNode(instance);
assert.equal(anchor.nodeName, 'A');
assert.ok(anchor.getAttribute('href'), '#');
});
});
|
app/components/stations/StationValuesChart.js | sheldhur/Vector | // @flow
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { ProgressAlert, NoDataAlert } from '../widgets/ChartAlert';
import LineChart from '../chart/LineChart';
import TitleCurrentTime from '../main/TitleCurrentTime';
import * as mainActions from '../../actions/main';
import * as app from '../../constants/app';
const COMP_XYZ = 'XYZ';
const COMP_HDZ = 'HDZ';
const VIEW_RAW = 'RAW';
const VIEW_DELTA = 'VIEW_DELTA';
const VIEW_DELTA_SIMPLE = 'VIEW_DELTA_SIMPLE';
class StationValuesChart extends Component {
state = {
comp: COMP_XYZ,
view: VIEW_RAW,
};
handlerContextMenu = (e) => {
if (!e.ctrlKey) {
e.preventDefault();
}
};
prepareValuesForChart = (values) => {
const colorGroup = app.DATA_SET_COLOR;
if (!values) {
return [];
}
let data = {};
const compNames = this.state.comp.split('');
compNames.forEach((compName) => {
data[compName] = [];
});
values.forEach((value) => {
compNames.forEach((compName) => {
const field = `comp${compName}`;
data[compName].push({
x: value.time,
y: Math.abs(value[field]) < 99999 ? value[field] : null
});
});
});
data = compNames.map((compName, compKey) => ({
si: 'nT',
lines: [
{
name: compName,
si: 'nT',
format: '%(name)s: %(y).2f %(si)s',
style: {
stroke: colorGroup[compKey % colorGroup.length],
strokeWidth: 1
},
points: data[compName]
}
],
}));
return data;
};
render = () => {
const {
isLoading, isError, data, progress
} = this.props;
let container = null;
if (isLoading || isError) {
container = (<ProgressAlert
text={progress.title}
percent={progress.value}
error={isError}
onContextMenu={this.handlerContextMenu}
/>);
}
if (!container) {
const chartLines = this.prepareValuesForChart(data);
container = (
<div style={{ width: this.props.width, height: this.props.height }} onContextMenu={this.handlerContextMenu}>
<LineChart
width={this.props.width}
height={this.props.height}
data={chartLines}
tooltipDelay={100}
antiAliasing={this.props.antiAliasing}
emptyMessage={<NoDataAlert onContextMenu={this.handlerContextMenu} />}
>
<TitleCurrentTime />
</LineChart>
</div>
);
}
return container;
};
}
StationValuesChart.propTypes = {
width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
height: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
};
StationValuesChart.defaultProps = {
width: '100%',
height: '100%',
};
function mapStateToProps(state) {
return {
isLoading: state.station.stationView.isLoading,
isError: state.station.stationView.isError,
progress: state.station.stationView.progress,
data: state.station.stationView.values,
antiAliasing: state.main.settings.appAntiAliasing,
};
}
function mapDispatchToProps(dispatch) {
return {
mainActions: bindActionCreators(mainActions, dispatch),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(StationValuesChart);
|
client/trello/src/app/routes/home/routes/boardView/BoardViewContainer.js | Madmous/Trello-Clone | import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import BoardView from './BoardView';
import {
boardViewActionCreators,
cardActionCreators
} from './modules/index';
const mapStateToProps = state => {
const {
isFocusOnUpdateBoardNameForm,
isUpdateBoardNameOpen,
isFocusOnCreateCardForm,
isCreateCardFormOpen
} = state.boardView;
const {
isFocusOnCreateCardItemForm,
isCreateCardItemFormOpen
} = state.card;
return {
isFocusOnUpdateBoardNameForm,
isUpdateBoardNameOpen,
isFocusOnCreateCardForm,
isCreateCardFormOpen,
isFocusOnCreateCardItemForm,
isCreateCardItemFormOpen
};
}
const mapDispatchToProps = dispatch => {
return {
boardViewActions: bindActionCreators(boardViewActionCreators, dispatch),
cardActions: bindActionCreators(cardActionCreators, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(BoardView);
|
packages/base-shell/src/providers/Auth/Context.js | TarikHuber/react-most-wanted | import React from 'react'
export const Context = React.createContext(null)
export default Context
|
docs/dist/main.14afeb337ce7f0478cd9.js | leo60228/HouseRuler | !function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var n=window.webpackJsonp;window.webpackJsonp=function(t,r,i){for(var a,l,s=0,c=[];s<t.length;s++)l=t[s],o[l]&&c.push(o[l][0]),o[l]=0;for(a in r)Object.prototype.hasOwnProperty.call(r,a)&&(e[a]=r[a]);for(n&&n(t,r,i);c.length;)c.shift()()};var r={},o={1:0};t.e=function(e){function n(){i.onerror=i.onload=null,clearTimeout(a);var t=o[e];0!==t&&(t&&t[1](new Error("Loading chunk "+e+" failed.")),o[e]=void 0)}if(0===o[e])return Promise.resolve();if(o[e])return o[e][2];var r=document.getElementsByTagName("head")[0],i=document.createElement("script");i.type="text/javascript",i.charset="utf-8",i.async=!0,i.timeout=12e4,t.nc&&i.setAttribute("nonce",t.nc),i.src=t.p+""+e+"."+{0:"fa92e56754ca1bc50c6d"}[e]+".js";var a=setTimeout(n,12e4);i.onerror=i.onload=n;var l=new Promise(function(t,n){o[e]=[t,n]});return o[e][2]=l,r.appendChild(i),l},t.m=e,t.c=r,t.i=function(e){return e},t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="/dist/",t.oe=function(e){throw console.error(e),e},t(t.s=712)}([function(e,t,n){var r=n(3),o=n(40),i=n(21),a=n(22),l=n(41),s="prototype",c=function(e,t,n){var u,d,p,f,m=e&c.F,h=e&c.G,g=e&c.S,b=e&c.P,y=e&c.B,v=h?r:g?r[t]||(r[t]={}):(r[t]||{})[s],_=h?o:o[t]||(o[t]={}),x=_[s]||(_[s]={});h&&(n=t);for(u in n)d=!m&&v&&void 0!==v[u],p=(d?v:n)[u],f=y&&d?l(p,r):b&&"function"==typeof p?l(Function.call,p):p,v&&a(v,u,p,e&c.U),_[u]!=p&&i(_,u,f),b&&x[u]!=p&&(x[u]=p)};r.core=o,c.F=1,c.G=2,c.S=4,c.P=8,c.B=16,c.W=32,c.U=64,c.R=128,e.exports=c},function(e,t,n){"use strict";function r(e,t,n,r,i,a,l,s){if(o(t),!e){var c;if(void 0===t)c=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var u=[n,r,i,a,l,s],d=0;c=new Error(t.replace(/%s/g,function(){return u[d++]})),c.name="Invariant Violation"}throw c.framesToPop=1,c}}var o=function(e){};e.exports=r},function(e,t,n){var r=n(7);e.exports=function(e){if(!r(e))throw TypeError(e+" is not an object!");return e}},function(e,t){var n=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(e,t,n){"use strict";var r=n(28),o=r;e.exports=o},function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t,n){"use strict";function r(e){for(var t=arguments.length-1,n="Minified React error #"+e+"; visit http://facebook.github.io/react/docs/error-decoder.html?invariant="+e,r=0;r<t;r++)n+="&args[]="+encodeURIComponent(arguments[r+1]);n+=" for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";var o=new Error(n);throw o.name="Invariant Violation",o.framesToPop=1,o}e.exports=r},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t,n){var r=n(118)("wks"),o=n(68),i=n(3).Symbol,a="function"==typeof i;(e.exports=function(e){return r[e]||(r[e]=a&&i[e]||(a?i:o)("Symbol."+e))}).store=r},function(e,t,n){"use strict";function r(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function o(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach(function(e){r[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(e){return!1}}/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
var i=Object.getOwnPropertySymbols,a=Object.prototype.hasOwnProperty,l=Object.prototype.propertyIsEnumerable;e.exports=o()?Object.assign:function(e,t){for(var n,o,s=r(e),c=1;c<arguments.length;c++){n=Object(arguments[c]);for(var u in n)a.call(n,u)&&(s[u]=n[u]);if(i){o=i(n);for(var d=0;d<o.length;d++)l.call(n,o[d])&&(s[o[d]]=n[o[d]])}}return s}},function(e,t,n){"use strict";e.exports=n(71)},function(e,t,n){e.exports=!n(5)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,t,n){var r=n(2),o=n(228),i=n(36),a=Object.defineProperty;t.f=n(11)?Object.defineProperty:function(e,t,n){if(r(e),t=i(t,!0),r(n),o)try{return a(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},function(e,t,n){"use strict";function r(e,t){return 1===e.nodeType&&e.getAttribute(m)===String(t)||8===e.nodeType&&e.nodeValue===" react-text: "+t+" "||8===e.nodeType&&e.nodeValue===" react-empty: "+t+" "}function o(e){for(var t;t=e._renderedComponent;)e=t;return e}function i(e,t){var n=o(e);n._hostNode=t,t[g]=n}function a(e){var t=e._hostNode;t&&(delete t[g],e._hostNode=null)}function l(e,t){if(!(e._flags&h.hasCachedChildNodes)){var n=e._renderedChildren,a=t.firstChild;e:for(var l in n)if(n.hasOwnProperty(l)){var s=n[l],c=o(s)._domID;if(0!==c){for(;null!==a;a=a.nextSibling)if(r(a,c)){i(s,a);continue e}d("32",c)}}e._flags|=h.hasCachedChildNodes}}function s(e){if(e[g])return e[g];for(var t=[];!e[g];){if(t.push(e),!e.parentNode)return null;e=e.parentNode}for(var n,r;e&&(r=e[g]);e=t.pop())n=r,t.length&&l(r,e);return n}function c(e){var t=s(e);return null!=t&&t._hostNode===e?t:null}function u(e){if(void 0===e._hostNode&&d("33"),e._hostNode)return e._hostNode;for(var t=[];!e._hostNode;)t.push(e),e._hostParent||d("34"),e=e._hostParent;for(;t.length;e=t.pop())l(e,e._hostNode);return e._hostNode}var d=n(6),p=n(84),f=n(258),m=(n(1),p.ID_ATTRIBUTE_NAME),h=f,g="__reactInternalInstance$"+Math.random().toString(36).slice(2),b={getClosestInstanceFromNode:s,getInstanceFromNode:c,getNodeFromInstance:u,precacheChildNodes:l,precacheNode:i,uncacheNode:a};e.exports=b},function(e,t){var n=e.exports={version:"2.4.0"};"number"==typeof __e&&(__e=n)},function(e,t,n){var r=n(49),o=Math.min;e.exports=function(e){return e>0?o(r(e),9007199254740991):0}},function(e,t,n){var r=n(31);e.exports=function(e){return Object(r(e))}},function(e,t,n){var r=n(138)("wks"),o=n(107),i=n(25).Symbol,a="function"==typeof i;(e.exports=function(e){return r[e]||(r[e]=a&&i[e]||(a?i:o)("Symbol."+e))}).store=r},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t,n){"use strict";var r=!("undefined"==typeof window||!window.document||!window.document.createElement),o={canUseDOM:r,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:r&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:r&&!!window.screen,isInWorker:!r};e.exports=o},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},function(e,t,n){var r=n(12),o=n(48);e.exports=n(11)?function(e,t,n){return r.f(e,t,o(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t,n){var r=n(3),o=n(21),i=n(18),a=n(68)("src"),l="toString",s=Function[l],c=(""+s).split(l);n(40).inspectSource=function(e){return s.call(e)},(e.exports=function(e,t,n,l){var s="function"==typeof n;s&&(i(n,"name")||o(n,"name",t)),e[t]!==n&&(s&&(i(n,a)||o(n,a,e[t]?""+e[t]:c.join(String(t)))),e===r?e[t]=n:l?e[t]?e[t]=n:o(e,t,n):(delete e[t],o(e,t,n)))})(Function.prototype,l,function(){return"function"==typeof this&&this[a]||s.call(this)})},function(e,t,n){var r=n(0),o=n(5),i=n(31),a=/"/g,l=function(e,t,n,r){var o=String(i(e)),l="<"+t;return""!==n&&(l+=" "+n+'="'+String(r).replace(a,""")+'"'),l+">"+o+"</"+t+">"};e.exports=function(e,t){var n={};n[e]=t(l),r(r.P+r.F*o(function(){var t=""[e]('"');return t!==t.toLowerCase()||t.split('"').length>3}),"String",n)}},function(e,t,n){var r=n(94),o=n(31);e.exports=function(e){return r(o(e))}},function(e,t){var n=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(e,t,n){var r=n(95),o=n(48),i=n(24),a=n(36),l=n(18),s=n(228),c=Object.getOwnPropertyDescriptor;t.f=n(11)?c:function(e,t){if(e=i(e),t=a(t,!0),s)try{return c(e,t)}catch(e){}if(l(e,t))return o(!r.f.call(e,t),e[t])}},function(e,t,n){var r=n(18),o=n(16),i=n(160)("IE_PROTO"),a=Object.prototype;e.exports=Object.getPrototypeOf||function(e){return e=o(e),r(e,i)?e[i]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?a:null}},function(e,t,n){"use strict";function r(e){return function(){return e}}var o=function(){};o.thatReturns=r,o.thatReturnsFalse=r(!1),o.thatReturnsTrue=r(!0),o.thatReturnsNull=r(null),o.thatReturnsThis=function(){return this},o.thatReturnsArgument=function(e){return e},e.exports=o},function(e,t,n){"use strict";var r=null;e.exports={debugTool:r}},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},function(e,t,n){var r=n(5);e.exports=function(e,t){return!!e&&r(function(){t?e.call(null,function(){},1):e.call(null)})}},function(e,t,n){"use strict";function r(){S.ReactReconcileTransaction&&x||u("123")}function o(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=p.getPooled(),this.reconcileTransaction=S.ReactReconcileTransaction.getPooled(!0)}function i(e,t,n,o,i,a){return r(),x.batchedUpdates(e,t,n,o,i,a)}function a(e,t){return e._mountOrder-t._mountOrder}function l(e){var t=e.dirtyComponentsLength;t!==b.length&&u("124",t,b.length),b.sort(a),y++;for(var n=0;n<t;n++){var r=b[n],o=r._pendingCallbacks;r._pendingCallbacks=null;var i;if(m.logTopLevelRenders){var l=r;r._currentElement.type.isReactTopLevelWrapper&&(l=r._renderedComponent),i="React update: "+l.getName(),console.time(i)}if(h.performUpdateIfNecessary(r,e.reconcileTransaction,y),i&&console.timeEnd(i),o)for(var s=0;s<o.length;s++)e.callbackQueue.enqueue(o[s],r.getPublicInstance())}}function s(e){if(r(),!x.isBatchingUpdates)return void x.batchedUpdates(s,e);b.push(e),null==e._updateBatchNumber&&(e._updateBatchNumber=y+1)}function c(e,t){x.isBatchingUpdates||u("125"),v.enqueue(e,t),_=!0}var u=n(6),d=n(9),p=n(256),f=n(69),m=n(264),h=n(70),g=n(123),b=(n(1),[]),y=0,v=p.getPooled(),_=!1,x=null,w={initialize:function(){this.dirtyComponentsLength=b.length},close:function(){this.dirtyComponentsLength!==b.length?(b.splice(0,this.dirtyComponentsLength),E()):b.length=0}},C={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},k=[w,C];d(o.prototype,g,{getTransactionWrappers:function(){return k},destructor:function(){this.dirtyComponentsLength=null,p.release(this.callbackQueue),this.callbackQueue=null,S.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,n){return g.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,n)}}),f.addPoolingTo(o);var E=function(){for(;b.length||_;){if(b.length){var e=o.getPooled();e.perform(l,null,e),o.release(e)}if(_){_=!1;var t=v;v=p.getPooled(),t.notifyAll(),p.release(t)}}},A={injectReconcileTransaction:function(e){e||u("126"),S.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){e||u("127"),"function"!=typeof e.batchedUpdates&&u("128"),"boolean"!=typeof e.isBatchingUpdates&&u("129"),x=e}},S={ReactReconcileTransaction:null,batchedUpdates:i,enqueueUpdate:s,flushBatchedUpdates:E,injection:A,asap:c};e.exports=S},function(e,t,n){var r=n(41),o=n(94),i=n(16),a=n(15),l=n(371);e.exports=function(e,t){var n=1==e,s=2==e,c=3==e,u=4==e,d=6==e,p=5==e||d,f=t||l;return function(t,l,m){for(var h,g,b=i(t),y=o(b),v=r(l,m,3),_=a(y.length),x=0,w=n?f(t,_):s?f(t,0):void 0;_>x;x++)if((p||x in y)&&(h=y[x],g=v(h,x,b),e))if(n)w[x]=g;else if(g)switch(e){case 3:return!0;case 5:return h;case 6:return x;case 2:w.push(h)}else if(u)return!1;return d?-1:c||u?u:w}}},function(e,t,n){var r=n(0),o=n(40),i=n(5);e.exports=function(e,t){var n=(o.Object||{})[e]||Object[e],a={};a[e]=t(n),r(r.S+r.F*i(function(){n(1)}),"Object",a)}},function(e,t,n){var r=n(7);e.exports=function(e,t){if(!r(e))return e;var n,o;if(t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;if("function"==typeof(n=e.valueOf)&&!r(o=n.call(e)))return o;if(!t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;throw TypeError("Can't convert object to primitive value")}},function(e,t,n){var r=n(74);e.exports=function(e){if(!r(e))throw TypeError(e+" is not an object!");return e}},function(e,t,n){var r=n(25),o=n(14),i=n(72),a=n(58),l="prototype",s=function(e,t,n){var c,u,d,p=e&s.F,f=e&s.G,m=e&s.S,h=e&s.P,g=e&s.B,b=e&s.W,y=f?o:o[t]||(o[t]={}),v=y[l],_=f?r:m?r[t]:(r[t]||{})[l];f&&(n=t);for(c in n)(u=!p&&_&&void 0!==_[c])&&c in y||(d=u?_[c]:n[c],y[c]=f&&"function"!=typeof _[c]?n[c]:g&&u?i(d,r):b&&_[c]==d?function(e){var t=function(t,n,r){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,n)}return new e(t,n,r)}return e.apply(this,arguments)};return t[l]=e[l],t}(d):h&&"function"==typeof d?i(Function.call,d):d,h&&((y.virtual||(y.virtual={}))[c]=d,e&s.R&&v&&!v[c]&&a(v,c,d)))};s.F=1,s.G=2,s.S=4,s.P=8,s.B=16,s.W=32,s.U=64,s.R=128,e.exports=s},function(e,t,n){var r=n(37),o=n(206),i=n(141),a=Object.defineProperty;t.f=n(46)?Object.defineProperty:function(e,t,n){if(r(e),t=i(t,!0),r(n),o)try{return a(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},function(e,t){var n=e.exports={version:"2.4.0"};"number"==typeof __e&&(__e=n)},function(e,t,n){var r=n(20);e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,o){return e.call(t,n,r,o)}}return function(){return e.apply(t,arguments)}}},function(e,t,n){var r=n(244),o=n(0),i=n(118)("metadata"),a=i.store||(i.store=new(n(247))),l=function(e,t,n){var o=a.get(e);if(!o){if(!n)return;a.set(e,o=new r)}var i=o.get(t);if(!i){if(!n)return;o.set(t,i=new r)}return i},s=function(e,t,n){var r=l(t,n,!1);return void 0!==r&&r.has(e)},c=function(e,t,n){var r=l(t,n,!1);return void 0===r?void 0:r.get(e)},u=function(e,t,n,r){l(n,r,!0).set(e,t)},d=function(e,t){var n=l(e,t,!1),r=[];return n&&n.forEach(function(e,t){r.push(t)}),r},p=function(e){return void 0===e||"symbol"==typeof e?e:String(e)},f=function(e){o(o.S,"Reflect",e)};e.exports={store:a,map:l,has:s,get:c,set:u,keys:d,key:p,exp:f}},function(e,t,n){"use strict";if(n(11)){var r=n(61),o=n(3),i=n(5),a=n(0),l=n(119),s=n(167),c=n(41),u=n(60),d=n(48),p=n(21),f=n(65),m=n(49),h=n(15),g=n(67),b=n(36),y=n(18),v=n(241),_=n(93),x=n(7),w=n(16),C=n(152),k=n(62),E=n(27),A=n(63).f,S=n(169),I=n(68),T=n(8),P=n(34),O=n(109),M=n(161),R=n(170),N=n(79),L=n(115),D=n(66),j=n(145),F=n(221),z=n(12),U=n(26),B=z.f,H=U.f,W=o.RangeError,V=o.TypeError,G=o.Uint8Array,Y="ArrayBuffer",q="Shared"+Y,K="BYTES_PER_ELEMENT",Z="prototype",X=Array[Z],Q=s.ArrayBuffer,J=s.DataView,$=P(0),ee=P(2),te=P(3),ne=P(4),re=P(5),oe=P(6),ie=O(!0),ae=O(!1),le=R.values,se=R.keys,ce=R.entries,ue=X.lastIndexOf,de=X.reduce,pe=X.reduceRight,fe=X.join,me=X.sort,he=X.slice,ge=X.toString,be=X.toLocaleString,ye=T("iterator"),ve=T("toStringTag"),_e=I("typed_constructor"),xe=I("def_constructor"),we=l.CONSTR,Ce=l.TYPED,ke=l.VIEW,Ee="Wrong length!",Ae=P(1,function(e,t){return Me(M(e,e[xe]),t)}),Se=i(function(){return 1===new G(new Uint16Array([1]).buffer)[0]}),Ie=!!G&&!!G[Z].set&&i(function(){new G(1).set({})}),Te=function(e,t){if(void 0===e)throw V(Ee);var n=+e,r=h(e);if(t&&!v(n,r))throw W(Ee);return r},Pe=function(e,t){var n=m(e);if(n<0||n%t)throw W("Wrong offset!");return n},Oe=function(e){if(x(e)&&Ce in e)return e;throw V(e+" is not a typed array!")},Me=function(e,t){if(!(x(e)&&_e in e))throw V("It is not a typed array constructor!");return new e(t)},Re=function(e,t){return Ne(M(e,e[xe]),t)},Ne=function(e,t){for(var n=0,r=t.length,o=Me(e,r);r>n;)o[n]=t[n++];return o},Le=function(e,t,n){B(e,t,{get:function(){return this._d[n]}})},De=function(e){var t,n,r,o,i,a,l=w(e),s=arguments.length,u=s>1?arguments[1]:void 0,d=void 0!==u,p=S(l);if(void 0!=p&&!C(p)){for(a=p.call(l),r=[],t=0;!(i=a.next()).done;t++)r.push(i.value);l=r}for(d&&s>2&&(u=c(u,arguments[2],2)),t=0,n=h(l.length),o=Me(this,n);n>t;t++)o[t]=d?u(l[t],t):l[t];return o},je=function(){for(var e=0,t=arguments.length,n=Me(this,t);t>e;)n[e]=arguments[e++];return n},Fe=!!G&&i(function(){be.call(new G(1))}),ze=function(){return be.apply(Fe?he.call(Oe(this)):Oe(this),arguments)},Ue={copyWithin:function(e,t){return F.call(Oe(this),e,t,arguments.length>2?arguments[2]:void 0)},every:function(e){return ne(Oe(this),e,arguments.length>1?arguments[1]:void 0)},fill:function(e){return j.apply(Oe(this),arguments)},filter:function(e){return Re(this,ee(Oe(this),e,arguments.length>1?arguments[1]:void 0))},find:function(e){return re(Oe(this),e,arguments.length>1?arguments[1]:void 0)},findIndex:function(e){return oe(Oe(this),e,arguments.length>1?arguments[1]:void 0)},forEach:function(e){$(Oe(this),e,arguments.length>1?arguments[1]:void 0)},indexOf:function(e){return ae(Oe(this),e,arguments.length>1?arguments[1]:void 0)},includes:function(e){return ie(Oe(this),e,arguments.length>1?arguments[1]:void 0)},join:function(e){return fe.apply(Oe(this),arguments)},lastIndexOf:function(e){return ue.apply(Oe(this),arguments)},map:function(e){return Ae(Oe(this),e,arguments.length>1?arguments[1]:void 0)},reduce:function(e){return de.apply(Oe(this),arguments)},reduceRight:function(e){return pe.apply(Oe(this),arguments)},reverse:function(){for(var e,t=this,n=Oe(t).length,r=Math.floor(n/2),o=0;o<r;)e=t[o],t[o++]=t[--n],t[n]=e;return t},some:function(e){return te(Oe(this),e,arguments.length>1?arguments[1]:void 0)},sort:function(e){return me.call(Oe(this),e)},subarray:function(e,t){var n=Oe(this),r=n.length,o=g(e,r);return new(M(n,n[xe]))(n.buffer,n.byteOffset+o*n.BYTES_PER_ELEMENT,h((void 0===t?r:g(t,r))-o))}},Be=function(e,t){return Re(this,he.call(Oe(this),e,t))},He=function(e){Oe(this);var t=Pe(arguments[1],1),n=this.length,r=w(e),o=h(r.length),i=0;if(o+t>n)throw W(Ee);for(;i<o;)this[t+i]=r[i++]},We={entries:function(){return ce.call(Oe(this))},keys:function(){return se.call(Oe(this))},values:function(){return le.call(Oe(this))}},Ve=function(e,t){return x(e)&&e[Ce]&&"symbol"!=typeof t&&t in e&&String(+t)==String(t)},Ge=function(e,t){return Ve(e,t=b(t,!0))?d(2,e[t]):H(e,t)},Ye=function(e,t,n){return!(Ve(e,t=b(t,!0))&&x(n)&&y(n,"value"))||y(n,"get")||y(n,"set")||n.configurable||y(n,"writable")&&!n.writable||y(n,"enumerable")&&!n.enumerable?B(e,t,n):(e[t]=n.value,e)};we||(U.f=Ge,z.f=Ye),a(a.S+a.F*!we,"Object",{getOwnPropertyDescriptor:Ge,defineProperty:Ye}),i(function(){ge.call({})})&&(ge=be=function(){return fe.call(this)});var qe=f({},Ue);f(qe,We),p(qe,ye,We.values),f(qe,{slice:Be,set:He,constructor:function(){},toString:ge,toLocaleString:ze}),Le(qe,"buffer","b"),Le(qe,"byteOffset","o"),Le(qe,"byteLength","l"),Le(qe,"length","e"),B(qe,ve,{get:function(){return this[Ce]}}),e.exports=function(e,t,n,s){s=!!s;var c=e+(s?"Clamped":"")+"Array",d="Uint8Array"!=c,f="get"+e,m="set"+e,g=o[c],b=g||{},y=g&&E(g),v=!g||!l.ABV,w={},C=g&&g[Z],S=function(e,n){var r=e._d;return r.v[f](n*t+r.o,Se)},I=function(e,n,r){var o=e._d;s&&(r=(r=Math.round(r))<0?0:r>255?255:255&r),o.v[m](n*t+o.o,r,Se)},T=function(e,t){B(e,t,{get:function(){return S(this,t)},set:function(e){return I(this,t,e)},enumerable:!0})};v?(g=n(function(e,n,r,o){u(e,g,c,"_d");var i,a,l,s,d=0,f=0;if(x(n)){if(!(n instanceof Q||(s=_(n))==Y||s==q))return Ce in n?Ne(g,n):De.call(g,n);i=n,f=Pe(r,t);var m=n.byteLength;if(void 0===o){if(m%t)throw W(Ee);if((a=m-f)<0)throw W(Ee)}else if((a=h(o)*t)+f>m)throw W(Ee);l=a/t}else l=Te(n,!0),a=l*t,i=new Q(a);for(p(e,"_d",{b:i,o:f,l:a,e:l,v:new J(i)});d<l;)T(e,d++)}),C=g[Z]=k(qe),p(C,"constructor",g)):L(function(e){new g(null),new g(e)},!0)||(g=n(function(e,n,r,o){u(e,g,c);var i;return x(n)?n instanceof Q||(i=_(n))==Y||i==q?void 0!==o?new b(n,Pe(r,t),o):void 0!==r?new b(n,Pe(r,t)):new b(n):Ce in n?Ne(g,n):De.call(g,n):new b(Te(n,d))}),$(y!==Function.prototype?A(b).concat(A(y)):A(b),function(e){e in g||p(g,e,b[e])}),g[Z]=C,r||(C.constructor=g));var P=C[ye],O=!!P&&("values"==P.name||void 0==P.name),M=We.values;p(g,_e,!0),p(C,Ce,c),p(C,ke,!0),p(C,xe,g),(s?new g(1)[ve]==c:ve in C)||B(C,ve,{get:function(){return c}}),w[c]=g,a(a.G+a.W+a.F*(g!=b),w),a(a.S,c,{BYTES_PER_ELEMENT:t,from:De,of:je}),K in C||p(C,K,t),a(a.P,c,Ue),D(c),a(a.P+a.F*Ie,c,{set:He}),a(a.P+a.F*!O,c,We),a(a.P+a.F*(C.toString!=ge),c,{toString:ge}),a(a.P+a.F*i(function(){new g(1).slice()}),c,{slice:Be}),a(a.P+a.F*(i(function(){return[1,2].toLocaleString()!=new g([1,2]).toLocaleString()})||!i(function(){C.toLocaleString.call([1,2])})),c,{toLocaleString:ze}),N[c]=O?P:M,r||O||p(C,ye,M)}}else e.exports=function(){}},function(e,t,n){"use strict";function r(e,t,n,r){this.dispatchConfig=e,this._targetInst=t,this.nativeEvent=n;var o=this.constructor.Interface;for(var i in o)if(o.hasOwnProperty(i)){var l=o[i];l?this[i]=l(n):"target"===i?this.target=r:this[i]=n[i]}var s=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;return this.isDefaultPrevented=s?a.thatReturnsTrue:a.thatReturnsFalse,this.isPropagationStopped=a.thatReturnsFalse,this}var o=n(9),i=n(69),a=n(28),l=(n(4),["dispatchConfig","_targetInst","nativeEvent","isDefaultPrevented","isPropagationStopped","_dispatchListeners","_dispatchInstances"]),s={type:null,target:null,currentTarget:a.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};o(r.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():"unknown"!=typeof e.returnValue&&(e.returnValue=!1),this.isDefaultPrevented=a.thatReturnsTrue)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():"unknown"!=typeof e.cancelBubble&&(e.cancelBubble=!0),this.isPropagationStopped=a.thatReturnsTrue)},persist:function(){this.isPersistent=a.thatReturnsTrue},isPersistent:a.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;for(var n=0;n<l.length;n++)this[l[n]]=null}}),r.Interface=s,r.augmentClass=function(e,t){var n=this,r=function(){};r.prototype=n.prototype;var a=new r;o(a,e.prototype),e.prototype=a,e.prototype.constructor=e,e.Interface=o({},n.Interface,t),e.augmentClass=n.augmentClass,i.addPoolingTo(e,i.fourArgumentPooler)},i.addPoolingTo(r,i.fourArgumentPooler),e.exports=r},function(e,t,n){"use strict";var r={current:null};e.exports=r},function(e,t,n){e.exports=!n(73)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,t,n){var r=n(68)("meta"),o=n(7),i=n(18),a=n(12).f,l=0,s=Object.isExtensible||function(){return!0},c=!n(5)(function(){return s(Object.preventExtensions({}))}),u=function(e){a(e,r,{value:{i:"O"+ ++l,w:{}}})},d=function(e,t){if(!o(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!i(e,r)){if(!s(e))return"F";if(!t)return"E";u(e)}return e[r].i},p=function(e,t){if(!i(e,r)){if(!s(e))return!0;if(!t)return!1;u(e)}return e[r].w},f=function(e){return c&&m.NEED&&s(e)&&!i(e,r)&&u(e),e},m=e.exports={KEY:r,NEED:!1,fastKey:d,getWeak:p,onFreeze:f}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e)}},function(e,t,n){e.exports={default:n(328),__esModule:!0}},function(e,t,n){"use strict";t.__esModule=!0,t.default=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(202),i=r(o);t.default=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),(0,i.default)(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}()},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(312),i=r(o),a=n(201),l=r(a),s=n(129),c=r(s);t.default=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+(void 0===t?"undefined":(0,c.default)(t)));e.prototype=(0,l.default)(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(i.default?(0,i.default)(e,t):e.__proto__=t)}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(129),i=r(o);t.default=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==(void 0===t?"undefined":(0,i.default)(t))&&"function"!=typeof t?e:t}},function(e,t,n){(function(t){function n(e,t){var n=e[1]||"",o=e[3];if(!o)return n;if(t){var i=r(o),a=o.sources.map(function(e){return"/*# sourceURL="+o.sourceRoot+e+" */"});return[n].concat(a).concat([i]).join("\n")}return[n].join("\n")}function r(e){return"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,"+new t(JSON.stringify(e)).toString("base64")+" */"}e.exports=function(e){var t=[];return t.toString=function(){return this.map(function(t){var r=n(t,e);return t[2]?"@media "+t[2]+"{"+r+"}":r}).join("")},t.i=function(e,n){"string"==typeof e&&(e=[[null,e,""]]);for(var r={},o=0;o<this.length;o++){var i=this[o][0];"number"==typeof i&&(r[i]=!0)}for(o=0;o<e.length;o++){var a=e[o];"number"==typeof a[0]&&r[a[0]]||(n&&!a[2]?a[2]=n:n&&(a[2]="("+a[2]+") and ("+n+")"),t.push(a))}},t}}).call(t,n(320).Buffer)},function(e,t,n){function r(e,t){for(var n=0;n<e.length;n++){var r=e[n],o=m[r.id];if(o){o.refs++;for(var i=0;i<o.parts.length;i++)o.parts[i](r.parts[i]);for(;i<r.parts.length;i++)o.parts.push(u(r.parts[i],t))}else{for(var a=[],i=0;i<r.parts.length;i++)a.push(u(r.parts[i],t));m[r.id]={id:r.id,refs:1,parts:a}}}}function o(e){for(var t=[],n={},r=0;r<e.length;r++){var o=e[r],i=o[0],a=o[1],l=o[2],s=o[3],c={css:a,media:l,sourceMap:s};n[i]?n[i].parts.push(c):t.push(n[i]={id:i,parts:[c]})}return t}function i(e,t){var n=b(),r=_[_.length-1];if("top"===e.insertAt)r?r.nextSibling?n.insertBefore(t,r.nextSibling):n.appendChild(t):n.insertBefore(t,n.firstChild),_.push(t);else{if("bottom"!==e.insertAt)throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");n.appendChild(t)}}function a(e){e.parentNode.removeChild(e);var t=_.indexOf(e);t>=0&&_.splice(t,1)}function l(e){var t=document.createElement("style");return e.attrs.type="text/css",c(t,e.attrs),i(e,t),t}function s(e){var t=document.createElement("link");return e.attrs.type="text/css",e.attrs.rel="stylesheet",c(t,e.attrs),i(e,t),t}function c(e,t){Object.keys(t).forEach(function(n){e.setAttribute(n,t[n])})}function u(e,t){var n,r,o;if(t.singleton){var i=v++;n=y||(y=l(t)),r=d.bind(null,n,i,!1),o=d.bind(null,n,i,!0)}else e.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(n=s(t),r=f.bind(null,n,t),o=function(){a(n),n.href&&URL.revokeObjectURL(n.href)}):(n=l(t),r=p.bind(null,n),o=function(){a(n)});return r(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap)return;r(e=t)}else o()}}function d(e,t,n,r){var o=n?"":r.css;if(e.styleSheet)e.styleSheet.cssText=w(t,o);else{var i=document.createTextNode(o),a=e.childNodes;a[t]&&e.removeChild(a[t]),a.length?e.insertBefore(i,a[t]):e.appendChild(i)}}function p(e,t){var n=t.css,r=t.media;if(r&&e.setAttribute("media",r),e.styleSheet)e.styleSheet.cssText=n;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(n))}}function f(e,t,n){var r=n.css,o=n.sourceMap,i=void 0===t.convertToAbsoluteUrls&&o;(t.convertToAbsoluteUrls||i)&&(r=x(r)),o&&(r+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(o))))+" */");var a=new Blob([r],{type:"text/css"}),l=e.href;e.href=URL.createObjectURL(a),l&&URL.revokeObjectURL(l)}var m={},h=function(e){var t;return function(){return void 0===t&&(t=e.apply(this,arguments)),t}},g=h(function(){return/msie [6-9]\b/.test(self.navigator.userAgent.toLowerCase())}),b=h(function(){return document.head||document.getElementsByTagName("head")[0]}),y=null,v=0,_=[],x=n(693);e.exports=function(e,t){if("undefined"!=typeof DEBUG&&DEBUG&&"object"!=typeof document)throw new Error("The style-loader cannot be used in a non-browser environment");t=t||{},t.attrs="object"==typeof t.attrs?t.attrs:{},void 0===t.singleton&&(t.singleton=g()),void 0===t.insertAt&&(t.insertAt="bottom");var n=o(e);return r(n,t),function(e){for(var i=[],a=0;a<n.length;a++){var l=n[a],s=m[l.id];s.refs--,i.push(s)}if(e){r(o(e),t)}for(var a=0;a<i.length;a++){var s=i[a];if(0===s.refs){for(var c=0;c<s.parts.length;c++)s.parts[c]();delete m[s.id]}}}};var w=function(){var e=[];return function(t,n){return e[t]=n,e.filter(Boolean).join("\n")}}()},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t,n){var r=n(39),o=n(90);e.exports=n(46)?function(e,t,n){return r.f(e,t,o(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t,n){var r=n(207),o=n(132);e.exports=function(e){return r(o(e))}},function(e,t){e.exports=function(e,t,n,r){if(!(e instanceof t)||void 0!==r&&r in e)throw TypeError(n+": incorrect invocation!");return e}},function(e,t){e.exports=!1},function(e,t,n){var r=n(2),o=n(234),i=n(148),a=n(160)("IE_PROTO"),l=function(){},s="prototype",c=function(){var e,t=n(147)("iframe"),r=i.length,o="<",a=">";for(t.style.display="none",n(150).appendChild(t),t.src="javascript:",e=t.contentWindow.document,e.open(),e.write(o+"script"+a+"document.F=Object"+o+"/script"+a),e.close(),c=e.F;r--;)delete c[s][i[r]];return c()};e.exports=Object.create||function(e,t){var n;return null!==e?(l[s]=r(e),n=new l,l[s]=null,n[a]=e):n=c(),void 0===t?n:o(n,t)}},function(e,t,n){var r=n(236),o=n(148).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(e){return r(e,o)}},function(e,t,n){var r=n(236),o=n(148);e.exports=Object.keys||function(e){return r(e,o)}},function(e,t,n){var r=n(22);e.exports=function(e,t,n){for(var o in t)r(e,o,t[o],n);return e}},function(e,t,n){"use strict";var r=n(3),o=n(12),i=n(11),a=n(8)("species");e.exports=function(e){var t=r[e];i&&t&&!t[a]&&o.f(t,a,{configurable:!0,get:function(){return this}})}},function(e,t,n){var r=n(49),o=Math.max,i=Math.min;e.exports=function(e,t){return e=r(e),e<0?o(e+t,0):i(e,t)}},function(e,t){var n=0,r=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+r).toString(36))}},function(e,t,n){"use strict";var r=n(6),o=(n(1),function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)}),i=function(e,t){var n=this;if(n.instancePool.length){var r=n.instancePool.pop();return n.call(r,e,t),r}return new n(e,t)},a=function(e,t,n){var r=this;if(r.instancePool.length){var o=r.instancePool.pop();return r.call(o,e,t,n),o}return new r(e,t,n)},l=function(e,t,n,r){var o=this;if(o.instancePool.length){var i=o.instancePool.pop();return o.call(i,e,t,n,r),i}return new o(e,t,n,r)},s=function(e){var t=this;e instanceof t||r("25"),e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},c=10,u=o,d=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||u,n.poolSize||(n.poolSize=c),n.release=s,n},p={addPoolingTo:d,oneArgumentPooler:o,twoArgumentPooler:i,threeArgumentPooler:a,fourArgumentPooler:l};e.exports=p},function(e,t,n){"use strict";function r(){o.attachRefs(this,this._currentElement)}var o=n(623),i=(n(29),n(4),{mountComponent:function(e,t,n,o,i,a){var l=e.mountComponent(t,n,o,i,a);return e._currentElement&&null!=e._currentElement.ref&&t.getReactMountReady().enqueue(r,e),l},getHostNode:function(e){return e.getHostNode()},unmountComponent:function(e,t){o.detachRefs(e,e._currentElement),e.unmountComponent(t)},receiveComponent:function(e,t,n,i){var a=e._currentElement;if(t!==a||i!==e._context){var l=o.shouldUpdateRefs(a,t);l&&o.detachRefs(e,a),e.receiveComponent(t,n,i),l&&e._currentElement&&null!=e._currentElement.ref&&n.getReactMountReady().enqueue(r,e)}},performUpdateIfNecessary:function(e,t,n){e._updateBatchNumber===n&&e.performUpdateIfNecessary(t)}});e.exports=i},function(e,t,n){"use strict";var r=n(9),o=n(678),i=n(195),a=n(683),l=n(679),s=n(680),c=n(85),u=n(681),d=n(684),p=n(685),f=(n(4),c.createElement),m=c.createFactory,h=c.cloneElement,g=r,b={Children:{map:o.map,forEach:o.forEach,count:o.count,toArray:o.toArray,only:p},Component:i,PureComponent:a,createElement:f,cloneElement:h,isValidElement:c.isValidElement,PropTypes:u,createClass:l.createClass,createFactory:m,createMixin:function(e){return e},DOM:s,version:d,__spread:g};e.exports=b},function(e,t,n){var r=n(130);e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,o){return e.call(t,n,r,o)}}return function(){return e.apply(t,arguments)}}},function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t){e.exports={}},function(e,t,n){var r=n(215),o=n(134);e.exports=Object.keys||function(e){return r(e,o)}},function(e,t,n){var r=n(8)("unscopables"),o=Array.prototype;void 0==o[r]&&n(21)(o,r,{}),e.exports=function(e){o[r][e]=!0}},function(e,t,n){var r=n(41),o=n(230),i=n(152),a=n(2),l=n(15),s=n(169),c={},u={},t=e.exports=function(e,t,n,d,p){var f,m,h,g,b=p?function(){return e}:s(e),y=r(n,d,t?2:1),v=0;if("function"!=typeof b)throw TypeError(e+" is not iterable!");if(i(b)){for(f=l(e.length);f>v;v++)if((g=t?y(a(m=e[v])[0],m[1]):y(e[v]))===c||g===u)return g}else for(h=b.call(e);!(m=h.next()).done;)if((g=o(h,y,m.value,t))===c||g===u)return g};t.BREAK=c,t.RETURN=u},function(e,t){e.exports={}},function(e,t,n){var r=n(12).f,o=n(18),i=n(8)("toStringTag");e.exports=function(e,t,n){e&&!o(e=n?e:e.prototype,i)&&r(e,i,{configurable:!0,value:t})}},function(e,t,n){var r=n(0),o=n(31),i=n(5),a=n(165),l="["+a+"]",s="
",c=RegExp("^"+l+l+"*"),u=RegExp(l+l+"*$"),d=function(e,t,n){var o={},l=i(function(){return!!a[e]()||s[e]()!=s}),c=o[e]=l?t(p):a[e];n&&(o[n]=c),r(r.P+r.F*l,"String",o)},p=d.trim=function(e,t){return e=String(o(e)),1&t&&(e=e.replace(c,"")),2&t&&(e=e.replace(u,"")),e};e.exports=d},function(e,t,n){"use strict";var r={};e.exports=r},function(e,t,n){"use strict";function r(e){if(g){var t=e.node,n=e.children;if(n.length)for(var r=0;r<n.length;r++)b(t,n[r],null);else null!=e.html?d(t,e.html):null!=e.text&&f(t,e.text)}}function o(e,t){e.parentNode.replaceChild(t.node,e),r(t)}function i(e,t){g?e.children.push(t):e.node.appendChild(t.node)}function a(e,t){g?e.html=t:d(e.node,t)}function l(e,t){g?e.text=t:f(e.node,t)}function s(){return this.node.nodeName}function c(e){return{node:e,children:[],html:null,text:null,toString:s}}var u=n(175),d=n(125),p=n(183),f=n(278),m=1,h=11,g="undefined"!=typeof document&&"number"==typeof document.documentMode||"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent&&/\bEdge\/\d/.test(navigator.userAgent),b=p(function(e,t,n){t.node.nodeType===h||t.node.nodeType===m&&"object"===t.node.nodeName.toLowerCase()&&(null==t.node.namespaceURI||t.node.namespaceURI===u.html)?(r(t),e.insertBefore(t.node,n)):(e.insertBefore(t.node,n),r(t))});c.insertTreeBefore=b,c.replaceChildWithTree=o,c.queueChild=i,c.queueHTML=a,c.queueText=l,e.exports=c},function(e,t,n){"use strict";function r(e,t){return(e&t)===t}var o=n(6),i=(n(1),{MUST_USE_PROPERTY:1,HAS_BOOLEAN_VALUE:4,HAS_NUMERIC_VALUE:8,HAS_POSITIVE_NUMERIC_VALUE:24,HAS_OVERLOADED_BOOLEAN_VALUE:32,injectDOMPropertyConfig:function(e){var t=i,n=e.Properties||{},a=e.DOMAttributeNamespaces||{},s=e.DOMAttributeNames||{},c=e.DOMPropertyNames||{},u=e.DOMMutationMethods||{};e.isCustomAttribute&&l._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var d in n){l.properties.hasOwnProperty(d)&&o("48",d);var p=d.toLowerCase(),f=n[d],m={attributeName:p,attributeNamespace:null,propertyName:d,mutationMethod:null,mustUseProperty:r(f,t.MUST_USE_PROPERTY),hasBooleanValue:r(f,t.HAS_BOOLEAN_VALUE),hasNumericValue:r(f,t.HAS_NUMERIC_VALUE),hasPositiveNumericValue:r(f,t.HAS_POSITIVE_NUMERIC_VALUE),hasOverloadedBooleanValue:r(f,t.HAS_OVERLOADED_BOOLEAN_VALUE)};if(m.hasBooleanValue+m.hasNumericValue+m.hasOverloadedBooleanValue<=1||o("50",d),s.hasOwnProperty(d)){var h=s[d];m.attributeName=h}a.hasOwnProperty(d)&&(m.attributeNamespace=a[d]),c.hasOwnProperty(d)&&(m.propertyName=c[d]),u.hasOwnProperty(d)&&(m.mutationMethod=u[d]),l.properties[d]=m}}}),a=":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",l={ID_ATTRIBUTE_NAME:"data-reactid",ROOT_ATTRIBUTE_NAME:"data-reactroot",ATTRIBUTE_NAME_START_CHAR:a,ATTRIBUTE_NAME_CHAR:a+"\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",properties:{},getPossibleStandardName:null,_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<l._isCustomAttributeFunctions.length;t++){if((0,l._isCustomAttributeFunctions[t])(e))return!0}return!1},injection:i};e.exports=l},function(e,t,n){"use strict";function r(e){return void 0!==e.ref}function o(e){return void 0!==e.key}var i=n(9),a=n(45),l=(n(4),n(290),Object.prototype.hasOwnProperty),s=n(288),c={key:!0,ref:!0,__self:!0,__source:!0},u=function(e,t,n,r,o,i,a){var l={$$typeof:s,type:e,key:t,ref:n,props:a,_owner:i};return l};u.createElement=function(e,t,n){var i,s={},d=null,p=null,f=null,m=null;if(null!=t){r(t)&&(p=t.ref),o(t)&&(d=""+t.key),f=void 0===t.__self?null:t.__self,m=void 0===t.__source?null:t.__source;for(i in t)l.call(t,i)&&!c.hasOwnProperty(i)&&(s[i]=t[i])}var h=arguments.length-2;if(1===h)s.children=n;else if(h>1){for(var g=Array(h),b=0;b<h;b++)g[b]=arguments[b+2];s.children=g}if(e&&e.defaultProps){var y=e.defaultProps;for(i in y)void 0===s[i]&&(s[i]=y[i])}return u(e,d,p,f,m,a.current,s)},u.createFactory=function(e){var t=u.createElement.bind(null,e);return t.type=e,t},u.cloneAndReplaceKey=function(e,t){return u(e.type,t,e.ref,e._self,e._source,e._owner,e.props)},u.cloneElement=function(e,t,n){var s,d=i({},e.props),p=e.key,f=e.ref,m=e._self,h=e._source,g=e._owner;if(null!=t){r(t)&&(f=t.ref,g=a.current),o(t)&&(p=""+t.key);var b;e.type&&e.type.defaultProps&&(b=e.type.defaultProps);for(s in t)l.call(t,s)&&!c.hasOwnProperty(s)&&(void 0===t[s]&&void 0!==b?d[s]=b[s]:d[s]=t[s])}var y=arguments.length-2;if(1===y)d.children=n;else if(y>1){for(var v=Array(y),_=0;_<y;_++)v[_]=arguments[_+2];d.children=v}return u(e.type,p,f,m,h,g,d)},u.isValidElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===s},e.exports=u},function(e,t,n){"use strict";function r(e){for(var t=arguments.length-1,n="Minified React error #"+e+"; visit http://facebook.github.io/react/docs/error-decoder.html?invariant="+e,r=0;r<t;r++)n+="&args[]="+encodeURIComponent(arguments[r+1]);n+=" for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";var o=new Error(n);throw o.name="Invariant Violation",o.framesToPop=1,o}e.exports=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(200),i=r(o);t.default=i.default||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}},function(e,t,n){var r,o;/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
!function(){"use strict";function n(){for(var e=[],t=0;t<arguments.length;t++){var r=arguments[t];if(r){var o=typeof r;if("string"===o||"number"===o)e.push(r);else if(Array.isArray(r))e.push(n.apply(null,r));else if("object"===o)for(var a in r)i.call(r,a)&&r[a]&&e.push(a)}}return e.join(" ")}var i={}.hasOwnProperty;void 0!==e&&e.exports?e.exports=n:(r=[],void 0!==(o=function(){return n}.apply(t,r))&&(e.exports=o))}()},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t,n){var r=n(132);e.exports=function(e){return Object(r(e))}},function(e,t,n){"use strict";var r=n(354)(!0);n(210)(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,n=this._i;return n>=t.length?{value:void 0,done:!0}:(e=r(t,n),this._i+=e.length,{value:e,done:!1})})},function(e,t,n){var r=n(30),o=n(8)("toStringTag"),i="Arguments"==r(function(){return arguments}()),a=function(e,t){try{return e[t]}catch(e){}};e.exports=function(e){var t,n,l;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=a(t=Object(e),o))?n:i?r(t):"Object"==(l=r(t))&&"function"==typeof t.callee?"Arguments":l}},function(e,t,n){var r=n(30);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==r(e)?e.split(""):Object(e)}},function(e,t){t.f={}.propertyIsEnumerable},function(e,t,n){"use strict";function r(e){return"button"===e||"input"===e||"select"===e||"textarea"===e}function o(e,t,n){switch(e){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":return!(!n.disabled||!r(t));default:return!1}}var i=n(6),a=n(176),l=n(177),s=n(181),c=n(273),u=n(274),d=(n(1),{}),p=null,f=function(e,t){e&&(l.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e))},m=function(e){return f(e,!0)},h=function(e){return f(e,!1)},g=function(e){return"."+e._rootNodeID},b={injection:{injectEventPluginOrder:a.injectEventPluginOrder,injectEventPluginsByName:a.injectEventPluginsByName},putListener:function(e,t,n){"function"!=typeof n&&i("94",t,typeof n);var r=g(e);(d[t]||(d[t]={}))[r]=n;var o=a.registrationNameModules[t];o&&o.didPutListener&&o.didPutListener(e,t,n)},getListener:function(e,t){var n=d[t];if(o(t,e._currentElement.type,e._currentElement.props))return null;var r=g(e);return n&&n[r]},deleteListener:function(e,t){var n=a.registrationNameModules[t];n&&n.willDeleteListener&&n.willDeleteListener(e,t);var r=d[t];if(r){delete r[g(e)]}},deleteAllListeners:function(e){var t=g(e);for(var n in d)if(d.hasOwnProperty(n)&&d[n][t]){var r=a.registrationNameModules[n];r&&r.willDeleteListener&&r.willDeleteListener(e,n),delete d[n][t]}},extractEvents:function(e,t,n,r){for(var o,i=a.plugins,l=0;l<i.length;l++){var s=i[l];if(s){var u=s.extractEvents(e,t,n,r);u&&(o=c(o,u))}}return o},enqueueEvents:function(e){e&&(p=c(p,e))},processEventQueue:function(e){var t=p;p=null,e?u(t,m):u(t,h),p&&i("95"),s.rethrowCaughtError()},__purge:function(){d={}},__getListenerBank:function(){return d}};e.exports=b},function(e,t,n){"use strict";function r(e,t,n){return b(e,t.dispatchConfig.phasedRegistrationNames[n])}function o(e,t,n){var o=r(e,n,t);o&&(n._dispatchListeners=h(n._dispatchListeners,o),n._dispatchInstances=h(n._dispatchInstances,e))}function i(e){e&&e.dispatchConfig.phasedRegistrationNames&&m.traverseTwoPhase(e._targetInst,o,e)}function a(e){if(e&&e.dispatchConfig.phasedRegistrationNames){var t=e._targetInst,n=t?m.getParentInstance(t):null;m.traverseTwoPhase(n,o,e)}}function l(e,t,n){if(n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,o=b(e,r);o&&(n._dispatchListeners=h(n._dispatchListeners,o),n._dispatchInstances=h(n._dispatchInstances,e))}}function s(e){e&&e.dispatchConfig.registrationName&&l(e._targetInst,null,e)}function c(e){g(e,i)}function u(e){g(e,a)}function d(e,t,n,r){m.traverseEnterLeave(n,r,l,e,t)}function p(e){g(e,s)}var f=n(96),m=n(177),h=n(273),g=n(274),b=(n(4),f.getListener),y={accumulateTwoPhaseDispatches:c,accumulateTwoPhaseDispatchesSkipTarget:u,accumulateDirectDispatches:p,accumulateEnterLeaveDispatches:d};e.exports=y},function(e,t,n){"use strict";var r={remove:function(e){e._reactInternalInstance=void 0},get:function(e){return e._reactInternalInstance},has:function(e){return void 0!==e._reactInternalInstance},set:function(e,t){e._reactInternalInstance=t}};e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(44),i=n(186),a={view:function(e){if(e.view)return e.view;var t=i(e);if(t.window===t)return t;var n=t.ownerDocument;return n?n.defaultView||n.parentWindow:window},detail:function(e){return e.detail||0}};o.augmentClass(r,a),e.exports=r},function(e,t,n){"use strict";t.__esModule=!0;var r={replace:"replace",replaceIn:"replaceIn",push:"push",pushIn:"pushIn"};t.default=r},function(e,t){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t,n){"use strict";var r=n(87),o=n.n(r),i=n(316),a=n.n(i),l=n(50),s=n.n(l),c=n(51),u=n.n(c),d=n(52),p=n.n(d),f=n(54),m=n.n(f),h=n(53),g=n.n(h),b=n(10),y=n.n(b),v=n(103),_=function(e){function t(){var e,n,r,o;u()(this,t);for(var i=arguments.length,a=Array(i),l=0;l<i;l++)a[l]=arguments[l];return n=r=m()(this,(e=t.__proto__||s()(t)).call.apply(e,[this].concat(a))),r.handleClick=function(e){r.props.onClick&&r.props.onClick(e),0===e.button&&(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey||e.defaultPrevented!==!0&&(e.preventDefault(),r.props.to?v.a.push(r.props.to):v.a.push({pathname:e.currentTarget.pathname,search:e.currentTarget.search})))},o=n,m()(r,o)}return g()(t,e),p()(t,[{key:"render",value:function(){var e=this.props,t=e.to,n=a()(e,["to"]);return y.a.createElement("a",o()({href:"string"==typeof t?t:v.a.createHref(t)},n,{onClick:this.handleClick}))}}]),t}(y.a.Component);_.propTypes={to:b.PropTypes.oneOfType([b.PropTypes.string,b.PropTypes.object]).isRequired,onClick:b.PropTypes.func},t.a=_},function(e,t,n){"use strict";var r=n(572),o=n.n(r);t.a=o()()},function(e,t){e.exports=!0},function(e,t){t.f={}.propertyIsEnumerable},function(e,t,n){var r=n(39).f,o=n(57),i=n(17)("toStringTag");e.exports=function(e,t,n){e&&!o(e=n?e:e.prototype,i)&&r(e,i,{configurable:!0,value:t})}},function(e,t){var n=0,r=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+r).toString(36))}},function(e,t,n){n(359);for(var r=n(25),o=n(58),i=n(75),a=n(17)("toStringTag"),l=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],s=0;s<5;s++){var c=l[s],u=r[c],d=u&&u.prototype;d&&!d[a]&&o(d,a,c),i[c]=i.Array}},function(e,t,n){var r=n(24),o=n(15),i=n(67);e.exports=function(e){return function(t,n,a){var l,s=r(t),c=o(s.length),u=i(a,c);if(e&&n!=n){for(;c>u;)if((l=s[u++])!=l)return!0}else for(;c>u;u++)if((e||u in s)&&s[u]===n)return e||u||0;return!e&&-1}}},function(e,t,n){"use strict";var r=n(3),o=n(0),i=n(22),a=n(65),l=n(47),s=n(78),c=n(60),u=n(7),d=n(5),p=n(115),f=n(80),m=n(151);e.exports=function(e,t,n,h,g,b){var y=r[e],v=y,_=g?"set":"add",x=v&&v.prototype,w={},C=function(e){var t=x[e];i(x,e,"delete"==e?function(e){return!(b&&!u(e))&&t.call(this,0===e?0:e)}:"has"==e?function(e){return!(b&&!u(e))&&t.call(this,0===e?0:e)}:"get"==e?function(e){return b&&!u(e)?void 0:t.call(this,0===e?0:e)}:"add"==e?function(e){return t.call(this,0===e?0:e),this}:function(e,n){return t.call(this,0===e?0:e,n),this})};if("function"==typeof v&&(b||x.forEach&&!d(function(){(new v).entries().next()}))){var k=new v,E=k[_](b?{}:-0,1)!=k,A=d(function(){k.has(1)}),S=p(function(e){new v(e)}),I=!b&&d(function(){for(var e=new v,t=5;t--;)e[_](t,t);return!e.has(-0)});S||(v=t(function(t,n){c(t,v,e);var r=m(new y,t,v);return void 0!=n&&s(n,g,r[_],r),r}),v.prototype=x,x.constructor=v),(A||I)&&(C("delete"),C("has"),g&&C("get")),(I||E)&&C(_),b&&x.clear&&delete x.clear}else v=h.getConstructor(t,e,g,_),a(v.prototype,n),l.NEED=!0;return f(v,e),w[e]=v,o(o.G+o.W+o.F*(v!=y),w),b||h.setStrong(v,e,g),v}},function(e,t,n){"use strict";var r=n(21),o=n(22),i=n(5),a=n(31),l=n(8);e.exports=function(e,t,n){var s=l(e),c=n(a,s,""[e]),u=c[0],d=c[1];i(function(){var t={};return t[s]=function(){return 7},7!=""[e](t)})&&(o(String.prototype,e,u),r(RegExp.prototype,s,2==t?function(e,t){return d.call(e,this,t)}:function(e){return d.call(e,this)}))}},function(e,t,n){"use strict";var r=n(2);e.exports=function(){var e=r(this),t="";return e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.unicode&&(t+="u"),e.sticky&&(t+="y"),t}},function(e,t){e.exports=function(e,t,n){var r=void 0===n;switch(t.length){case 0:return r?e():e.call(n);case 1:return r?e(t[0]):e.call(n,t[0]);case 2:return r?e(t[0],t[1]):e.call(n,t[0],t[1]);case 3:return r?e(t[0],t[1],t[2]):e.call(n,t[0],t[1],t[2]);case 4:return r?e(t[0],t[1],t[2],t[3]):e.call(n,t[0],t[1],t[2],t[3])}return e.apply(n,t)}},function(e,t,n){var r=n(7),o=n(30),i=n(8)("match");e.exports=function(e){var t;return r(e)&&(void 0!==(t=e[i])?!!t:"RegExp"==o(e))}},function(e,t,n){var r=n(8)("iterator"),o=!1;try{var i=[7][r]();i.return=function(){o=!0},Array.from(i,function(){throw 2})}catch(e){}e.exports=function(e,t){if(!t&&!o)return!1;var n=!1;try{var i=[7],a=i[r]();a.next=function(){return{done:n=!0}},i[r]=function(){return a},e(i)}catch(e){}return n}},function(e,t,n){e.exports=n(61)||!n(5)(function(){var e=Math.random();__defineSetter__.call(null,e,function(){}),delete n(3)[e]})},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t,n){var r=n(3),o="__core-js_shared__",i=r[o]||(r[o]={});e.exports=function(e){return i[e]||(i[e]={})}},function(e,t,n){for(var r,o=n(3),i=n(21),a=n(68),l=a("typed_array"),s=a("view"),c=!(!o.ArrayBuffer||!o.DataView),u=c,d=0,p=9,f="Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array".split(",");d<p;)(r=o[f[d++]])?(i(r.prototype,l,!0),i(r.prototype,s,!0)):u=!1;e.exports={ABV:c,CONSTR:u,TYPED:l,VIEW:s}},function(e,t,n){e.exports=n(587)()},function(e,t,n){"use strict";function r(e){return Object.prototype.hasOwnProperty.call(e,h)||(e[h]=f++,d[e[h]]={}),d[e[h]]}var o,i=n(9),a=n(176),l=n(616),s=n(272),c=n(648),u=n(188),d={},p=!1,f=0,m={topAbort:"abort",topAnimationEnd:c("animationend")||"animationend",topAnimationIteration:c("animationiteration")||"animationiteration",topAnimationStart:c("animationstart")||"animationstart",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",topTransitionEnd:c("transitionend")||"transitionend",topVolumeChange:"volumechange",topWaiting:"waiting",topWheel:"wheel"},h="_reactListenersID"+String(Math.random()).slice(2),g=i({},l,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(g.handleTopLevel),g.ReactEventListener=e}},setEnabled:function(e){g.ReactEventListener&&g.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!g.ReactEventListener||!g.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var n=t,o=r(n),i=a.registrationNameDependencies[e],l=0;l<i.length;l++){var s=i[l];o.hasOwnProperty(s)&&o[s]||("topWheel"===s?u("wheel")?g.ReactEventListener.trapBubbledEvent("topWheel","wheel",n):u("mousewheel")?g.ReactEventListener.trapBubbledEvent("topWheel","mousewheel",n):g.ReactEventListener.trapBubbledEvent("topWheel","DOMMouseScroll",n):"topScroll"===s?u("scroll",!0)?g.ReactEventListener.trapCapturedEvent("topScroll","scroll",n):g.ReactEventListener.trapBubbledEvent("topScroll","scroll",g.ReactEventListener.WINDOW_HANDLE):"topFocus"===s||"topBlur"===s?(u("focus",!0)?(g.ReactEventListener.trapCapturedEvent("topFocus","focus",n),g.ReactEventListener.trapCapturedEvent("topBlur","blur",n)):u("focusin")&&(g.ReactEventListener.trapBubbledEvent("topFocus","focusin",n),g.ReactEventListener.trapBubbledEvent("topBlur","focusout",n)),o.topBlur=!0,o.topFocus=!0):m.hasOwnProperty(s)&&g.ReactEventListener.trapBubbledEvent(s,m[s],n),o[s]=!0)}},trapBubbledEvent:function(e,t,n){return g.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return g.ReactEventListener.trapCapturedEvent(e,t,n)},supportsEventPageXY:function(){if(!document.createEvent)return!1;var e=document.createEvent("MouseEvent");return null!=e&&"pageX"in e},ensureScrollValueMonitoring:function(){if(void 0===o&&(o=g.supportsEventPageXY()),!o&&!p){var e=s.refreshScrollValues;g.ReactEventListener.monitorScrollValue(e),p=!0}}});e.exports=g},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(99),i=n(272),a=n(185),l={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:a,button:function(e){var t=e.button;return"which"in e?t:2===t?2:4===t?1:0},buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},pageX:function(e){return"pageX"in e?e.pageX:e.clientX+i.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+i.currentScrollTop}};o.augmentClass(r,l),e.exports=r},function(e,t,n){"use strict";var r=n(6),o=(n(1),{}),i={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers(),this.wrapperInitData?this.wrapperInitData.length=0:this.wrapperInitData=[],this._isInTransaction=!1},_isInTransaction:!1,getTransactionWrappers:null,isInTransaction:function(){return!!this._isInTransaction},perform:function(e,t,n,o,i,a,l,s){this.isInTransaction()&&r("27");var c,u;try{this._isInTransaction=!0,c=!0,this.initializeAll(0),u=e.call(t,n,o,i,a,l,s),c=!1}finally{try{if(c)try{this.closeAll(0)}catch(e){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return u},initializeAll:function(e){for(var t=this.transactionWrappers,n=e;n<t.length;n++){var r=t[n];try{this.wrapperInitData[n]=o,this.wrapperInitData[n]=r.initialize?r.initialize.call(this):null}finally{if(this.wrapperInitData[n]===o)try{this.initializeAll(n+1)}catch(e){}}}},closeAll:function(e){this.isInTransaction()||r("28");for(var t=this.transactionWrappers,n=e;n<t.length;n++){var i,a=t[n],l=this.wrapperInitData[n];try{i=!0,l!==o&&a.close&&a.close.call(this,l),i=!1}finally{if(i)try{this.closeAll(n+1)}catch(e){}}}this.wrapperInitData.length=0}};e.exports=i},function(e,t,n){"use strict";function r(e){var t=""+e,n=i.exec(t);if(!n)return t;var r,o="",a=0,l=0;for(a=n.index;a<t.length;a++){switch(t.charCodeAt(a)){case 34:r=""";break;case 38:r="&";break;case 39:r="'";break;case 60:r="<";break;case 62:r=">";break;default:continue}l!==a&&(o+=t.substring(l,a)),l=a+1,o+=r}return l!==a?o+t.substring(l,a):o}function o(e){return"boolean"==typeof e||"number"==typeof e?""+e:r(e)}var i=/["'&<>]/;e.exports=o},function(e,t,n){"use strict";var r,o=n(19),i=n(175),a=/^[ \r\n\t\f]/,l=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/,s=n(183),c=s(function(e,t){if(e.namespaceURI!==i.svg||"innerHTML"in e)e.innerHTML=t;else{r=r||document.createElement("div"),r.innerHTML="<svg>"+t+"</svg>";for(var n=r.firstChild;n.firstChild;)e.appendChild(n.firstChild)}});if(o.canUseDOM){var u=document.createElement("div");u.innerHTML=" ",""===u.innerHTML&&(c=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),a.test(t)||"<"===t[0]&&l.test(t)){e.innerHTML=String.fromCharCode(65279)+t;var n=e.firstChild;1===n.data.length?e.removeChild(n):n.deleteData(0,1)}else e.innerHTML=t}),u=null}e.exports=c},function(e,t,n){"use strict";function r(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function o(e){if(null==e)return e;var t=e.getFullYear(),n=e.getMonth()+1,r=e.getDate();return t+"-"+(n<10?"0"+n:n)+"-"+(r<10?"0"+r:r)}function i(e){if(null!=e&&e.length){var t=e.split("-");null!=t[1]?t[1]-=1:(t[1]=0,t[2]=1);var n=new(Function.prototype.bind.apply(Date,[null].concat(r(t))));if(!isNaN(n.getTime()))return n}}function a(e){if(void 0!==e)return e?"1":"0"}function l(e){return"1"===e||"0"!==e&&void 0}function s(e){if(null!=e)return JSON.stringify(e)}function c(e){if(e){var t=void 0;try{t=JSON.parse(e)}catch(e){}return t}}function u(e){var t=arguments.length<=1||void 0===arguments[1]?"_":arguments[1];if(e)return e.join(t)}function d(e){var t=arguments.length<=1||void 0===arguments[1]?"_":arguments[1];if(e)return e.split(t).map(function(e){return""===e?void 0:e})}function p(e){var t=arguments.length<=1||void 0===arguments[1]?"_":arguments[1],n=d(e,t);if(n)return n.map(function(e){return null==e?e:+e})}function f(e){var t=arguments.length<=1||void 0===arguments[1]?"-":arguments[1],n=arguments.length<=2||void 0===arguments[2]?"_":arguments[2];if(e&&Object.keys(e).length)return Object.keys(e).map(function(n){return""+n+t+e[n]}).join(n)}function m(e){var t=arguments.length<=1||void 0===arguments[1]?"-":arguments[1],n=arguments.length<=2||void 0===arguments[2]?"_":arguments[2];if(e&&e.length){var r={};return e.split(n).forEach(function(e){var n=e.split(t),o=v(n,2),i=o[0],a=o[1];r[i]=a}),r}}function h(e){var t=arguments.length<=1||void 0===arguments[1]?"-":arguments[1],n=arguments.length<=2||void 0===arguments[2]?"_":arguments[2],r=m(e,t,n);if(r)return Object.keys(r).forEach(function(e){r[e]=null==r[e]?r[e]:+r[e]}),r}function g(e,t,n){return"function"==typeof e?e(t,n):"object"===(void 0===e?"undefined":y(e))&&e.decode?e.decode(t,n):void 0===t?n:w[e]?w[e](t,n):t}function b(e,t){return"function"==typeof e?e(t):"object"===(void 0===e?"undefined":y(e))&&e.encode?e.encode(t):C[e]?C[e](t):t}t.__esModule=!0;var y="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},v=function(){function e(e,t){var n=[],r=!0,o=!1,i=void 0;try{for(var a,l=e[Symbol.iterator]();!(r=(a=l.next()).done)&&(n.push(a.value),!t||n.length!==t);r=!0);}catch(e){o=!0,i=e}finally{try{!r&&l.return&&l.return()}finally{if(o)throw i}}return n}return function(t,n){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,n);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}();t.encodeDate=o,t.decodeDate=i,t.encodeBoolean=a,t.decodeBoolean=l,t.encodeJson=s,t.decodeJson=c,t.encodeArray=u,t.decodeArray=d,t.decodeNumericArray=p,t.encodeObject=f,t.decodeObject=m,t.decodeNumericObject=h,t.decode=g,t.encode=b;var _=t.encodeNumericArray=u,x=t.encodeNumericObject=f,w=t.Decoders={number:parseFloat,string:function(e){return e},object:m,array:d,json:c,date:i,boolean:l,numericObject:h,numericArray:p},C=t.Encoders={number:String,string:function(e){return e},object:f,array:u,json:s,date:o,boolean:a,numericObject:x,numericArray:_}},function(e,t,n){"use strict";function r(){return{addUrlChangeHandlers:!0,addRouterParams:!0,changeHandlerName:function(e){return"onChange"+e[0].toUpperCase()+e.substring(1)},history:{push:function(){console.error("No history provided to react-url-query. Please provide one via configureUrlQuery.")},replace:function(){console.error("No history provided to react-url-query. Please provide one via configureUrlQuery.")}},readLocationFromStore:function(e){if(e&&e.routing)return e.routing.locationBeforeTransitions}}}t.__esModule=!0,t.default=r()},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(50),o=n.n(r),i=n(51),a=n.n(i),l=n(52),s=n.n(l),c=n(54),u=n.n(c),d=n(53),p=n.n(d),f=n(10),m=n.n(f),h=n(300),g=n(197),b=n(699),y=n.n(b),v=n(711),_=(n.n(v),function(e){function t(){return a()(this,t),u()(this,(t.__proto__||o()(t)).apply(this,arguments))}return p()(t,e),s()(t,[{key:"componentDidMount",value:function(){document.title=v.title}},{key:"render",value:function(){return m.a.createElement(h.a,{className:y.a.content},m.a.createElement(g.a,null))}}]),t}(m.a.Component));_.propTypes={},t.default=_},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(314),i=r(o),a=n(313),l=r(a),s="function"==typeof l.default&&"symbol"==typeof i.default?function(e){return typeof e}:function(e){return e&&"function"==typeof l.default&&e.constructor===l.default&&e!==l.default.prototype?"symbol":typeof e};t.default="function"==typeof l.default&&"symbol"===s(i.default)?function(e){return void 0===e?"undefined":s(e)}:function(e){return e&&"function"==typeof l.default&&e.constructor===l.default&&e!==l.default.prototype?"symbol":void 0===e?"undefined":s(e)}},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},function(e,t,n){var r=n(89),o=n(17)("toStringTag"),i="Arguments"==r(function(){return arguments}()),a=function(e,t){try{return e[t]}catch(e){}};e.exports=function(e){var t,n,l;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=a(t=Object(e),o))?n:i?r(t):"Object"==(l=r(t))&&"function"==typeof t.callee?"Arguments":l}},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},function(e,t,n){var r=n(74),o=n(25).document,i=r(o)&&r(o.createElement);e.exports=function(e){return i?o.createElement(e):{}}},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t,n){var r=n(37),o=n(348),i=n(134),a=n(137)("IE_PROTO"),l=function(){},s="prototype",c=function(){var e,t=n(133)("iframe"),r=i.length,o="<",a=">";for(t.style.display="none",n(205).appendChild(t),t.src="javascript:",e=t.contentWindow.document,e.open(),e.write(o+"script"+a+"document.F=Object"+o+"/script"+a),e.close(),c=e.F;r--;)delete c[s][i[r]];return c()};e.exports=Object.create||function(e,t){var n;return null!==e?(l[s]=r(e),n=new l,l[s]=null,n[a]=e):n=c(),void 0===t?n:o(n,t)}},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t,n){var r=n(138)("keys"),o=n(107);e.exports=function(e){return r[e]||(r[e]=o(e))}},function(e,t,n){var r=n(25),o="__core-js_shared__",i=r[o]||(r[o]={});e.exports=function(e){return i[e]||(i[e]={})}},function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e)}},function(e,t,n){var r=n(139),o=Math.min;e.exports=function(e){return e>0?o(r(e),9007199254740991):0}},function(e,t,n){var r=n(74);e.exports=function(e,t){if(!r(e))return e;var n,o;if(t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;if("function"==typeof(n=e.valueOf)&&!r(o=n.call(e)))return o;if(!t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;throw TypeError("Can't convert object to primitive value")}},function(e,t,n){var r=n(25),o=n(14),i=n(104),a=n(143),l=n(39).f;e.exports=function(e){var t=o.Symbol||(o.Symbol=i?{}:r.Symbol||{});"_"==e.charAt(0)||e in t||l(t,e,{value:a.f(e)})}},function(e,t,n){t.f=n(17)},function(e,t,n){var r=n(131),o=n(17)("iterator"),i=n(75);e.exports=n(14).getIteratorMethod=function(e){if(void 0!=e)return e[o]||e["@@iterator"]||i[r(e)]}},function(e,t,n){"use strict";var r=n(16),o=n(67),i=n(15);e.exports=function(e){for(var t=r(this),n=i(t.length),a=arguments.length,l=o(a>1?arguments[1]:void 0,n),s=a>2?arguments[2]:void 0,c=void 0===s?n:o(s,n);c>l;)t[l++]=e;return t}},function(e,t,n){"use strict";var r=n(12),o=n(48);e.exports=function(e,t,n){t in e?r.f(e,t,o(0,n)):e[t]=n}},function(e,t,n){var r=n(7),o=n(3).document,i=r(o)&&r(o.createElement);e.exports=function(e){return i?o.createElement(e):{}}},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t,n){var r=n(8)("match");e.exports=function(e){var t=/./;try{"/./"[e](t)}catch(n){try{return t[r]=!1,!"/./"[e](t)}catch(e){}}return!0}},function(e,t,n){e.exports=n(3).document&&document.documentElement},function(e,t,n){var r=n(7),o=n(159).set;e.exports=function(e,t,n){var i,a=t.constructor;return a!==n&&"function"==typeof a&&(i=a.prototype)!==n.prototype&&r(i)&&o&&o(e,i),e}},function(e,t,n){var r=n(79),o=n(8)("iterator"),i=Array.prototype;e.exports=function(e){return void 0!==e&&(r.Array===e||i[o]===e)}},function(e,t,n){var r=n(30);e.exports=Array.isArray||function(e){return"Array"==r(e)}},function(e,t,n){"use strict";var r=n(62),o=n(48),i=n(80),a={};n(21)(a,n(8)("iterator"),function(){return this}),e.exports=function(e,t,n){e.prototype=r(a,{next:o(1,n)}),i(e,t+" Iterator")}},function(e,t,n){"use strict";var r=n(61),o=n(0),i=n(22),a=n(21),l=n(18),s=n(79),c=n(154),u=n(80),d=n(27),p=n(8)("iterator"),f=!([].keys&&"next"in[].keys()),m="keys",h="values",g=function(){return this};e.exports=function(e,t,n,b,y,v,_){c(n,t,b);var x,w,C,k=function(e){if(!f&&e in I)return I[e];switch(e){case m:return function(){return new n(this,e)};case h:return function(){return new n(this,e)}}return function(){return new n(this,e)}},E=t+" Iterator",A=y==h,S=!1,I=e.prototype,T=I[p]||I["@@iterator"]||y&&I[y],P=T||k(y),O=y?A?k("entries"):P:void 0,M="Array"==t?I.entries||T:T;if(M&&(C=d(M.call(new e)))!==Object.prototype&&(u(C,E,!0),r||l(C,p)||a(C,p,g)),A&&T&&T.name!==h&&(S=!0,P=function(){return T.call(this)}),r&&!_||!f&&!S&&I[p]||a(I,p,P),s[t]=P,s[E]=g,y)if(x={values:A?P:k(h),keys:v?P:k(m),entries:O},_)for(w in x)w in I||i(I,w,x[w]);else o(o.P+o.F*(f||S),t,x);return x}},function(e,t){var n=Math.expm1;e.exports=!n||n(10)>22025.465794806718||n(10)<22025.465794806718||n(-2e-17)!=-2e-17?function(e){return 0==(e=+e)?e:e>-1e-6&&e<1e-6?e+e*e/2:Math.exp(e)-1}:n},function(e,t){e.exports=Math.sign||function(e){return 0==(e=+e)||e!=e?e:e<0?-1:1}},function(e,t,n){var r=n(3),o=n(166).set,i=r.MutationObserver||r.WebKitMutationObserver,a=r.process,l=r.Promise,s="process"==n(30)(a);e.exports=function(){var e,t,n,c=function(){var r,o;for(s&&(r=a.domain)&&r.exit();e;){o=e.fn,e=e.next;try{o()}catch(r){throw e?n():t=void 0,r}}t=void 0,r&&r.enter()};if(s)n=function(){a.nextTick(c)};else if(i){var u=!0,d=document.createTextNode("");new i(c).observe(d,{characterData:!0}),n=function(){d.data=u=!u}}else if(l&&l.resolve){var p=l.resolve();n=function(){p.then(c)}}else n=function(){o.call(r,c)};return function(r){var o={fn:r,next:void 0};t&&(t.next=o),e||(e=o,n()),t=o}}},function(e,t,n){var r=n(7),o=n(2),i=function(e,t){if(o(e),!r(t)&&null!==t)throw TypeError(t+": can't set as prototype!")};e.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,r){try{r=n(41)(Function.call,n(26).f(Object.prototype,"__proto__").set,2),r(e,[]),t=!(e instanceof Array)}catch(e){t=!0}return function(e,n){return i(e,n),t?e.__proto__=n:r(e,n),e}}({},!1):void 0),check:i}},function(e,t,n){var r=n(118)("keys"),o=n(68);e.exports=function(e){return r[e]||(r[e]=o(e))}},function(e,t,n){var r=n(2),o=n(20),i=n(8)("species");e.exports=function(e,t){var n,a=r(e).constructor;return void 0===a||void 0==(n=r(a)[i])?t:o(n)}},function(e,t,n){var r=n(49),o=n(31);e.exports=function(e){return function(t,n){var i,a,l=String(o(t)),s=r(n),c=l.length;return s<0||s>=c?e?"":void 0:(i=l.charCodeAt(s),i<55296||i>56319||s+1===c||(a=l.charCodeAt(s+1))<56320||a>57343?e?l.charAt(s):i:e?l.slice(s,s+2):a-56320+(i-55296<<10)+65536)}}},function(e,t,n){var r=n(114),o=n(31);e.exports=function(e,t,n){if(r(t))throw TypeError("String#"+n+" doesn't accept regex!");return String(o(e))}},function(e,t,n){"use strict";var r=n(49),o=n(31);e.exports=function(e){var t=String(o(this)),n="",i=r(e);if(i<0||i==1/0)throw RangeError("Count can't be negative");for(;i>0;(i>>>=1)&&(t+=t))1&i&&(n+=t);return n}},function(e,t){e.exports="\t\n\v\f\r \u2028\u2029\ufeff"},function(e,t,n){var r,o,i,a=n(41),l=n(113),s=n(150),c=n(147),u=n(3),d=u.process,p=u.setImmediate,f=u.clearImmediate,m=u.MessageChannel,h=0,g={},b="onreadystatechange",y=function(){var e=+this;if(g.hasOwnProperty(e)){var t=g[e];delete g[e],t()}},v=function(e){y.call(e.data)};p&&f||(p=function(e){for(var t=[],n=1;arguments.length>n;)t.push(arguments[n++]);return g[++h]=function(){l("function"==typeof e?e:Function(e),t)},r(h),h},f=function(e){delete g[e]},"process"==n(30)(d)?r=function(e){d.nextTick(a(y,e,1))}:m?(o=new m,i=o.port2,o.port1.onmessage=v,r=a(i.postMessage,i,1)):u.addEventListener&&"function"==typeof postMessage&&!u.importScripts?(r=function(e){u.postMessage(e+"","*")},u.addEventListener("message",v,!1)):r=b in c("script")?function(e){s.appendChild(c("script"))[b]=function(){s.removeChild(this),y.call(e)}}:function(e){setTimeout(a(y,e,1),0)}),e.exports={set:p,clear:f}},function(e,t,n){"use strict";var r=n(3),o=n(11),i=n(61),a=n(119),l=n(21),s=n(65),c=n(5),u=n(60),d=n(49),p=n(15),f=n(63).f,m=n(12).f,h=n(145),g=n(80),b="ArrayBuffer",y="DataView",v="prototype",_="Wrong length!",x="Wrong index!",w=r[b],C=r[y],k=r.Math,E=r.RangeError,A=r.Infinity,S=w,I=k.abs,T=k.pow,P=k.floor,O=k.log,M=k.LN2,R="buffer",N="byteLength",L="byteOffset",D=o?"_b":R,j=o?"_l":N,F=o?"_o":L,z=function(e,t,n){var r,o,i,a=Array(n),l=8*n-t-1,s=(1<<l)-1,c=s>>1,u=23===t?T(2,-24)-T(2,-77):0,d=0,p=e<0||0===e&&1/e<0?1:0;for(e=I(e),e!=e||e===A?(o=e!=e?1:0,r=s):(r=P(O(e)/M),e*(i=T(2,-r))<1&&(r--,i*=2),e+=r+c>=1?u/i:u*T(2,1-c),e*i>=2&&(r++,i/=2),r+c>=s?(o=0,r=s):r+c>=1?(o=(e*i-1)*T(2,t),r+=c):(o=e*T(2,c-1)*T(2,t),r=0));t>=8;a[d++]=255&o,o/=256,t-=8);for(r=r<<t|o,l+=t;l>0;a[d++]=255&r,r/=256,l-=8);return a[--d]|=128*p,a},U=function(e,t,n){var r,o=8*n-t-1,i=(1<<o)-1,a=i>>1,l=o-7,s=n-1,c=e[s--],u=127&c;for(c>>=7;l>0;u=256*u+e[s],s--,l-=8);for(r=u&(1<<-l)-1,u>>=-l,l+=t;l>0;r=256*r+e[s],s--,l-=8);if(0===u)u=1-a;else{if(u===i)return r?NaN:c?-A:A;r+=T(2,t),u-=a}return(c?-1:1)*r*T(2,u-t)},B=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},H=function(e){return[255&e]},W=function(e){return[255&e,e>>8&255]},V=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},G=function(e){return z(e,52,8)},Y=function(e){return z(e,23,4)},q=function(e,t,n){m(e[v],t,{get:function(){return this[n]}})},K=function(e,t,n,r){var o=+n,i=d(o);if(o!=i||i<0||i+t>e[j])throw E(x);var a=e[D]._b,l=i+e[F],s=a.slice(l,l+t);return r?s:s.reverse()},Z=function(e,t,n,r,o,i){var a=+n,l=d(a);if(a!=l||l<0||l+t>e[j])throw E(x);for(var s=e[D]._b,c=l+e[F],u=r(+o),p=0;p<t;p++)s[c+p]=u[i?p:t-p-1]},X=function(e,t){u(e,w,b);var n=+t,r=p(n);if(n!=r)throw E(_);return r};if(a.ABV){if(!c(function(){new w})||!c(function(){new w(.5)})){w=function(e){return new S(X(this,e))};for(var Q,J=w[v]=S[v],$=f(S),ee=0;$.length>ee;)(Q=$[ee++])in w||l(w,Q,S[Q]);i||(J.constructor=w)}var te=new C(new w(2)),ne=C[v].setInt8;te.setInt8(0,2147483648),te.setInt8(1,2147483649),!te.getInt8(0)&&te.getInt8(1)||s(C[v],{setInt8:function(e,t){ne.call(this,e,t<<24>>24)},setUint8:function(e,t){ne.call(this,e,t<<24>>24)}},!0)}else w=function(e){var t=X(this,e);this._b=h.call(Array(t),0),this[j]=t},C=function(e,t,n){u(this,C,y),u(e,w,y);var r=e[j],o=d(t);if(o<0||o>r)throw E("Wrong offset!");if(n=void 0===n?r-o:p(n),o+n>r)throw E(_);this[D]=e,this[F]=o,this[j]=n},o&&(q(w,N,"_l"),q(C,R,"_b"),q(C,N,"_l"),q(C,L,"_o")),s(C[v],{getInt8:function(e){return K(this,1,e)[0]<<24>>24},getUint8:function(e){return K(this,1,e)[0]},getInt16:function(e){var t=K(this,2,e,arguments[1]);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=K(this,2,e,arguments[1]);return t[1]<<8|t[0]},getInt32:function(e){return B(K(this,4,e,arguments[1]))},getUint32:function(e){return B(K(this,4,e,arguments[1]))>>>0},getFloat32:function(e){return U(K(this,4,e,arguments[1]),23,4)},getFloat64:function(e){return U(K(this,8,e,arguments[1]),52,8)},setInt8:function(e,t){Z(this,1,e,H,t)},setUint8:function(e,t){Z(this,1,e,H,t)},setInt16:function(e,t){Z(this,2,e,W,t,arguments[2])},setUint16:function(e,t){Z(this,2,e,W,t,arguments[2])},setInt32:function(e,t){Z(this,4,e,V,t,arguments[2])},setUint32:function(e,t){Z(this,4,e,V,t,arguments[2])},setFloat32:function(e,t){Z(this,4,e,Y,t,arguments[2])},setFloat64:function(e,t){Z(this,8,e,G,t,arguments[2])}});g(w,b),g(C,y),l(C[v],a.VIEW,!0),t[b]=w,t[y]=C},function(e,t,n){var r=n(3),o=n(40),i=n(61),a=n(243),l=n(12).f;e.exports=function(e){var t=o.Symbol||(o.Symbol=i?{}:r.Symbol||{});"_"==e.charAt(0)||e in t||l(t,e,{value:a.f(e)})}},function(e,t,n){var r=n(93),o=n(8)("iterator"),i=n(79);e.exports=n(40).getIteratorMethod=function(e){if(void 0!=e)return e[o]||e["@@iterator"]||i[r(e)]}},function(e,t,n){"use strict";var r=n(77),o=n(231),i=n(79),a=n(24);e.exports=n(155)(Array,"Array",function(e,t){this._t=a(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,n=this._i++;return!e||n>=e.length?(this._t=void 0,o(1)):"keys"==t?o(0,n):"values"==t?o(0,e[n]):o(0,[n,e[n]])},"values"),i.Arguments=i.Array,r("keys"),r("values"),r("entries")},function(e,t,n){"use strict";function r(e,t){return e===t?0!==e||0!==t||1/e==1/t:e!==e&&t!==t}function o(e,t){if(r(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length)return!1;for(var a=0;a<n.length;a++)if(!i.call(t,n[a])||!r(e[n[a]],t[n[a]]))return!1;return!0}var i=Object.prototype.hasOwnProperty;e.exports=o},function(e,t,n){"use strict";function r(e){if(!n.i(a.a)(e)||n.i(o.a)(e)!=l)return!1;var t=n.i(i.a)(e);if(null===t)return!0;var r=d.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&u.call(r)==p}var o=n(579),i=n(581),a=n(586),l="[object Object]",s=Function.prototype,c=Object.prototype,u=s.toString,d=c.hasOwnProperty,p=u.call(Object);t.a=r},function(e,t){function n(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function o(e){if(u===setTimeout)return setTimeout(e,0);if((u===n||!u)&&setTimeout)return u=setTimeout,setTimeout(e,0);try{return u(e,0)}catch(t){try{return u.call(null,e,0)}catch(t){return u.call(this,e,0)}}}function i(e){if(d===clearTimeout)return clearTimeout(e);if((d===r||!d)&&clearTimeout)return d=clearTimeout,clearTimeout(e);try{return d(e)}catch(t){try{return d.call(null,e)}catch(t){return d.call(this,e)}}}function a(){h&&f&&(h=!1,f.length?m=f.concat(m):g=-1,m.length&&l())}function l(){if(!h){var e=o(a);h=!0;for(var t=m.length;t;){for(f=m,m=[];++g<t;)f&&f[g].run();g=-1,t=m.length}f=null,h=!1,i(e)}}function s(e,t){this.fun=e,this.array=t}function c(){}var u,d,p=e.exports={};!function(){try{u="function"==typeof setTimeout?setTimeout:n}catch(e){u=n}try{d="function"==typeof clearTimeout?clearTimeout:r}catch(e){d=r}}();var f,m=[],h=!1,g=-1;p.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];m.push(new s(e,t)),1!==m.length||h||o(l)},s.prototype.run=function(){this.fun.apply(null,this.array)},p.title="browser",p.browser=!0,p.env={},p.argv=[],p.version="",p.versions={},p.on=c,p.addListener=c,p.once=c,p.off=c,p.removeListener=c,p.removeAllListeners=c,p.emit=c,p.binding=function(e){throw new Error("process.binding is not supported")},p.cwd=function(){return"/"},p.chdir=function(e){throw new Error("process.chdir is not supported")},p.umask=function(){return 0}},function(e,t,n){"use strict";function r(e,t){return Array.isArray(t)&&(t=t[1]),t?t.nextSibling:e.firstChild}function o(e,t,n){u.insertTreeBefore(e,t,n)}function i(e,t,n){Array.isArray(t)?l(e,t[0],t[1],n):h(e,t,n)}function a(e,t){if(Array.isArray(t)){var n=t[1];t=t[0],s(e,t,n),e.removeChild(n)}e.removeChild(t)}function l(e,t,n,r){for(var o=t;;){var i=o.nextSibling;if(h(e,o,r),o===n)break;o=i}}function s(e,t,n){for(;;){var r=t.nextSibling;if(r===n)break;e.removeChild(r)}}function c(e,t,n){var r=e.parentNode,o=e.nextSibling;o===t?n&&h(r,document.createTextNode(n),o):n?(m(o,n),s(r,o,t)):s(r,e,t)}var u=n(83),d=n(595),p=(n(13),n(29),n(183)),f=n(125),m=n(278),h=p(function(e,t,n){e.insertBefore(t,n)}),g=d.dangerouslyReplaceNodeWithMarkup,b={dangerouslyReplaceNodeWithMarkup:g,replaceDelimitedText:c,processUpdates:function(e,t){for(var n=0;n<t.length;n++){var l=t[n];switch(l.type){case"INSERT_MARKUP":o(e,l.content,r(e,l.afterNode));break;case"MOVE_EXISTING":i(e,l.fromNode,r(e,l.afterNode));break;case"SET_MARKUP":f(e,l.content);break;case"TEXT_CONTENT":m(e,l.content);break;case"REMOVE_NODE":a(e,l.fromNode)}}}};e.exports=b},function(e,t,n){"use strict";var r={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"};e.exports=r},function(e,t,n){"use strict";function r(){if(l)for(var e in s){var t=s[e],n=l.indexOf(e);if(n>-1||a("96",e),!c.plugins[n]){t.extractEvents||a("97",e),c.plugins[n]=t;var r=t.eventTypes;for(var i in r)o(r[i],t,i)||a("98",i,e)}}}function o(e,t,n){c.eventNameDispatchConfigs.hasOwnProperty(n)&&a("99",n),c.eventNameDispatchConfigs[n]=e;var r=e.phasedRegistrationNames;if(r){for(var o in r)if(r.hasOwnProperty(o)){var l=r[o];i(l,t,n)}return!0}return!!e.registrationName&&(i(e.registrationName,t,n),!0)}function i(e,t,n){c.registrationNameModules[e]&&a("100",e),c.registrationNameModules[e]=t,c.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var a=n(6),l=(n(1),null),s={},c={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},possibleRegistrationNames:null,injectEventPluginOrder:function(e){l&&a("101"),l=Array.prototype.slice.call(e),r()},injectEventPluginsByName:function(e){var t=!1;for(var n in e)if(e.hasOwnProperty(n)){var o=e[n];s.hasOwnProperty(n)&&s[n]===o||(s[n]&&a("102",n),s[n]=o,t=!0)}t&&r()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return c.registrationNameModules[t.registrationName]||null;if(void 0!==t.phasedRegistrationNames){var n=t.phasedRegistrationNames;for(var r in n)if(n.hasOwnProperty(r)){var o=c.registrationNameModules[n[r]];if(o)return o}}return null},_resetEventPlugins:function(){l=null;for(var e in s)s.hasOwnProperty(e)&&delete s[e];c.plugins.length=0;var t=c.eventNameDispatchConfigs;for(var n in t)t.hasOwnProperty(n)&&delete t[n];var r=c.registrationNameModules;for(var o in r)r.hasOwnProperty(o)&&delete r[o]}};e.exports=c},function(e,t,n){"use strict";function r(e){return"topMouseUp"===e||"topTouchEnd"===e||"topTouchCancel"===e}function o(e){return"topMouseMove"===e||"topTouchMove"===e}function i(e){return"topMouseDown"===e||"topTouchStart"===e}function a(e,t,n,r){var o=e.type||"unknown-event";e.currentTarget=b.getNodeFromInstance(r),t?h.invokeGuardedCallbackWithCatch(o,n,e):h.invokeGuardedCallback(o,n,e),e.currentTarget=null}function l(e,t){var n=e._dispatchListeners,r=e._dispatchInstances;if(Array.isArray(n))for(var o=0;o<n.length&&!e.isPropagationStopped();o++)a(e,t,n[o],r[o]);else n&&a(e,t,n,r);e._dispatchListeners=null,e._dispatchInstances=null}function s(e){var t=e._dispatchListeners,n=e._dispatchInstances;if(Array.isArray(t)){for(var r=0;r<t.length&&!e.isPropagationStopped();r++)if(t[r](e,n[r]))return n[r]}else if(t&&t(e,n))return n;return null}function c(e){var t=s(e);return e._dispatchInstances=null,e._dispatchListeners=null,t}function u(e){var t=e._dispatchListeners,n=e._dispatchInstances;Array.isArray(t)&&m("103"),e.currentTarget=t?b.getNodeFromInstance(n):null;var r=t?t(e):null;return e.currentTarget=null,e._dispatchListeners=null,e._dispatchInstances=null,r}function d(e){return!!e._dispatchListeners}var p,f,m=n(6),h=n(181),g=(n(1),n(4),{injectComponentTree:function(e){p=e},injectTreeTraversal:function(e){f=e}}),b={isEndish:r,isMoveish:o,isStartish:i,executeDirectDispatch:u,executeDispatchesInOrder:l,executeDispatchesInOrderStopAtTrue:c,hasDispatches:d,getInstanceFromNode:function(e){return p.getInstanceFromNode(e)},getNodeFromInstance:function(e){return p.getNodeFromInstance(e)},isAncestor:function(e,t){return f.isAncestor(e,t)},getLowestCommonAncestor:function(e,t){return f.getLowestCommonAncestor(e,t)},getParentInstance:function(e){return f.getParentInstance(e)},traverseTwoPhase:function(e,t,n){return f.traverseTwoPhase(e,t,n)},traverseEnterLeave:function(e,t,n,r,o){return f.traverseEnterLeave(e,t,n,r,o)},injection:g};e.exports=b},function(e,t,n){"use strict";function r(e){var t=/[=:]/g,n={"=":"=0",":":"=2"};return"$"+(""+e).replace(t,function(e){return n[e]})}function o(e){var t=/(=0|=2)/g,n={"=0":"=","=2":":"};return(""+("."===e[0]&&"$"===e[1]?e.substring(2):e.substring(1))).replace(t,function(e){return n[e]})}var i={escape:r,unescape:o};e.exports=i},function(e,t,n){"use strict";function r(e){null!=e.checkedLink&&null!=e.valueLink&&l("87")}function o(e){r(e),(null!=e.value||null!=e.onChange)&&l("88")}function i(e){r(e),(null!=e.checked||null!=e.onChange)&&l("89")}function a(e){if(e){var t=e.getName();if(t)return" Check the render method of `"+t+"`."}return""}var l=n(6),s=n(71),c=n(621),u=(n(1),n(4),{button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0}),d={value:function(e,t,n){return!e[t]||u[e.type]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.")},checked:function(e,t,n){return!e[t]||e.onChange||e.readOnly||e.disabled?null:new Error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.")},onChange:s.PropTypes.func},p={},f={checkPropTypes:function(e,t,n){for(var r in d){if(d.hasOwnProperty(r))var o=d[r](t,r,e,"prop",null,c);if(o instanceof Error&&!(o.message in p)){p[o.message]=!0;a(n)}}},getValue:function(e){return e.valueLink?(o(e),e.valueLink.value):e.value},getChecked:function(e){return e.checkedLink?(i(e),e.checkedLink.value):e.checked},executeOnChange:function(e,t){return e.valueLink?(o(e),e.valueLink.requestChange(t.target.value)):e.checkedLink?(i(e),e.checkedLink.requestChange(t.target.checked)):e.onChange?e.onChange.call(void 0,t):void 0}};e.exports=f},function(e,t,n){"use strict";var r=n(6),o=(n(1),!1),i={replaceNodeWithMarkup:null,processChildrenUpdates:null,injection:{injectEnvironment:function(e){o&&r("104"),i.replaceNodeWithMarkup=e.replaceNodeWithMarkup,i.processChildrenUpdates=e.processChildrenUpdates,o=!0}}};e.exports=i},function(e,t,n){"use strict";function r(e,t,n){try{t(n)}catch(e){null===o&&(o=e)}}var o=null,i={invokeGuardedCallback:r,invokeGuardedCallbackWithCatch:r,rethrowCaughtError:function(){if(o){var e=o;throw o=null,e}}};e.exports=i},function(e,t,n){"use strict";function r(e){s.enqueueUpdate(e)}function o(e){var t=typeof e;if("object"!==t)return t;var n=e.constructor&&e.constructor.name||t,r=Object.keys(e);return r.length>0&&r.length<20?n+" (keys: "+r.join(", ")+")":n}function i(e,t){var n=l.get(e);if(!n){return null}return n}var a=n(6),l=(n(45),n(98)),s=(n(29),n(33)),c=(n(1),n(4),{isMounted:function(e){var t=l.get(e);return!!t&&!!t._renderedComponent},enqueueCallback:function(e,t,n){c.validateCallback(t,n);var o=i(e);if(!o)return null;o._pendingCallbacks?o._pendingCallbacks.push(t):o._pendingCallbacks=[t],r(o)},enqueueCallbackInternal:function(e,t){e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t],r(e)},enqueueForceUpdate:function(e){var t=i(e,"forceUpdate");t&&(t._pendingForceUpdate=!0,r(t))},enqueueReplaceState:function(e,t){var n=i(e,"replaceState");n&&(n._pendingStateQueue=[t],n._pendingReplaceState=!0,r(n))},enqueueSetState:function(e,t){var n=i(e,"setState");if(n){(n._pendingStateQueue||(n._pendingStateQueue=[])).push(t),r(n)}},enqueueElementInternal:function(e,t,n){e._pendingElement=t,e._context=n,r(e)},validateCallback:function(e,t){e&&"function"!=typeof e&&a("122",t,o(e))}});e.exports=c},function(e,t,n){"use strict";var r=function(e){return"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction?function(t,n,r,o){MSApp.execUnsafeLocalFunction(function(){return e(t,n,r,o)})}:e};e.exports=r},function(e,t,n){"use strict";function r(e){var t,n=e.keyCode;return"charCode"in e?0===(t=e.charCode)&&13===n&&(t=13):t=n,t>=32||13===t?t:0}e.exports=r},function(e,t,n){"use strict";function r(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var r=i[e];return!!r&&!!n[r]}function o(e){return r}var i={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};e.exports=o},function(e,t,n){"use strict";function r(e){var t=e.target||e.srcElement||window;return t.correspondingUseElement&&(t=t.correspondingUseElement),3===t.nodeType?t.parentNode:t}e.exports=r},function(e,t,n){"use strict";function r(e){if(e){var t=e.getName();if(t)return" Check the render method of `"+t+"`."}return""}function o(e){return"function"==typeof e&&void 0!==e.prototype&&"function"==typeof e.prototype.mountComponent&&"function"==typeof e.prototype.receiveComponent}function i(e,t){var n;if(null===e||e===!1)n=c.create(i);else if("object"==typeof e){var l=e,s=l.type;if("function"!=typeof s&&"string"!=typeof s){var p="";p+=r(l._owner),a("130",null==s?s:typeof s,p)}"string"==typeof l.type?n=u.createInternalComponent(l):o(l.type)?(n=new l.type(l),n.getHostNode||(n.getHostNode=n.getNativeNode)):n=new d(l)}else"string"==typeof e||"number"==typeof e?n=u.createInstanceForText(e):a("131",typeof e);return n._mountIndex=0,n._mountImage=null,n}var a=n(6),l=n(9),s=n(602),c=n(263),u=n(265),d=(n(646),n(1),n(4),function(e){this.construct(e)});l(d.prototype,s,{_instantiateReactComponent:i}),e.exports=i},function(e,t,n){"use strict";/**
* 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 r(e,t){if(!i.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,r=n in document;if(!r){var a=document.createElement("div");a.setAttribute(n,"return;"),r="function"==typeof a[n]}return!r&&o&&"wheel"===e&&(r=document.implementation.hasFeature("Events.wheel","3.0")),r}var o,i=n(19);i.canUseDOM&&(o=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),e.exports=r},function(e,t,n){"use strict";function r(e,t){var n=null===e||e===!1,r=null===t||t===!1;if(n||r)return n===r;var o=typeof e,i=typeof t;return"string"===o||"number"===o?"string"===i||"number"===i:"object"===i&&e.type===t.type&&e.key===t.key}e.exports=r},function(e,t,n){"use strict";var r=(n(9),n(28)),o=(n(4),r);e.exports=o},function(e,t,n){"use strict";var r=n(653),o=(n(280),n(654));n.d(t,"a",function(){return r.a}),n.d(t,"b",function(){return o.a})},function(e,t,n){"use strict";function r(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(e){}}t.a=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function i(e,t,n){if(!t)return e;var r=y(t),o=void 0;try{o=r.reduce(function(e,t){return e[t]},e)}catch(e){}return void 0!==o?o:n}function a(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1],n=arguments[2],r=y(t),o=void 0,i=e;(o=r.shift())&&r.length;)i[o]||(i[o]={}),i=i[o];return i[o]=n,e}function l(e,t){var n=t>e.length?0:e.length-t;return e.slice(n)}function s(e){return e[e.length-1]}function c(e){for(var t=[],n=0;n<e;n++)t.push(e);return t}function u(e,t,n,r){return e.sort(function(e,o){for(var i=0;i<t.length;i++){var a=t[i],l=n[i]===!1||"desc"===n[i],s=a(e,o);if(s)return l?-s:s}return n[0]?e[r]-o[r]:o[r]-e[r]})}function d(e,t){return e.filter(function(n,r){return!!t(n)&&(e.splice(r,1),!0)})}function p(e){try{return JSON.parse(JSON.stringify(e,function(e,t){return"function"==typeof t?t.toString():t}))}catch(t){return e}}function f(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];for(var r=0;r<t.length;r++)if(void 0!==t[r])return t[r]}function m(e){return e.reduce(function(e,t){return e+t},0)}function h(e){return function(t){var n=t.children,r=t.className,i=o(t,["children","className"]);return A.default.createElement("div",k({className:(0,I.default)(e,r)},i),n)}}function g(e,t){return e.reduce(function(e,n,r){var o="function"==typeof t?t(n,r):n[t];return e[o]=b(e[o])?e[o]:[],e[o].push(n),e},{})}function b(e){return Array.isArray(e)}function y(e){return v(e).join(".").replace("[",".").replace("]","").split(".")}function v(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];if(b(e))for(var n=0;n<e.length;n++)v(e[n],t);else t.push(e);return t}function _(e){return{className:e.className,style:e.style,rest:o(e,["className","style"])}}function x(e){var t={};for(var n in e)e.hasOwnProperty(n)&&void 0!==e[n]&&void 0!==e[n]&&(t[n]=e[n]);return t}function w(e){return!("desc"!==e.sort&&e.desc!==!0&&e.asc!==!1)}function C(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e;return"function"==typeof e?Object.getPrototypeOf(e).isReactComponent?A.default.createElement(e,t):e(t):n}Object.defineProperty(t,"__esModule",{value:!0});var k=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},E=n(10),A=r(E),S=n(88),I=r(S);t.default={get:i,set:a,takeRight:l,last:s,orderBy:u,range:c,remove:d,clone:p,getFirstDefined:f,sum:m,makeTemplateComponent:h,groupBy:g,isArray:b,splitProps:_,compactObject:x,isSortingDesc:w,normalizeComponent:C}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){if(e)return e;var t=x.default.history;return t.location?t.location:window.location}function a(e,t){if(e.query)return y({},e,{query:t,search:void 0});var n=(0,v.stringify)(t);return y({},e,{search:n.length?"?"+n:void 0})}function l(e,t){t=i(t);var n=Object.keys(e).reduce(function(t,n){var r=e[n];return null!=r&&""!==r&&(t[n]=r),t},{}),r=a(t,n);return delete r.key,r}function s(e,t,n){n=i(n);var r=n.query||(0,v.parse)(n.search),l=y({},r,o({},e,t));null!=t&&""!==t||delete l[e];var s=a(n,l);return delete s.key,s}function c(e,t){t=i(t);var n=t.query||(0,v.parse)(t.search),r=y({},n,e);Object.keys(e).forEach(function(t){var n=e[t];null!=n&&""!==n||delete r[t]});var o=a(t,r);return delete o.key,o}function u(e,t){var n=l(e,t);return x.default.history.replace(n)}function d(e,t){var n=l(e,t);return x.default.history.push(n)}function p(e,t,n){var r=s(e,t,n);return x.default.history.replace(r)}function f(e,t,n){var r=s(e,t,n);return x.default.history.push(r)}function m(e,t){var n=c(e,t);return x.default.history.replace(n)}function h(e,t){var n=c(e,t);return x.default.history.push(n)}function g(){var e=arguments.length<=0||void 0===arguments[0]?C.default.replaceIn:arguments[0],t=arguments[1],n=arguments[2],r=arguments[3];if(e===C.default.replaceIn)return p(t,n,r);if(e===C.default.pushIn)return f(t,n,r);var i=o({},t,n);return e===C.default.replace?u(i,r):e===C.default.push?d(i,r):void 0}function b(){var e=arguments.length<=0||void 0===arguments[0]?C.default.replaceIn:arguments[0],t=arguments[1],n=arguments[2];return e===C.default.replaceIn?m(t,n):e===C.default.pushIn?h(t,n):e===C.default.replace?u(t,n):e===C.default.push?d(t,n):void 0}t.__esModule=!0;var y=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t.replaceUrlQuery=u,t.pushUrlQuery=d,t.replaceInUrlQuery=p,t.pushInUrlQuery=f,t.multiReplaceInUrlQuery=m,t.multiPushInUrlQuery=h,t.updateUrlQuerySingle=g,t.updateUrlQueryMulti=b;var v=n(254),_=n(127),x=r(_),w=n(100),C=r(w)},function(e,t,n){"use strict";function r(e,t,n){this.props=e,this.context=t,this.refs=a,this.updater=n||i}var o=n(86),i=n(196),a=(n(290),n(82));n(1),n(4);r.prototype.isReactComponent={},r.prototype.setState=function(e,t){"object"!=typeof e&&"function"!=typeof e&&null!=e&&o("85"),this.updater.enqueueSetState(this,e),t&&this.updater.enqueueCallback(this,t,"setState")},r.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this),e&&this.updater.enqueueCallback(this,e,"forceUpdate")};e.exports=r},function(e,t,n){"use strict";function r(e,t){}var o=(n(4),{isMounted:function(e){return!1},enqueueCallback:function(e,t){},enqueueForceUpdate:function(e){r(e,"forceUpdate")},enqueueReplaceState:function(e,t){r(e,"replaceState")},enqueueSetState:function(e,t){r(e,"setState")}});e.exports=o},function(e,t,n){"use strict";function r(e){var t=[];return e.forEach(function(e){t.push(e.name),t.push(e.location)}),t.join("%00sp%00")}function o(e){var t=e.split("%00sp%00");return t.forEach(function(e,t,n){t%2==0&&(n[t/2]={name:e,location:n[t+1]})}),t.splice((t.length-1)/2+1),t}var i=n(204),a=n.n(i),l=n(200),s=n.n(l),c=n(50),u=n.n(c),d=n(51),p=n.n(d),f=n(52),m=n.n(f),h=n(54),g=n.n(h),b=n(53),y=n.n(b),v=n(10),_=n.n(v),x=n(663),w=n.n(x),C=n(652),k=n.n(C),E=n(120),A=(n.n(E),n(651)),S=(n.n(A),n(668)),I=(n.n(S),n(191)),T=n(103),P=n(694),O=(n.n(P),n(697)),M=n.n(O),R={data:{type:S.UrlQueryParamTypes.string}};n.i(S.configureUrlQuery)({history:T.a});var N=function(e){return{editing:e.editing}},L=function(e){function t(e,n){p()(this,t);var r=g()(this,(t.__proto__||u()(t)).call(this,e,n));r.renderEditable=r.renderEditable.bind(r),r.renderRemove=r.renderRemove.bind(r),r.state={},s()(r.state,e);var i=e.data?o(e.data):t.defaultState.data,a=function e(){var t=i[i.length-2],n=i[i.length-3];""!==t.name||""!==t.location?i.push({name:"",location:""}):void 0!==n&&""==n.name&&""==n.location&&(i.pop(),e())};return a(),a(),r.state.data=i,r.state.columns=[{Header:"Ruleset Name",accessor:"name",Cell:r.renderEditable("PHB")},{Header:"Location",accessor:"location",Cell:r.renderEditable("Local Bookstore")},{Header:"Remove",id:"remove",accessor:function(){return"x"},show:r.props.editing,Cell:r.renderRemove,width:100}],r}return y()(t,e),m()(t,[{key:"componentWillReceiveProps",value:function(e){!e.editing&&this.props.editing&&this.state.onChangeData(r(this.state.data));var t=[].concat(a()(this.state.columns));t[2].show=e.editing,this.setState({columns:t})}},{key:"renderRemove",value:function(e){var t=this;return _.a.createElement("span",{onClick:function(){var n=[].concat(a()(t.state.data));(""!==n[e.index].name||""!==n[e.index].location&&n.length>1)&&n.splice(e.index,1),t.setState({data:n})}},"x")}},{key:"renderEditable",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return function(n){return e.props.editing?_.a.createElement("div",null,_.a.createElement("div",{style:{backgroundColor:"#fafafa"},"data-ph":t,className:M.a.editableCell+" "+M.a.tableCell,contentEditable:!0,suppressContentEditableWarning:!0,onBlur:function(t){var r=[].concat(a()(e.state.data));r[n.index][n.column.id]=t.target.textContent,function e(){var t=r[r.length-2],n=r[r.length-3];""!==t.name||""!==t.location?r.push({name:"",location:""}):void 0!==n&&""==n.name&&""==n.location&&(r.pop(),e())}(),e.setState({data:r})}},e.state.data[n.index][n.column.id])):_.a.createElement("div",null,_.a.createElement(k.a,{className:M.a.tableCell},e.state.data[n.index][n.column.id]))}}},{key:"render",value:function(){return _.a.createElement("div",{className:"table-wrap",style:{marginBottom:"20px"}},_.a.createElement("br",null),_.a.createElement(w.a,{data:this.state.data,columns:this.state.columns,pageSize:this.state.data.length,showPageSizeOptions:!1,showPagination:!1,key:this.props.editing}))}}]),t}(_.a.PureComponent);L.defaultState={data:[{name:"",location:""},{name:"",location:""}]},t.a=n.i(S.addUrlProps)({urlPropsQueryConfig:R})(n.i(I.b)(N)(L))},function(e,t,n){e.exports={default:n(322),__esModule:!0}},function(e,t,n){e.exports={default:n(323),__esModule:!0}},function(e,t,n){e.exports={default:n(325),__esModule:!0}},function(e,t,n){e.exports={default:n(326),__esModule:!0}},function(e,t,n){e.exports={default:n(327),__esModule:!0}},function(e,t,n){e.exports={default:n(331),__esModule:!0}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(198),i=r(o);t.default=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return(0,i.default)(e)}},function(e,t,n){e.exports=n(25).document&&document.documentElement},function(e,t,n){e.exports=!n(46)&&!n(73)(function(){return 7!=Object.defineProperty(n(133)("div"),"a",{get:function(){return 7}}).a})},function(e,t,n){var r=n(89);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==r(e)?e.split(""):Object(e)}},function(e,t,n){var r=n(75),o=n(17)("iterator"),i=Array.prototype;e.exports=function(e){return void 0!==e&&(r.Array===e||i[o]===e)}},function(e,t,n){var r=n(37);e.exports=function(e,t,n,o){try{return o?t(r(n)[0],n[1]):t(n)}catch(t){var i=e.return;throw void 0!==i&&r(i.call(e)),t}}},function(e,t,n){"use strict";var r=n(104),o=n(38),i=n(217),a=n(58),l=n(57),s=n(75),c=n(342),u=n(106),d=n(214),p=n(17)("iterator"),f=!([].keys&&"next"in[].keys()),m="keys",h="values",g=function(){return this};e.exports=function(e,t,n,b,y,v,_){c(n,t,b);var x,w,C,k=function(e){if(!f&&e in I)return I[e];switch(e){case m:return function(){return new n(this,e)};case h:return function(){return new n(this,e)}}return function(){return new n(this,e)}},E=t+" Iterator",A=y==h,S=!1,I=e.prototype,T=I[p]||I["@@iterator"]||y&&I[y],P=T||k(y),O=y?A?k("entries"):P:void 0,M="Array"==t?I.entries||T:T;if(M&&(C=d(M.call(new e)))!==Object.prototype&&(u(C,E,!0),r||l(C,p)||a(C,p,g)),A&&T&&T.name!==h&&(S=!0,P=function(){return T.call(this)}),r&&!_||!f&&!S&&I[p]||a(I,p,P),s[t]=P,s[E]=g,y)if(x={values:A?P:k(h),keys:v?P:k(m),entries:O},_)for(w in x)w in I||i(I,w,x[w]);else o(o.P+o.F*(f||S),t,x);return x}},function(e,t,n){var r=n(17)("iterator"),o=!1;try{var i=[7][r]();i.return=function(){o=!0},Array.from(i,function(){throw 2})}catch(e){}e.exports=function(e,t){if(!t&&!o)return!1;var n=!1;try{var i=[7],a=i[r]();a.next=function(){return{done:n=!0}},i[r]=function(){return a},e(i)}catch(e){}return n}},function(e,t,n){var r=n(105),o=n(90),i=n(59),a=n(141),l=n(57),s=n(206),c=Object.getOwnPropertyDescriptor;t.f=n(46)?c:function(e,t){if(e=i(e),t=a(t,!0),s)try{return c(e,t)}catch(e){}if(l(e,t))return o(!r.f.call(e,t),e[t])}},function(e,t,n){var r=n(215),o=n(134).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(e){return r(e,o)}},function(e,t,n){var r=n(57),o=n(91),i=n(137)("IE_PROTO"),a=Object.prototype;e.exports=Object.getPrototypeOf||function(e){return e=o(e),r(e,i)?e[i]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?a:null}},function(e,t,n){var r=n(57),o=n(59),i=n(336)(!1),a=n(137)("IE_PROTO");e.exports=function(e,t){var n,l=o(e),s=0,c=[];for(n in l)n!=a&&r(l,n)&&c.push(n);for(;t.length>s;)r(l,n=t[s++])&&(~i(c,n)||c.push(n));return c}},function(e,t,n){var r=n(38),o=n(14),i=n(73);e.exports=function(e,t){var n=(o.Object||{})[e]||Object[e],a={};a[e]=t(n),r(r.S+r.F*i(function(){n(1)}),"Object",a)}},function(e,t,n){e.exports=n(58)},function(e,t,n){var r,o,i,a=n(72),l=n(340),s=n(205),c=n(133),u=n(25),d=u.process,p=u.setImmediate,f=u.clearImmediate,m=u.MessageChannel,h=0,g={},b="onreadystatechange",y=function(){var e=+this;if(g.hasOwnProperty(e)){var t=g[e];delete g[e],t()}},v=function(e){y.call(e.data)};p&&f||(p=function(e){for(var t=[],n=1;arguments.length>n;)t.push(arguments[n++]);return g[++h]=function(){l("function"==typeof e?e:Function(e),t)},r(h),h},f=function(e){delete g[e]},"process"==n(89)(d)?r=function(e){d.nextTick(a(y,e,1))}:m?(o=new m,i=o.port2,o.port1.onmessage=v,r=a(i.postMessage,i,1)):u.addEventListener&&"function"==typeof postMessage&&!u.importScripts?(r=function(e){u.postMessage(e+"","*")},u.addEventListener("message",v,!1)):r=b in c("script")?function(e){s.appendChild(c("script"))[b]=function(){s.removeChild(this),y.call(e)}}:function(e){setTimeout(a(y,e,1),0)}),e.exports={set:p,clear:f}},function(e,t){},function(e,t,n){var r=n(30);e.exports=function(e,t){if("number"!=typeof e&&"Number"!=r(e))throw TypeError(t);return+e}},function(e,t,n){"use strict";var r=n(16),o=n(67),i=n(15);e.exports=[].copyWithin||function(e,t){var n=r(this),a=i(n.length),l=o(e,a),s=o(t,a),c=arguments.length>2?arguments[2]:void 0,u=Math.min((void 0===c?a:o(c,a))-s,a-l),d=1;for(s<l&&l<s+u&&(d=-1,s+=u-1,l+=u-1);u-- >0;)s in n?n[l]=n[s]:delete n[l],l+=d,s+=d;return n}},function(e,t,n){var r=n(78);e.exports=function(e,t){var n=[];return r(e,!1,n.push,n,t),n}},function(e,t,n){var r=n(20),o=n(16),i=n(94),a=n(15);e.exports=function(e,t,n,l,s){r(t);var c=o(e),u=i(c),d=a(c.length),p=s?d-1:0,f=s?-1:1;if(n<2)for(;;){if(p in u){l=u[p],p+=f;break}if(p+=f,s?p<0:d<=p)throw TypeError("Reduce of empty array with no initial value")}for(;s?p>=0:d>p;p+=f)p in u&&(l=t(l,u[p],p,c));return l}},function(e,t,n){"use strict";var r=n(20),o=n(7),i=n(113),a=[].slice,l={},s=function(e,t,n){if(!(t in l)){for(var r=[],o=0;o<t;o++)r[o]="a["+o+"]";l[t]=Function("F,a","return new F("+r.join(",")+")")}return l[t](e,n)};e.exports=Function.bind||function(e){var t=r(this),n=a.call(arguments,1),l=function(){var r=n.concat(a.call(arguments));return this instanceof l?s(t,r.length,r):i(t,r,e)};return o(t.prototype)&&(l.prototype=t.prototype),l}},function(e,t,n){"use strict";var r=n(12).f,o=n(62),i=n(65),a=n(41),l=n(60),s=n(31),c=n(78),u=n(155),d=n(231),p=n(66),f=n(11),m=n(47).fastKey,h=f?"_s":"size",g=function(e,t){var n,r=m(t);if("F"!==r)return e._i[r];for(n=e._f;n;n=n.n)if(n.k==t)return n};e.exports={getConstructor:function(e,t,n,u){var d=e(function(e,r){l(e,d,t,"_i"),e._i=o(null),e._f=void 0,e._l=void 0,e[h]=0,void 0!=r&&c(r,n,e[u],e)});return i(d.prototype,{clear:function(){for(var e=this,t=e._i,n=e._f;n;n=n.n)n.r=!0,n.p&&(n.p=n.p.n=void 0),delete t[n.i];e._f=e._l=void 0,e[h]=0},delete:function(e){var t=this,n=g(t,e);if(n){var r=n.n,o=n.p;delete t._i[n.i],n.r=!0,o&&(o.n=r),r&&(r.p=o),t._f==n&&(t._f=r),t._l==n&&(t._l=o),t[h]--}return!!n},forEach:function(e){l(this,d,"forEach");for(var t,n=a(e,arguments.length>1?arguments[1]:void 0,3);t=t?t.n:this._f;)for(n(t.v,t.k,this);t&&t.r;)t=t.p},has:function(e){return!!g(this,e)}}),f&&r(d.prototype,"size",{get:function(){return s(this[h])}}),d},def:function(e,t,n){var r,o,i=g(e,t);return i?i.v=n:(e._l=i={i:o=m(t,!0),k:t,v:n,p:r=e._l,n:void 0,r:!1},e._f||(e._f=i),r&&(r.n=i),e[h]++,"F"!==o&&(e._i[o]=i)),e},getEntry:g,setStrong:function(e,t,n){u(e,t,function(e,t){this._t=e,this._k=t,this._l=void 0},function(){for(var e=this,t=e._k,n=e._l;n&&n.r;)n=n.p;return e._t&&(e._l=n=n?n.n:e._t._f)?"keys"==t?d(0,n.k):"values"==t?d(0,n.v):d(0,[n.k,n.v]):(e._t=void 0,d(1))},n?"entries":"values",!n,!0),p(t)}}},function(e,t,n){var r=n(93),o=n(222);e.exports=function(e){return function(){if(r(this)!=e)throw TypeError(e+"#toJSON isn't generic");return o(this)}}},function(e,t,n){"use strict";var r=n(65),o=n(47).getWeak,i=n(2),a=n(7),l=n(60),s=n(78),c=n(34),u=n(18),d=c(5),p=c(6),f=0,m=function(e){return e._l||(e._l=new h)},h=function(){this.a=[]},g=function(e,t){return d(e.a,function(e){return e[0]===t})};h.prototype={get:function(e){var t=g(this,e);if(t)return t[1]},has:function(e){return!!g(this,e)},set:function(e,t){var n=g(this,e);n?n[1]=t:this.a.push([e,t])},delete:function(e){var t=p(this.a,function(t){return t[0]===e});return~t&&this.a.splice(t,1),!!~t}},e.exports={getConstructor:function(e,t,n,i){var c=e(function(e,r){l(e,c,t,"_i"),e._i=f++,e._l=void 0,void 0!=r&&s(r,n,e[i],e)});return r(c.prototype,{delete:function(e){if(!a(e))return!1;var t=o(e);return t===!0?m(this).delete(e):t&&u(t,this._i)&&delete t[this._i]},has:function(e){if(!a(e))return!1;var t=o(e);return t===!0?m(this).has(e):t&&u(t,this._i)}}),c},def:function(e,t,n){var r=o(i(t),!0);return r===!0?m(e).set(t,n):r[e._i]=n,e},ufstore:m}},function(e,t,n){e.exports=!n(11)&&!n(5)(function(){return 7!=Object.defineProperty(n(147)("div"),"a",{get:function(){return 7}}).a})},function(e,t,n){var r=n(7),o=Math.floor;e.exports=function(e){return!r(e)&&isFinite(e)&&o(e)===e}},function(e,t,n){var r=n(2);e.exports=function(e,t,n,o){try{return o?t(r(n)[0],n[1]):t(n)}catch(t){var i=e.return;throw void 0!==i&&r(i.call(e)),t}}},function(e,t){e.exports=function(e,t){return{value:t,done:!!e}}},function(e,t){e.exports=Math.log1p||function(e){return(e=+e)>-1e-8&&e<1e-8?e-e*e/2:Math.log(1+e)}},function(e,t,n){"use strict";var r=n(64),o=n(117),i=n(95),a=n(16),l=n(94),s=Object.assign;e.exports=!s||n(5)(function(){var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach(function(e){t[e]=e}),7!=s({},e)[n]||Object.keys(s({},t)).join("")!=r})?function(e,t){for(var n=a(e),s=arguments.length,c=1,u=o.f,d=i.f;s>c;)for(var p,f=l(arguments[c++]),m=u?r(f).concat(u(f)):r(f),h=m.length,g=0;h>g;)d.call(f,p=m[g++])&&(n[p]=f[p]);return n}:s},function(e,t,n){var r=n(12),o=n(2),i=n(64);e.exports=n(11)?Object.defineProperties:function(e,t){o(e);for(var n,a=i(t),l=a.length,s=0;l>s;)r.f(e,n=a[s++],t[n]);return e}},function(e,t,n){var r=n(24),o=n(63).f,i={}.toString,a="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],l=function(e){try{return o(e)}catch(e){return a.slice()}};e.exports.f=function(e){return a&&"[object Window]"==i.call(e)?l(e):o(r(e))}},function(e,t,n){var r=n(18),o=n(24),i=n(109)(!1),a=n(160)("IE_PROTO");e.exports=function(e,t){var n,l=o(e),s=0,c=[];for(n in l)n!=a&&r(l,n)&&c.push(n);for(;t.length>s;)r(l,n=t[s++])&&(~i(c,n)||c.push(n));return c}},function(e,t,n){var r=n(64),o=n(24),i=n(95).f;e.exports=function(e){return function(t){for(var n,a=o(t),l=r(a),s=l.length,c=0,u=[];s>c;)i.call(a,n=l[c++])&&u.push(e?[n,a[n]]:a[n]);return u}}},function(e,t,n){var r=n(63),o=n(117),i=n(2),a=n(3).Reflect;e.exports=a&&a.ownKeys||function(e){var t=r.f(i(e)),n=o.f;return n?t.concat(n(e)):t}},function(e,t,n){var r=n(3).parseFloat,o=n(81).trim;e.exports=1/r(n(165)+"-0")!=-(1/0)?function(e){var t=o(String(e),3),n=r(t);return 0===n&&"-"==t.charAt(0)?-0:n}:r},function(e,t,n){var r=n(3).parseInt,o=n(81).trim,i=n(165),a=/^[\-+]?0[xX]/;e.exports=8!==r(i+"08")||22!==r(i+"0x16")?function(e,t){var n=o(String(e),3);return r(n,t>>>0||(a.test(n)?16:10))}:r},function(e,t){e.exports=Object.is||function(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t}},function(e,t,n){var r=n(15),o=n(164),i=n(31);e.exports=function(e,t,n,a){var l=String(i(e)),s=l.length,c=void 0===n?" ":String(n),u=r(t);if(u<=s||""==c)return l;var d=u-s,p=o.call(c,Math.ceil(d/c.length));return p.length>d&&(p=p.slice(0,d)),a?p+l:l+p}},function(e,t,n){t.f=n(8)},function(e,t,n){"use strict";var r=n(225);e.exports=n(110)("Map",function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0)}},{get:function(e){var t=r.getEntry(this,e);return t&&t.v},set:function(e,t){return r.def(this,0===e?0:e,t)}},r,!0)},function(e,t,n){n(11)&&"g"!=/./g.flags&&n(12).f(RegExp.prototype,"flags",{configurable:!0,get:n(112)})},function(e,t,n){"use strict";var r=n(225);e.exports=n(110)("Set",function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0)}},{add:function(e){return r.def(this,e=0===e?0:e,e)}},r)},function(e,t,n){"use strict";var r,o=n(34)(0),i=n(22),a=n(47),l=n(233),s=n(227),c=n(7),u=a.getWeak,d=Object.isExtensible,p=s.ufstore,f={},m=function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0)}},h={get:function(e){if(c(e)){var t=u(e);return t===!0?p(this).get(e):t?t[this._i]:void 0}},set:function(e,t){return s.def(this,e,t)}},g=e.exports=n(110)("WeakMap",m,h,s,!0,!0);7!=(new g).set((Object.freeze||Object)(f),7).get(f)&&(r=s.getConstructor(m),l(r.prototype,h),a.NEED=!0,o(["delete","has","get","set"],function(e){var t=g.prototype,n=t[e];i(t,e,function(t,o){if(c(t)&&!d(t)){this._f||(this._f=new r);var i=this._f[e](t,o);return"set"==e?this:i}return n.call(this,t,o)})}))},function(e,t,n){"use strict";var r=n(28),o={listen:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!1),{remove:function(){e.removeEventListener(t,n,!1)}}):e.attachEvent?(e.attachEvent("on"+t,n),{remove:function(){e.detachEvent("on"+t,n)}}):void 0},capture:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!0),{remove:function(){e.removeEventListener(t,n,!0)}}):{remove:r}},registerDefault:function(){}};e.exports=o},function(e,t,n){"use strict";function r(e){try{e.focus()}catch(e){}}e.exports=r},function(e,t,n){"use strict";function r(){if("undefined"==typeof document)return null;try{return document.activeElement||document.body}catch(e){return document.body}}e.exports=r},function(e,t,n){"use strict";t.__esModule=!0;t.addLeadingSlash=function(e){return"/"===e.charAt(0)?e:"/"+e},t.stripLeadingSlash=function(e){return"/"===e.charAt(0)?e.substr(1):e},t.stripPrefix=function(e,t){return 0===e.indexOf(t)?e.substr(t.length):e},t.stripTrailingSlash=function(e){return"/"===e.charAt(e.length-1)?e.slice(0,-1):e},t.parsePath=function(e){var t=e||"/",n="",r="",o=t.indexOf("#");o!==-1&&(r=t.substr(o),t=t.substr(0,o));var i=t.indexOf("?");return i!==-1&&(n=t.substr(i),t=t.substr(0,i)),t=decodeURI(t),{pathname:t,search:"?"===n?"":n,hash:"#"===r?"":r}},t.createPath=function(e){var t=e.pathname,n=e.search,r=e.hash,o=encodeURI(t||"/");return n&&"?"!==n&&(o+="?"===n.charAt(0)?n:"?"+n),r&&"#"!==r&&(o+="#"===r.charAt(0)?r:"#"+r),o}},function(e,t,n){"use strict";var r=function(e,t,n,r,o,i,a,l){if(!e){var s;if(void 0===t)s=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[n,r,o,i,a,l],u=0;s=new Error(t.replace(/%s/g,function(){return c[u++]})),s.name="Invariant Violation"}throw s.framesToPop=1,s}};e.exports=r},function(e,t,n){"use strict";var r=n(585),o=r.a.Symbol;t.a=o},function(e,t,n){"use strict";function r(e){switch(e.arrayFormat){case"index":return function(t,n,r){return null===n?[i(t,e),"[",r,"]"].join(""):[i(t,e),"[",i(r,e),"]=",i(n,e)].join("")};case"bracket":return function(t,n){return null===n?i(t,e):[i(t,e),"[]=",i(n,e)].join("")};default:return function(t,n){return null===n?i(t,e):[i(t,e),"=",i(n,e)].join("")}}}function o(e){var t;switch(e.arrayFormat){case"index":return function(e,n,r){if(t=/\[(\d*)\]$/.exec(e),e=e.replace(/\[\d*\]$/,""),!t)return void(r[e]=n);void 0===r[e]&&(r[e]={}),r[e][t[1]]=n};case"bracket":return function(e,n,r){if(t=/(\[\])$/.exec(e),e=e.replace(/\[\]$/,""),!t||void 0===r[e])return void(r[e]=n);r[e]=[].concat(r[e],n)};default:return function(e,t,n){if(void 0===n[e])return void(n[e]=t);n[e]=[].concat(n[e],t)}}}function i(e,t){return t.encode?t.strict?l(e):encodeURIComponent(e):e}function a(e){return Array.isArray(e)?e.sort():"object"==typeof e?a(Object.keys(e)).sort(function(e,t){return Number(e)-Number(t)}).map(function(t){return e[t]}):e}var l=n(692),s=n(9);t.extract=function(e){return e.split("?")[1]||""},t.parse=function(e,t){t=s({arrayFormat:"none"},t);var n=o(t),r=Object.create(null);return"string"!=typeof e?r:(e=e.trim().replace(/^(\?|#|&)/,""))?(e.split("&").forEach(function(e){var t=e.replace(/\+/g," ").split("="),o=t.shift(),i=t.length>0?t.join("="):void 0;i=void 0===i?null:decodeURIComponent(i),n(decodeURIComponent(o),i,r)}),Object.keys(r).sort().reduce(function(e,t){var n=r[t];return Boolean(n)&&"object"==typeof n&&!Array.isArray(n)?e[t]=a(n):e[t]=n,e},Object.create(null))):r},t.stringify=function(e,t){t=s({encode:!0,strict:!0,arrayFormat:"none"},t);var n=r(t);return e?Object.keys(e).sort().map(function(r){var o=e[r];if(void 0===o)return"";if(null===o)return i(r,t);if(Array.isArray(o)){var a=[];return o.slice().forEach(function(e){void 0!==e&&a.push(n(r,e,a.length))}),a.join("&")}return i(r,t)+"="+i(o,t)}).filter(function(e){return e.length>0}).join("&"):""}},function(e,t,n){"use strict";function r(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var o={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridRow:!0,gridColumn:!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},i=["Webkit","ms","Moz","O"];Object.keys(o).forEach(function(e){i.forEach(function(t){o[r(t,e)]=o[e]})});var a={background:{backgroundAttachment:!0,backgroundColor:!0,backgroundImage:!0,backgroundPositionX:!0,backgroundPositionY:!0,backgroundRepeat:!0},backgroundPosition:{backgroundPositionX:!0,backgroundPositionY:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0},outline:{outlineWidth:!0,outlineStyle:!0,outlineColor:!0}},l={isUnitlessNumber:o,shorthandPropertyExpansions:a};e.exports=l},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var o=n(6),i=n(69),a=(n(1),function(){function e(t){r(this,e),this._callbacks=null,this._contexts=null,this._arg=t}return e.prototype.enqueue=function(e,t){this._callbacks=this._callbacks||[],this._callbacks.push(e),this._contexts=this._contexts||[],this._contexts.push(t)},e.prototype.notifyAll=function(){var e=this._callbacks,t=this._contexts,n=this._arg;if(e&&t){e.length!==t.length&&o("24"),this._callbacks=null,this._contexts=null;for(var r=0;r<e.length;r++)e[r].call(t[r],n);e.length=0,t.length=0}},e.prototype.checkpoint=function(){return this._callbacks?this._callbacks.length:0},e.prototype.rollback=function(e){this._callbacks&&this._contexts&&(this._callbacks.length=e,this._contexts.length=e)},e.prototype.reset=function(){this._callbacks=null,this._contexts=null},e.prototype.destructor=function(){this.reset()},e}());e.exports=i.addPoolingTo(a)},function(e,t,n){"use strict";function r(e){return!!c.hasOwnProperty(e)||!s.hasOwnProperty(e)&&(l.test(e)?(c[e]=!0,!0):(s[e]=!0,!1))}function o(e,t){return null==t||e.hasBooleanValue&&!t||e.hasNumericValue&&isNaN(t)||e.hasPositiveNumericValue&&t<1||e.hasOverloadedBooleanValue&&t===!1}var i=n(84),a=(n(13),n(29),n(649)),l=(n(4),new RegExp("^["+i.ATTRIBUTE_NAME_START_CHAR+"]["+i.ATTRIBUTE_NAME_CHAR+"]*$")),s={},c={},u={createMarkupForID:function(e){return i.ID_ATTRIBUTE_NAME+"="+a(e)},setAttributeForID:function(e,t){e.setAttribute(i.ID_ATTRIBUTE_NAME,t)},createMarkupForRoot:function(){return i.ROOT_ATTRIBUTE_NAME+'=""'},setAttributeForRoot:function(e){e.setAttribute(i.ROOT_ATTRIBUTE_NAME,"")},createMarkupForProperty:function(e,t){var n=i.properties.hasOwnProperty(e)?i.properties[e]:null;if(n){if(o(n,t))return"";var r=n.attributeName;return n.hasBooleanValue||n.hasOverloadedBooleanValue&&t===!0?r+'=""':r+"="+a(t)}return i.isCustomAttribute(e)?null==t?"":e+"="+a(t):null},createMarkupForCustomAttribute:function(e,t){return r(e)&&null!=t?e+"="+a(t):""},setValueForProperty:function(e,t,n){var r=i.properties.hasOwnProperty(t)?i.properties[t]:null;if(r){var a=r.mutationMethod;if(a)a(e,n);else{if(o(r,n))return void this.deleteValueForProperty(e,t);if(r.mustUseProperty)e[r.propertyName]=n;else{var l=r.attributeName,s=r.attributeNamespace;s?e.setAttributeNS(s,l,""+n):r.hasBooleanValue||r.hasOverloadedBooleanValue&&n===!0?e.setAttribute(l,""):e.setAttribute(l,""+n)}}}else if(i.isCustomAttribute(t))return void u.setValueForAttribute(e,t,n)},setValueForAttribute:function(e,t,n){if(r(t)){null==n?e.removeAttribute(t):e.setAttribute(t,""+n)}},deleteValueForAttribute:function(e,t){e.removeAttribute(t)},deleteValueForProperty:function(e,t){var n=i.properties.hasOwnProperty(t)?i.properties[t]:null;if(n){var r=n.mutationMethod;if(r)r(e,void 0);else if(n.mustUseProperty){var o=n.propertyName;n.hasBooleanValue?e[o]=!1:e[o]=""}else e.removeAttribute(n.attributeName)}else i.isCustomAttribute(t)&&e.removeAttribute(t)}};e.exports=u},function(e,t,n){"use strict";var r={hasCachedChildNodes:1};e.exports=r},function(e,t,n){"use strict";function r(e,t){var n={_topLevelWrapper:e,_idCounter:1,_ownerDocument:t?t.nodeType===o?t:t.ownerDocument:null,_node:t,_tag:t?t.nodeName.toLowerCase():null,_namespaceURI:t?t.namespaceURI:null};return n}var o=(n(190),9);e.exports=r},function(e,t,n){"use strict";function r(){if(this._rootNodeID&&this._wrapperState.pendingUpdate){this._wrapperState.pendingUpdate=!1;var e=this._currentElement.props,t=l.getValue(e);null!=t&&o(this,Boolean(e.multiple),t)}}function o(e,t,n){var r,o,i=s.getNodeFromInstance(e).options;if(t){for(r={},o=0;o<n.length;o++)r[""+n[o]]=!0;for(o=0;o<i.length;o++){var a=r.hasOwnProperty(i[o].value);i[o].selected!==a&&(i[o].selected=a)}}else{for(r=""+n,o=0;o<i.length;o++)if(i[o].value===r)return void(i[o].selected=!0);i.length&&(i[0].selected=!0)}}function i(e){var t=this._currentElement.props,n=l.executeOnChange(t,e);return this._rootNodeID&&(this._wrapperState.pendingUpdate=!0),c.asap(r,this),n}var a=n(9),l=n(179),s=n(13),c=n(33),u=(n(4),!1),d={getHostProps:function(e,t){return a({},t,{onChange:e._wrapperState.onChange,value:void 0})},mountWrapper:function(e,t){var n=l.getValue(t);e._wrapperState={pendingUpdate:!1,initialValue:null!=n?n:t.defaultValue,listeners:null,onChange:i.bind(e),wasMultiple:Boolean(t.multiple)},void 0===t.value||void 0===t.defaultValue||u||(u=!0)},getSelectValueContext:function(e){return e._wrapperState.initialValue},postUpdateWrapper:function(e){var t=e._currentElement.props;e._wrapperState.initialValue=void 0;var n=e._wrapperState.wasMultiple;e._wrapperState.wasMultiple=Boolean(t.multiple);var r=l.getValue(t);null!=r?(e._wrapperState.pendingUpdate=!1,o(e,Boolean(t.multiple),r)):n!==Boolean(t.multiple)&&(null!=t.defaultValue?o(e,Boolean(t.multiple),t.defaultValue):o(e,Boolean(t.multiple),t.multiple?[]:""))}};e.exports=d},function(e,t,n){"use strict";function r(){this.reinitializeTransaction()}var o=n(9),i=n(33),a=n(123),l=n(28),s={initialize:l,close:function(){p.isBatchingUpdates=!1}},c={initialize:l,close:i.flushBatchedUpdates.bind(i)},u=[c,s];o(r.prototype,a,{getTransactionWrappers:function(){return u}});var d=new r,p={isBatchingUpdates:!1,batchedUpdates:function(e,t,n,r,o,i){var a=p.isBatchingUpdates;return p.isBatchingUpdates=!0,a?e(t,n,r,o,i):d.perform(e,null,t,n,r,o,i)}};e.exports=p},function(e,t,n){"use strict";function r(){C||(C=!0,y.EventEmitter.injectReactEventListener(b),y.EventPluginHub.injectEventPluginOrder(l),y.EventPluginUtils.injectComponentTree(p),y.EventPluginUtils.injectTreeTraversal(m),y.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:w,EnterLeaveEventPlugin:s,ChangeEventPlugin:a,SelectEventPlugin:x,BeforeInputEventPlugin:i}),y.HostComponent.injectGenericComponentClass(d),y.HostComponent.injectTextComponentClass(h),y.DOMProperty.injectDOMPropertyConfig(o),y.DOMProperty.injectDOMPropertyConfig(c),y.DOMProperty.injectDOMPropertyConfig(_),y.EmptyComponent.injectEmptyComponentFactory(function(e){return new f(e)}),y.Updates.injectReconcileTransaction(v),y.Updates.injectBatchingStrategy(g),y.Component.injectEnvironment(u))}var o=n(590),i=n(592),a=n(594),l=n(596),s=n(597),c=n(599),u=n(601),d=n(604),p=n(13),f=n(605),m=n(614),h=n(612),g=n(261),b=n(617),y=n(618),v=n(622),_=n(627),x=n(628),w=n(629),C=!1;e.exports={inject:r}},function(e,t,n){"use strict";var r,o={injectEmptyComponentFactory:function(e){r=e}},i={create:function(e){return r(e)}};i.injection=o,e.exports=i},function(e,t,n){"use strict";var r={logTopLevelRenders:!1};e.exports=r},function(e,t,n){"use strict";function r(e){return l||a("111",e.type),new l(e)}function o(e){return new s(e)}function i(e){return e instanceof s}var a=n(6),l=(n(1),null),s=null,c={injectGenericComponentClass:function(e){l=e},injectTextComponentClass:function(e){s=e}},u={createInternalComponent:r,createInstanceForText:o,isTextComponent:i,injection:c};e.exports=u},function(e,t,n){"use strict";function r(e){return i(document.documentElement,e)}var o=n(610),i=n(560),a=n(249),l=n(250),s={hasSelectionCapabilities:function(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&"text"===e.type||"textarea"===t||"true"===e.contentEditable)},getSelectionInformation:function(){var e=l();return{focusedElem:e,selectionRange:s.hasSelectionCapabilities(e)?s.getSelection(e):null}},restoreSelection:function(e){var t=l(),n=e.focusedElem,o=e.selectionRange;t!==n&&r(n)&&(s.hasSelectionCapabilities(n)&&s.setSelection(n,o),a(n))},getSelection:function(e){var t;if("selectionStart"in e)t={start:e.selectionStart,end:e.selectionEnd};else if(document.selection&&e.nodeName&&"input"===e.nodeName.toLowerCase()){var n=document.selection.createRange();n.parentElement()===e&&(t={start:-n.moveStart("character",-e.value.length),end:-n.moveEnd("character",-e.value.length)})}else t=o.getOffsets(e);return t||{start:0,end:0}},setSelection:function(e,t){var n=t.start,r=t.end;if(void 0===r&&(r=n),"selectionStart"in e)e.selectionStart=n,e.selectionEnd=Math.min(r,e.value.length);else if(document.selection&&e.nodeName&&"input"===e.nodeName.toLowerCase()){var i=e.createTextRange();i.collapse(!0),i.moveStart("character",n),i.moveEnd("character",r-n),i.select()}else o.setOffsets(e,t)}};e.exports=s},function(e,t,n){"use strict";var r=n(640),o=/\/?>/,i=/^<\!\-\-/,a={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=r(e);return i.test(e)?e:e.replace(o," "+a.CHECKSUM_ATTR_NAME+'="'+t+'"$&')},canReuseMarkup:function(e,t){var n=t.getAttribute(a.CHECKSUM_ATTR_NAME);return n=n&&parseInt(n,10),r(e)===n}};e.exports=a},function(e,t,n){"use strict";function r(e,t){for(var n=Math.min(e.length,t.length),r=0;r<n;r++)if(e.charAt(r)!==t.charAt(r))return r;return e.length===t.length?-1:n}function o(e){return e?e.nodeType===N?e.documentElement:e.firstChild:null}function i(e){return e.getAttribute&&e.getAttribute(O)||""}function a(e,t,n,r,o){var i;if(x.logTopLevelRenders){var a=e._currentElement.props.child,l=a.type;i="React mount: "+("string"==typeof l?l:l.displayName||l.name),console.time(i)}var s=k.mountComponent(e,n,null,v(e,t),o,0);i&&console.timeEnd(i),e._renderedComponent._topLevelWrapper=e,z._mountImageIntoNode(s,t,e,r,n)}function l(e,t,n,r){var o=A.ReactReconcileTransaction.getPooled(!n&&_.useCreateElement);o.perform(a,null,e,t,o,n,r),A.ReactReconcileTransaction.release(o)}function s(e,t,n){for(k.unmountComponent(e,n),t.nodeType===N&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)}function c(e){var t=o(e);if(t){var n=y.getInstanceFromNode(t);return!(!n||!n._hostParent)}}function u(e){return!(!e||e.nodeType!==R&&e.nodeType!==N&&e.nodeType!==L)}function d(e){var t=o(e),n=t&&y.getInstanceFromNode(t);return n&&!n._hostParent?n:null}function p(e){var t=d(e);return t?t._hostContainerInfo._topLevelWrapper:null}var f=n(6),m=n(83),h=n(84),g=n(71),b=n(121),y=(n(45),n(13)),v=n(259),_=n(606),x=n(264),w=n(98),C=(n(29),n(267)),k=n(70),E=n(182),A=n(33),S=n(82),I=n(187),T=(n(1),n(125)),P=n(189),O=(n(4),h.ID_ATTRIBUTE_NAME),M=h.ROOT_ATTRIBUTE_NAME,R=1,N=9,L=11,D={},j=1,F=function(){this.rootID=j++};F.prototype.isReactComponent={},F.prototype.render=function(){return this.props.child},F.isReactTopLevelWrapper=!0;var z={TopLevelWrapper:F,_instancesByReactRootID:D,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,t,n,r,o){return z.scrollMonitor(r,function(){E.enqueueElementInternal(e,t,n),o&&E.enqueueCallbackInternal(e,o)}),e},_renderNewRootComponent:function(e,t,n,r){u(t)||f("37"),b.ensureScrollValueMonitoring();var o=I(e,!1);return A.batchedUpdates(l,o,t,n,r),D[o._instance.rootID]=o,o},renderSubtreeIntoContainer:function(e,t,n,r){return null!=e&&w.has(e)||f("38"),z._renderSubtreeIntoContainer(e,t,n,r)},_renderSubtreeIntoContainer:function(e,t,n,r){E.validateCallback(r,"ReactDOM.render"),g.isValidElement(t)||f("39","string"==typeof t?" Instead of passing a string like 'div', pass React.createElement('div') or <div />.":"function"==typeof t?" Instead of passing a class like Foo, pass React.createElement(Foo) or <Foo />.":null!=t&&void 0!==t.props?" This may be caused by unintentionally loading two independent copies of React.":"");var a,l=g.createElement(F,{child:t});if(e){var s=w.get(e);a=s._processChildContext(s._context)}else a=S;var u=p(n);if(u){if(P(u._currentElement.props.child,t)){var d=u._renderedComponent.getPublicInstance(),m=r&&function(){r.call(d)};return z._updateRootComponent(u,l,a,n,m),d}z.unmountComponentAtNode(n)}var h=o(n),b=h&&!!i(h),y=c(n),v=b&&!u&&!y,_=z._renderNewRootComponent(l,n,v,a)._renderedComponent.getPublicInstance();return r&&r.call(_),_},render:function(e,t,n){return z._renderSubtreeIntoContainer(null,e,t,n)},unmountComponentAtNode:function(e){u(e)||f("40");var t=p(e);if(!t){c(e),1===e.nodeType&&e.hasAttribute(M);return!1}return delete D[t._instance.rootID],A.batchedUpdates(s,t,e,!1),!0},_mountImageIntoNode:function(e,t,n,i,a){if(u(t)||f("41"),i){var l=o(t);if(C.canReuseMarkup(e,l))return void y.precacheNode(n,l);var s=l.getAttribute(C.CHECKSUM_ATTR_NAME);l.removeAttribute(C.CHECKSUM_ATTR_NAME);var c=l.outerHTML;l.setAttribute(C.CHECKSUM_ATTR_NAME,s);var d=e,p=r(d,c),h=" (client) "+d.substring(p-20,p+20)+"\n (server) "+c.substring(p-20,p+20);t.nodeType===N&&f("42",h)}if(t.nodeType===N&&f("43"),a.useCreateElement){for(;t.lastChild;)t.removeChild(t.lastChild);m.insertTreeBefore(t,e,null)}else T(t,e),y.precacheNode(n,t.firstChild)}};e.exports=z},function(e,t,n){"use strict";var r=n(6),o=n(71),i=(n(1),{HOST:0,COMPOSITE:1,EMPTY:2,getType:function(e){return null===e||e===!1?i.EMPTY:o.isValidElement(e)?"function"==typeof e.type?i.COMPOSITE:i.HOST:void r("26",e)}});e.exports=i},function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.useCreateElement=!1,this.updateQueue=new l(this)}var o=n(9),i=n(69),a=n(123),l=(n(29),n(626)),s=[],c={enqueue:function(){}},u={getTransactionWrappers:function(){return s},getReactMountReady:function(){return c},getUpdateQueue:function(){return this.updateQueue},destructor:function(){},checkpoint:function(){},rollback:function(){}};o(r.prototype,a,u),i.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";e.exports="15.4.2"},function(e,t,n){"use strict";var r={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(e){r.currentScrollLeft=e.x,r.currentScrollTop=e.y}};e.exports=r},function(e,t,n){"use strict";function r(e,t){return null==t&&o("30"),null==e?t:Array.isArray(e)?Array.isArray(t)?(e.push.apply(e,t),e):(e.push(t),e):Array.isArray(t)?[e].concat(t):[e,t]}var o=n(6);n(1);e.exports=r},function(e,t,n){"use strict";function r(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)}e.exports=r},function(e,t,n){"use strict";function r(e){for(var t;(t=e._renderedNodeType)===o.COMPOSITE;)e=e._renderedComponent;return t===o.HOST?e._renderedComponent:t===o.EMPTY?null:void 0}var o=n(269);e.exports=r},function(e,t,n){"use strict";function r(){return!i&&o.canUseDOM&&(i="textContent"in document.documentElement?"textContent":"innerText"),i}var o=n(19),i=null;e.exports=r},function(e,t,n){"use strict";function r(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===t?!!o[e.type]:"textarea"===t}var o={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};e.exports=r},function(e,t,n){"use strict";var r=n(19),o=n(124),i=n(125),a=function(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&3===n.nodeType)return void(n.nodeValue=t)}e.textContent=t};r.canUseDOM&&("textContent"in document.documentElement||(a=function(e,t){if(3===e.nodeType)return void(e.nodeValue=t);i(e,o(t))})),e.exports=a},function(e,t,n){"use strict";function r(e,t){return e&&"object"==typeof e&&null!=e.key?c.escape(e.key):t.toString(36)}function o(e,t,n,i){var p=typeof e;if("undefined"!==p&&"boolean"!==p||(e=null),null===e||"string"===p||"number"===p||"object"===p&&e.$$typeof===l)return n(i,e,""===t?u+r(e,0):t),1;var f,m,h=0,g=""===t?u:t+d;if(Array.isArray(e))for(var b=0;b<e.length;b++)f=e[b],m=g+r(f,b),h+=o(f,m,n,i);else{var y=s(e);if(y){var v,_=y.call(e);if(y!==e.entries)for(var x=0;!(v=_.next()).done;)f=v.value,m=g+r(f,x++),h+=o(f,m,n,i);else for(;!(v=_.next()).done;){var w=v.value;w&&(f=w[1],m=g+c.escape(w[0])+d+r(f,0),h+=o(f,m,n,i))}}else if("object"===p){var C="",k=String(e);a("31","[object Object]"===k?"object with keys {"+Object.keys(e).join(", ")+"}":k,C)}}return h}function i(e,t,n){return null==e?0:o(e,"",t,n)}var a=n(6),l=(n(45),n(615)),s=n(645),c=(n(1),n(178)),u=(n(4),"."),d=":";e.exports=i},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function l(){}function s(e,t){var n={run:function(r){try{var o=e(t.getState(),r);(o!==n.props||n.error)&&(n.shouldComponentUpdate=!0,n.props=o,n.error=null)}catch(e){n.shouldComponentUpdate=!0,n.error=e}}};return n}function c(e){var t,c,u=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},p=u.getDisplayName,_=void 0===p?function(e){return"ConnectAdvanced("+e+")"}:p,x=u.methodName,w=void 0===x?"connectAdvanced":x,C=u.renderCountProp,k=void 0===C?void 0:C,E=u.shouldHandleStateChanges,A=void 0===E||E,S=u.storeKey,I=void 0===S?"store":S,T=u.withRef,P=void 0!==T&&T,O=a(u,["getDisplayName","methodName","renderCountProp","shouldHandleStateChanges","storeKey","withRef"]),M=I+"Subscription",R=y++,N=(t={},t[I]=g.a,t[M]=g.b,t),L=(c={},c[M]=g.b,c);return function(t){f()("function"==typeof t,"You must pass a component to the function returned by connect. Instead received "+JSON.stringify(t));var a=t.displayName||t.name||"Component",c=_(a),u=b({},O,{getDisplayName:_,methodName:w,renderCountProp:k,shouldHandleStateChanges:A,storeKey:I,withRef:P,displayName:c,wrappedComponentName:a,WrappedComponent:t}),p=function(a){function d(e,t){r(this,d);var n=o(this,a.call(this,e,t));return n.version=R,n.state={},n.renderCount=0,n.store=e[I]||t[I],n.propsMode=Boolean(e[I]),n.setWrappedInstance=n.setWrappedInstance.bind(n),f()(n.store,'Could not find "'+I+'" in either the context or props of "'+c+'". Either wrap the root component in a <Provider>, or explicitly pass "'+I+'" as a prop to "'+c+'".'),n.initSelector(),n.initSubscription(),n}return i(d,a),d.prototype.getChildContext=function(){var e,t=this.propsMode?null:this.subscription;return e={},e[M]=t||this.context[M],e},d.prototype.componentDidMount=function(){A&&(this.subscription.trySubscribe(),this.selector.run(this.props),this.selector.shouldComponentUpdate&&this.forceUpdate())},d.prototype.componentWillReceiveProps=function(e){this.selector.run(e)},d.prototype.shouldComponentUpdate=function(){return this.selector.shouldComponentUpdate},d.prototype.componentWillUnmount=function(){this.subscription&&this.subscription.tryUnsubscribe(),this.subscription=null,this.notifyNestedSubs=l,this.store=null,this.selector.run=l,this.selector.shouldComponentUpdate=!1},d.prototype.getWrappedInstance=function(){return f()(P,"To access the wrapped instance, you need to specify { withRef: true } in the options argument of the "+w+"() call."),this.wrappedInstance},d.prototype.setWrappedInstance=function(e){this.wrappedInstance=e},d.prototype.initSelector=function(){var t=e(this.store.dispatch,u);this.selector=s(t,this.store),this.selector.run(this.props)},d.prototype.initSubscription=function(){if(A){var e=(this.propsMode?this.props:this.context)[M];this.subscription=new h.a(this.store,e,this.onStateChange.bind(this)),this.notifyNestedSubs=this.subscription.notifyNestedSubs.bind(this.subscription)}},d.prototype.onStateChange=function(){this.selector.run(this.props),this.selector.shouldComponentUpdate?(this.componentDidUpdate=this.notifyNestedSubsOnComponentDidUpdate,this.setState(v)):this.notifyNestedSubs()},d.prototype.notifyNestedSubsOnComponentDidUpdate=function(){this.componentDidUpdate=void 0,this.notifyNestedSubs()},d.prototype.isSubscribed=function(){return Boolean(this.subscription)&&this.subscription.isSubscribed()},d.prototype.addExtraProps=function(e){if(!(P||k||this.propsMode&&this.subscription))return e;var t=b({},e);return P&&(t.ref=this.setWrappedInstance),k&&(t[k]=this.renderCount++),this.propsMode&&this.subscription&&(t[M]=this.subscription),t},d.prototype.render=function(){var e=this.selector;if(e.shouldComponentUpdate=!1,e.error)throw e.error;return n.i(m.createElement)(t,this.addExtraProps(e.props))},d}(m.Component);return p.WrappedComponent=t,p.displayName=c,p.childContextTypes=L,p.contextTypes=N,p.propTypes=N,d()(p,t)}}var u=n(574),d=n.n(u),p=n(252),f=n.n(p),m=n(10),h=(n.n(m),n(660)),g=n(282);t.a=c;var b=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},y=0,v={}},function(e,t,n){"use strict";function r(e){return function(t,n){function r(){return o}var o=e(t,n);return r.dependsOnOwnProps=!1,r}}function o(e){return null!==e.dependsOnOwnProps&&void 0!==e.dependsOnOwnProps?Boolean(e.dependsOnOwnProps):1!==e.length}function i(e,t){return function(t,n){var r=(n.displayName,function(e,t){return r.dependsOnOwnProps?r.mapToProps(e,t):r.mapToProps(e)});return r.dependsOnOwnProps=!0,r.mapToProps=function(t,n){r.mapToProps=e,r.dependsOnOwnProps=o(e);var i=r(t,n);return"function"==typeof i&&(r.mapToProps=i,r.dependsOnOwnProps=o(i),i=r(t,n)),i},r}}n(283);t.b=r,t.a=i},function(e,t,n){"use strict";var r=n(10);n.n(r);n.d(t,"b",function(){return o}),n.d(t,"a",function(){return i});var o=r.PropTypes.shape({trySubscribe:r.PropTypes.func.isRequired,tryUnsubscribe:r.PropTypes.func.isRequired,notifyNestedSubs:r.PropTypes.func.isRequired,isSubscribed:r.PropTypes.func.isRequired}),i=r.PropTypes.shape({subscribe:r.PropTypes.func.isRequired,dispatch:r.PropTypes.func.isRequired,getState:r.PropTypes.func.isRequired})},function(e,t,n){"use strict";n(172),n(192)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e){Object.assign(a.default,e)}t.__esModule=!0,t.default=o;var i=n(127),a=r(i)},function(e,t,n){"use strict";function r(e,t){var n=e.payload.encodedQuery;(0,l.replaceUrlQuery)(n,t)}function o(e,t){var n=e.payload.encodedQuery;(0,l.pushUrlQuery)(n,t)}function i(e,t){var n=e.payload,r=n.queryParam,o=n.encodedValue;(0,l.replaceInUrlQuery)(r,o,t)}function a(e,t){var n=e.payload,r=n.queryParam,o=n.encodedValue;(0,l.pushInUrlQuery)(r,o,t)}t.__esModule=!0,t.replaceUrlQueryFromAction=r,t.pushUrlQueryFromAction=o,t.replaceInUrlQueryFromAction=i,t.pushInUrlQueryFromAction=a;var l=n(194)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var n=e&&e.meta&&e.meta.updateType;switch(n){case l.default.replaceIn:return(0,i.replaceInUrlQueryFromAction)(e,t);case l.default.replace:return(0,i.replaceUrlQueryFromAction)(e,t);case l.default.pushIn:return(0,i.pushInUrlQueryFromAction)(e,t);case l.default.push:return(0,i.pushUrlQueryFromAction)(e,t)}}t.__esModule=!0,t.default=o;var i=n(285),a=n(100),l=r(a)},function(e,t,n){"use strict";function r(e){var t=Function.prototype.toString,n=Object.prototype.hasOwnProperty,r=RegExp("^"+t.call(n).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");try{var o=t.call(e);return r.test(o)}catch(e){return!1}}function o(e){var t=c(e);if(t){var n=t.childIDs;u(e),n.forEach(o)}}function i(e,t,n){return"\n in "+(e||"Unknown")+(t?" (at "+t.fileName.replace(/^.*[\\\/]/,"")+":"+t.lineNumber+")":n?" (created by "+n+")":"")}function a(e){return null==e?"#empty":"string"==typeof e||"number"==typeof e?"#text":"string"==typeof e.type?e.type:e.type.displayName||e.type.name||"Unknown"}function l(e){var t,n=E.getDisplayName(e),r=E.getElement(e),o=E.getOwnerID(e);return o&&(t=E.getDisplayName(o)),i(n,r&&r._source,t)}var s,c,u,d,p,f,m,h=n(86),g=n(45),b=(n(1),n(4),"function"==typeof Array.from&&"function"==typeof Map&&r(Map)&&null!=Map.prototype&&"function"==typeof Map.prototype.keys&&r(Map.prototype.keys)&&"function"==typeof Set&&r(Set)&&null!=Set.prototype&&"function"==typeof Set.prototype.keys&&r(Set.prototype.keys));if(b){var y=new Map,v=new Set;s=function(e,t){y.set(e,t)},c=function(e){return y.get(e)},u=function(e){y.delete(e)},d=function(){return Array.from(y.keys())},p=function(e){v.add(e)},f=function(e){v.delete(e)},m=function(){return Array.from(v.keys())}}else{var _={},x={},w=function(e){return"."+e},C=function(e){return parseInt(e.substr(1),10)};s=function(e,t){_[w(e)]=t},c=function(e){return _[w(e)]},u=function(e){delete _[w(e)]},d=function(){return Object.keys(_).map(C)},p=function(e){x[w(e)]=!0},f=function(e){delete x[w(e)]},m=function(){return Object.keys(x).map(C)}}var k=[],E={onSetChildren:function(e,t){var n=c(e);n||h("144"),n.childIDs=t;for(var r=0;r<t.length;r++){var o=t[r],i=c(o);i||h("140"),null==i.childIDs&&"object"==typeof i.element&&null!=i.element&&h("141"),i.isMounted||h("71"),null==i.parentID&&(i.parentID=e),i.parentID!==e&&h("142",o,i.parentID,e)}},onBeforeMountComponent:function(e,t,n){s(e,{element:t,parentID:n,text:null,childIDs:[],isMounted:!1,updateCount:0})},onBeforeUpdateComponent:function(e,t){var n=c(e);n&&n.isMounted&&(n.element=t)},onMountComponent:function(e){var t=c(e);t||h("144"),t.isMounted=!0,0===t.parentID&&p(e)},onUpdateComponent:function(e){var t=c(e);t&&t.isMounted&&t.updateCount++},onUnmountComponent:function(e){var t=c(e);if(t){t.isMounted=!1;0===t.parentID&&f(e)}k.push(e)},purgeUnmountedComponents:function(){if(!E._preventPurging){for(var e=0;e<k.length;e++){o(k[e])}k.length=0}},isMounted:function(e){var t=c(e);return!!t&&t.isMounted},getCurrentStackAddendum:function(e){var t="";if(e){var n=a(e),r=e._owner;t+=i(n,e._source,r&&r.getName())}var o=g.current,l=o&&o._debugID;return t+=E.getStackAddendumByID(l)},getStackAddendumByID:function(e){for(var t="";e;)t+=l(e),e=E.getParentID(e);return t},getChildIDs:function(e){var t=c(e);return t?t.childIDs:[]},getDisplayName:function(e){var t=E.getElement(e);return t?a(t):null},getElement:function(e){var t=c(e);return t?t.element:null},getOwnerID:function(e){var t=E.getElement(e);return t&&t._owner?t._owner._debugID:null},getParentID:function(e){var t=c(e);return t?t.parentID:null},getSource:function(e){var t=c(e),n=t?t.element:null;return null!=n?n._source:null},getText:function(e){var t=E.getElement(e);return"string"==typeof t?t:"number"==typeof t?""+t:null},getUpdateCount:function(e){var t=c(e);return t?t.updateCount:0},getRootIDs:m,getRegisteredIDs:d};e.exports=E},function(e,t,n){"use strict";var r="function"==typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103;e.exports=r},function(e,t,n){"use strict";var r={};e.exports=r},function(e,t,n){"use strict";var r=!1;e.exports=r},function(e,t,n){"use strict";function r(e){var t=e&&(o&&e[o]||e[i]);if("function"==typeof t)return t}var o="function"==typeof Symbol&&Symbol.iterator,i="@@iterator";e.exports=r},function(e,t,n){"use strict";function r(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];if(0===t.length)return function(e){return e};if(1===t.length)return t[0];var r=t[t.length-1],o=t.slice(0,-1);return function(){return o.reduceRight(function(e,t){return t(e)},r.apply(void 0,arguments))}}t.a=r},function(e,t,n){"use strict";function r(e,t,i){function s(){y===b&&(y=b.slice())}function c(){return g}function u(e){if("function"!=typeof e)throw new Error("Expected listener to be a function.");var t=!0;return s(),y.push(e),function(){if(t){t=!1,s();var n=y.indexOf(e);y.splice(n,1)}}}function d(e){if(!n.i(o.a)(e))throw new Error("Actions must be plain objects. Use custom middleware for async actions.");if(void 0===e.type)throw new Error('Actions may not have an undefined "type" property. Have you misspelled a constant?');if(v)throw new Error("Reducers may not dispatch actions.");try{v=!0,g=h(g,e)}finally{v=!1}for(var t=b=y,r=0;r<t.length;r++)t[r]();return e}function p(e){if("function"!=typeof e)throw new Error("Expected the nextReducer to be a function.");h=e,d({type:l.INIT})}function f(){var e,t=u;return e={subscribe:function(e){function n(){e.next&&e.next(c())}if("object"!=typeof e)throw new TypeError("Expected the observer to be an object.");return n(),{unsubscribe:t(n)}}},e[a.a]=function(){return this},e}var m;if("function"==typeof t&&void 0===i&&(i=t,t=void 0),void 0!==i){if("function"!=typeof i)throw new Error("Expected the enhancer to be a function.");return i(r)(e,t)}if("function"!=typeof e)throw new Error("Expected the reducer to be a function.");var h=e,g=t,b=[],y=b,v=!1;return d({type:l.INIT}),m={dispatch:d,subscribe:u,getState:c,replaceReducer:p},m[a.a]=f,m}var o=n(172),i=n(700),a=n.n(i);n.d(t,"b",function(){return l}),t.a=r;var l={INIT:"@@redux/INIT"}},function(e,t,n){"use strict";var r=n(293),o=(n(689),n(688));n(687),n(292),n(295);n.d(t,"a",function(){return r.a}),n.d(t,"b",function(){return o.a})},function(e,t,n){"use strict"},function(e,t,n){"use strict";var r=function(){};e.exports=r},function(e,t,n){"use strict";function r(e){p.a.render(u.a.createElement(h.a,{store:g.a},e),_)}function o(e){b.a.resolve(v,e).then(r).catch(function(t){return b.a.resolve(v,a()({},e,{error:t})).then(r)})}Object.defineProperty(t,"__esModule",{value:!0});var i=n(87),a=n.n(i),l=n(309),s=(n.n(l),n(710)),c=(n.n(s),n(10)),u=n.n(c),d=n(589),p=n.n(d),f=n(557),m=n.n(f),h=n(191),g=n(307),b=n(306),y=n(103),v=n(308).default,_=document.getElementById("container");y.a.listen(o),o(y.a.location),m.a.attach(document.body)},function(e,t){/**
* material-design-lite - Material Design Components in CSS, JS and HTML
* @version v1.2.1
* @license Apache-2.0
* @copyright 2015 Google, Inc.
* @link https://github.com/google/material-design-lite
*/
!function(){"use strict";function e(e,t){if(e){if(t.element_.classList.contains(t.CssClasses_.MDL_JS_RIPPLE_EFFECT)){var n=document.createElement("span");n.classList.add(t.CssClasses_.MDL_RIPPLE_CONTAINER),n.classList.add(t.CssClasses_.MDL_JS_RIPPLE_EFFECT);var r=document.createElement("span");r.classList.add(t.CssClasses_.MDL_RIPPLE),n.appendChild(r),e.appendChild(n)}e.addEventListener("click",function(n){n.preventDefault(),t.resetTabState_(),e.classList.add(t.CssClasses_.ACTIVE_CLASS)})}}function t(e,t,n,r){function o(){r.resetTabState_(t),e.classList.add(r.CssClasses_.IS_ACTIVE)}if(r.tabBar_.classList.contains(r.CssClasses_.JS_RIPPLE_EFFECT)){var i=document.createElement("span");i.classList.add(r.CssClasses_.RIPPLE_CONTAINER),i.classList.add(r.CssClasses_.JS_RIPPLE_EFFECT);var a=document.createElement("span");a.classList.add(r.CssClasses_.RIPPLE),i.appendChild(a),e.appendChild(i)}e.addEventListener("click",function(e){e.preventDefault(),o()}),e.show=o}if("undefined"!=typeof window){var n={upgradeDom:function(e,t){},upgradeElement:function(e,t){},upgradeElements:function(e){},upgradeAllRegistered:function(){},registerUpgradedCallback:function(e,t){},register:function(e){},downgradeElements:function(e){}};n=function(){function e(e,t){for(var n=0;n<d.length;n++)if(d[n].className===e)return void 0!==t&&(d[n]=t),d[n];return!1}function t(e){var t=e.getAttribute("data-upgraded");return null===t?[""]:t.split(",")}function n(e,n){return t(e).indexOf(n)!==-1}function r(t,n){if(void 0===t&&void 0===n)for(var i=0;i<d.length;i++)r(d[i].className,d[i].cssClass);else{var a=t;if(void 0===n){var l=e(a);l&&(n=l.cssClass)}for(var s=document.querySelectorAll("."+n),c=0;c<s.length;c++)o(s[c],a)}}function o(r,o){if(!("object"==typeof r&&r instanceof Element))throw new Error("Invalid argument provided to upgrade MDL element.");var i=t(r),a=[];if(o)n(r,o)||a.push(e(o));else{var l=r.classList;d.forEach(function(e){l.contains(e.cssClass)&&a.indexOf(e)===-1&&!n(r,e.className)&&a.push(e)})}for(var s,c=0,u=a.length;c<u;c++){if(!(s=a[c]))throw new Error("Unable to find a registered component for the given class.");i.push(s.className),r.setAttribute("data-upgraded",i.join(","));var m=new s.classConstructor(r);m[f]=s,p.push(m);for(var h=0,g=s.callbacks.length;h<g;h++)s.callbacks[h](r);s.widget&&(r[s.className]=m);var b;"CustomEvent"in window&&"function"==typeof window.CustomEvent?b=new CustomEvent("mdl-componentupgraded",{bubbles:!0,cancelable:!1}):(b=document.createEvent("Events"),b.initEvent("mdl-componentupgraded",!0,!0)),r.dispatchEvent(b)}}function i(e){Array.isArray(e)||(e=e instanceof Element?[e]:Array.prototype.slice.call(e));for(var t,n=0,r=e.length;n<r;n++)(t=e[n])instanceof HTMLElement&&(o(t),t.children.length>0&&i(t.children))}function a(t){var n=void 0===t.widget&&void 0===t.widget,r=!0;n||(r=t.widget||t.widget);var o={classConstructor:t.constructor||t.constructor,className:t.classAsString||t.classAsString,cssClass:t.cssClass||t.cssClass,widget:r,callbacks:[]};if(d.forEach(function(e){if(e.cssClass===o.cssClass)throw new Error("The provided cssClass has already been registered: "+e.cssClass);if(e.className===o.className)throw new Error("The provided className has already been registered")}),t.constructor.prototype.hasOwnProperty(f))throw new Error("MDL component classes must not have "+f+" defined as a property.");e(t.classAsString,o)||d.push(o)}function l(t,n){var r=e(t);r&&r.callbacks.push(n)}function s(){for(var e=0;e<d.length;e++)r(d[e].className)}function c(e){if(e){var t=p.indexOf(e);p.splice(t,1);var n=e.element_.getAttribute("data-upgraded").split(","),r=n.indexOf(e[f].classAsString);n.splice(r,1),e.element_.setAttribute("data-upgraded",n.join(","));var o;"CustomEvent"in window&&"function"==typeof window.CustomEvent?o=new CustomEvent("mdl-componentdowngraded",{bubbles:!0,cancelable:!1}):(o=document.createEvent("Events"),o.initEvent("mdl-componentdowngraded",!0,!0)),e.element_.dispatchEvent(o)}}function u(e){var t=function(e){p.filter(function(t){return t.element_===e}).forEach(c)};if(e instanceof Array||e instanceof NodeList)for(var n=0;n<e.length;n++)t(e[n]);else{if(!(e instanceof Node))throw new Error("Invalid argument provided to downgrade MDL nodes.");t(e)}}var d=[],p=[],f="mdlComponentConfigInternal_";return{upgradeDom:r,upgradeElement:o,upgradeElements:i,upgradeAllRegistered:s,registerUpgradedCallback:l,register:a,downgradeElements:u}}(),n.ComponentConfigPublic,n.ComponentConfig,n.Component,n.upgradeDom=n.upgradeDom,n.upgradeElement=n.upgradeElement,n.upgradeElements=n.upgradeElements,n.upgradeAllRegistered=n.upgradeAllRegistered,n.registerUpgradedCallback=n.registerUpgradedCallback,n.register=n.register,n.downgradeElements=n.downgradeElements,window.componentHandler=n,window.componentHandler=n,window.addEventListener("load",function(){"classList"in document.createElement("div")&&"querySelector"in document&&"addEventListener"in window&&Array.prototype.forEach?document.documentElement.classList.add("mdl-js"):(n.upgradeElement=function(){},n.register=function(){})}),Date.now||(Date.now=function(){return(new Date).getTime()},Date.now=Date.now);for(var r=["webkit","moz"],o=0;o<r.length&&!window.requestAnimationFrame;++o){var i=r[o];window.requestAnimationFrame=window[i+"RequestAnimationFrame"],window.cancelAnimationFrame=window[i+"CancelAnimationFrame"]||window[i+"CancelRequestAnimationFrame"],window.requestAnimationFrame=window.requestAnimationFrame,window.cancelAnimationFrame=window.cancelAnimationFrame}if(/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent)||!window.requestAnimationFrame||!window.cancelAnimationFrame){var a=0;window.requestAnimationFrame=function(e){var t=Date.now(),n=Math.max(a+16,t);return setTimeout(function(){e(a=n)},n-t)},window.cancelAnimationFrame=clearTimeout,window.requestAnimationFrame=window.requestAnimationFrame,window.cancelAnimationFrame=window.cancelAnimationFrame}var l=function(e){this.element_=e,this.init()};window.MaterialButton=l,l.prototype.Constant_={},l.prototype.CssClasses_={RIPPLE_EFFECT:"mdl-js-ripple-effect",RIPPLE_CONTAINER:"mdl-button__ripple-container",RIPPLE:"mdl-ripple"},l.prototype.blurHandler_=function(e){e&&this.element_.blur()},l.prototype.disable=function(){this.element_.disabled=!0},l.prototype.disable=l.prototype.disable,l.prototype.enable=function(){this.element_.disabled=!1},l.prototype.enable=l.prototype.enable,l.prototype.init=function(){if(this.element_){if(this.element_.classList.contains(this.CssClasses_.RIPPLE_EFFECT)){var e=document.createElement("span");e.classList.add(this.CssClasses_.RIPPLE_CONTAINER),this.rippleElement_=document.createElement("span"),this.rippleElement_.classList.add(this.CssClasses_.RIPPLE),e.appendChild(this.rippleElement_),this.boundRippleBlurHandler=this.blurHandler_.bind(this),this.rippleElement_.addEventListener("mouseup",this.boundRippleBlurHandler),this.element_.appendChild(e)}this.boundButtonBlurHandler=this.blurHandler_.bind(this),this.element_.addEventListener("mouseup",this.boundButtonBlurHandler),this.element_.addEventListener("mouseleave",this.boundButtonBlurHandler)}},n.register({constructor:l,classAsString:"MaterialButton",cssClass:"mdl-js-button",widget:!0});var s=function(e){this.element_=e,this.init()};window.MaterialCheckbox=s,s.prototype.Constant_={TINY_TIMEOUT:.001},s.prototype.CssClasses_={INPUT:"mdl-checkbox__input",BOX_OUTLINE:"mdl-checkbox__box-outline",FOCUS_HELPER:"mdl-checkbox__focus-helper",TICK_OUTLINE:"mdl-checkbox__tick-outline",RIPPLE_EFFECT:"mdl-js-ripple-effect",RIPPLE_IGNORE_EVENTS:"mdl-js-ripple-effect--ignore-events",RIPPLE_CONTAINER:"mdl-checkbox__ripple-container",RIPPLE_CENTER:"mdl-ripple--center",RIPPLE:"mdl-ripple",IS_FOCUSED:"is-focused",IS_DISABLED:"is-disabled",IS_CHECKED:"is-checked",IS_UPGRADED:"is-upgraded"},s.prototype.onChange_=function(e){this.updateClasses_()},s.prototype.onFocus_=function(e){this.element_.classList.add(this.CssClasses_.IS_FOCUSED)},s.prototype.onBlur_=function(e){this.element_.classList.remove(this.CssClasses_.IS_FOCUSED)},s.prototype.onMouseUp_=function(e){this.blur_()},s.prototype.updateClasses_=function(){this.checkDisabled(),this.checkToggleState()},s.prototype.blur_=function(){window.setTimeout(function(){this.inputElement_.blur()}.bind(this),this.Constant_.TINY_TIMEOUT)},s.prototype.checkToggleState=function(){this.inputElement_.checked?this.element_.classList.add(this.CssClasses_.IS_CHECKED):this.element_.classList.remove(this.CssClasses_.IS_CHECKED)},s.prototype.checkToggleState=s.prototype.checkToggleState,s.prototype.checkDisabled=function(){this.inputElement_.disabled?this.element_.classList.add(this.CssClasses_.IS_DISABLED):this.element_.classList.remove(this.CssClasses_.IS_DISABLED)},s.prototype.checkDisabled=s.prototype.checkDisabled,s.prototype.disable=function(){this.inputElement_.disabled=!0,this.updateClasses_()},s.prototype.disable=s.prototype.disable,s.prototype.enable=function(){this.inputElement_.disabled=!1,this.updateClasses_()},s.prototype.enable=s.prototype.enable,s.prototype.check=function(){this.inputElement_.checked=!0,this.updateClasses_()},s.prototype.check=s.prototype.check,s.prototype.uncheck=function(){this.inputElement_.checked=!1,this.updateClasses_()},s.prototype.uncheck=s.prototype.uncheck,s.prototype.init=function(){if(this.element_){this.inputElement_=this.element_.querySelector("."+this.CssClasses_.INPUT);var e=document.createElement("span");e.classList.add(this.CssClasses_.BOX_OUTLINE);var t=document.createElement("span");t.classList.add(this.CssClasses_.FOCUS_HELPER);var n=document.createElement("span");if(n.classList.add(this.CssClasses_.TICK_OUTLINE),e.appendChild(n),this.element_.appendChild(t),this.element_.appendChild(e),this.element_.classList.contains(this.CssClasses_.RIPPLE_EFFECT)){this.element_.classList.add(this.CssClasses_.RIPPLE_IGNORE_EVENTS),this.rippleContainerElement_=document.createElement("span"),this.rippleContainerElement_.classList.add(this.CssClasses_.RIPPLE_CONTAINER),this.rippleContainerElement_.classList.add(this.CssClasses_.RIPPLE_EFFECT),this.rippleContainerElement_.classList.add(this.CssClasses_.RIPPLE_CENTER),this.boundRippleMouseUp=this.onMouseUp_.bind(this),this.rippleContainerElement_.addEventListener("mouseup",this.boundRippleMouseUp);var r=document.createElement("span");r.classList.add(this.CssClasses_.RIPPLE),this.rippleContainerElement_.appendChild(r),this.element_.appendChild(this.rippleContainerElement_)}this.boundInputOnChange=this.onChange_.bind(this),this.boundInputOnFocus=this.onFocus_.bind(this),this.boundInputOnBlur=this.onBlur_.bind(this),this.boundElementMouseUp=this.onMouseUp_.bind(this),this.inputElement_.addEventListener("change",this.boundInputOnChange),this.inputElement_.addEventListener("focus",this.boundInputOnFocus),this.inputElement_.addEventListener("blur",this.boundInputOnBlur),this.element_.addEventListener("mouseup",this.boundElementMouseUp),this.updateClasses_(),this.element_.classList.add(this.CssClasses_.IS_UPGRADED)}},n.register({constructor:s,classAsString:"MaterialCheckbox",cssClass:"mdl-js-checkbox",widget:!0});var c=function(e){this.element_=e,this.init()};window.MaterialIconToggle=c,c.prototype.Constant_={TINY_TIMEOUT:.001},c.prototype.CssClasses_={INPUT:"mdl-icon-toggle__input",JS_RIPPLE_EFFECT:"mdl-js-ripple-effect",RIPPLE_IGNORE_EVENTS:"mdl-js-ripple-effect--ignore-events",RIPPLE_CONTAINER:"mdl-icon-toggle__ripple-container",RIPPLE_CENTER:"mdl-ripple--center",RIPPLE:"mdl-ripple",IS_FOCUSED:"is-focused",IS_DISABLED:"is-disabled",IS_CHECKED:"is-checked"},c.prototype.onChange_=function(e){this.updateClasses_()},c.prototype.onFocus_=function(e){this.element_.classList.add(this.CssClasses_.IS_FOCUSED)},c.prototype.onBlur_=function(e){this.element_.classList.remove(this.CssClasses_.IS_FOCUSED)},c.prototype.onMouseUp_=function(e){this.blur_()},c.prototype.updateClasses_=function(){this.checkDisabled(),this.checkToggleState()},c.prototype.blur_=function(){window.setTimeout(function(){this.inputElement_.blur()}.bind(this),this.Constant_.TINY_TIMEOUT)},c.prototype.checkToggleState=function(){this.inputElement_.checked?this.element_.classList.add(this.CssClasses_.IS_CHECKED):this.element_.classList.remove(this.CssClasses_.IS_CHECKED)},c.prototype.checkToggleState=c.prototype.checkToggleState,c.prototype.checkDisabled=function(){this.inputElement_.disabled?this.element_.classList.add(this.CssClasses_.IS_DISABLED):this.element_.classList.remove(this.CssClasses_.IS_DISABLED)},c.prototype.checkDisabled=c.prototype.checkDisabled,c.prototype.disable=function(){this.inputElement_.disabled=!0,this.updateClasses_()},c.prototype.disable=c.prototype.disable,c.prototype.enable=function(){this.inputElement_.disabled=!1,this.updateClasses_()},c.prototype.enable=c.prototype.enable,c.prototype.check=function(){this.inputElement_.checked=!0,this.updateClasses_()},c.prototype.check=c.prototype.check,c.prototype.uncheck=function(){this.inputElement_.checked=!1,this.updateClasses_()},c.prototype.uncheck=c.prototype.uncheck,c.prototype.init=function(){if(this.element_){if(this.inputElement_=this.element_.querySelector("."+this.CssClasses_.INPUT),this.element_.classList.contains(this.CssClasses_.JS_RIPPLE_EFFECT)){this.element_.classList.add(this.CssClasses_.RIPPLE_IGNORE_EVENTS),this.rippleContainerElement_=document.createElement("span"),this.rippleContainerElement_.classList.add(this.CssClasses_.RIPPLE_CONTAINER),this.rippleContainerElement_.classList.add(this.CssClasses_.JS_RIPPLE_EFFECT),this.rippleContainerElement_.classList.add(this.CssClasses_.RIPPLE_CENTER),this.boundRippleMouseUp=this.onMouseUp_.bind(this),this.rippleContainerElement_.addEventListener("mouseup",this.boundRippleMouseUp);var e=document.createElement("span");e.classList.add(this.CssClasses_.RIPPLE),this.rippleContainerElement_.appendChild(e),this.element_.appendChild(this.rippleContainerElement_)}this.boundInputOnChange=this.onChange_.bind(this),this.boundInputOnFocus=this.onFocus_.bind(this),this.boundInputOnBlur=this.onBlur_.bind(this),this.boundElementOnMouseUp=this.onMouseUp_.bind(this),this.inputElement_.addEventListener("change",this.boundInputOnChange),this.inputElement_.addEventListener("focus",this.boundInputOnFocus),this.inputElement_.addEventListener("blur",this.boundInputOnBlur),this.element_.addEventListener("mouseup",this.boundElementOnMouseUp),this.updateClasses_(),this.element_.classList.add("is-upgraded")}},n.register({constructor:c,classAsString:"MaterialIconToggle",cssClass:"mdl-js-icon-toggle",widget:!0});var u=function(e){this.element_=e,this.init()};window.MaterialMenu=u,u.prototype.Constant_={TRANSITION_DURATION_SECONDS:.3,TRANSITION_DURATION_FRACTION:.8,CLOSE_TIMEOUT:150},u.prototype.Keycodes_={ENTER:13,ESCAPE:27,SPACE:32,UP_ARROW:38,DOWN_ARROW:40},u.prototype.CssClasses_={CONTAINER:"mdl-menu__container",OUTLINE:"mdl-menu__outline",ITEM:"mdl-menu__item",ITEM_RIPPLE_CONTAINER:"mdl-menu__item-ripple-container",RIPPLE_EFFECT:"mdl-js-ripple-effect",RIPPLE_IGNORE_EVENTS:"mdl-js-ripple-effect--ignore-events",RIPPLE:"mdl-ripple",IS_UPGRADED:"is-upgraded",IS_VISIBLE:"is-visible",IS_ANIMATING:"is-animating",BOTTOM_LEFT:"mdl-menu--bottom-left",BOTTOM_RIGHT:"mdl-menu--bottom-right",TOP_LEFT:"mdl-menu--top-left",TOP_RIGHT:"mdl-menu--top-right",UNALIGNED:"mdl-menu--unaligned"},u.prototype.init=function(){if(this.element_){var e=document.createElement("div");e.classList.add(this.CssClasses_.CONTAINER),this.element_.parentElement.insertBefore(e,this.element_),this.element_.parentElement.removeChild(this.element_),e.appendChild(this.element_),this.container_=e;var t=document.createElement("div");t.classList.add(this.CssClasses_.OUTLINE),this.outline_=t,e.insertBefore(t,this.element_);var n=this.element_.getAttribute("for")||this.element_.getAttribute("data-mdl-for"),r=null;n&&(r=document.getElementById(n))&&(this.forElement_=r,r.addEventListener("click",this.handleForClick_.bind(this)),r.addEventListener("keydown",this.handleForKeyboardEvent_.bind(this)));var o=this.element_.querySelectorAll("."+this.CssClasses_.ITEM);this.boundItemKeydown_=this.handleItemKeyboardEvent_.bind(this),this.boundItemClick_=this.handleItemClick_.bind(this);for(var i=0;i<o.length;i++)o[i].addEventListener("click",this.boundItemClick_),o[i].tabIndex="-1",o[i].addEventListener("keydown",this.boundItemKeydown_);if(this.element_.classList.contains(this.CssClasses_.RIPPLE_EFFECT))for(this.element_.classList.add(this.CssClasses_.RIPPLE_IGNORE_EVENTS),i=0;i<o.length;i++){var a=o[i],l=document.createElement("span");l.classList.add(this.CssClasses_.ITEM_RIPPLE_CONTAINER);var s=document.createElement("span");s.classList.add(this.CssClasses_.RIPPLE),l.appendChild(s),a.appendChild(l),a.classList.add(this.CssClasses_.RIPPLE_EFFECT)}this.element_.classList.contains(this.CssClasses_.BOTTOM_LEFT)&&this.outline_.classList.add(this.CssClasses_.BOTTOM_LEFT),this.element_.classList.contains(this.CssClasses_.BOTTOM_RIGHT)&&this.outline_.classList.add(this.CssClasses_.BOTTOM_RIGHT),this.element_.classList.contains(this.CssClasses_.TOP_LEFT)&&this.outline_.classList.add(this.CssClasses_.TOP_LEFT),this.element_.classList.contains(this.CssClasses_.TOP_RIGHT)&&this.outline_.classList.add(this.CssClasses_.TOP_RIGHT),this.element_.classList.contains(this.CssClasses_.UNALIGNED)&&this.outline_.classList.add(this.CssClasses_.UNALIGNED),e.classList.add(this.CssClasses_.IS_UPGRADED)}},u.prototype.handleForClick_=function(e){if(this.element_&&this.forElement_){var t=this.forElement_.getBoundingClientRect(),n=this.forElement_.parentElement.getBoundingClientRect();this.element_.classList.contains(this.CssClasses_.UNALIGNED)||(this.element_.classList.contains(this.CssClasses_.BOTTOM_RIGHT)?(this.container_.style.right=n.right-t.right+"px",this.container_.style.top=this.forElement_.offsetTop+this.forElement_.offsetHeight+"px"):this.element_.classList.contains(this.CssClasses_.TOP_LEFT)?(this.container_.style.left=this.forElement_.offsetLeft+"px",this.container_.style.bottom=n.bottom-t.top+"px"):this.element_.classList.contains(this.CssClasses_.TOP_RIGHT)?(this.container_.style.right=n.right-t.right+"px",this.container_.style.bottom=n.bottom-t.top+"px"):(this.container_.style.left=this.forElement_.offsetLeft+"px",this.container_.style.top=this.forElement_.offsetTop+this.forElement_.offsetHeight+"px"))}this.toggle(e)},u.prototype.handleForKeyboardEvent_=function(e){if(this.element_&&this.container_&&this.forElement_){var t=this.element_.querySelectorAll("."+this.CssClasses_.ITEM+":not([disabled])");t&&t.length>0&&this.container_.classList.contains(this.CssClasses_.IS_VISIBLE)&&(e.keyCode===this.Keycodes_.UP_ARROW?(e.preventDefault(),t[t.length-1].focus()):e.keyCode===this.Keycodes_.DOWN_ARROW&&(e.preventDefault(),t[0].focus()))}},u.prototype.handleItemKeyboardEvent_=function(e){if(this.element_&&this.container_){var t=this.element_.querySelectorAll("."+this.CssClasses_.ITEM+":not([disabled])");if(t&&t.length>0&&this.container_.classList.contains(this.CssClasses_.IS_VISIBLE)){var n=Array.prototype.slice.call(t).indexOf(e.target);if(e.keyCode===this.Keycodes_.UP_ARROW)e.preventDefault(),n>0?t[n-1].focus():t[t.length-1].focus();else if(e.keyCode===this.Keycodes_.DOWN_ARROW)e.preventDefault(),t.length>n+1?t[n+1].focus():t[0].focus();else if(e.keyCode===this.Keycodes_.SPACE||e.keyCode===this.Keycodes_.ENTER){e.preventDefault();var r=new MouseEvent("mousedown");e.target.dispatchEvent(r),r=new MouseEvent("mouseup"),e.target.dispatchEvent(r),e.target.click()}else e.keyCode===this.Keycodes_.ESCAPE&&(e.preventDefault(),this.hide())}}},u.prototype.handleItemClick_=function(e){e.target.hasAttribute("disabled")?e.stopPropagation():(this.closing_=!0,window.setTimeout(function(e){this.hide(),this.closing_=!1}.bind(this),this.Constant_.CLOSE_TIMEOUT))},u.prototype.applyClip_=function(e,t){this.element_.classList.contains(this.CssClasses_.UNALIGNED)?this.element_.style.clip="":this.element_.classList.contains(this.CssClasses_.BOTTOM_RIGHT)?this.element_.style.clip="rect(0 "+t+"px 0 "+t+"px)":this.element_.classList.contains(this.CssClasses_.TOP_LEFT)?this.element_.style.clip="rect("+e+"px 0 "+e+"px 0)":this.element_.classList.contains(this.CssClasses_.TOP_RIGHT)?this.element_.style.clip="rect("+e+"px "+t+"px "+e+"px "+t+"px)":this.element_.style.clip=""},u.prototype.removeAnimationEndListener_=function(e){e.target.classList.remove(u.prototype.CssClasses_.IS_ANIMATING)},u.prototype.addAnimationEndListener_=function(){this.element_.addEventListener("transitionend",this.removeAnimationEndListener_),this.element_.addEventListener("webkitTransitionEnd",this.removeAnimationEndListener_)},u.prototype.show=function(e){if(this.element_&&this.container_&&this.outline_){var t=this.element_.getBoundingClientRect().height,n=this.element_.getBoundingClientRect().width;this.container_.style.width=n+"px",this.container_.style.height=t+"px",this.outline_.style.width=n+"px",this.outline_.style.height=t+"px";for(var r=this.Constant_.TRANSITION_DURATION_SECONDS*this.Constant_.TRANSITION_DURATION_FRACTION,o=this.element_.querySelectorAll("."+this.CssClasses_.ITEM),i=0;i<o.length;i++){var a=null;a=this.element_.classList.contains(this.CssClasses_.TOP_LEFT)||this.element_.classList.contains(this.CssClasses_.TOP_RIGHT)?(t-o[i].offsetTop-o[i].offsetHeight)/t*r+"s":o[i].offsetTop/t*r+"s",o[i].style.transitionDelay=a}this.applyClip_(t,n),window.requestAnimationFrame(function(){this.element_.classList.add(this.CssClasses_.IS_ANIMATING),this.element_.style.clip="rect(0 "+n+"px "+t+"px 0)",this.container_.classList.add(this.CssClasses_.IS_VISIBLE)}.bind(this)),this.addAnimationEndListener_();var l=function(t){t===e||this.closing_||t.target.parentNode===this.element_||(document.removeEventListener("click",l),this.hide())}.bind(this);document.addEventListener("click",l)}},u.prototype.show=u.prototype.show,u.prototype.hide=function(){if(this.element_&&this.container_&&this.outline_){for(var e=this.element_.querySelectorAll("."+this.CssClasses_.ITEM),t=0;t<e.length;t++)e[t].style.removeProperty("transition-delay");var n=this.element_.getBoundingClientRect(),r=n.height,o=n.width;this.element_.classList.add(this.CssClasses_.IS_ANIMATING),this.applyClip_(r,o),this.container_.classList.remove(this.CssClasses_.IS_VISIBLE),this.addAnimationEndListener_()}},u.prototype.hide=u.prototype.hide,u.prototype.toggle=function(e){this.container_.classList.contains(this.CssClasses_.IS_VISIBLE)?this.hide():this.show(e)},u.prototype.toggle=u.prototype.toggle,n.register({constructor:u,classAsString:"MaterialMenu",cssClass:"mdl-js-menu",widget:!0});var d=function(e){this.element_=e,this.init()};window.MaterialProgress=d,d.prototype.Constant_={},d.prototype.CssClasses_={INDETERMINATE_CLASS:"mdl-progress__indeterminate"},d.prototype.setProgress=function(e){this.element_.classList.contains(this.CssClasses_.INDETERMINATE_CLASS)||(this.progressbar_.style.width=e+"%")},d.prototype.setProgress=d.prototype.setProgress,d.prototype.setBuffer=function(e){this.bufferbar_.style.width=e+"%",this.auxbar_.style.width=100-e+"%"},d.prototype.setBuffer=d.prototype.setBuffer,d.prototype.init=function(){if(this.element_){var e=document.createElement("div");e.className="progressbar bar bar1",this.element_.appendChild(e),this.progressbar_=e,e=document.createElement("div"),e.className="bufferbar bar bar2",this.element_.appendChild(e),this.bufferbar_=e,e=document.createElement("div"),e.className="auxbar bar bar3",this.element_.appendChild(e),this.auxbar_=e,this.progressbar_.style.width="0%",this.bufferbar_.style.width="100%",this.auxbar_.style.width="0%",this.element_.classList.add("is-upgraded")}},n.register({constructor:d,classAsString:"MaterialProgress",cssClass:"mdl-js-progress",widget:!0});var p=function(e){this.element_=e,this.init()};window.MaterialRadio=p,p.prototype.Constant_={TINY_TIMEOUT:.001},p.prototype.CssClasses_={IS_FOCUSED:"is-focused",IS_DISABLED:"is-disabled",IS_CHECKED:"is-checked",IS_UPGRADED:"is-upgraded",JS_RADIO:"mdl-js-radio",RADIO_BTN:"mdl-radio__button",RADIO_OUTER_CIRCLE:"mdl-radio__outer-circle",RADIO_INNER_CIRCLE:"mdl-radio__inner-circle",RIPPLE_EFFECT:"mdl-js-ripple-effect",RIPPLE_IGNORE_EVENTS:"mdl-js-ripple-effect--ignore-events",RIPPLE_CONTAINER:"mdl-radio__ripple-container",RIPPLE_CENTER:"mdl-ripple--center",RIPPLE:"mdl-ripple"},p.prototype.onChange_=function(e){for(var t=document.getElementsByClassName(this.CssClasses_.JS_RADIO),n=0;n<t.length;n++){t[n].querySelector("."+this.CssClasses_.RADIO_BTN).getAttribute("name")===this.btnElement_.getAttribute("name")&&t[n].MaterialRadio.updateClasses_()}},p.prototype.onFocus_=function(e){this.element_.classList.add(this.CssClasses_.IS_FOCUSED)},p.prototype.onBlur_=function(e){this.element_.classList.remove(this.CssClasses_.IS_FOCUSED)},p.prototype.onMouseup_=function(e){this.blur_()},p.prototype.updateClasses_=function(){this.checkDisabled(),this.checkToggleState()},p.prototype.blur_=function(){window.setTimeout(function(){this.btnElement_.blur()}.bind(this),this.Constant_.TINY_TIMEOUT)},p.prototype.checkDisabled=function(){this.btnElement_.disabled?this.element_.classList.add(this.CssClasses_.IS_DISABLED):this.element_.classList.remove(this.CssClasses_.IS_DISABLED)},p.prototype.checkDisabled=p.prototype.checkDisabled,p.prototype.checkToggleState=function(){this.btnElement_.checked?this.element_.classList.add(this.CssClasses_.IS_CHECKED):this.element_.classList.remove(this.CssClasses_.IS_CHECKED)},p.prototype.checkToggleState=p.prototype.checkToggleState,p.prototype.disable=function(){this.btnElement_.disabled=!0,this.updateClasses_()},p.prototype.disable=p.prototype.disable,p.prototype.enable=function(){this.btnElement_.disabled=!1,this.updateClasses_()},p.prototype.enable=p.prototype.enable,p.prototype.check=function(){this.btnElement_.checked=!0,this.onChange_(null)},p.prototype.check=p.prototype.check,p.prototype.uncheck=function(){this.btnElement_.checked=!1,this.onChange_(null)},p.prototype.uncheck=p.prototype.uncheck,p.prototype.init=function(){if(this.element_){this.btnElement_=this.element_.querySelector("."+this.CssClasses_.RADIO_BTN),this.boundChangeHandler_=this.onChange_.bind(this),this.boundFocusHandler_=this.onChange_.bind(this),this.boundBlurHandler_=this.onBlur_.bind(this),this.boundMouseUpHandler_=this.onMouseup_.bind(this);var e=document.createElement("span");e.classList.add(this.CssClasses_.RADIO_OUTER_CIRCLE);var t=document.createElement("span");t.classList.add(this.CssClasses_.RADIO_INNER_CIRCLE),this.element_.appendChild(e),this.element_.appendChild(t);var n;if(this.element_.classList.contains(this.CssClasses_.RIPPLE_EFFECT)){this.element_.classList.add(this.CssClasses_.RIPPLE_IGNORE_EVENTS),n=document.createElement("span"),n.classList.add(this.CssClasses_.RIPPLE_CONTAINER),n.classList.add(this.CssClasses_.RIPPLE_EFFECT),n.classList.add(this.CssClasses_.RIPPLE_CENTER),n.addEventListener("mouseup",this.boundMouseUpHandler_);var r=document.createElement("span");r.classList.add(this.CssClasses_.RIPPLE),n.appendChild(r),this.element_.appendChild(n)}this.btnElement_.addEventListener("change",this.boundChangeHandler_),this.btnElement_.addEventListener("focus",this.boundFocusHandler_),this.btnElement_.addEventListener("blur",this.boundBlurHandler_),this.element_.addEventListener("mouseup",this.boundMouseUpHandler_),this.updateClasses_(),this.element_.classList.add(this.CssClasses_.IS_UPGRADED)}},n.register({constructor:p,classAsString:"MaterialRadio",cssClass:"mdl-js-radio",widget:!0});var f=function(e){this.element_=e,this.isIE_=window.navigator.msPointerEnabled,this.init()};window.MaterialSlider=f,f.prototype.Constant_={},f.prototype.CssClasses_={IE_CONTAINER:"mdl-slider__ie-container",SLIDER_CONTAINER:"mdl-slider__container",BACKGROUND_FLEX:"mdl-slider__background-flex",BACKGROUND_LOWER:"mdl-slider__background-lower",BACKGROUND_UPPER:"mdl-slider__background-upper",IS_LOWEST_VALUE:"is-lowest-value",IS_UPGRADED:"is-upgraded"},f.prototype.onInput_=function(e){this.updateValueStyles_()},f.prototype.onChange_=function(e){this.updateValueStyles_()},f.prototype.onMouseUp_=function(e){e.target.blur()},f.prototype.onContainerMouseDown_=function(e){if(e.target===this.element_.parentElement){e.preventDefault();var t=new MouseEvent("mousedown",{target:e.target,buttons:e.buttons,clientX:e.clientX,clientY:this.element_.getBoundingClientRect().y});this.element_.dispatchEvent(t)}},f.prototype.updateValueStyles_=function(){var e=(this.element_.value-this.element_.min)/(this.element_.max-this.element_.min);0===e?this.element_.classList.add(this.CssClasses_.IS_LOWEST_VALUE):this.element_.classList.remove(this.CssClasses_.IS_LOWEST_VALUE),this.isIE_||(this.backgroundLower_.style.flex=e,this.backgroundLower_.style.webkitFlex=e,this.backgroundUpper_.style.flex=1-e,this.backgroundUpper_.style.webkitFlex=1-e)},f.prototype.disable=function(){this.element_.disabled=!0},f.prototype.disable=f.prototype.disable,f.prototype.enable=function(){this.element_.disabled=!1},f.prototype.enable=f.prototype.enable,f.prototype.change=function(e){void 0!==e&&(this.element_.value=e),this.updateValueStyles_()},f.prototype.change=f.prototype.change,f.prototype.init=function(){if(this.element_){if(this.isIE_){var e=document.createElement("div");e.classList.add(this.CssClasses_.IE_CONTAINER),this.element_.parentElement.insertBefore(e,this.element_),this.element_.parentElement.removeChild(this.element_),e.appendChild(this.element_)}else{var t=document.createElement("div");t.classList.add(this.CssClasses_.SLIDER_CONTAINER),this.element_.parentElement.insertBefore(t,this.element_),this.element_.parentElement.removeChild(this.element_),t.appendChild(this.element_);var n=document.createElement("div");n.classList.add(this.CssClasses_.BACKGROUND_FLEX),t.appendChild(n),this.backgroundLower_=document.createElement("div"),this.backgroundLower_.classList.add(this.CssClasses_.BACKGROUND_LOWER),n.appendChild(this.backgroundLower_),this.backgroundUpper_=document.createElement("div"),this.backgroundUpper_.classList.add(this.CssClasses_.BACKGROUND_UPPER),n.appendChild(this.backgroundUpper_)}this.boundInputHandler=this.onInput_.bind(this),this.boundChangeHandler=this.onChange_.bind(this),this.boundMouseUpHandler=this.onMouseUp_.bind(this),this.boundContainerMouseDownHandler=this.onContainerMouseDown_.bind(this),this.element_.addEventListener("input",this.boundInputHandler),this.element_.addEventListener("change",this.boundChangeHandler),this.element_.addEventListener("mouseup",this.boundMouseUpHandler),this.element_.parentElement.addEventListener("mousedown",this.boundContainerMouseDownHandler),this.updateValueStyles_(),this.element_.classList.add(this.CssClasses_.IS_UPGRADED)}},n.register({constructor:f,classAsString:"MaterialSlider",cssClass:"mdl-js-slider",widget:!0});var m=function(e){if(this.element_=e,this.textElement_=this.element_.querySelector("."+this.cssClasses_.MESSAGE),this.actionElement_=this.element_.querySelector("."+this.cssClasses_.ACTION),!this.textElement_)throw new Error("There must be a message element for a snackbar.");if(!this.actionElement_)throw new Error("There must be an action element for a snackbar.");this.active=!1,this.actionHandler_=void 0,this.message_=void 0,this.actionText_=void 0,this.queuedNotifications_=[],this.setActionHidden_(!0)};window.MaterialSnackbar=m,m.prototype.Constant_={ANIMATION_LENGTH:250},m.prototype.cssClasses_={SNACKBAR:"mdl-snackbar",MESSAGE:"mdl-snackbar__text",ACTION:"mdl-snackbar__action",ACTIVE:"mdl-snackbar--active"},m.prototype.displaySnackbar_=function(){this.element_.setAttribute("aria-hidden","true"),this.actionHandler_&&(this.actionElement_.textContent=this.actionText_,this.actionElement_.addEventListener("click",this.actionHandler_),this.setActionHidden_(!1)),this.textElement_.textContent=this.message_,this.element_.classList.add(this.cssClasses_.ACTIVE),this.element_.setAttribute("aria-hidden","false"),setTimeout(this.cleanup_.bind(this),this.timeout_)},m.prototype.showSnackbar=function(e){if(void 0===e)throw new Error("Please provide a data object with at least a message to display.");if(void 0===e.message)throw new Error("Please provide a message to be displayed.");if(e.actionHandler&&!e.actionText)throw new Error("Please provide action text with the handler.");this.active?this.queuedNotifications_.push(e):(this.active=!0,this.message_=e.message,e.timeout?this.timeout_=e.timeout:this.timeout_=2750,e.actionHandler&&(this.actionHandler_=e.actionHandler),e.actionText&&(this.actionText_=e.actionText),this.displaySnackbar_())},m.prototype.showSnackbar=m.prototype.showSnackbar,m.prototype.checkQueue_=function(){this.queuedNotifications_.length>0&&this.showSnackbar(this.queuedNotifications_.shift())},m.prototype.cleanup_=function(){this.element_.classList.remove(this.cssClasses_.ACTIVE),setTimeout(function(){this.element_.setAttribute("aria-hidden","true"),this.textElement_.textContent="",Boolean(this.actionElement_.getAttribute("aria-hidden"))||(this.setActionHidden_(!0),this.actionElement_.textContent="",this.actionElement_.removeEventListener("click",this.actionHandler_)),this.actionHandler_=void 0,this.message_=void 0,this.actionText_=void 0,this.active=!1,this.checkQueue_()}.bind(this),this.Constant_.ANIMATION_LENGTH)},m.prototype.setActionHidden_=function(e){e?this.actionElement_.setAttribute("aria-hidden","true"):this.actionElement_.removeAttribute("aria-hidden")},n.register({constructor:m,classAsString:"MaterialSnackbar",cssClass:"mdl-js-snackbar",widget:!0});var h=function(e){this.element_=e,this.init()};window.MaterialSpinner=h,h.prototype.Constant_={MDL_SPINNER_LAYER_COUNT:4},h.prototype.CssClasses_={MDL_SPINNER_LAYER:"mdl-spinner__layer",MDL_SPINNER_CIRCLE_CLIPPER:"mdl-spinner__circle-clipper",MDL_SPINNER_CIRCLE:"mdl-spinner__circle",MDL_SPINNER_GAP_PATCH:"mdl-spinner__gap-patch",MDL_SPINNER_LEFT:"mdl-spinner__left",MDL_SPINNER_RIGHT:"mdl-spinner__right"},h.prototype.createLayer=function(e){var t=document.createElement("div");t.classList.add(this.CssClasses_.MDL_SPINNER_LAYER),t.classList.add(this.CssClasses_.MDL_SPINNER_LAYER+"-"+e);var n=document.createElement("div");n.classList.add(this.CssClasses_.MDL_SPINNER_CIRCLE_CLIPPER),n.classList.add(this.CssClasses_.MDL_SPINNER_LEFT);var r=document.createElement("div");r.classList.add(this.CssClasses_.MDL_SPINNER_GAP_PATCH);var o=document.createElement("div");o.classList.add(this.CssClasses_.MDL_SPINNER_CIRCLE_CLIPPER),o.classList.add(this.CssClasses_.MDL_SPINNER_RIGHT);for(var i=[n,r,o],a=0;a<i.length;a++){var l=document.createElement("div");l.classList.add(this.CssClasses_.MDL_SPINNER_CIRCLE),i[a].appendChild(l)}t.appendChild(n),t.appendChild(r),t.appendChild(o),this.element_.appendChild(t)},h.prototype.createLayer=h.prototype.createLayer,h.prototype.stop=function(){this.element_.classList.remove("is-active")},h.prototype.stop=h.prototype.stop,h.prototype.start=function(){this.element_.classList.add("is-active")},h.prototype.start=h.prototype.start,h.prototype.init=function(){if(this.element_){for(var e=1;e<=this.Constant_.MDL_SPINNER_LAYER_COUNT;e++)this.createLayer(e);this.element_.classList.add("is-upgraded")}},n.register({constructor:h,classAsString:"MaterialSpinner",cssClass:"mdl-js-spinner",widget:!0});var g=function(e){this.element_=e,this.init()};window.MaterialSwitch=g,g.prototype.Constant_={TINY_TIMEOUT:.001},g.prototype.CssClasses_={INPUT:"mdl-switch__input",TRACK:"mdl-switch__track",THUMB:"mdl-switch__thumb",FOCUS_HELPER:"mdl-switch__focus-helper",RIPPLE_EFFECT:"mdl-js-ripple-effect",RIPPLE_IGNORE_EVENTS:"mdl-js-ripple-effect--ignore-events",RIPPLE_CONTAINER:"mdl-switch__ripple-container",RIPPLE_CENTER:"mdl-ripple--center",RIPPLE:"mdl-ripple",IS_FOCUSED:"is-focused",IS_DISABLED:"is-disabled",IS_CHECKED:"is-checked"},g.prototype.onChange_=function(e){this.updateClasses_()},g.prototype.onFocus_=function(e){this.element_.classList.add(this.CssClasses_.IS_FOCUSED)},g.prototype.onBlur_=function(e){this.element_.classList.remove(this.CssClasses_.IS_FOCUSED)},g.prototype.onMouseUp_=function(e){this.blur_()},g.prototype.updateClasses_=function(){this.checkDisabled(),this.checkToggleState()},g.prototype.blur_=function(){window.setTimeout(function(){this.inputElement_.blur()}.bind(this),this.Constant_.TINY_TIMEOUT)},g.prototype.checkDisabled=function(){this.inputElement_.disabled?this.element_.classList.add(this.CssClasses_.IS_DISABLED):this.element_.classList.remove(this.CssClasses_.IS_DISABLED)},g.prototype.checkDisabled=g.prototype.checkDisabled,g.prototype.checkToggleState=function(){this.inputElement_.checked?this.element_.classList.add(this.CssClasses_.IS_CHECKED):this.element_.classList.remove(this.CssClasses_.IS_CHECKED)},g.prototype.checkToggleState=g.prototype.checkToggleState,g.prototype.disable=function(){this.inputElement_.disabled=!0,this.updateClasses_()},g.prototype.disable=g.prototype.disable,g.prototype.enable=function(){this.inputElement_.disabled=!1,this.updateClasses_()},g.prototype.enable=g.prototype.enable,g.prototype.on=function(){this.inputElement_.checked=!0,this.updateClasses_()},g.prototype.on=g.prototype.on,g.prototype.off=function(){this.inputElement_.checked=!1,this.updateClasses_()},g.prototype.off=g.prototype.off,g.prototype.init=function(){if(this.element_){this.inputElement_=this.element_.querySelector("."+this.CssClasses_.INPUT);var e=document.createElement("div");e.classList.add(this.CssClasses_.TRACK);var t=document.createElement("div");t.classList.add(this.CssClasses_.THUMB);var n=document.createElement("span");if(n.classList.add(this.CssClasses_.FOCUS_HELPER),t.appendChild(n),this.element_.appendChild(e),this.element_.appendChild(t),this.boundMouseUpHandler=this.onMouseUp_.bind(this),this.element_.classList.contains(this.CssClasses_.RIPPLE_EFFECT)){this.element_.classList.add(this.CssClasses_.RIPPLE_IGNORE_EVENTS),this.rippleContainerElement_=document.createElement("span"),this.rippleContainerElement_.classList.add(this.CssClasses_.RIPPLE_CONTAINER),this.rippleContainerElement_.classList.add(this.CssClasses_.RIPPLE_EFFECT),this.rippleContainerElement_.classList.add(this.CssClasses_.RIPPLE_CENTER),this.rippleContainerElement_.addEventListener("mouseup",this.boundMouseUpHandler);var r=document.createElement("span");r.classList.add(this.CssClasses_.RIPPLE),this.rippleContainerElement_.appendChild(r),this.element_.appendChild(this.rippleContainerElement_)}this.boundChangeHandler=this.onChange_.bind(this),this.boundFocusHandler=this.onFocus_.bind(this),this.boundBlurHandler=this.onBlur_.bind(this),this.inputElement_.addEventListener("change",this.boundChangeHandler),this.inputElement_.addEventListener("focus",this.boundFocusHandler),this.inputElement_.addEventListener("blur",this.boundBlurHandler),this.element_.addEventListener("mouseup",this.boundMouseUpHandler),this.updateClasses_(),this.element_.classList.add("is-upgraded")}},n.register({constructor:g,classAsString:"MaterialSwitch",cssClass:"mdl-js-switch",widget:!0});var b=function(e){this.element_=e,this.init()};window.MaterialTabs=b,b.prototype.Constant_={},b.prototype.CssClasses_={TAB_CLASS:"mdl-tabs__tab",PANEL_CLASS:"mdl-tabs__panel",ACTIVE_CLASS:"is-active",UPGRADED_CLASS:"is-upgraded",MDL_JS_RIPPLE_EFFECT:"mdl-js-ripple-effect",MDL_RIPPLE_CONTAINER:"mdl-tabs__ripple-container",MDL_RIPPLE:"mdl-ripple",MDL_JS_RIPPLE_EFFECT_IGNORE_EVENTS:"mdl-js-ripple-effect--ignore-events"},b.prototype.initTabs_=function(){this.element_.classList.contains(this.CssClasses_.MDL_JS_RIPPLE_EFFECT)&&this.element_.classList.add(this.CssClasses_.MDL_JS_RIPPLE_EFFECT_IGNORE_EVENTS),this.tabs_=this.element_.querySelectorAll("."+this.CssClasses_.TAB_CLASS),this.panels_=this.element_.querySelectorAll("."+this.CssClasses_.PANEL_CLASS);for(var t=0;t<this.tabs_.length;t++)new e(this.tabs_[t],this);this.element_.classList.add(this.CssClasses_.UPGRADED_CLASS)},b.prototype.resetTabState_=function(){for(var e=0;e<this.tabs_.length;e++)this.tabs_[e].classList.remove(this.CssClasses_.ACTIVE_CLASS)},b.prototype.resetPanelState_=function(){for(var e=0;e<this.panels_.length;e++)this.panels_[e].classList.remove(this.CssClasses_.ACTIVE_CLASS)},b.prototype.init=function(){this.element_&&this.initTabs_()},n.register({constructor:b,classAsString:"MaterialTabs",cssClass:"mdl-js-tabs"});var y=function(e){this.element_=e,this.maxRows=this.Constant_.NO_MAX_ROWS,this.init()};window.MaterialTextfield=y,y.prototype.Constant_={NO_MAX_ROWS:-1,MAX_ROWS_ATTRIBUTE:"maxrows"},y.prototype.CssClasses_={LABEL:"mdl-textfield__label",INPUT:"mdl-textfield__input",IS_DIRTY:"is-dirty",IS_FOCUSED:"is-focused",IS_DISABLED:"is-disabled",IS_INVALID:"is-invalid",IS_UPGRADED:"is-upgraded",HAS_PLACEHOLDER:"has-placeholder"},y.prototype.onKeyDown_=function(e){var t=e.target.value.split("\n").length;13===e.keyCode&&t>=this.maxRows&&e.preventDefault()},y.prototype.onFocus_=function(e){this.element_.classList.add(this.CssClasses_.IS_FOCUSED)},y.prototype.onBlur_=function(e){this.element_.classList.remove(this.CssClasses_.IS_FOCUSED)},y.prototype.onReset_=function(e){this.updateClasses_()},y.prototype.updateClasses_=function(){this.checkDisabled(),this.checkValidity(),this.checkDirty(),this.checkFocus()},y.prototype.checkDisabled=function(){this.input_.disabled?this.element_.classList.add(this.CssClasses_.IS_DISABLED):this.element_.classList.remove(this.CssClasses_.IS_DISABLED)},y.prototype.checkDisabled=y.prototype.checkDisabled,y.prototype.checkFocus=function(){Boolean(this.element_.querySelector(":focus"))?this.element_.classList.add(this.CssClasses_.IS_FOCUSED):this.element_.classList.remove(this.CssClasses_.IS_FOCUSED)},y.prototype.checkFocus=y.prototype.checkFocus,y.prototype.checkValidity=function(){this.input_.validity&&(this.input_.validity.valid?this.element_.classList.remove(this.CssClasses_.IS_INVALID):this.element_.classList.add(this.CssClasses_.IS_INVALID))},y.prototype.checkValidity=y.prototype.checkValidity,y.prototype.checkDirty=function(){this.input_.value&&this.input_.value.length>0?this.element_.classList.add(this.CssClasses_.IS_DIRTY):this.element_.classList.remove(this.CssClasses_.IS_DIRTY)},y.prototype.checkDirty=y.prototype.checkDirty,y.prototype.disable=function(){this.input_.disabled=!0,this.updateClasses_()},y.prototype.disable=y.prototype.disable,y.prototype.enable=function(){this.input_.disabled=!1,this.updateClasses_()},y.prototype.enable=y.prototype.enable,y.prototype.change=function(e){this.input_.value=e||"",this.updateClasses_()},y.prototype.change=y.prototype.change,y.prototype.init=function(){if(this.element_&&(this.label_=this.element_.querySelector("."+this.CssClasses_.LABEL),this.input_=this.element_.querySelector("."+this.CssClasses_.INPUT),this.input_)){this.input_.hasAttribute(this.Constant_.MAX_ROWS_ATTRIBUTE)&&(this.maxRows=parseInt(this.input_.getAttribute(this.Constant_.MAX_ROWS_ATTRIBUTE),10),isNaN(this.maxRows)&&(this.maxRows=this.Constant_.NO_MAX_ROWS)),this.input_.hasAttribute("placeholder")&&this.element_.classList.add(this.CssClasses_.HAS_PLACEHOLDER),this.boundUpdateClassesHandler=this.updateClasses_.bind(this),this.boundFocusHandler=this.onFocus_.bind(this),this.boundBlurHandler=this.onBlur_.bind(this),this.boundResetHandler=this.onReset_.bind(this),this.input_.addEventListener("input",this.boundUpdateClassesHandler),this.input_.addEventListener("focus",this.boundFocusHandler),this.input_.addEventListener("blur",this.boundBlurHandler),this.input_.addEventListener("reset",this.boundResetHandler),this.maxRows!==this.Constant_.NO_MAX_ROWS&&(this.boundKeyDownHandler=this.onKeyDown_.bind(this),this.input_.addEventListener("keydown",this.boundKeyDownHandler));var e=this.element_.classList.contains(this.CssClasses_.IS_INVALID);this.updateClasses_(),this.element_.classList.add(this.CssClasses_.IS_UPGRADED),e&&this.element_.classList.add(this.CssClasses_.IS_INVALID),this.input_.hasAttribute("autofocus")&&(this.element_.focus(),this.checkFocus())}},n.register({constructor:y,classAsString:"MaterialTextfield",cssClass:"mdl-js-textfield",widget:!0});var v=function(e){this.element_=e,this.init()};window.MaterialTooltip=v,v.prototype.Constant_={},v.prototype.CssClasses_={IS_ACTIVE:"is-active",BOTTOM:"mdl-tooltip--bottom",LEFT:"mdl-tooltip--left",RIGHT:"mdl-tooltip--right",TOP:"mdl-tooltip--top"},v.prototype.handleMouseEnter_=function(e){var t=e.target.getBoundingClientRect(),n=t.left+t.width/2,r=t.top+t.height/2,o=-1*(this.element_.offsetWidth/2),i=-1*(this.element_.offsetHeight/2);this.element_.classList.contains(this.CssClasses_.LEFT)||this.element_.classList.contains(this.CssClasses_.RIGHT)?(n=t.width/2,r+i<0?(this.element_.style.top="0",this.element_.style.marginTop="0"):(this.element_.style.top=r+"px",this.element_.style.marginTop=i+"px")):n+o<0?(this.element_.style.left="0",this.element_.style.marginLeft="0"):(this.element_.style.left=n+"px",this.element_.style.marginLeft=o+"px"),this.element_.classList.contains(this.CssClasses_.TOP)?this.element_.style.top=t.top-this.element_.offsetHeight-10+"px":this.element_.classList.contains(this.CssClasses_.RIGHT)?this.element_.style.left=t.left+t.width+10+"px":this.element_.classList.contains(this.CssClasses_.LEFT)?this.element_.style.left=t.left-this.element_.offsetWidth-10+"px":this.element_.style.top=t.top+t.height+10+"px",this.element_.classList.add(this.CssClasses_.IS_ACTIVE)},v.prototype.hideTooltip_=function(){this.element_.classList.remove(this.CssClasses_.IS_ACTIVE)},v.prototype.init=function(){if(this.element_){var e=this.element_.getAttribute("for")||this.element_.getAttribute("data-mdl-for");e&&(this.forElement_=document.getElementById(e)),this.forElement_&&(this.forElement_.hasAttribute("tabindex")||this.forElement_.setAttribute("tabindex","0"),this.boundMouseEnterHandler=this.handleMouseEnter_.bind(this),this.boundMouseLeaveAndScrollHandler=this.hideTooltip_.bind(this),this.forElement_.addEventListener("mouseenter",this.boundMouseEnterHandler,!1),this.forElement_.addEventListener("touchend",this.boundMouseEnterHandler,!1),this.forElement_.addEventListener("mouseleave",this.boundMouseLeaveAndScrollHandler,!1),window.addEventListener("scroll",this.boundMouseLeaveAndScrollHandler,!0),window.addEventListener("touchstart",this.boundMouseLeaveAndScrollHandler))}},n.register({constructor:v,classAsString:"MaterialTooltip",cssClass:"mdl-tooltip"});var _=function(e){this.element_=e,this.innerContainer_=e.querySelector("."+this.CssClasses_.INNER_CONTAINER),this.init()};window.MaterialLayout=_,_.prototype.Constant_={MAX_WIDTH:"(max-width: 1024px)",TAB_SCROLL_PIXELS:100,RESIZE_TIMEOUT:100,MENU_ICON:"",CHEVRON_LEFT:"chevron_left",CHEVRON_RIGHT:"chevron_right"},_.prototype.Keycodes_={ENTER:13,ESCAPE:27,SPACE:32},_.prototype.Mode_={STANDARD:0,SEAMED:1,WATERFALL:2,SCROLL:3},_.prototype.CssClasses_={INNER_CONTAINER:"mdl-layout__inner-container",HEADER:"mdl-layout__header",DRAWER:"mdl-layout__drawer",CONTENT:"mdl-layout__content",DRAWER_BTN:"mdl-layout__drawer-button",ICON:"material-icons",JS_RIPPLE_EFFECT:"mdl-js-ripple-effect",RIPPLE_CONTAINER:"mdl-layout__tab-ripple-container",RIPPLE:"mdl-ripple",RIPPLE_IGNORE_EVENTS:"mdl-js-ripple-effect--ignore-events",HEADER_SEAMED:"mdl-layout__header--seamed",HEADER_WATERFALL:"mdl-layout__header--waterfall",HEADER_SCROLL:"mdl-layout__header--scroll",FIXED_HEADER:"mdl-layout--fixed-header",OBFUSCATOR:"mdl-layout__obfuscator",TAB_BAR:"mdl-layout__tab-bar",TAB_CONTAINER:"mdl-layout__tab-bar-container",TAB:"mdl-layout__tab",TAB_BAR_BUTTON:"mdl-layout__tab-bar-button",TAB_BAR_LEFT_BUTTON:"mdl-layout__tab-bar-left-button",TAB_BAR_RIGHT_BUTTON:"mdl-layout__tab-bar-right-button",PANEL:"mdl-layout__tab-panel",HAS_DRAWER:"has-drawer",HAS_TABS:"has-tabs",HAS_SCROLLING_HEADER:"has-scrolling-header",CASTING_SHADOW:"is-casting-shadow",IS_COMPACT:"is-compact",IS_SMALL_SCREEN:"is-small-screen",IS_DRAWER_OPEN:"is-visible",IS_ACTIVE:"is-active",IS_UPGRADED:"is-upgraded",IS_ANIMATING:"is-animating",ON_LARGE_SCREEN:"mdl-layout--large-screen-only",ON_SMALL_SCREEN:"mdl-layout--small-screen-only"},_.prototype.contentScrollHandler_=function(){if(!this.header_.classList.contains(this.CssClasses_.IS_ANIMATING)){var e=!this.element_.classList.contains(this.CssClasses_.IS_SMALL_SCREEN)||this.element_.classList.contains(this.CssClasses_.FIXED_HEADER);this.content_.scrollTop>0&&!this.header_.classList.contains(this.CssClasses_.IS_COMPACT)?(this.header_.classList.add(this.CssClasses_.CASTING_SHADOW),this.header_.classList.add(this.CssClasses_.IS_COMPACT),e&&this.header_.classList.add(this.CssClasses_.IS_ANIMATING)):this.content_.scrollTop<=0&&this.header_.classList.contains(this.CssClasses_.IS_COMPACT)&&(this.header_.classList.remove(this.CssClasses_.CASTING_SHADOW),this.header_.classList.remove(this.CssClasses_.IS_COMPACT),e&&this.header_.classList.add(this.CssClasses_.IS_ANIMATING))}},_.prototype.keyboardEventHandler_=function(e){e.keyCode===this.Keycodes_.ESCAPE&&this.drawer_.classList.contains(this.CssClasses_.IS_DRAWER_OPEN)&&this.toggleDrawer()},_.prototype.screenSizeHandler_=function(){this.screenSizeMediaQuery_.matches?this.element_.classList.add(this.CssClasses_.IS_SMALL_SCREEN):(this.element_.classList.remove(this.CssClasses_.IS_SMALL_SCREEN),this.drawer_&&(this.drawer_.classList.remove(this.CssClasses_.IS_DRAWER_OPEN),this.obfuscator_.classList.remove(this.CssClasses_.IS_DRAWER_OPEN)))},_.prototype.drawerToggleHandler_=function(e){if(e&&"keydown"===e.type){if(e.keyCode!==this.Keycodes_.SPACE&&e.keyCode!==this.Keycodes_.ENTER)return;e.preventDefault()}this.toggleDrawer()},_.prototype.headerTransitionEndHandler_=function(){this.header_.classList.remove(this.CssClasses_.IS_ANIMATING)},_.prototype.headerClickHandler_=function(){this.header_.classList.contains(this.CssClasses_.IS_COMPACT)&&(this.header_.classList.remove(this.CssClasses_.IS_COMPACT),this.header_.classList.add(this.CssClasses_.IS_ANIMATING))},_.prototype.resetTabState_=function(e){for(var t=0;t<e.length;t++)e[t].classList.remove(this.CssClasses_.IS_ACTIVE)},_.prototype.resetPanelState_=function(e){for(var t=0;t<e.length;t++)e[t].classList.remove(this.CssClasses_.IS_ACTIVE)},_.prototype.toggleDrawer=function(){var e=this.innerContainer_.querySelector("."+this.CssClasses_.DRAWER_BTN);this.drawer_.classList.toggle(this.CssClasses_.IS_DRAWER_OPEN),this.obfuscator_.classList.toggle(this.CssClasses_.IS_DRAWER_OPEN),this.drawer_.classList.contains(this.CssClasses_.IS_DRAWER_OPEN)?(this.drawer_.setAttribute("aria-hidden","false"),e.setAttribute("aria-expanded","true")):(this.drawer_.setAttribute("aria-hidden","true"),e.setAttribute("aria-expanded","false"))},_.prototype.toggleDrawer=_.prototype.toggleDrawer,_.prototype.init=function(){if(this.element_){var e=this.element_.querySelector(":focus");e&&e.focus();for(var n=this.innerContainer_.childNodes,r=n.length,o=0;o<r;o++){var i=n[o];i.classList&&i.classList.contains(this.CssClasses_.HEADER)&&(this.header_=i),i.classList&&i.classList.contains(this.CssClasses_.DRAWER)&&(this.drawer_=i),i.classList&&i.classList.contains(this.CssClasses_.CONTENT)&&(this.content_=i)}window.addEventListener("pageshow",function(e){e.persisted&&(this.innerContainer_.style.overflowY="hidden",requestAnimationFrame(function(){this.innerContainer_.style.overflowY=""}.bind(this)))}.bind(this),!1),this.header_&&(this.tabBar_=this.header_.querySelector("."+this.CssClasses_.TAB_BAR));var a=this.Mode_.STANDARD;if(this.header_&&(this.header_.classList.contains(this.CssClasses_.HEADER_SEAMED)?a=this.Mode_.SEAMED:this.header_.classList.contains(this.CssClasses_.HEADER_WATERFALL)?(a=this.Mode_.WATERFALL,this.header_.addEventListener("transitionend",this.headerTransitionEndHandler_.bind(this)),this.header_.addEventListener("click",this.headerClickHandler_.bind(this))):this.header_.classList.contains(this.CssClasses_.HEADER_SCROLL)&&(a=this.Mode_.SCROLL,this.element_.classList.add(this.CssClasses_.HAS_SCROLLING_HEADER)),a===this.Mode_.STANDARD?(this.header_.classList.add(this.CssClasses_.CASTING_SHADOW),this.tabBar_&&this.tabBar_.classList.add(this.CssClasses_.CASTING_SHADOW)):a===this.Mode_.SEAMED||a===this.Mode_.SCROLL?(this.header_.classList.remove(this.CssClasses_.CASTING_SHADOW),this.tabBar_&&this.tabBar_.classList.remove(this.CssClasses_.CASTING_SHADOW)):a===this.Mode_.WATERFALL&&(this.content_.addEventListener("scroll",this.contentScrollHandler_.bind(this)),this.contentScrollHandler_())),this.drawer_){var l=this.innerContainer_.querySelector("."+this.CssClasses_.DRAWER_BTN);if(!l){l=document.createElement("div"),l.setAttribute("aria-expanded","false"),l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.classList.add(this.CssClasses_.DRAWER_BTN);var s=document.createElement("i");s.classList.add(this.CssClasses_.ICON),s.innerHTML=this.Constant_.MENU_ICON,l.appendChild(s)}this.drawer_.classList.contains(this.CssClasses_.ON_LARGE_SCREEN)?l.classList.add(this.CssClasses_.ON_LARGE_SCREEN):this.drawer_.classList.contains(this.CssClasses_.ON_SMALL_SCREEN)&&l.classList.add(this.CssClasses_.ON_SMALL_SCREEN),l.addEventListener("click",this.drawerToggleHandler_.bind(this)),l.addEventListener("keydown",this.drawerToggleHandler_.bind(this)),this.element_.classList.add(this.CssClasses_.HAS_DRAWER),this.element_.classList.contains(this.CssClasses_.FIXED_HEADER)?this.header_.insertBefore(l,this.header_.firstChild):this.innerContainer_.insertBefore(l,this.content_);var c=document.createElement("div");c.classList.add(this.CssClasses_.OBFUSCATOR),this.innerContainer_.appendChild(c),c.addEventListener("click",this.drawerToggleHandler_.bind(this)),this.obfuscator_=c,this.drawer_.addEventListener("keydown",this.keyboardEventHandler_.bind(this)),this.drawer_.setAttribute("aria-hidden","true")}if(this.screenSizeMediaQuery_=window.matchMedia(this.Constant_.MAX_WIDTH),this.screenSizeMediaQuery_.addListener(this.screenSizeHandler_.bind(this)),this.screenSizeHandler_(),this.header_&&this.tabBar_){this.element_.classList.add(this.CssClasses_.HAS_TABS);var u=document.createElement("div");u.classList.add(this.CssClasses_.TAB_CONTAINER),this.header_.insertBefore(u,this.tabBar_),this.header_.removeChild(this.tabBar_);var d=document.createElement("div");d.classList.add(this.CssClasses_.TAB_BAR_BUTTON),d.classList.add(this.CssClasses_.TAB_BAR_LEFT_BUTTON);var p=document.createElement("i");p.classList.add(this.CssClasses_.ICON),p.textContent=this.Constant_.CHEVRON_LEFT,d.appendChild(p),d.addEventListener("click",function(){this.tabBar_.scrollLeft-=this.Constant_.TAB_SCROLL_PIXELS}.bind(this));var f=document.createElement("div");f.classList.add(this.CssClasses_.TAB_BAR_BUTTON),f.classList.add(this.CssClasses_.TAB_BAR_RIGHT_BUTTON);var m=document.createElement("i");m.classList.add(this.CssClasses_.ICON),m.textContent=this.Constant_.CHEVRON_RIGHT,f.appendChild(m),f.addEventListener("click",function(){this.tabBar_.scrollLeft+=this.Constant_.TAB_SCROLL_PIXELS}.bind(this)),u.appendChild(d),u.appendChild(this.tabBar_),u.appendChild(f);var h=function(){this.tabBar_.scrollLeft>0?d.classList.add(this.CssClasses_.IS_ACTIVE):d.classList.remove(this.CssClasses_.IS_ACTIVE),this.tabBar_.scrollLeft<this.tabBar_.scrollWidth-this.tabBar_.offsetWidth?f.classList.add(this.CssClasses_.IS_ACTIVE):f.classList.remove(this.CssClasses_.IS_ACTIVE)}.bind(this);this.tabBar_.addEventListener("scroll",h),h();var g=function(){this.resizeTimeoutId_&&clearTimeout(this.resizeTimeoutId_),this.resizeTimeoutId_=setTimeout(function(){h(),this.resizeTimeoutId_=null}.bind(this),this.Constant_.RESIZE_TIMEOUT)}.bind(this);window.addEventListener("resize",g),this.tabBar_.classList.contains(this.CssClasses_.JS_RIPPLE_EFFECT)&&this.tabBar_.classList.add(this.CssClasses_.RIPPLE_IGNORE_EVENTS);for(var b=this.tabBar_.querySelectorAll("."+this.CssClasses_.TAB),y=this.content_.querySelectorAll("."+this.CssClasses_.PANEL),v=0;v<b.length;v++)new t(b[v],b,y,this)}this.element_.classList.add(this.CssClasses_.IS_UPGRADED)}},window.MaterialLayoutTab=t,n.register({constructor:_,classAsString:"MaterialLayout",cssClass:"mdl-js-layout"});var x=function(e){this.element_=e,this.init()};window.MaterialDataTable=x,x.prototype.Constant_={},x.prototype.CssClasses_={DATA_TABLE:"mdl-data-table",SELECTABLE:"mdl-data-table--selectable",SELECT_ELEMENT:"mdl-data-table__select",IS_SELECTED:"is-selected",IS_UPGRADED:"is-upgraded"},x.prototype.selectRow_=function(e,t,n){return t?function(){e.checked?t.classList.add(this.CssClasses_.IS_SELECTED):t.classList.remove(this.CssClasses_.IS_SELECTED)}.bind(this):n?function(){var t,r;if(e.checked)for(t=0;t<n.length;t++)r=n[t].querySelector("td").querySelector(".mdl-checkbox"),r.MaterialCheckbox.check(),n[t].classList.add(this.CssClasses_.IS_SELECTED);else for(t=0;t<n.length;t++)r=n[t].querySelector("td").querySelector(".mdl-checkbox"),r.MaterialCheckbox.uncheck(),n[t].classList.remove(this.CssClasses_.IS_SELECTED)}.bind(this):void 0},x.prototype.createCheckbox_=function(e,t){var r=document.createElement("label"),o=["mdl-checkbox","mdl-js-checkbox","mdl-js-ripple-effect",this.CssClasses_.SELECT_ELEMENT];r.className=o.join(" ");var i=document.createElement("input");return i.type="checkbox",i.classList.add("mdl-checkbox__input"),e?(i.checked=e.classList.contains(this.CssClasses_.IS_SELECTED),i.addEventListener("change",this.selectRow_(i,e))):t&&i.addEventListener("change",this.selectRow_(i,null,t)),r.appendChild(i),n.upgradeElement(r,"MaterialCheckbox"),r},x.prototype.init=function(){if(this.element_){var e=this.element_.querySelector("th"),t=Array.prototype.slice.call(this.element_.querySelectorAll("tbody tr")),n=Array.prototype.slice.call(this.element_.querySelectorAll("tfoot tr")),r=t.concat(n);if(this.element_.classList.contains(this.CssClasses_.SELECTABLE)){var o=document.createElement("th"),i=this.createCheckbox_(null,r);o.appendChild(i),e.parentElement.insertBefore(o,e);for(var a=0;a<r.length;a++){var l=r[a].querySelector("td");if(l){var s=document.createElement("td");if("TBODY"===r[a].parentNode.nodeName.toUpperCase()){var c=this.createCheckbox_(r[a]);s.appendChild(c)}r[a].insertBefore(s,l)}}this.element_.classList.add(this.CssClasses_.IS_UPGRADED)}}},n.register({constructor:x,classAsString:"MaterialDataTable",cssClass:"mdl-js-data-table"});var w=function(e){this.element_=e,this.init()};window.MaterialRipple=w,w.prototype.Constant_={INITIAL_SCALE:"scale(0.0001, 0.0001)",INITIAL_SIZE:"1px",INITIAL_OPACITY:"0.4",FINAL_OPACITY:"0",FINAL_SCALE:""},w.prototype.CssClasses_={RIPPLE_CENTER:"mdl-ripple--center",RIPPLE_EFFECT_IGNORE_EVENTS:"mdl-js-ripple-effect--ignore-events",RIPPLE:"mdl-ripple",IS_ANIMATING:"is-animating",IS_VISIBLE:"is-visible"},w.prototype.downHandler_=function(e){if(!this.rippleElement_.style.width&&!this.rippleElement_.style.height){var t=this.element_.getBoundingClientRect();this.boundHeight=t.height,this.boundWidth=t.width,this.rippleSize_=2*Math.sqrt(t.width*t.width+t.height*t.height)+2,this.rippleElement_.style.width=this.rippleSize_+"px",this.rippleElement_.style.height=this.rippleSize_+"px"}if(this.rippleElement_.classList.add(this.CssClasses_.IS_VISIBLE),"mousedown"===e.type&&this.ignoringMouseDown_)this.ignoringMouseDown_=!1;else{"touchstart"===e.type&&(this.ignoringMouseDown_=!0);if(this.getFrameCount()>0)return;this.setFrameCount(1);var n,r,o=e.currentTarget.getBoundingClientRect();if(0===e.clientX&&0===e.clientY)n=Math.round(o.width/2),r=Math.round(o.height/2);else{var i=e.clientX?e.clientX:e.touches[0].clientX,a=e.clientY?e.clientY:e.touches[0].clientY;n=Math.round(i-o.left),r=Math.round(a-o.top)}this.setRippleXY(n,r),this.setRippleStyles(!0),window.requestAnimationFrame(this.animFrameHandler.bind(this))}},w.prototype.upHandler_=function(e){e&&2!==e.detail&&window.setTimeout(function(){this.rippleElement_.classList.remove(this.CssClasses_.IS_VISIBLE)}.bind(this),0)},w.prototype.init=function(){if(this.element_){var e=this.element_.classList.contains(this.CssClasses_.RIPPLE_CENTER);this.element_.classList.contains(this.CssClasses_.RIPPLE_EFFECT_IGNORE_EVENTS)||(this.rippleElement_=this.element_.querySelector("."+this.CssClasses_.RIPPLE),this.frameCount_=0,this.rippleSize_=0,this.x_=0,this.y_=0,this.ignoringMouseDown_=!1,this.boundDownHandler=this.downHandler_.bind(this),this.element_.addEventListener("mousedown",this.boundDownHandler),this.element_.addEventListener("touchstart",this.boundDownHandler),this.boundUpHandler=this.upHandler_.bind(this),this.element_.addEventListener("mouseup",this.boundUpHandler),this.element_.addEventListener("mouseleave",this.boundUpHandler),this.element_.addEventListener("touchend",this.boundUpHandler),this.element_.addEventListener("blur",this.boundUpHandler),this.getFrameCount=function(){return this.frameCount_},this.setFrameCount=function(e){this.frameCount_=e},this.getRippleElement=function(){return this.rippleElement_},this.setRippleXY=function(e,t){this.x_=e,this.y_=t},this.setRippleStyles=function(t){if(null!==this.rippleElement_){var n,r,o="translate("+this.x_+"px, "+this.y_+"px)";t?(r=this.Constant_.INITIAL_SCALE,this.Constant_.INITIAL_SIZE):(r=this.Constant_.FINAL_SCALE,this.rippleSize_+"px",e&&(o="translate("+this.boundWidth/2+"px, "+this.boundHeight/2+"px)")),n="translate(-50%, -50%) "+o+r,this.rippleElement_.style.webkitTransform=n,this.rippleElement_.style.msTransform=n,this.rippleElement_.style.transform=n,t?this.rippleElement_.classList.remove(this.CssClasses_.IS_ANIMATING):this.rippleElement_.classList.add(this.CssClasses_.IS_ANIMATING)}},this.animFrameHandler=function(){this.frameCount_-- >0?window.requestAnimationFrame(this.animFrameHandler.bind(this)):this.setRippleStyles(!1)})}},n.register({constructor:w,classAsString:"MaterialRipple",cssClass:"mdl-js-ripple-effect",widget:!1})}}()},function(e,t,n){var r=n(550);"string"==typeof r&&(r=[[e.i,r,""]]);n(56)(r,{});r.locals&&(e.exports=r.locals)},function(e,t,n){"use strict";var r=n(87),o=n.n(r),i=n(50),a=n.n(i),l=n(51),s=n.n(l),c=n(52),u=n.n(c),d=n(54),p=n.n(d),f=n(53),m=n.n(f),h=n(10),g=n.n(h),b=n(88),y=n.n(b),v=n(303),_=n(302),x=(n(197),n(696)),w=n.n(x),C=function(e){function t(){return s()(this,t),p()(this,(t.__proto__||a()(t)).apply(this,arguments))}return m()(t,e),u()(t,[{key:"componentDidMount",value:function(){window.componentHandler.upgradeElement(this.root)}},{key:"componentWillUnmount",value:function(){window.componentHandler.downgradeElements(this.root)}},{key:"render",value:function(){var e=this;return g.a.createElement("div",{className:"mdl-layout mdl-js-layout",ref:function(t){return e.root=t}},g.a.createElement("div",{className:"mdl-layout__inner-container"},g.a.createElement(v.a,null),g.a.createElement("main",{className:"mdl-layout__content"},g.a.createElement("div",o()({},this.props,{className:y()(w.a.content,this.props.className)})),g.a.createElement(_.a,null))))}}]),t}(g.a.Component);C.propTypes={className:h.PropTypes.string},t.a=C},,function(e,t,n){"use strict";function r(){return i.a.createElement("footer",{className:"mdl-mini-footer"},i.a.createElement("div",{className:"mdl-mini-footer__left-section"},i.a.createElement("div",{className:"mdl-logo"},"© leo60228")),i.a.createElement("div",{className:"mdl-mini-footer__right-section"},i.a.createElement("ul",{className:"mdl-mini-footer__link-list"},i.a.createElement("li",{className:"mdl-mini-footer--social-btn",style:{backgroundColor:"transparent"}},i.a.createElement("a",{href:"https://github.com/leo60228/HouseRuler",role:"button",title:"GitHub"},i.a.createElement("svg",{width:"36",height:"36",viewBox:"0 0 24 24"},i.a.createElement("path",{fill:"#fff",d:"M12,2A10,10 0 0,0 2,12C2,16.42 4.87,20.17 8.84,21.5C9.34,21.58 9.5,21.27 9.5,21C9.5,20.77 9.5,20.14 9.5,19.31C6.73,19.91 6.14,17.97 6.14, 17.97C5.68,16.81 5.03,16.5 5.03,16.5C4.12,15.88 5.1,15.9 5.1,15.9C6.1,15.97 6.63, 16.93 6.63,16.93C7.5,18.45 8.97,18 9.54,17.76C9.63,17.11 9.89,16.67 10.17, 16.42C7.95,16.17 5.62,15.31 5.62,11.5C5.62,10.39 6,9.5 6.65,8.79C6.55,8.54 6.2, 7.5 6.75,6.15C6.75,6.15 7.59,5.88 9.5,7.17C10.29,6.95 11.15,6.84 12,6.84C12.85, 6.84 13.71,6.95 14.5,7.17C16.41,5.88 17.25,6.15 17.25,6.15C17.8,7.5 17.45,8.54 17.35,8.79C18,9.5 18.38,10.39 18.38,11.5C18.38,15.32 16.04,16.16 13.81, 16.41C14.17,16.72 14.5,17.33 14.5,18.26C14.5,19.6 14.5,20.68 14.5,21C14.5,21.27 14.66,21.59 15.17,21.5C19.14,20.16 22,16.42 22,12A10,10 0 0,0 12,2Z"})))))))}var o=n(10),i=n.n(o);n(102);t.a=r},function(e,t,n){"use strict";var r=n(50),o=n.n(r),i=n(51),a=n.n(i),l=n(52),s=n.n(l),c=n(54),u=n.n(c),d=n(53),p=n.n(d),f=n(10),m=n.n(f),h=n(304),g=n(102),b=n(695),y=n.n(b),v=function(e){function t(){return a()(this,t),u()(this,(t.__proto__||o()(t)).apply(this,arguments))}return p()(t,e),s()(t,[{key:"componentDidMount",value:function(){window.componentHandler.upgradeElement(this.root)}},{key:"componentWillUnmount",value:function(){window.componentHandler.downgradeElements(this.root)}},{key:"render",value:function(){var e=this;return m.a.createElement("header",{className:"mdl-layout__header "+y.a.header,ref:function(t){return e.root=t}},m.a.createElement("div",{className:"mdl-layout__header-row "+y.a.row},m.a.createElement(g.a,{className:"mdl-layout-title "+y.a.title,to:"/"},"HouseRuler"),m.a.createElement("div",{className:"mdl-layout-spacer"}),m.a.createElement(h.a,null)))}}]),t}(m.a.Component);t.a=v},function(e,t,n){"use strict";var r=n(50),o=n.n(r),i=n(51),a=n.n(i),l=n(52),s=n.n(l),c=n(54),u=n.n(c),d=n(53),p=n.n(d),f=n(10),m=n.n(f),h=n(102),g=n(191),b=function(e){return{editing:e.editing}},y=function(e){return{changeMode:function(t){e({type:"CHANGE_MODE"})}}},v=function(e){function t(){return a()(this,t),u()(this,(t.__proto__||o()(t)).apply(this,arguments))}return p()(t,e),s()(t,[{key:"componentDidMount",value:function(){window.componentHandler.upgradeElement(this.root)}},{key:"componentWillUnmount",value:function(){window.componentHandler.downgradeElements(this.root)}},{key:"render",value:function(){var e=this;return m.a.createElement("nav",{className:"mdl-navigation",ref:function(t){return e.root=t}},m.a.createElement("span",{className:"mdl-navigation__link",onClick:this.props.changeMode},this.props.editing?"💾 Save":"✎ Edit"),m.a.createElement(h.a,{className:"mdl-navigation__link",to:"/"},"Home"),m.a.createElement(h.a,{className:"mdl-navigation__link",to:"/about"},"About"))}}]),t}(m.a.Component);t.a=n.i(g.b)(b,y)(v)},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(317),o=n.n(r),i=n(50),a=n.n(i),l=n(51),s=n.n(l),c=n(52),u=n.n(c),d=n(54),p=n.n(d),f=n(53),m=n.n(f),h=n(10),g=n.n(h),b=n(103),y=n(102),v=n(698),_=n.n(v),x=function(e){function t(){var e,n,r,o;s()(this,t);for(var i=arguments.length,l=Array(i),c=0;c<i;c++)l[c]=arguments[c];return n=r=p()(this,(e=t.__proto__||a()(t)).call.apply(e,[this].concat(l))),r.goBack=function(e){e.preventDefault(),b.a.goBack()},o=n,p()(r,o)}return m()(t,e),u()(t,[{key:"componentDidMount",value:function(){document.title=this.props.error&&404===this.props.error.status?"Page Not Found":"Error"}},{key:"render",value:function(){this.props.error&&console.error(this.props.error);var e=this.props.error&&404===this.props.error.status?["404","Page not found"]:["Error","Oups, something went wrong"],t=o()(e,2),n=t[0],r=t[1];return g.a.createElement("div",{className:_.a.container},g.a.createElement("main",{className:_.a.content},g.a.createElement("h1",{className:_.a.code},n),g.a.createElement("p",{className:_.a.title},r),"404"===n&&g.a.createElement("p",{className:_.a.text},"The page you're looking for does not exist or an another error occurred."),g.a.createElement("p",{className:_.a.text},g.a.createElement("a",{href:"/",onClick:this.goBack},"Go back"),", or head over to the ",g.a.createElement(y.a,{to:"/"},"home page"),"to choose a new direction.")))}}]),t}(g.a.Component);x.propTypes={error:g.a.PropTypes.object},t.default=x},function(e,t,n){"use strict";function r(e){if("string"!=typeof e&&0!==e.length)return e;try{return decodeURIComponent(e)}catch(t){throw t instanceof URIError&&(t.message="Failed to decode param '"+e+"'",t.status=400),t}}function o(e,t){var n=e.pattern.exec(t);if(!n)return null;for(var o=C()(null),i=1;i<n.length;i+=1)o[e.keys[i-1].name]=void 0!==n[i]?r(n[i]):void 0;return o}function i(e,t){var n=!0,r=!1,i=void 0;try{for(var a,s=function(){var e=a.value,n=o(e,t.error?"/error":t.pathname);if(!n)return"continue";if(e.data){var r=h()(e.data);return{v:x.a.all([e.load()].concat(f()(r.map(function(t){var r=e.data[t],o=r.substring(0,r.indexOf(" ")),i=r.substr(r.indexOf(" ")+1);return h()(n).forEach(function(e){i=i.replace(""+e,n[e])}),fetch(i,{method:o}).then(function(e){return e.json()})})))).then(function(o){var i=d()(o),a=i[0],s=i.slice(1),u=r.reduce(function(e,t,n){return c()({},e,l()({},t,s[n]))},{});return E.a.createElement(a,c()({route:c()({},e,{params:n}),error:t.error},u))})}}return{v:e.load().then(function(r){return E.a.createElement(r,{route:c()({},e,{params:n}),error:t.error})})}},u=v()(e);!(n=(a=u.next()).done);n=!0){var p=s();switch(p){case"continue":continue;default:if("object"===(void 0===p?"undefined":b()(p)))return p.v}}}catch(e){r=!0,i=e}finally{try{!n&&u.return&&u.return()}finally{if(r)throw i}}var m=new Error("Page not found");return m.status=404,x.a.reject(m)}var a=n(315),l=n.n(a),s=n(87),c=n.n(s),u=n(318),d=n.n(u),p=n(204),f=n.n(p),m=n(311),h=n.n(m),g=n(129),b=n.n(g),y=n(199),v=n.n(y),_=n(203),x=n.n(_),w=n(201),C=n.n(w),k=n(10),E=n.n(k);t.a={resolve:i}},function(e,t,n){"use strict";var r=n(87),o=n.n(r),i=n(294),a=""!==window.location.search;console.log(a);var l={editing:!a},s=n.i(i.a)(function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:l;switch(arguments[1].type){case"CHANGE_MODE":return console.log("mode changed"),o()({},e,{editing:!e.editing});default:return e}});t.a=s},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(203),o=n.n(r);t.default=[{path:"/",pattern:/^(?:\/(?=$))?$/i,keys:[],page:"./home",load:function(){return o.a.resolve(n(128).default)}},{path:"/error",pattern:/^\/error(?:\/(?=$))?$/i,keys:[],page:"./error",load:function(){return o.a.resolve(n(305).default)}},{path:"/about",pattern:/^\/about(?:\/(?=$))?$/i,keys:[],page:"./about",load:function(){return new o.a(function(e,t){try{n.e(0).then(function(t){e(n(301).default)}.bind(null,n)).catch(n.oe)}catch(e){t(e)}})}},{path:"/tasks/:status(pending|completed)?",pattern:/^\/tasks(?:\/((?:pending|completed)))?(?:\/(?=$))?$/i,keys:[{name:"status",prefix:"/",delimiter:"/",optional:!0,repeat:!1,partial:!1,asterisk:!1,pattern:"pending|completed"}],page:"./home",load:function(){return new o.a(function(e,t){try{Promise.resolve().then(function(t){e(n(128).default)}.bind(null,n)).catch(n.oe)}catch(e){t(e)}})}}]},function(e,t,n){"use strict";(function(e){function t(e,t,n){e[t]||Object[r](e,t,{writable:!0,configurable:!0,value:n})}if(n(549),n(690),n(321),e._babelPolyfill)throw new Error("only one instance of babel-polyfill is allowed");e._babelPolyfill=!0;var r="defineProperty";t(String.prototype,"padLeft","".padStart),t(String.prototype,"padRight","".padEnd),"pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function(e){[][e]&&t(Array,e,Function.call.bind([][e]))})}).call(t,n(101))},function(e,t,n){e.exports={default:n(324),__esModule:!0}},function(e,t,n){e.exports={default:n(329),__esModule:!0}},function(e,t,n){e.exports={default:n(330),__esModule:!0}},function(e,t,n){e.exports={default:n(332),__esModule:!0}},function(e,t,n){e.exports={default:n(333),__esModule:!0}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(202),i=r(o);t.default=function(e,t,n){return t in e?(0,i.default)(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}},function(e,t,n){"use strict";t.__esModule=!0,t.default=function(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(310),i=r(o),a=n(199),l=r(a);t.default=function(){function e(e,t){var n=[],r=!0,o=!1,i=void 0;try{for(var a,s=(0,l.default)(e);!(r=(a=s.next()).done)&&(n.push(a.value),!t||n.length!==t);r=!0);}catch(e){o=!0,i=e}finally{try{!r&&s.return&&s.return()}finally{if(o)throw i}}return n}return function(t,n){if(Array.isArray(t))return t;if((0,i.default)(Object(t)))return e(t,n);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}()},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(198),i=r(o);t.default=function(e){return Array.isArray(e)?e:(0,i.default)(e)}},function(e,t,n){"use strict";function r(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===e[t-2]?2:"="===e[t-1]?1:0}function o(e){return 3*e.length/4-r(e)}function i(e){var t,n,o,i,a,l,s=e.length;a=r(e),l=new d(3*s/4-a),o=a>0?s-4:s;var c=0;for(t=0,n=0;t<o;t+=4,n+=3)i=u[e.charCodeAt(t)]<<18|u[e.charCodeAt(t+1)]<<12|u[e.charCodeAt(t+2)]<<6|u[e.charCodeAt(t+3)],l[c++]=i>>16&255,l[c++]=i>>8&255,l[c++]=255&i;return 2===a?(i=u[e.charCodeAt(t)]<<2|u[e.charCodeAt(t+1)]>>4,l[c++]=255&i):1===a&&(i=u[e.charCodeAt(t)]<<10|u[e.charCodeAt(t+1)]<<4|u[e.charCodeAt(t+2)]>>2,l[c++]=i>>8&255,l[c++]=255&i),l}function a(e){return c[e>>18&63]+c[e>>12&63]+c[e>>6&63]+c[63&e]}function l(e,t,n){for(var r,o=[],i=t;i<n;i+=3)r=(e[i]<<16)+(e[i+1]<<8)+e[i+2],o.push(a(r));return o.join("")}function s(e){for(var t,n=e.length,r=n%3,o="",i=[],a=16383,s=0,u=n-r;s<u;s+=a)i.push(l(e,s,s+a>u?u:s+a));return 1===r?(t=e[n-1],o+=c[t>>2],o+=c[t<<4&63],o+="=="):2===r&&(t=(e[n-2]<<8)+e[n-1],o+=c[t>>10],o+=c[t>>4&63],o+=c[t<<2&63],o+="="),i.push(o),i.join("")}t.byteLength=o,t.toByteArray=i,t.fromByteArray=s;for(var c=[],u=[],d="undefined"!=typeof Uint8Array?Uint8Array:Array,p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",f=0,m=p.length;f<m;++f)c[f]=p[f],u[p.charCodeAt(f)]=f;u["-".charCodeAt(0)]=62,u["_".charCodeAt(0)]=63},function(e,t,n){"use strict";(function(e){function r(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}function o(){return a.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function i(e,t){if(o()<t)throw new RangeError("Invalid typed array length");return a.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t),e.__proto__=a.prototype):(null===e&&(e=new a(t)),e.length=t),e}function a(e,t,n){if(!(a.TYPED_ARRAY_SUPPORT||this instanceof a))return new a(e,t,n);if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return u(this,e)}return l(this,e,t,n)}function l(e,t,n,r){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer?f(e,t,n,r):"string"==typeof t?d(e,t,n):m(e,t)}function s(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative')}function c(e,t,n,r){return s(t),t<=0?i(e,t):void 0!==n?"string"==typeof r?i(e,t).fill(n,r):i(e,t).fill(n):i(e,t)}function u(e,t){if(s(t),e=i(e,t<0?0:0|h(t)),!a.TYPED_ARRAY_SUPPORT)for(var n=0;n<t;++n)e[n]=0;return e}function d(e,t,n){if("string"==typeof n&&""!==n||(n="utf8"),!a.isEncoding(n))throw new TypeError('"encoding" must be a valid string encoding');var r=0|b(t,n);e=i(e,r);var o=e.write(t,n);return o!==r&&(e=e.slice(0,o)),e}function p(e,t){var n=t.length<0?0:0|h(t.length);e=i(e,n);for(var r=0;r<n;r+=1)e[r]=255&t[r];return e}function f(e,t,n,r){if(t.byteLength,n<0||t.byteLength<n)throw new RangeError("'offset' is out of bounds");if(t.byteLength<n+(r||0))throw new RangeError("'length' is out of bounds");return t=void 0===n&&void 0===r?new Uint8Array(t):void 0===r?new Uint8Array(t,n):new Uint8Array(t,n,r),a.TYPED_ARRAY_SUPPORT?(e=t,e.__proto__=a.prototype):e=p(e,t),e}function m(e,t){if(a.isBuffer(t)){var n=0|h(t.length);return e=i(e,n),0===e.length?e:(t.copy(e,0,0,n),e)}if(t){if("undefined"!=typeof ArrayBuffer&&t.buffer instanceof ArrayBuffer||"length"in t)return"number"!=typeof t.length||X(t.length)?i(e,0):p(e,t);if("Buffer"===t.type&&$(t.data))return p(e,t.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function h(e){if(e>=o())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o().toString(16)+" bytes");return 0|e}function g(e){return+e!=e&&(e=0),a.alloc(+e)}function b(e,t){if(a.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return G(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return K(e).length;default:if(r)return G(e).length;t=(""+t).toLowerCase(),r=!0}}function y(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if(n>>>=0,t>>>=0,n<=t)return"";for(e||(e="utf8");;)switch(e){case"hex":return R(this,t,n);case"utf8":case"utf-8":return T(this,t,n);case"ascii":return O(this,t,n);case"latin1":case"binary":return M(this,t,n);case"base64":return I(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return N(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function v(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function _(e,t,n,r,o){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof t&&(t=a.from(t,r)),a.isBuffer(t))return 0===t.length?-1:x(e,t,n,r,o);if("number"==typeof t)return t&=255,a.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):x(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function x(e,t,n,r,o){function i(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}var a=1,l=e.length,s=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;a=2,l/=2,s/=2,n/=2}var c;if(o){var u=-1;for(c=n;c<l;c++)if(i(e,c)===i(t,u===-1?0:c-u)){if(u===-1&&(u=c),c-u+1===s)return u*a}else u!==-1&&(c-=c-u),u=-1}else for(n+s>l&&(n=l-s),c=n;c>=0;c--){for(var d=!0,p=0;p<s;p++)if(i(e,c+p)!==i(t,p)){d=!1;break}if(d)return c}return-1}function w(e,t,n,r){n=Number(n)||0;var o=e.length-n;r?(r=Number(r))>o&&(r=o):r=o;var i=t.length;if(i%2!=0)throw new TypeError("Invalid hex string");r>i/2&&(r=i/2);for(var a=0;a<r;++a){var l=parseInt(t.substr(2*a,2),16);if(isNaN(l))return a;e[n+a]=l}return a}function C(e,t,n,r){return Z(G(t,e.length-n),e,n,r)}function k(e,t,n,r){return Z(Y(t),e,n,r)}function E(e,t,n,r){return k(e,t,n,r)}function A(e,t,n,r){return Z(K(t),e,n,r)}function S(e,t,n,r){return Z(q(t,e.length-n),e,n,r)}function I(e,t,n){return 0===t&&n===e.length?Q.fromByteArray(e):Q.fromByteArray(e.slice(t,n))}function T(e,t,n){n=Math.min(e.length,n);for(var r=[],o=t;o<n;){var i=e[o],a=null,l=i>239?4:i>223?3:i>191?2:1;if(o+l<=n){var s,c,u,d;switch(l){case 1:i<128&&(a=i);break;case 2:s=e[o+1],128==(192&s)&&(d=(31&i)<<6|63&s)>127&&(a=d);break;case 3:s=e[o+1],c=e[o+2],128==(192&s)&&128==(192&c)&&(d=(15&i)<<12|(63&s)<<6|63&c)>2047&&(d<55296||d>57343)&&(a=d);break;case 4:s=e[o+1],c=e[o+2],u=e[o+3],128==(192&s)&&128==(192&c)&&128==(192&u)&&(d=(15&i)<<18|(63&s)<<12|(63&c)<<6|63&u)>65535&&d<1114112&&(a=d)}}null===a?(a=65533,l=1):a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|1023&a),r.push(a),o+=l}return P(r)}function P(e){var t=e.length;if(t<=ee)return String.fromCharCode.apply(String,e);for(var n="",r=0;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=ee));return n}function O(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;o<n;++o)r+=String.fromCharCode(127&e[o]);return r}function M(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;o<n;++o)r+=String.fromCharCode(e[o]);return r}function R(e,t,n){var r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);for(var o="",i=t;i<n;++i)o+=V(e[i]);return o}function N(e,t,n){for(var r=e.slice(t,n),o="",i=0;i<r.length;i+=2)o+=String.fromCharCode(r[i]+256*r[i+1]);return o}function L(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function D(e,t,n,r,o,i){if(!a.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<i)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function j(e,t,n,r){t<0&&(t=65535+t+1);for(var o=0,i=Math.min(e.length-n,2);o<i;++o)e[n+o]=(t&255<<8*(r?o:1-o))>>>8*(r?o:1-o)}function F(e,t,n,r){t<0&&(t=4294967295+t+1);for(var o=0,i=Math.min(e.length-n,4);o<i;++o)e[n+o]=t>>>8*(r?o:3-o)&255}function z(e,t,n,r,o,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function U(e,t,n,r,o){return o||z(e,t,n,4,3.4028234663852886e38,-3.4028234663852886e38),J.write(e,t,n,r,23,4),n+4}function B(e,t,n,r,o){return o||z(e,t,n,8,1.7976931348623157e308,-1.7976931348623157e308),J.write(e,t,n,r,52,8),n+8}function H(e){if(e=W(e).replace(te,""),e.length<2)return"";for(;e.length%4!=0;)e+="=";return e}function W(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function V(e){return e<16?"0"+e.toString(16):e.toString(16)}function G(e,t){t=t||1/0;for(var n,r=e.length,o=null,i=[],a=0;a<r;++a){if((n=e.charCodeAt(a))>55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function Y(e){for(var t=[],n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}function q(e,t){for(var n,r,o,i=[],a=0;a<e.length&&!((t-=2)<0);++a)n=e.charCodeAt(a),r=n>>8,o=n%256,i.push(o),i.push(r);return i}function K(e){return Q.toByteArray(H(e))}function Z(e,t,n,r){for(var o=0;o<r&&!(o+n>=t.length||o>=e.length);++o)t[o+n]=e[o];return o}function X(e){return e!==e}/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <[email protected]> <http://feross.org>
* @license MIT
*/
var Q=n(319),J=n(575),$=n(576);t.Buffer=a,t.SlowBuffer=g,t.INSPECT_MAX_BYTES=50,a.TYPED_ARRAY_SUPPORT=void 0!==e.TYPED_ARRAY_SUPPORT?e.TYPED_ARRAY_SUPPORT:r(),t.kMaxLength=o(),a.poolSize=8192,a._augment=function(e){return e.__proto__=a.prototype,e},a.from=function(e,t,n){return l(null,e,t,n)},a.TYPED_ARRAY_SUPPORT&&(a.prototype.__proto__=Uint8Array.prototype,a.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&a[Symbol.species]===a&&Object.defineProperty(a,Symbol.species,{value:null,configurable:!0})),a.alloc=function(e,t,n){return c(null,e,t,n)},a.allocUnsafe=function(e){return u(null,e)},a.allocUnsafeSlow=function(e){return u(null,e)},a.isBuffer=function(e){return!(null==e||!e._isBuffer)},a.compare=function(e,t){if(!a.isBuffer(e)||!a.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,o=0,i=Math.min(n,r);o<i;++o)if(e[o]!==t[o]){n=e[o],r=t[o];break}return n<r?-1:r<n?1:0},a.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(e,t){if(!$(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return a.alloc(0);var n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;var r=a.allocUnsafe(t),o=0;for(n=0;n<e.length;++n){var i=e[n];if(!a.isBuffer(i))throw new TypeError('"list" argument must be an Array of Buffers');i.copy(r,o),o+=i.length}return r},a.byteLength=b,a.prototype._isBuffer=!0,a.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)v(this,t,t+1);return this},a.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)v(this,t,t+3),v(this,t+1,t+2);return this},a.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)v(this,t,t+7),v(this,t+1,t+6),v(this,t+2,t+5),v(this,t+3,t+4);return this},a.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?T(this,0,e):y.apply(this,arguments)},a.prototype.equals=function(e){if(!a.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===a.compare(this,e)},a.prototype.inspect=function(){var e="",n=t.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),"<Buffer "+e+">"},a.prototype.compare=function(e,t,n,r,o){if(!a.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,o>>>=0,this===e)return 0;for(var i=o-r,l=n-t,s=Math.min(i,l),c=this.slice(r,o),u=e.slice(t,n),d=0;d<s;++d)if(c[d]!==u[d]){i=c[d],l=u[d];break}return i<l?-1:l<i?1:0},a.prototype.includes=function(e,t,n){return this.indexOf(e,t,n)!==-1},a.prototype.indexOf=function(e,t,n){return _(this,e,t,n,!0)},a.prototype.lastIndexOf=function(e,t,n){return _(this,e,t,n,!1)},a.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t|=0,isFinite(n)?(n|=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var o=this.length-t;if((void 0===n||n>o)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var i=!1;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return C(this,e,t,n);case"ascii":return k(this,e,t,n);case"latin1":case"binary":return E(this,e,t,n);case"base64":return A(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var ee=4096;a.prototype.slice=function(e,t){var n=this.length;e=~~e,t=void 0===t?n:~~t,e<0?(e+=n)<0&&(e=0):e>n&&(e=n),t<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);var r;if(a.TYPED_ARRAY_SUPPORT)r=this.subarray(e,t),r.__proto__=a.prototype;else{var o=t-e;r=new a(o,void 0);for(var i=0;i<o;++i)r[i]=this[i+e]}return r},a.prototype.readUIntLE=function(e,t,n){e|=0,t|=0,n||L(e,t,this.length);for(var r=this[e],o=1,i=0;++i<t&&(o*=256);)r+=this[e+i]*o;return r},a.prototype.readUIntBE=function(e,t,n){e|=0,t|=0,n||L(e,t,this.length);for(var r=this[e+--t],o=1;t>0&&(o*=256);)r+=this[e+--t]*o;return r},a.prototype.readUInt8=function(e,t){return t||L(e,1,this.length),this[e]},a.prototype.readUInt16LE=function(e,t){return t||L(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUInt16BE=function(e,t){return t||L(e,2,this.length),this[e]<<8|this[e+1]},a.prototype.readUInt32LE=function(e,t){return t||L(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},a.prototype.readUInt32BE=function(e,t){return t||L(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},a.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||L(e,t,this.length);for(var r=this[e],o=1,i=0;++i<t&&(o*=256);)r+=this[e+i]*o;return o*=128,r>=o&&(r-=Math.pow(2,8*t)),r},a.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||L(e,t,this.length);for(var r=t,o=1,i=this[e+--r];r>0&&(o*=256);)i+=this[e+--r]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},a.prototype.readInt8=function(e,t){return t||L(e,1,this.length),128&this[e]?(255-this[e]+1)*-1:this[e]},a.prototype.readInt16LE=function(e,t){t||L(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},a.prototype.readInt16BE=function(e,t){t||L(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},a.prototype.readInt32LE=function(e,t){return t||L(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},a.prototype.readInt32BE=function(e,t){return t||L(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},a.prototype.readFloatLE=function(e,t){return t||L(e,4,this.length),J.read(this,e,!0,23,4)},a.prototype.readFloatBE=function(e,t){return t||L(e,4,this.length),J.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function(e,t){return t||L(e,8,this.length),J.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function(e,t){return t||L(e,8,this.length),J.read(this,e,!1,52,8)},a.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t|=0,n|=0,!r){D(this,e,t,n,Math.pow(2,8*n)-1,0)}var o=1,i=0;for(this[t]=255&e;++i<n&&(o*=256);)this[t+i]=e/o&255;return t+n},a.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t|=0,n|=0,!r){D(this,e,t,n,Math.pow(2,8*n)-1,0)}var o=n-1,i=1;for(this[t+o]=255&e;--o>=0&&(i*=256);)this[t+o]=e/i&255;return t+n},a.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,1,255,0),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},a.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):j(this,e,t,!0),t+2},a.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):j(this,e,t,!1),t+2},a.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):F(this,e,t,!0),t+4},a.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):F(this,e,t,!1),t+4},a.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var o=Math.pow(2,8*n-1);D(this,e,t,n,o-1,-o)}var i=0,a=1,l=0;for(this[t]=255&e;++i<n&&(a*=256);)e<0&&0===l&&0!==this[t+i-1]&&(l=1),this[t+i]=(e/a>>0)-l&255;return t+n},a.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var o=Math.pow(2,8*n-1);D(this,e,t,n,o-1,-o)}var i=n-1,a=1,l=0;for(this[t+i]=255&e;--i>=0&&(a*=256);)e<0&&0===l&&0!==this[t+i+1]&&(l=1),this[t+i]=(e/a>>0)-l&255;return t+n},a.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,1,127,-128),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},a.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):j(this,e,t,!0),t+2},a.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):j(this,e,t,!1),t+2},a.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,2147483647,-2147483648),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):F(this,e,t,!0),t+4},a.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):F(this,e,t,!1),t+4},a.prototype.writeFloatLE=function(e,t,n){return U(this,e,t,!0,n)},a.prototype.writeFloatBE=function(e,t,n){return U(this,e,t,!1,n)},a.prototype.writeDoubleLE=function(e,t,n){return B(this,e,t,!0,n)},a.prototype.writeDoubleBE=function(e,t,n){return B(this,e,t,!1,n)},a.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var o,i=r-n;if(this===e&&n<t&&t<r)for(o=i-1;o>=0;--o)e[o+t]=this[o+n];else if(i<1e3||!a.TYPED_ARRAY_SUPPORT)for(o=0;o<i;++o)e[o+t]=this[o+n];else Uint8Array.prototype.set.call(e,this.subarray(n,n+i),t);return i},a.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),1===e.length){var o=e.charCodeAt(0);o<256&&(e=o)}if(void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!a.isEncoding(r))throw new TypeError("Unknown encoding: "+r)}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0);var i;if("number"==typeof e)for(i=t;i<n;++i)this[i]=e;else{var l=a.isBuffer(e)?e:G(new a(e,r).toString()),s=l.length;for(i=0;i<n-t;++i)this[i+t]=l[i%s]}return this};var te=/[^+\/0-9A-Za-z-_]/g}).call(t,n(101))},function(e,t,n){n(378),e.exports=n(40).RegExp.escape},function(e,t,n){n(92),n(358),e.exports=n(14).Array.from},function(e,t,n){n(108),n(92),e.exports=n(356)},function(e,t,n){n(108),n(92),e.exports=n(357)},function(e,t,n){n(360),e.exports=n(14).Object.assign},function(e,t,n){n(361);var r=n(14).Object;e.exports=function(e,t){return r.create(e,t)}},function(e,t,n){n(362);var r=n(14).Object;e.exports=function(e,t,n){return r.defineProperty(e,t,n)}},function(e,t,n){n(363),e.exports=n(14).Object.getPrototypeOf},function(e,t,n){n(364),e.exports=n(14).Object.keys},function(e,t,n){n(365),e.exports=n(14).Object.setPrototypeOf},function(e,t,n){n(219),n(92),n(108),n(366),e.exports=n(14).Promise},function(e,t,n){n(367),n(219),n(368),n(369),e.exports=n(14).Symbol},function(e,t,n){n(92),n(108),e.exports=n(143).f("iterator")},function(e,t){e.exports=function(){}},function(e,t){e.exports=function(e,t,n,r){if(!(e instanceof t)||void 0!==r&&r in e)throw TypeError(n+": incorrect invocation!");return e}},function(e,t,n){var r=n(59),o=n(140),i=n(355);e.exports=function(e){return function(t,n,a){var l,s=r(t),c=o(s.length),u=i(a,c);if(e&&n!=n){for(;c>u;)if((l=s[u++])!=l)return!0}else for(;c>u;u++)if((e||u in s)&&s[u]===n)return e||u||0;return!e&&-1}}},function(e,t,n){"use strict";var r=n(39),o=n(90);e.exports=function(e,t,n){t in e?r.f(e,t,o(0,n)):e[t]=n}},function(e,t,n){var r=n(76),o=n(136),i=n(105);e.exports=function(e){var t=r(e),n=o.f;if(n)for(var a,l=n(e),s=i.f,c=0;l.length>c;)s.call(e,a=l[c++])&&t.push(a);return t}},function(e,t,n){var r=n(72),o=n(209),i=n(208),a=n(37),l=n(140),s=n(144),c={},u={},t=e.exports=function(e,t,n,d,p){var f,m,h,g,b=p?function(){return e}:s(e),y=r(n,d,t?2:1),v=0;if("function"!=typeof b)throw TypeError(e+" is not iterable!");if(i(b)){for(f=l(e.length);f>v;v++)if((g=t?y(a(m=e[v])[0],m[1]):y(e[v]))===c||g===u)return g}else for(h=b.call(e);!(m=h.next()).done;)if((g=o(h,y,m.value,t))===c||g===u)return g};t.BREAK=c,t.RETURN=u},function(e,t){e.exports=function(e,t,n){var r=void 0===n;switch(t.length){case 0:return r?e():e.call(n);case 1:return r?e(t[0]):e.call(n,t[0]);case 2:return r?e(t[0],t[1]):e.call(n,t[0],t[1]);case 3:return r?e(t[0],t[1],t[2]):e.call(n,t[0],t[1],t[2]);case 4:return r?e(t[0],t[1],t[2],t[3]):e.call(n,t[0],t[1],t[2],t[3])}return e.apply(n,t)}},function(e,t,n){var r=n(89);e.exports=Array.isArray||function(e){return"Array"==r(e)}},function(e,t,n){"use strict";var r=n(135),o=n(90),i=n(106),a={};n(58)(a,n(17)("iterator"),function(){return this}),e.exports=function(e,t,n){e.prototype=r(a,{next:o(1,n)}),i(e,t+" Iterator")}},function(e,t){e.exports=function(e,t){return{value:t,done:!!e}}},function(e,t,n){var r=n(76),o=n(59);e.exports=function(e,t){for(var n,i=o(e),a=r(i),l=a.length,s=0;l>s;)if(i[n=a[s++]]===t)return n}},function(e,t,n){var r=n(107)("meta"),o=n(74),i=n(57),a=n(39).f,l=0,s=Object.isExtensible||function(){return!0},c=!n(73)(function(){return s(Object.preventExtensions({}))}),u=function(e){a(e,r,{value:{i:"O"+ ++l,w:{}}})},d=function(e,t){if(!o(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!i(e,r)){if(!s(e))return"F";if(!t)return"E";u(e)}return e[r].i},p=function(e,t){if(!i(e,r)){if(!s(e))return!0;if(!t)return!1;u(e)}return e[r].w},f=function(e){return c&&m.NEED&&s(e)&&!i(e,r)&&u(e),e},m=e.exports={KEY:r,NEED:!1,fastKey:d,getWeak:p,onFreeze:f}},function(e,t,n){var r=n(25),o=n(218).set,i=r.MutationObserver||r.WebKitMutationObserver,a=r.process,l=r.Promise,s="process"==n(89)(a);e.exports=function(){var e,t,n,c=function(){var r,o;for(s&&(r=a.domain)&&r.exit();e;){o=e.fn,e=e.next;try{o()}catch(r){throw e?n():t=void 0,r}}t=void 0,r&&r.enter()};if(s)n=function(){a.nextTick(c)};else if(i){var u=!0,d=document.createTextNode("");new i(c).observe(d,{characterData:!0}),n=function(){d.data=u=!u}}else if(l&&l.resolve){var p=l.resolve();n=function(){p.then(c)}}else n=function(){o.call(r,c)};return function(r){var o={fn:r,next:void 0};t&&(t.next=o),e||(e=o,n()),t=o}}},function(e,t,n){"use strict";var r=n(76),o=n(136),i=n(105),a=n(91),l=n(207),s=Object.assign;e.exports=!s||n(73)(function(){var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach(function(e){t[e]=e}),7!=s({},e)[n]||Object.keys(s({},t)).join("")!=r})?function(e,t){for(var n=a(e),s=arguments.length,c=1,u=o.f,d=i.f;s>c;)for(var p,f=l(arguments[c++]),m=u?r(f).concat(u(f)):r(f),h=m.length,g=0;h>g;)d.call(f,p=m[g++])&&(n[p]=f[p]);return n}:s},function(e,t,n){var r=n(39),o=n(37),i=n(76);e.exports=n(46)?Object.defineProperties:function(e,t){o(e);for(var n,a=i(t),l=a.length,s=0;l>s;)r.f(e,n=a[s++],t[n]);return e}},function(e,t,n){var r=n(59),o=n(213).f,i={}.toString,a="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],l=function(e){try{return o(e)}catch(e){return a.slice()}};e.exports.f=function(e){return a&&"[object Window]"==i.call(e)?l(e):o(r(e))}},function(e,t,n){var r=n(58);e.exports=function(e,t,n){for(var o in t)n&&e[o]?e[o]=t[o]:r(e,o,t[o]);return e}},function(e,t,n){var r=n(74),o=n(37),i=function(e,t){if(o(e),!r(t)&&null!==t)throw TypeError(t+": can't set as prototype!")};e.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,r){try{r=n(72)(Function.call,n(212).f(Object.prototype,"__proto__").set,2),r(e,[]),t=!(e instanceof Array)}catch(e){t=!0}return function(e,n){return i(e,n),t?e.__proto__=n:r(e,n),e}}({},!1):void 0),check:i}},function(e,t,n){"use strict";var r=n(25),o=n(14),i=n(39),a=n(46),l=n(17)("species");e.exports=function(e){var t="function"==typeof o[e]?o[e]:r[e];a&&t&&!t[l]&&i.f(t,l,{configurable:!0,get:function(){return this}})}},function(e,t,n){var r=n(37),o=n(130),i=n(17)("species");e.exports=function(e,t){var n,a=r(e).constructor;return void 0===a||void 0==(n=r(a)[i])?t:o(n)}},function(e,t,n){var r=n(139),o=n(132);e.exports=function(e){return function(t,n){var i,a,l=String(o(t)),s=r(n),c=l.length;return s<0||s>=c?e?"":void 0:(i=l.charCodeAt(s),i<55296||i>56319||s+1===c||(a=l.charCodeAt(s+1))<56320||a>57343?e?l.charAt(s):i:e?l.slice(s,s+2):a-56320+(i-55296<<10)+65536)}}},function(e,t,n){var r=n(139),o=Math.max,i=Math.min;e.exports=function(e,t){return e=r(e),e<0?o(e+t,0):i(e,t)}},function(e,t,n){var r=n(37),o=n(144);e.exports=n(14).getIterator=function(e){var t=o(e);if("function"!=typeof t)throw TypeError(e+" is not iterable!");return r(t.call(e))}},function(e,t,n){var r=n(131),o=n(17)("iterator"),i=n(75);e.exports=n(14).isIterable=function(e){var t=Object(e);return void 0!==t[o]||"@@iterator"in t||i.hasOwnProperty(r(t))}},function(e,t,n){"use strict";var r=n(72),o=n(38),i=n(91),a=n(209),l=n(208),s=n(140),c=n(337),u=n(144);o(o.S+o.F*!n(211)(function(e){Array.from(e)}),"Array",{from:function(e){var t,n,o,d,p=i(e),f="function"==typeof this?this:Array,m=arguments.length,h=m>1?arguments[1]:void 0,g=void 0!==h,b=0,y=u(p);if(g&&(h=r(h,m>2?arguments[2]:void 0,2)),void 0==y||f==Array&&l(y))for(t=s(p.length),n=new f(t);t>b;b++)c(n,b,g?h(p[b],b):p[b]);else for(d=y.call(p),n=new f;!(o=d.next()).done;b++)c(n,b,g?a(d,h,[o.value,b],!0):o.value);return n.length=b,n}})},function(e,t,n){"use strict";var r=n(334),o=n(343),i=n(75),a=n(59);e.exports=n(210)(Array,"Array",function(e,t){this._t=a(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,n=this._i++;return!e||n>=e.length?(this._t=void 0,o(1)):"keys"==t?o(0,n):"values"==t?o(0,e[n]):o(0,[n,e[n]])},"values"),i.Arguments=i.Array,r("keys"),r("values"),r("entries")},function(e,t,n){var r=n(38);r(r.S+r.F,"Object",{assign:n(347)})},function(e,t,n){var r=n(38);r(r.S,"Object",{create:n(135)})},function(e,t,n){var r=n(38);r(r.S+r.F*!n(46),"Object",{defineProperty:n(39).f})},function(e,t,n){var r=n(91),o=n(214);n(216)("getPrototypeOf",function(){return function(e){return o(r(e))}})},function(e,t,n){var r=n(91),o=n(76);n(216)("keys",function(){return function(e){return o(r(e))}})},function(e,t,n){var r=n(38);r(r.S,"Object",{setPrototypeOf:n(351).set})},function(e,t,n){"use strict";var r,o,i,a=n(104),l=n(25),s=n(72),c=n(131),u=n(38),d=n(74),p=n(130),f=n(335),m=n(339),h=n(353),g=n(218).set,b=n(346)(),y="Promise",v=l.TypeError,_=l.process,x=l[y],_=l.process,w="process"==c(_),C=function(){},k=!!function(){try{var e=x.resolve(1),t=(e.constructor={})[n(17)("species")]=function(e){e(C,C)};return(w||"function"==typeof PromiseRejectionEvent)&&e.then(C)instanceof t}catch(e){}}(),E=function(e,t){return e===t||e===x&&t===i},A=function(e){var t;return!(!d(e)||"function"!=typeof(t=e.then))&&t},S=function(e){return E(x,e)?new I(e):new o(e)},I=o=function(e){var t,n;this.promise=new e(function(e,r){if(void 0!==t||void 0!==n)throw v("Bad Promise constructor");t=e,n=r}),this.resolve=p(t),this.reject=p(n)},T=function(e){try{e()}catch(e){return{error:e}}},P=function(e,t){if(!e._n){e._n=!0;var n=e._c;b(function(){for(var r=e._v,o=1==e._s,i=0,a=function(t){var n,i,a=o?t.ok:t.fail,l=t.resolve,s=t.reject,c=t.domain;try{a?(o||(2==e._h&&R(e),e._h=1),a===!0?n=r:(c&&c.enter(),n=a(r),c&&c.exit()),n===t.promise?s(v("Promise-chain cycle")):(i=A(n))?i.call(n,l,s):l(n)):s(r)}catch(e){s(e)}};n.length>i;)a(n[i++]);e._c=[],e._n=!1,t&&!e._h&&O(e)})}},O=function(e){g.call(l,function(){var t,n,r,o=e._v;if(M(e)&&(t=T(function(){w?_.emit("unhandledRejection",o,e):(n=l.onunhandledrejection)?n({promise:e,reason:o}):(r=l.console)&&r.error&&r.error("Unhandled promise rejection",o)}),e._h=w||M(e)?2:1),e._a=void 0,t)throw t.error})},M=function(e){if(1==e._h)return!1;for(var t,n=e._a||e._c,r=0;n.length>r;)if(t=n[r++],t.fail||!M(t.promise))return!1;return!0},R=function(e){g.call(l,function(){var t;w?_.emit("rejectionHandled",e):(t=l.onrejectionhandled)&&t({promise:e,reason:e._v})})},N=function(e){var t=this;t._d||(t._d=!0,t=t._w||t,t._v=e,t._s=2,t._a||(t._a=t._c.slice()),P(t,!0))},L=function(e){var t,n=this;if(!n._d){n._d=!0,n=n._w||n;try{if(n===e)throw v("Promise can't be resolved itself");(t=A(e))?b(function(){var r={_w:n,_d:!1};try{t.call(e,s(L,r,1),s(N,r,1))}catch(e){N.call(r,e)}}):(n._v=e,n._s=1,P(n,!1))}catch(e){N.call({_w:n,_d:!1},e)}}};k||(x=function(e){f(this,x,y,"_h"),p(e),r.call(this);try{e(s(L,this,1),s(N,this,1))}catch(e){N.call(this,e)}},r=function(e){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},r.prototype=n(350)(x.prototype,{then:function(e,t){var n=S(h(this,x));return n.ok="function"!=typeof e||e,n.fail="function"==typeof t&&t,n.domain=w?_.domain:void 0,this._c.push(n),this._a&&this._a.push(n),this._s&&P(this,!1),n.promise},catch:function(e){return this.then(void 0,e)}}),I=function(){var e=new r;this.promise=e,this.resolve=s(L,e,1),this.reject=s(N,e,1)}),u(u.G+u.W+u.F*!k,{Promise:x}),n(106)(x,y),n(352)(y),i=n(14)[y],u(u.S+u.F*!k,y,{reject:function(e){var t=S(this);return(0,t.reject)(e),t.promise}}),u(u.S+u.F*(a||!k),y,{resolve:function(e){if(e instanceof x&&E(e.constructor,this))return e;var t=S(this);return(0,t.resolve)(e),t.promise}}),u(u.S+u.F*!(k&&n(211)(function(e){x.all(e).catch(C)})),y,{all:function(e){var t=this,n=S(t),r=n.resolve,o=n.reject,i=T(function(){var n=[],i=0,a=1;m(e,!1,function(e){var l=i++,s=!1;n.push(void 0),a++,t.resolve(e).then(function(e){s||(s=!0,n[l]=e,--a||r(n))},o)}),--a||r(n)});return i&&o(i.error),n.promise},race:function(e){var t=this,n=S(t),r=n.reject,o=T(function(){m(e,!1,function(e){t.resolve(e).then(n.resolve,r)})});return o&&r(o.error),n.promise}})},function(e,t,n){"use strict";var r=n(25),o=n(57),i=n(46),a=n(38),l=n(217),s=n(345).KEY,c=n(73),u=n(138),d=n(106),p=n(107),f=n(17),m=n(143),h=n(142),g=n(344),b=n(338),y=n(341),v=n(37),_=n(59),x=n(141),w=n(90),C=n(135),k=n(349),E=n(212),A=n(39),S=n(76),I=E.f,T=A.f,P=k.f,O=r.Symbol,M=r.JSON,R=M&&M.stringify,N="prototype",L=f("_hidden"),D=f("toPrimitive"),j={}.propertyIsEnumerable,F=u("symbol-registry"),z=u("symbols"),U=u("op-symbols"),B=Object[N],H="function"==typeof O,W=r.QObject,V=!W||!W[N]||!W[N].findChild,G=i&&c(function(){return 7!=C(T({},"a",{get:function(){return T(this,"a",{value:7}).a}})).a})?function(e,t,n){var r=I(B,t);r&&delete B[t],T(e,t,n),r&&e!==B&&T(B,t,r)}:T,Y=function(e){var t=z[e]=C(O[N]);return t._k=e,t},q=H&&"symbol"==typeof O.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof O},K=function(e,t,n){return e===B&&K(U,t,n),v(e),t=x(t,!0),v(n),o(z,t)?(n.enumerable?(o(e,L)&&e[L][t]&&(e[L][t]=!1),n=C(n,{enumerable:w(0,!1)})):(o(e,L)||T(e,L,w(1,{})),e[L][t]=!0),G(e,t,n)):T(e,t,n)},Z=function(e,t){v(e);for(var n,r=b(t=_(t)),o=0,i=r.length;i>o;)K(e,n=r[o++],t[n]);return e},X=function(e,t){return void 0===t?C(e):Z(C(e),t)},Q=function(e){var t=j.call(this,e=x(e,!0));return!(this===B&&o(z,e)&&!o(U,e))&&(!(t||!o(this,e)||!o(z,e)||o(this,L)&&this[L][e])||t)},J=function(e,t){if(e=_(e),t=x(t,!0),e!==B||!o(z,t)||o(U,t)){var n=I(e,t);return!n||!o(z,t)||o(e,L)&&e[L][t]||(n.enumerable=!0),n}},$=function(e){for(var t,n=P(_(e)),r=[],i=0;n.length>i;)o(z,t=n[i++])||t==L||t==s||r.push(t);return r},ee=function(e){for(var t,n=e===B,r=P(n?U:_(e)),i=[],a=0;r.length>a;)!o(z,t=r[a++])||n&&!o(B,t)||i.push(z[t]);return i};H||(O=function(){if(this instanceof O)throw TypeError("Symbol is not a constructor!");var e=p(arguments.length>0?arguments[0]:void 0),t=function(n){this===B&&t.call(U,n),o(this,L)&&o(this[L],e)&&(this[L][e]=!1),G(this,e,w(1,n))};return i&&V&&G(B,e,{configurable:!0,set:t}),Y(e)},l(O[N],"toString",function(){return this._k}),E.f=J,A.f=K,n(213).f=k.f=$,n(105).f=Q,n(136).f=ee,i&&!n(104)&&l(B,"propertyIsEnumerable",Q,!0),m.f=function(e){return Y(f(e))}),a(a.G+a.W+a.F*!H,{Symbol:O});for(var te="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),ne=0;te.length>ne;)f(te[ne++]);for(var te=S(f.store),ne=0;te.length>ne;)h(te[ne++]);a(a.S+a.F*!H,"Symbol",{for:function(e){return o(F,e+="")?F[e]:F[e]=O(e)},keyFor:function(e){if(q(e))return g(F,e);throw TypeError(e+" is not a symbol!")},useSetter:function(){V=!0},useSimple:function(){V=!1}}),a(a.S+a.F*!H,"Object",{create:X,defineProperty:K,defineProperties:Z,getOwnPropertyDescriptor:J,getOwnPropertyNames:$,getOwnPropertySymbols:ee}),M&&a(a.S+a.F*(!H||c(function(){var e=O();return"[null]"!=R([e])||"{}"!=R({a:e})||"{}"!=R(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!q(e)){for(var t,n,r=[e],o=1;arguments.length>o;)r.push(arguments[o++]);return t=r[1],"function"==typeof t&&(n=t),!n&&y(t)||(t=function(e,t){if(n&&(t=n.call(this,e,t)),!q(t))return t}),r[1]=t,R.apply(M,r)}}}),O[N][D]||n(58)(O[N],D,O[N].valueOf),d(O,"Symbol"),d(Math,"Math",!0),d(r.JSON,"JSON",!0)},function(e,t,n){n(142)("asyncIterator")},function(e,t,n){n(142)("observable")},function(e,t,n){var r=n(7),o=n(153),i=n(8)("species");e.exports=function(e){var t;return o(e)&&(t=e.constructor,"function"!=typeof t||t!==Array&&!o(t.prototype)||(t=void 0),r(t)&&null===(t=t[i])&&(t=void 0)),void 0===t?Array:t}},function(e,t,n){var r=n(370);e.exports=function(e,t){return new(r(e))(t)}},function(e,t,n){"use strict";var r=n(2),o=n(36),i="number";e.exports=function(e){if("string"!==e&&e!==i&&"default"!==e)throw TypeError("Incorrect hint");return o(r(this),e!=i)}},function(e,t,n){var r=n(64),o=n(117),i=n(95);e.exports=function(e){var t=r(e),n=o.f;if(n)for(var a,l=n(e),s=i.f,c=0;l.length>c;)s.call(e,a=l[c++])&&t.push(a);return t}},function(e,t,n){var r=n(64),o=n(24);e.exports=function(e,t){for(var n,i=o(e),a=r(i),l=a.length,s=0;l>s;)if(i[n=a[s++]]===t)return n}},function(e,t,n){"use strict";var r=n(376),o=n(113),i=n(20);e.exports=function(){for(var e=i(this),t=arguments.length,n=Array(t),a=0,l=r._,s=!1;t>a;)(n[a]=arguments[a++])===l&&(s=!0);return function(){var r,i=this,a=arguments.length,c=0,u=0;if(!s&&!a)return o(e,n,i);if(r=n.slice(),s)for(;t>c;c++)r[c]===l&&(r[c]=arguments[u++]);for(;a>u;)r.push(arguments[u++]);return o(e,r,i)}}},function(e,t,n){e.exports=n(3)},function(e,t){e.exports=function(e,t){var n=t===Object(t)?function(e){return t[e]}:t;return function(t){return String(t).replace(e,n)}}},function(e,t,n){var r=n(0),o=n(377)(/[\\^$*+?.()|[\]{}]/g,"\\$&");r(r.S,"RegExp",{escape:function(e){return o(e)}})},function(e,t,n){var r=n(0);r(r.P,"Array",{copyWithin:n(221)}),n(77)("copyWithin")},function(e,t,n){"use strict";var r=n(0),o=n(34)(4);r(r.P+r.F*!n(32)([].every,!0),"Array",{every:function(e){return o(this,e,arguments[1])}})},function(e,t,n){var r=n(0);r(r.P,"Array",{fill:n(145)}),n(77)("fill")},function(e,t,n){"use strict";var r=n(0),o=n(34)(2);r(r.P+r.F*!n(32)([].filter,!0),"Array",{filter:function(e){return o(this,e,arguments[1])}})},function(e,t,n){"use strict";var r=n(0),o=n(34)(6),i="findIndex",a=!0;i in[]&&Array(1)[i](function(){a=!1}),r(r.P+r.F*a,"Array",{findIndex:function(e){return o(this,e,arguments.length>1?arguments[1]:void 0)}}),n(77)(i)},function(e,t,n){"use strict";var r=n(0),o=n(34)(5),i="find",a=!0;i in[]&&Array(1)[i](function(){a=!1}),r(r.P+r.F*a,"Array",{find:function(e){return o(this,e,arguments.length>1?arguments[1]:void 0)}}),n(77)(i)},function(e,t,n){"use strict";var r=n(0),o=n(34)(0),i=n(32)([].forEach,!0);r(r.P+r.F*!i,"Array",{forEach:function(e){return o(this,e,arguments[1])}})},function(e,t,n){"use strict";var r=n(41),o=n(0),i=n(16),a=n(230),l=n(152),s=n(15),c=n(146),u=n(169);o(o.S+o.F*!n(115)(function(e){Array.from(e)}),"Array",{from:function(e){var t,n,o,d,p=i(e),f="function"==typeof this?this:Array,m=arguments.length,h=m>1?arguments[1]:void 0,g=void 0!==h,b=0,y=u(p);if(g&&(h=r(h,m>2?arguments[2]:void 0,2)),void 0==y||f==Array&&l(y))for(t=s(p.length),n=new f(t);t>b;b++)c(n,b,g?h(p[b],b):p[b]);else for(d=y.call(p),n=new f;!(o=d.next()).done;b++)c(n,b,g?a(d,h,[o.value,b],!0):o.value);return n.length=b,n}})},function(e,t,n){"use strict";var r=n(0),o=n(109)(!1),i=[].indexOf,a=!!i&&1/[1].indexOf(1,-0)<0;r(r.P+r.F*(a||!n(32)(i)),"Array",{indexOf:function(e){return a?i.apply(this,arguments)||0:o(this,e,arguments[1])}})},function(e,t,n){var r=n(0);r(r.S,"Array",{isArray:n(153)})},function(e,t,n){"use strict";var r=n(0),o=n(24),i=[].join;r(r.P+r.F*(n(94)!=Object||!n(32)(i)),"Array",{join:function(e){return i.call(o(this),void 0===e?",":e)}})},function(e,t,n){"use strict";var r=n(0),o=n(24),i=n(49),a=n(15),l=[].lastIndexOf,s=!!l&&1/[1].lastIndexOf(1,-0)<0;r(r.P+r.F*(s||!n(32)(l)),"Array",{lastIndexOf:function(e){if(s)return l.apply(this,arguments)||0;var t=o(this),n=a(t.length),r=n-1;for(arguments.length>1&&(r=Math.min(r,i(arguments[1]))),r<0&&(r=n+r);r>=0;r--)if(r in t&&t[r]===e)return r||0;return-1}})},function(e,t,n){"use strict";var r=n(0),o=n(34)(1);r(r.P+r.F*!n(32)([].map,!0),"Array",{map:function(e){return o(this,e,arguments[1])}})},function(e,t,n){"use strict";var r=n(0),o=n(146);r(r.S+r.F*n(5)(function(){function e(){}return!(Array.of.call(e)instanceof e)}),"Array",{of:function(){for(var e=0,t=arguments.length,n=new("function"==typeof this?this:Array)(t);t>e;)o(n,e,arguments[e++]);return n.length=t,n}})},function(e,t,n){"use strict";var r=n(0),o=n(223);r(r.P+r.F*!n(32)([].reduceRight,!0),"Array",{reduceRight:function(e){return o(this,e,arguments.length,arguments[1],!0)}})},function(e,t,n){"use strict";var r=n(0),o=n(223);r(r.P+r.F*!n(32)([].reduce,!0),"Array",{reduce:function(e){return o(this,e,arguments.length,arguments[1],!1)}})},function(e,t,n){"use strict";var r=n(0),o=n(150),i=n(30),a=n(67),l=n(15),s=[].slice;r(r.P+r.F*n(5)(function(){o&&s.call(o)}),"Array",{slice:function(e,t){var n=l(this.length),r=i(this);if(t=void 0===t?n:t,"Array"==r)return s.call(this,e,t);for(var o=a(e,n),c=a(t,n),u=l(c-o),d=Array(u),p=0;p<u;p++)d[p]="String"==r?this.charAt(o+p):this[o+p];return d}})},function(e,t,n){"use strict";var r=n(0),o=n(34)(3);r(r.P+r.F*!n(32)([].some,!0),"Array",{some:function(e){return o(this,e,arguments[1])}})},function(e,t,n){"use strict";var r=n(0),o=n(20),i=n(16),a=n(5),l=[].sort,s=[1,2,3];r(r.P+r.F*(a(function(){s.sort(void 0)})||!a(function(){s.sort(null)})||!n(32)(l)),"Array",{sort:function(e){return void 0===e?l.call(i(this)):l.call(i(this),o(e))}})},function(e,t,n){n(66)("Array")},function(e,t,n){var r=n(0);r(r.S,"Date",{now:function(){return(new Date).getTime()}})},function(e,t,n){"use strict";var r=n(0),o=n(5),i=Date.prototype.getTime,a=function(e){return e>9?e:"0"+e};r(r.P+r.F*(o(function(){return"0385-07-25T07:06:39.999Z"!=new Date(-5e13-1).toISOString()})||!o(function(){new Date(NaN).toISOString()})),"Date",{toISOString:function(){if(!isFinite(i.call(this)))throw RangeError("Invalid time value");var e=this,t=e.getUTCFullYear(),n=e.getUTCMilliseconds(),r=t<0?"-":t>9999?"+":"";return r+("00000"+Math.abs(t)).slice(r?-6:-4)+"-"+a(e.getUTCMonth()+1)+"-"+a(e.getUTCDate())+"T"+a(e.getUTCHours())+":"+a(e.getUTCMinutes())+":"+a(e.getUTCSeconds())+"."+(n>99?n:"0"+a(n))+"Z"}})},function(e,t,n){"use strict";var r=n(0),o=n(16),i=n(36);r(r.P+r.F*n(5)(function(){return null!==new Date(NaN).toJSON()||1!==Date.prototype.toJSON.call({toISOString:function(){return 1}})}),"Date",{toJSON:function(e){var t=o(this),n=i(t);return"number"!=typeof n||isFinite(n)?t.toISOString():null}})},function(e,t,n){var r=n(8)("toPrimitive"),o=Date.prototype;r in o||n(21)(o,r,n(372))},function(e,t,n){var r=Date.prototype,o="Invalid Date",i="toString",a=r[i],l=r.getTime;new Date(NaN)+""!=o&&n(22)(r,i,function(){var e=l.call(this);return e===e?a.call(this):o})},function(e,t,n){var r=n(0);r(r.P,"Function",{bind:n(224)})},function(e,t,n){"use strict";var r=n(7),o=n(27),i=n(8)("hasInstance"),a=Function.prototype;i in a||n(12).f(a,i,{value:function(e){if("function"!=typeof this||!r(e))return!1;if(!r(this.prototype))return e instanceof this;for(;e=o(e);)if(this.prototype===e)return!0;return!1}})},function(e,t,n){var r=n(12).f,o=n(48),i=n(18),a=Function.prototype,l=/^\s*function ([^ (]*)/,s="name",c=Object.isExtensible||function(){return!0};s in a||n(11)&&r(a,s,{configurable:!0,get:function(){try{var e=this,t=(""+e).match(l)[1];return i(e,s)||!c(e)||r(e,s,o(5,t)),t}catch(e){return""}}})},function(e,t,n){var r=n(0),o=n(232),i=Math.sqrt,a=Math.acosh;r(r.S+r.F*!(a&&710==Math.floor(a(Number.MAX_VALUE))&&a(1/0)==1/0),"Math",{acosh:function(e){return(e=+e)<1?NaN:e>94906265.62425156?Math.log(e)+Math.LN2:o(e-1+i(e-1)*i(e+1))}})},function(e,t,n){function r(e){return isFinite(e=+e)&&0!=e?e<0?-r(-e):Math.log(e+Math.sqrt(e*e+1)):e}var o=n(0),i=Math.asinh;o(o.S+o.F*!(i&&1/i(0)>0),"Math",{asinh:r})},function(e,t,n){var r=n(0),o=Math.atanh;r(r.S+r.F*!(o&&1/o(-0)<0),"Math",{atanh:function(e){return 0==(e=+e)?e:Math.log((1+e)/(1-e))/2}})},function(e,t,n){var r=n(0),o=n(157);r(r.S,"Math",{cbrt:function(e){return o(e=+e)*Math.pow(Math.abs(e),1/3)}})},function(e,t,n){var r=n(0);r(r.S,"Math",{clz32:function(e){return(e>>>=0)?31-Math.floor(Math.log(e+.5)*Math.LOG2E):32}})},function(e,t,n){var r=n(0),o=Math.exp;r(r.S,"Math",{cosh:function(e){return(o(e=+e)+o(-e))/2}})},function(e,t,n){var r=n(0),o=n(156);r(r.S+r.F*(o!=Math.expm1),"Math",{expm1:o})},function(e,t,n){var r=n(0),o=n(157),i=Math.pow,a=i(2,-52),l=i(2,-23),s=i(2,127)*(2-l),c=i(2,-126),u=function(e){return e+1/a-1/a};r(r.S,"Math",{fround:function(e){var t,n,r=Math.abs(e),i=o(e);return r<c?i*u(r/c/l)*c*l:(t=(1+l/a)*r,n=t-(t-r),n>s||n!=n?i*(1/0):i*n)}})},function(e,t,n){var r=n(0),o=Math.abs;r(r.S,"Math",{hypot:function(e,t){for(var n,r,i=0,a=0,l=arguments.length,s=0;a<l;)n=o(arguments[a++]),s<n?(r=s/n,i=i*r*r+1,s=n):n>0?(r=n/s,i+=r*r):i+=n;return s===1/0?1/0:s*Math.sqrt(i)}})},function(e,t,n){var r=n(0),o=Math.imul;r(r.S+r.F*n(5)(function(){return o(4294967295,5)!=-5||2!=o.length}),"Math",{imul:function(e,t){var n=65535,r=+e,o=+t,i=n&r,a=n&o;return 0|i*a+((n&r>>>16)*a+i*(n&o>>>16)<<16>>>0)}})},function(e,t,n){var r=n(0);r(r.S,"Math",{log10:function(e){return Math.log(e)/Math.LN10}})},function(e,t,n){var r=n(0);r(r.S,"Math",{log1p:n(232)})},function(e,t,n){var r=n(0);r(r.S,"Math",{log2:function(e){return Math.log(e)/Math.LN2}})},function(e,t,n){var r=n(0);r(r.S,"Math",{sign:n(157)})},function(e,t,n){var r=n(0),o=n(156),i=Math.exp;r(r.S+r.F*n(5)(function(){return!Math.sinh(-2e-17)!=-2e-17}),"Math",{sinh:function(e){return Math.abs(e=+e)<1?(o(e)-o(-e))/2:(i(e-1)-i(-e-1))*(Math.E/2)}})},function(e,t,n){var r=n(0),o=n(156),i=Math.exp;r(r.S,"Math",{tanh:function(e){var t=o(e=+e),n=o(-e);return t==1/0?1:n==1/0?-1:(t-n)/(i(e)+i(-e))}})},function(e,t,n){var r=n(0);r(r.S,"Math",{trunc:function(e){return(e>0?Math.floor:Math.ceil)(e)}})},function(e,t,n){"use strict";var r=n(3),o=n(18),i=n(30),a=n(151),l=n(36),s=n(5),c=n(63).f,u=n(26).f,d=n(12).f,p=n(81).trim,f="Number",m=r[f],h=m,g=m.prototype,b=i(n(62)(g))==f,y="trim"in String.prototype,v=function(e){var t=l(e,!1);if("string"==typeof t&&t.length>2){t=y?t.trim():p(t,3);var n,r,o,i=t.charCodeAt(0);if(43===i||45===i){if(88===(n=t.charCodeAt(2))||120===n)return NaN}else if(48===i){switch(t.charCodeAt(1)){case 66:case 98:r=2,o=49;break;case 79:case 111:r=8,o=55;break;default:return+t}for(var a,s=t.slice(2),c=0,u=s.length;c<u;c++)if((a=s.charCodeAt(c))<48||a>o)return NaN;return parseInt(s,r)}}return+t};if(!m(" 0o1")||!m("0b1")||m("+0x1")){m=function(e){var t=arguments.length<1?0:e,n=this;return n instanceof m&&(b?s(function(){g.valueOf.call(n)}):i(n)!=f)?a(new h(v(t)),n,m):v(t)};for(var _,x=n(11)?c(h):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger".split(","),w=0;x.length>w;w++)o(h,_=x[w])&&!o(m,_)&&d(m,_,u(h,_));m.prototype=g,g.constructor=m,n(22)(r,f,m)}},function(e,t,n){var r=n(0);r(r.S,"Number",{EPSILON:Math.pow(2,-52)})},function(e,t,n){var r=n(0),o=n(3).isFinite;r(r.S,"Number",{isFinite:function(e){return"number"==typeof e&&o(e)}})},function(e,t,n){var r=n(0);r(r.S,"Number",{isInteger:n(229)})},function(e,t,n){var r=n(0);r(r.S,"Number",{isNaN:function(e){return e!=e}})},function(e,t,n){var r=n(0),o=n(229),i=Math.abs;r(r.S,"Number",{isSafeInteger:function(e){return o(e)&&i(e)<=9007199254740991}})},function(e,t,n){var r=n(0);r(r.S,"Number",{MAX_SAFE_INTEGER:9007199254740991})},function(e,t,n){var r=n(0);r(r.S,"Number",{MIN_SAFE_INTEGER:-9007199254740991})},function(e,t,n){var r=n(0),o=n(239);r(r.S+r.F*(Number.parseFloat!=o),"Number",{parseFloat:o})},function(e,t,n){var r=n(0),o=n(240);r(r.S+r.F*(Number.parseInt!=o),"Number",{parseInt:o})},function(e,t,n){"use strict";var r=n(0),o=n(49),i=n(220),a=n(164),l=1..toFixed,s=Math.floor,c=[0,0,0,0,0,0],u="Number.toFixed: incorrect invocation!",d="0",p=function(e,t){for(var n=-1,r=t;++n<6;)r+=e*c[n],c[n]=r%1e7,r=s(r/1e7)},f=function(e){for(var t=6,n=0;--t>=0;)n+=c[t],c[t]=s(n/e),n=n%e*1e7},m=function(){for(var e=6,t="";--e>=0;)if(""!==t||0===e||0!==c[e]){var n=String(c[e]);t=""===t?n:t+a.call(d,7-n.length)+n}return t},h=function(e,t,n){return 0===t?n:t%2==1?h(e,t-1,n*e):h(e*e,t/2,n)},g=function(e){for(var t=0,n=e;n>=4096;)t+=12,n/=4096;for(;n>=2;)t+=1,n/=2;return t};r(r.P+r.F*(!!l&&("0.000"!==8e-5.toFixed(3)||"1"!==.9.toFixed(0)||"1.25"!==1.255.toFixed(2)||"1000000000000000128"!==(0xde0b6b3a7640080).toFixed(0))||!n(5)(function(){l.call({})})),"Number",{toFixed:function(e){var t,n,r,l,s=i(this,u),c=o(e),b="",y=d;if(c<0||c>20)throw RangeError(u);if(s!=s)return"NaN";if(s<=-1e21||s>=1e21)return String(s);if(s<0&&(b="-",s=-s),s>1e-21)if(t=g(s*h(2,69,1))-69,n=t<0?s*h(2,-t,1):s/h(2,t,1),n*=4503599627370496,(t=52-t)>0){for(p(0,n),r=c;r>=7;)p(1e7,0),r-=7;for(p(h(10,r,1),0),r=t-1;r>=23;)f(1<<23),r-=23;f(1<<r),p(1,1),f(2),y=m()}else p(0,n),p(1<<-t,0),y=m()+a.call(d,c);return c>0?(l=y.length,y=b+(l<=c?"0."+a.call(d,c-l)+y:y.slice(0,l-c)+"."+y.slice(l-c))):y=b+y,y}})},function(e,t,n){"use strict";var r=n(0),o=n(5),i=n(220),a=1..toPrecision;r(r.P+r.F*(o(function(){return"1"!==a.call(1,void 0)})||!o(function(){a.call({})})),"Number",{toPrecision:function(e){var t=i(this,"Number#toPrecision: incorrect invocation!");return void 0===e?a.call(t):a.call(t,e)}})},function(e,t,n){var r=n(0);r(r.S+r.F,"Object",{assign:n(233)})},function(e,t,n){var r=n(0);r(r.S,"Object",{create:n(62)})},function(e,t,n){var r=n(0);r(r.S+r.F*!n(11),"Object",{defineProperties:n(234)})},function(e,t,n){var r=n(0);r(r.S+r.F*!n(11),"Object",{defineProperty:n(12).f})},function(e,t,n){var r=n(7),o=n(47).onFreeze;n(35)("freeze",function(e){return function(t){return e&&r(t)?e(o(t)):t}})},function(e,t,n){var r=n(24),o=n(26).f;n(35)("getOwnPropertyDescriptor",function(){return function(e,t){return o(r(e),t)}})},function(e,t,n){n(35)("getOwnPropertyNames",function(){return n(235).f})},function(e,t,n){var r=n(16),o=n(27);n(35)("getPrototypeOf",function(){return function(e){return o(r(e))}})},function(e,t,n){var r=n(7);n(35)("isExtensible",function(e){return function(t){return!!r(t)&&(!e||e(t))}})},function(e,t,n){var r=n(7);n(35)("isFrozen",function(e){return function(t){return!r(t)||!!e&&e(t)}})},function(e,t,n){var r=n(7);n(35)("isSealed",function(e){return function(t){return!r(t)||!!e&&e(t)}})},function(e,t,n){var r=n(0);r(r.S,"Object",{is:n(241)})},function(e,t,n){var r=n(16),o=n(64);n(35)("keys",function(){return function(e){return o(r(e))}})},function(e,t,n){var r=n(7),o=n(47).onFreeze;n(35)("preventExtensions",function(e){return function(t){return e&&r(t)?e(o(t)):t}})},function(e,t,n){var r=n(7),o=n(47).onFreeze;n(35)("seal",function(e){return function(t){return e&&r(t)?e(o(t)):t}})},function(e,t,n){var r=n(0);r(r.S,"Object",{setPrototypeOf:n(159).set})},function(e,t,n){"use strict";var r=n(93),o={};o[n(8)("toStringTag")]="z",o+""!="[object z]"&&n(22)(Object.prototype,"toString",function(){return"[object "+r(this)+"]"},!0)},function(e,t,n){var r=n(0),o=n(239);r(r.G+r.F*(parseFloat!=o),{parseFloat:o})},function(e,t,n){var r=n(0),o=n(240);r(r.G+r.F*(parseInt!=o),{parseInt:o})},function(e,t,n){"use strict";var r,o,i,a=n(61),l=n(3),s=n(41),c=n(93),u=n(0),d=n(7),p=n(20),f=n(60),m=n(78),h=n(161),g=n(166).set,b=n(158)(),y="Promise",v=l.TypeError,_=l.process,x=l[y],_=l.process,w="process"==c(_),C=function(){},k=!!function(){try{var e=x.resolve(1),t=(e.constructor={})[n(8)("species")]=function(e){e(C,C)};return(w||"function"==typeof PromiseRejectionEvent)&&e.then(C)instanceof t}catch(e){}}(),E=function(e,t){return e===t||e===x&&t===i},A=function(e){var t;return!(!d(e)||"function"!=typeof(t=e.then))&&t},S=function(e){return E(x,e)?new I(e):new o(e)},I=o=function(e){var t,n;this.promise=new e(function(e,r){if(void 0!==t||void 0!==n)throw v("Bad Promise constructor");t=e,n=r}),this.resolve=p(t),this.reject=p(n)},T=function(e){try{e()}catch(e){return{error:e}}},P=function(e,t){if(!e._n){e._n=!0;var n=e._c;b(function(){for(var r=e._v,o=1==e._s,i=0,a=function(t){var n,i,a=o?t.ok:t.fail,l=t.resolve,s=t.reject,c=t.domain;try{a?(o||(2==e._h&&R(e),e._h=1),a===!0?n=r:(c&&c.enter(),n=a(r),c&&c.exit()),n===t.promise?s(v("Promise-chain cycle")):(i=A(n))?i.call(n,l,s):l(n)):s(r)}catch(e){s(e)}};n.length>i;)a(n[i++]);e._c=[],e._n=!1,t&&!e._h&&O(e)})}},O=function(e){g.call(l,function(){var t,n,r,o=e._v;if(M(e)&&(t=T(function(){w?_.emit("unhandledRejection",o,e):(n=l.onunhandledrejection)?n({promise:e,reason:o}):(r=l.console)&&r.error&&r.error("Unhandled promise rejection",o)}),e._h=w||M(e)?2:1),e._a=void 0,t)throw t.error})},M=function(e){if(1==e._h)return!1;for(var t,n=e._a||e._c,r=0;n.length>r;)if(t=n[r++],t.fail||!M(t.promise))return!1;return!0},R=function(e){g.call(l,function(){var t;w?_.emit("rejectionHandled",e):(t=l.onrejectionhandled)&&t({promise:e,reason:e._v})})},N=function(e){var t=this;t._d||(t._d=!0,t=t._w||t,t._v=e,t._s=2,t._a||(t._a=t._c.slice()),P(t,!0))},L=function(e){var t,n=this;if(!n._d){n._d=!0,n=n._w||n;try{if(n===e)throw v("Promise can't be resolved itself");(t=A(e))?b(function(){var r={_w:n,_d:!1};try{t.call(e,s(L,r,1),s(N,r,1))}catch(e){N.call(r,e)}}):(n._v=e,n._s=1,P(n,!1))}catch(e){N.call({_w:n,_d:!1},e)}}};k||(x=function(e){f(this,x,y,"_h"),p(e),r.call(this);try{e(s(L,this,1),s(N,this,1))}catch(e){N.call(this,e)}},r=function(e){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},r.prototype=n(65)(x.prototype,{then:function(e,t){var n=S(h(this,x));return n.ok="function"!=typeof e||e,n.fail="function"==typeof t&&t,n.domain=w?_.domain:void 0,this._c.push(n),this._a&&this._a.push(n),this._s&&P(this,!1),n.promise},catch:function(e){return this.then(void 0,e)}}),I=function(){var e=new r;this.promise=e,this.resolve=s(L,e,1),this.reject=s(N,e,1)}),u(u.G+u.W+u.F*!k,{Promise:x}),n(80)(x,y),n(66)(y),i=n(40)[y],u(u.S+u.F*!k,y,{reject:function(e){var t=S(this);return(0,t.reject)(e),t.promise}}),u(u.S+u.F*(a||!k),y,{resolve:function(e){if(e instanceof x&&E(e.constructor,this))return e;var t=S(this);return(0,t.resolve)(e),t.promise}}),u(u.S+u.F*!(k&&n(115)(function(e){x.all(e).catch(C)})),y,{all:function(e){var t=this,n=S(t),r=n.resolve,o=n.reject,i=T(function(){var n=[],i=0,a=1;m(e,!1,function(e){var l=i++,s=!1;n.push(void 0),a++,t.resolve(e).then(function(e){s||(s=!0,n[l]=e,--a||r(n))},o)}),--a||r(n)});return i&&o(i.error),n.promise},race:function(e){var t=this,n=S(t),r=n.reject,o=T(function(){m(e,!1,function(e){t.resolve(e).then(n.resolve,r)})});return o&&r(o.error),n.promise}})},function(e,t,n){var r=n(0),o=n(20),i=n(2),a=(n(3).Reflect||{}).apply,l=Function.apply;r(r.S+r.F*!n(5)(function(){a(function(){})}),"Reflect",{apply:function(e,t,n){var r=o(e),s=i(n);return a?a(r,t,s):l.call(r,t,s)}})},function(e,t,n){var r=n(0),o=n(62),i=n(20),a=n(2),l=n(7),s=n(5),c=n(224),u=(n(3).Reflect||{}).construct,d=s(function(){function e(){}return!(u(function(){},[],e)instanceof e)}),p=!s(function(){u(function(){})});r(r.S+r.F*(d||p),"Reflect",{construct:function(e,t){i(e),a(t);var n=arguments.length<3?e:i(arguments[2]);if(p&&!d)return u(e,t,n);if(e==n){switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3])}var r=[null];return r.push.apply(r,t),new(c.apply(e,r))}var s=n.prototype,f=o(l(s)?s:Object.prototype),m=Function.apply.call(e,f,t);return l(m)?m:f}})},function(e,t,n){var r=n(12),o=n(0),i=n(2),a=n(36);o(o.S+o.F*n(5)(function(){Reflect.defineProperty(r.f({},1,{value:1}),1,{value:2})}),"Reflect",{defineProperty:function(e,t,n){i(e),t=a(t,!0),i(n);try{return r.f(e,t,n),!0}catch(e){return!1}}})},function(e,t,n){var r=n(0),o=n(26).f,i=n(2);r(r.S,"Reflect",{deleteProperty:function(e,t){var n=o(i(e),t);return!(n&&!n.configurable)&&delete e[t]}})},function(e,t,n){"use strict";var r=n(0),o=n(2),i=function(e){this._t=o(e),this._i=0;var t,n=this._k=[];for(t in e)n.push(t)};n(154)(i,"Object",function(){var e,t=this,n=t._k;do{if(t._i>=n.length)return{value:void 0,done:!0}}while(!((e=n[t._i++])in t._t));return{value:e,done:!1}}),r(r.S,"Reflect",{enumerate:function(e){return new i(e)}})},function(e,t,n){var r=n(26),o=n(0),i=n(2);o(o.S,"Reflect",{getOwnPropertyDescriptor:function(e,t){return r.f(i(e),t)}})},function(e,t,n){var r=n(0),o=n(27),i=n(2);r(r.S,"Reflect",{getPrototypeOf:function(e){return o(i(e))}})},function(e,t,n){function r(e,t){var n,l,u=arguments.length<3?e:arguments[2];return c(e)===u?e[t]:(n=o.f(e,t))?a(n,"value")?n.value:void 0!==n.get?n.get.call(u):void 0:s(l=i(e))?r(l,t,u):void 0}var o=n(26),i=n(27),a=n(18),l=n(0),s=n(7),c=n(2);l(l.S,"Reflect",{get:r})},function(e,t,n){var r=n(0);r(r.S,"Reflect",{has:function(e,t){return t in e}})},function(e,t,n){var r=n(0),o=n(2),i=Object.isExtensible;r(r.S,"Reflect",{isExtensible:function(e){return o(e),!i||i(e)}})},function(e,t,n){var r=n(0);r(r.S,"Reflect",{ownKeys:n(238)})},function(e,t,n){var r=n(0),o=n(2),i=Object.preventExtensions;r(r.S,"Reflect",{preventExtensions:function(e){o(e);try{return i&&i(e),!0}catch(e){return!1}}})},function(e,t,n){var r=n(0),o=n(159);o&&r(r.S,"Reflect",{setPrototypeOf:function(e,t){o.check(e,t);try{return o.set(e,t),!0}catch(e){return!1}}})},function(e,t,n){function r(e,t,n){var s,p,f=arguments.length<4?e:arguments[3],m=i.f(u(e),t);if(!m){if(d(p=a(e)))return r(p,t,n,f);m=c(0)}return l(m,"value")?!(m.writable===!1||!d(f))&&(s=i.f(f,t)||c(0),s.value=n,o.f(f,t,s),!0):void 0!==m.set&&(m.set.call(f,n),!0)}var o=n(12),i=n(26),a=n(27),l=n(18),s=n(0),c=n(48),u=n(2),d=n(7);s(s.S,"Reflect",{set:r})},function(e,t,n){var r=n(3),o=n(151),i=n(12).f,a=n(63).f,l=n(114),s=n(112),c=r.RegExp,u=c,d=c.prototype,p=/a/g,f=/a/g,m=new c(p)!==p;if(n(11)&&(!m||n(5)(function(){return f[n(8)("match")]=!1,c(p)!=p||c(f)==f||"/a/i"!=c(p,"i")}))){c=function(e,t){var n=this instanceof c,r=l(e),i=void 0===t;return!n&&r&&e.constructor===c&&i?e:o(m?new u(r&&!i?e.source:e,t):u((r=e instanceof c)?e.source:e,r&&i?s.call(e):t),n?this:d,c)};for(var h=(function(e){e in c||i(c,e,{configurable:!0,get:function(){return u[e]},set:function(t){u[e]=t}})}),g=a(u),b=0;g.length>b;)h(g[b++]);d.constructor=c,c.prototype=d,n(22)(r,"RegExp",c)}n(66)("RegExp")},function(e,t,n){n(111)("match",1,function(e,t,n){return[function(n){"use strict";var r=e(this),o=void 0==n?void 0:n[t];return void 0!==o?o.call(n,r):new RegExp(n)[t](String(r))},n]})},function(e,t,n){n(111)("replace",2,function(e,t,n){return[function(r,o){"use strict";var i=e(this),a=void 0==r?void 0:r[t];return void 0!==a?a.call(r,i,o):n.call(String(i),r,o)},n]})},function(e,t,n){n(111)("search",1,function(e,t,n){return[function(n){"use strict";var r=e(this),o=void 0==n?void 0:n[t];return void 0!==o?o.call(n,r):new RegExp(n)[t](String(r))},n]})},function(e,t,n){n(111)("split",2,function(e,t,r){"use strict";var o=n(114),i=r,a=[].push,l="split",s="length",c="lastIndex";if("c"=="abbc"[l](/(b)*/)[1]||4!="test"[l](/(?:)/,-1)[s]||2!="ab"[l](/(?:ab)*/)[s]||4!="."[l](/(.?)(.?)/)[s]||"."[l](/()()/)[s]>1||""[l](/.?/)[s]){var u=void 0===/()??/.exec("")[1];r=function(e,t){var n=String(this);if(void 0===e&&0===t)return[];if(!o(e))return i.call(n,e,t);var r,l,d,p,f,m=[],h=(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.unicode?"u":"")+(e.sticky?"y":""),g=0,b=void 0===t?4294967295:t>>>0,y=new RegExp(e.source,h+"g");for(u||(r=new RegExp("^"+y.source+"$(?!\\s)",h));(l=y.exec(n))&&!((d=l.index+l[0][s])>g&&(m.push(n.slice(g,l.index)),!u&&l[s]>1&&l[0].replace(r,function(){for(f=1;f<arguments[s]-2;f++)void 0===arguments[f]&&(l[f]=void 0)}),l[s]>1&&l.index<n[s]&&a.apply(m,l.slice(1)),p=l[0][s],g=d,m[s]>=b));)y[c]===l.index&&y[c]++;return g===n[s]?!p&&y.test("")||m.push(""):m.push(n.slice(g)),m[s]>b?m.slice(0,b):m}}else"0"[l](void 0,0)[s]&&(r=function(e,t){return void 0===e&&0===t?[]:i.call(this,e,t)});return[function(n,o){var i=e(this),a=void 0==n?void 0:n[t];return void 0!==a?a.call(n,i,o):r.call(String(i),n,o)},r]})},function(e,t,n){"use strict";n(245);var r=n(2),o=n(112),i=n(11),a="toString",l=/./[a],s=function(e){n(22)(RegExp.prototype,a,e,!0)};n(5)(function(){return"/a/b"!=l.call({source:"a",flags:"b"})})?s(function(){var e=r(this);return"/".concat(e.source,"/","flags"in e?e.flags:!i&&e instanceof RegExp?o.call(e):void 0)}):l.name!=a&&s(function(){return l.call(this)})},function(e,t,n){"use strict";n(23)("anchor",function(e){return function(t){return e(this,"a","name",t)}})},function(e,t,n){"use strict";n(23)("big",function(e){return function(){return e(this,"big","","")}})},function(e,t,n){"use strict";n(23)("blink",function(e){return function(){return e(this,"blink","","")}})},function(e,t,n){"use strict";n(23)("bold",function(e){return function(){return e(this,"b","","")}})},function(e,t,n){"use strict";var r=n(0),o=n(162)(!1);r(r.P,"String",{codePointAt:function(e){return o(this,e)}})},function(e,t,n){"use strict";var r=n(0),o=n(15),i=n(163),a="endsWith",l=""[a];r(r.P+r.F*n(149)(a),"String",{endsWith:function(e){var t=i(this,e,a),n=arguments.length>1?arguments[1]:void 0,r=o(t.length),s=void 0===n?r:Math.min(o(n),r),c=String(e);return l?l.call(t,c,s):t.slice(s-c.length,s)===c}})},function(e,t,n){"use strict";n(23)("fixed",function(e){return function(){return e(this,"tt","","")}})},function(e,t,n){"use strict";n(23)("fontcolor",function(e){return function(t){return e(this,"font","color",t)}})},function(e,t,n){"use strict";n(23)("fontsize",function(e){return function(t){return e(this,"font","size",t)}})},function(e,t,n){var r=n(0),o=n(67),i=String.fromCharCode,a=String.fromCodePoint;r(r.S+r.F*(!!a&&1!=a.length),"String",{fromCodePoint:function(e){for(var t,n=[],r=arguments.length,a=0;r>a;){if(t=+arguments[a++],o(t,1114111)!==t)throw RangeError(t+" is not a valid code point");n.push(t<65536?i(t):i(55296+((t-=65536)>>10),t%1024+56320))}return n.join("")}})},function(e,t,n){"use strict";var r=n(0),o=n(163),i="includes";r(r.P+r.F*n(149)(i),"String",{includes:function(e){return!!~o(this,e,i).indexOf(e,arguments.length>1?arguments[1]:void 0)}})},function(e,t,n){"use strict";n(23)("italics",function(e){return function(){return e(this,"i","","")}})},function(e,t,n){"use strict";var r=n(162)(!0);n(155)(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,n=this._i;return n>=t.length?{value:void 0,done:!0}:(e=r(t,n),this._i+=e.length,{value:e,done:!1})})},function(e,t,n){"use strict";n(23)("link",function(e){return function(t){return e(this,"a","href",t)}})},function(e,t,n){var r=n(0),o=n(24),i=n(15);r(r.S,"String",{raw:function(e){for(var t=o(e.raw),n=i(t.length),r=arguments.length,a=[],l=0;n>l;)a.push(String(t[l++])),l<r&&a.push(String(arguments[l]));return a.join("")}})},function(e,t,n){var r=n(0);r(r.P,"String",{repeat:n(164)})},function(e,t,n){"use strict";n(23)("small",function(e){return function(){return e(this,"small","","")}})},function(e,t,n){"use strict";var r=n(0),o=n(15),i=n(163),a="startsWith",l=""[a];r(r.P+r.F*n(149)(a),"String",{startsWith:function(e){var t=i(this,e,a),n=o(Math.min(arguments.length>1?arguments[1]:void 0,t.length)),r=String(e);return l?l.call(t,r,n):t.slice(n,n+r.length)===r}})},function(e,t,n){"use strict";n(23)("strike",function(e){return function(){return e(this,"strike","","")}})},function(e,t,n){"use strict";n(23)("sub",function(e){return function(){return e(this,"sub","","")}})},function(e,t,n){"use strict";n(23)("sup",function(e){return function(){return e(this,"sup","","")}})},function(e,t,n){"use strict";n(81)("trim",function(e){return function(){return e(this,3)}})},function(e,t,n){"use strict";var r=n(3),o=n(18),i=n(11),a=n(0),l=n(22),s=n(47).KEY,c=n(5),u=n(118),d=n(80),p=n(68),f=n(8),m=n(243),h=n(168),g=n(374),b=n(373),y=n(153),v=n(2),_=n(24),x=n(36),w=n(48),C=n(62),k=n(235),E=n(26),A=n(12),S=n(64),I=E.f,T=A.f,P=k.f,O=r.Symbol,M=r.JSON,R=M&&M.stringify,N="prototype",L=f("_hidden"),D=f("toPrimitive"),j={}.propertyIsEnumerable,F=u("symbol-registry"),z=u("symbols"),U=u("op-symbols"),B=Object[N],H="function"==typeof O,W=r.QObject,V=!W||!W[N]||!W[N].findChild,G=i&&c(function(){return 7!=C(T({},"a",{get:function(){return T(this,"a",{value:7}).a}})).a})?function(e,t,n){var r=I(B,t);r&&delete B[t],T(e,t,n),r&&e!==B&&T(B,t,r)}:T,Y=function(e){var t=z[e]=C(O[N]);return t._k=e,t},q=H&&"symbol"==typeof O.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof O},K=function(e,t,n){return e===B&&K(U,t,n),v(e),t=x(t,!0),v(n),o(z,t)?(n.enumerable?(o(e,L)&&e[L][t]&&(e[L][t]=!1),n=C(n,{enumerable:w(0,!1)})):(o(e,L)||T(e,L,w(1,{})),e[L][t]=!0),G(e,t,n)):T(e,t,n)},Z=function(e,t){v(e);for(var n,r=b(t=_(t)),o=0,i=r.length;i>o;)K(e,n=r[o++],t[n]);return e},X=function(e,t){return void 0===t?C(e):Z(C(e),t)},Q=function(e){var t=j.call(this,e=x(e,!0));return!(this===B&&o(z,e)&&!o(U,e))&&(!(t||!o(this,e)||!o(z,e)||o(this,L)&&this[L][e])||t)},J=function(e,t){if(e=_(e),t=x(t,!0),e!==B||!o(z,t)||o(U,t)){var n=I(e,t);return!n||!o(z,t)||o(e,L)&&e[L][t]||(n.enumerable=!0),n}},$=function(e){for(var t,n=P(_(e)),r=[],i=0;n.length>i;)o(z,t=n[i++])||t==L||t==s||r.push(t);return r},ee=function(e){for(var t,n=e===B,r=P(n?U:_(e)),i=[],a=0;r.length>a;)!o(z,t=r[a++])||n&&!o(B,t)||i.push(z[t]);return i};H||(O=function(){if(this instanceof O)throw TypeError("Symbol is not a constructor!");var e=p(arguments.length>0?arguments[0]:void 0),t=function(n){this===B&&t.call(U,n),o(this,L)&&o(this[L],e)&&(this[L][e]=!1),G(this,e,w(1,n))};return i&&V&&G(B,e,{configurable:!0,set:t}),Y(e)},l(O[N],"toString",function(){return this._k}),E.f=J,A.f=K,n(63).f=k.f=$,n(95).f=Q,n(117).f=ee,i&&!n(61)&&l(B,"propertyIsEnumerable",Q,!0),m.f=function(e){return Y(f(e))}),a(a.G+a.W+a.F*!H,{Symbol:O});for(var te="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),ne=0;te.length>ne;)f(te[ne++]);for(var te=S(f.store),ne=0;te.length>ne;)h(te[ne++]);a(a.S+a.F*!H,"Symbol",{for:function(e){return o(F,e+="")?F[e]:F[e]=O(e)},keyFor:function(e){if(q(e))return g(F,e);throw TypeError(e+" is not a symbol!")},useSetter:function(){V=!0},useSimple:function(){V=!1}}),a(a.S+a.F*!H,"Object",{create:X,defineProperty:K,defineProperties:Z,getOwnPropertyDescriptor:J,getOwnPropertyNames:$,getOwnPropertySymbols:ee}),M&&a(a.S+a.F*(!H||c(function(){var e=O();return"[null]"!=R([e])||"{}"!=R({a:e})||"{}"!=R(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!q(e)){for(var t,n,r=[e],o=1;arguments.length>o;)r.push(arguments[o++]);return t=r[1],"function"==typeof t&&(n=t),!n&&y(t)||(t=function(e,t){if(n&&(t=n.call(this,e,t)),!q(t))return t}),r[1]=t,R.apply(M,r)}}}),O[N][D]||n(21)(O[N],D,O[N].valueOf),d(O,"Symbol"),d(Math,"Math",!0),d(r.JSON,"JSON",!0)},function(e,t,n){"use strict";var r=n(0),o=n(119),i=n(167),a=n(2),l=n(67),s=n(15),c=n(7),u=n(3).ArrayBuffer,d=n(161),p=i.ArrayBuffer,f=i.DataView,m=o.ABV&&u.isView,h=p.prototype.slice,g=o.VIEW,b="ArrayBuffer";r(r.G+r.W+r.F*(u!==p),{ArrayBuffer:p}),r(r.S+r.F*!o.CONSTR,b,{isView:function(e){return m&&m(e)||c(e)&&g in e}}),r(r.P+r.U+r.F*n(5)(function(){return!new p(2).slice(1,void 0).byteLength}),b,{slice:function(e,t){if(void 0!==h&&void 0===t)return h.call(a(this),e);for(var n=a(this).byteLength,r=l(e,n),o=l(void 0===t?n:t,n),i=new(d(this,p))(s(o-r)),c=new f(this),u=new f(i),m=0;r<o;)u.setUint8(m++,c.getUint8(r++));return i}}),n(66)(b)},function(e,t,n){var r=n(0);r(r.G+r.W+r.F*!n(119).ABV,{DataView:n(167).DataView})},function(e,t,n){n(43)("Float32",4,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(e,t,n){n(43)("Float64",8,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(e,t,n){n(43)("Int16",2,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(e,t,n){n(43)("Int32",4,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(e,t,n){n(43)("Int8",1,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(e,t,n){n(43)("Uint16",2,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(e,t,n){n(43)("Uint32",4,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(e,t,n){n(43)("Uint8",1,function(e){return function(t,n,r){return e(this,t,n,r)}})},function(e,t,n){n(43)("Uint8",1,function(e){return function(t,n,r){return e(this,t,n,r)}},!0)},function(e,t,n){"use strict";var r=n(227);n(110)("WeakSet",function(e){return function(){return e(this,arguments.length>0?arguments[0]:void 0)}},{add:function(e){return r.def(this,e,!0)}},r,!1,!0)},function(e,t,n){"use strict";var r=n(0),o=n(109)(!0);r(r.P,"Array",{includes:function(e){return o(this,e,arguments.length>1?arguments[1]:void 0)}}),n(77)("includes")},function(e,t,n){var r=n(0),o=n(158)(),i=n(3).process,a="process"==n(30)(i);r(r.G,{asap:function(e){var t=a&&i.domain;o(t?t.bind(e):e)}})},function(e,t,n){var r=n(0),o=n(30);r(r.S,"Error",{isError:function(e){return"Error"===o(e)}})},function(e,t,n){var r=n(0);r(r.P+r.R,"Map",{toJSON:n(226)("Map")})},function(e,t,n){var r=n(0);r(r.S,"Math",{iaddh:function(e,t,n,r){var o=e>>>0,i=t>>>0,a=n>>>0;return i+(r>>>0)+((o&a|(o|a)&~(o+a>>>0))>>>31)|0}})},function(e,t,n){var r=n(0);r(r.S,"Math",{imulh:function(e,t){var n=65535,r=+e,o=+t,i=r&n,a=o&n,l=r>>16,s=o>>16,c=(l*a>>>0)+(i*a>>>16);return l*s+(c>>16)+((i*s>>>0)+(c&n)>>16)}})},function(e,t,n){var r=n(0);r(r.S,"Math",{isubh:function(e,t,n,r){var o=e>>>0,i=t>>>0,a=n>>>0;return i-(r>>>0)-((~o&a|~(o^a)&o-a>>>0)>>>31)|0}})},function(e,t,n){var r=n(0);r(r.S,"Math",{umulh:function(e,t){var n=65535,r=+e,o=+t,i=r&n,a=o&n,l=r>>>16,s=o>>>16,c=(l*a>>>0)+(i*a>>>16);return l*s+(c>>>16)+((i*s>>>0)+(c&n)>>>16)}})},function(e,t,n){"use strict";var r=n(0),o=n(16),i=n(20),a=n(12);n(11)&&r(r.P+n(116),"Object",{__defineGetter__:function(e,t){a.f(o(this),e,{get:i(t),enumerable:!0,configurable:!0})}})},function(e,t,n){"use strict";var r=n(0),o=n(16),i=n(20),a=n(12);n(11)&&r(r.P+n(116),"Object",{__defineSetter__:function(e,t){a.f(o(this),e,{set:i(t),enumerable:!0,configurable:!0})}})},function(e,t,n){var r=n(0),o=n(237)(!0);r(r.S,"Object",{entries:function(e){return o(e)}})},function(e,t,n){var r=n(0),o=n(238),i=n(24),a=n(26),l=n(146);r(r.S,"Object",{getOwnPropertyDescriptors:function(e){for(var t,n=i(e),r=a.f,s=o(n),c={},u=0;s.length>u;)l(c,t=s[u++],r(n,t));return c}})},function(e,t,n){"use strict";var r=n(0),o=n(16),i=n(36),a=n(27),l=n(26).f;n(11)&&r(r.P+n(116),"Object",{__lookupGetter__:function(e){var t,n=o(this),r=i(e,!0);do{if(t=l(n,r))return t.get}while(n=a(n))}})},function(e,t,n){"use strict";var r=n(0),o=n(16),i=n(36),a=n(27),l=n(26).f;n(11)&&r(r.P+n(116),"Object",{__lookupSetter__:function(e){var t,n=o(this),r=i(e,!0);do{if(t=l(n,r))return t.set}while(n=a(n))}})},function(e,t,n){var r=n(0),o=n(237)(!1);r(r.S,"Object",{values:function(e){return o(e)}})},function(e,t,n){"use strict";var r=n(0),o=n(3),i=n(40),a=n(158)(),l=n(8)("observable"),s=n(20),c=n(2),u=n(60),d=n(65),p=n(21),f=n(78),m=f.RETURN,h=function(e){return null==e?void 0:s(e)},g=function(e){var t=e._c;t&&(e._c=void 0,t())},b=function(e){return void 0===e._o},y=function(e){b(e)||(e._o=void 0,g(e))},v=function(e,t){c(e),this._c=void 0,this._o=e,e=new _(this);try{var n=t(e),r=n;null!=n&&("function"==typeof n.unsubscribe?n=function(){r.unsubscribe()}:s(n),this._c=n)}catch(t){return void e.error(t)}b(this)&&g(this)};v.prototype=d({},{unsubscribe:function(){y(this)}});var _=function(e){this._s=e};_.prototype=d({},{next:function(e){var t=this._s;if(!b(t)){var n=t._o;try{var r=h(n.next);if(r)return r.call(n,e)}catch(e){try{y(t)}finally{throw e}}}},error:function(e){var t=this._s;if(b(t))throw e;var n=t._o;t._o=void 0;try{var r=h(n.error);if(!r)throw e;e=r.call(n,e)}catch(e){try{g(t)}finally{throw e}}return g(t),e},complete:function(e){var t=this._s;if(!b(t)){var n=t._o;t._o=void 0;try{var r=h(n.complete);e=r?r.call(n,e):void 0}catch(e){try{g(t)}finally{throw e}}return g(t),e}}});var x=function(e){u(this,x,"Observable","_f")._f=s(e)};d(x.prototype,{subscribe:function(e){return new v(e,this._f)},forEach:function(e){var t=this;return new(i.Promise||o.Promise)(function(n,r){s(e);var o=t.subscribe({next:function(t){try{return e(t)}catch(e){r(e),o.unsubscribe()}},error:r,complete:n})})}}),d(x,{from:function(e){var t="function"==typeof this?this:x,n=h(c(e)[l]);if(n){var r=c(n.call(e));return r.constructor===t?r:new t(function(e){return r.subscribe(e)})}return new t(function(t){var n=!1;return a(function(){if(!n){try{if(f(e,!1,function(e){if(t.next(e),n)return m})===m)return}catch(e){if(n)throw e;return void t.error(e)}t.complete()}}),function(){n=!0}})},of:function(){for(var e=0,t=arguments.length,n=Array(t);e<t;)n[e]=arguments[e++];return new("function"==typeof this?this:x)(function(e){var t=!1;return a(function(){if(!t){for(var r=0;r<n.length;++r)if(e.next(n[r]),t)return;e.complete()}}),function(){t=!0}})}}),p(x.prototype,l,function(){return this}),r(r.G,{Observable:x}),n(66)("Observable")},function(e,t,n){var r=n(42),o=n(2),i=r.key,a=r.set;r.exp({defineMetadata:function(e,t,n,r){a(e,t,o(n),i(r))}})},function(e,t,n){var r=n(42),o=n(2),i=r.key,a=r.map,l=r.store;r.exp({deleteMetadata:function(e,t){var n=arguments.length<3?void 0:i(arguments[2]),r=a(o(t),n,!1);if(void 0===r||!r.delete(e))return!1;if(r.size)return!0;var s=l.get(t);return s.delete(n),!!s.size||l.delete(t)}})},function(e,t,n){var r=n(246),o=n(222),i=n(42),a=n(2),l=n(27),s=i.keys,c=i.key,u=function(e,t){var n=s(e,t),i=l(e);if(null===i)return n;var a=u(i,t);return a.length?n.length?o(new r(n.concat(a))):a:n};i.exp({getMetadataKeys:function(e){return u(a(e),arguments.length<2?void 0:c(arguments[1]))}})},function(e,t,n){var r=n(42),o=n(2),i=n(27),a=r.has,l=r.get,s=r.key,c=function(e,t,n){if(a(e,t,n))return l(e,t,n);var r=i(t);return null!==r?c(e,r,n):void 0};r.exp({getMetadata:function(e,t){return c(e,o(t),arguments.length<3?void 0:s(arguments[2]))}})},function(e,t,n){var r=n(42),o=n(2),i=r.keys,a=r.key;r.exp({getOwnMetadataKeys:function(e){return i(o(e),arguments.length<2?void 0:a(arguments[1]))}})},function(e,t,n){var r=n(42),o=n(2),i=r.get,a=r.key;r.exp({getOwnMetadata:function(e,t){return i(e,o(t),arguments.length<3?void 0:a(arguments[2]))}})},function(e,t,n){var r=n(42),o=n(2),i=n(27),a=r.has,l=r.key,s=function(e,t,n){if(a(e,t,n))return!0;var r=i(t);return null!==r&&s(e,r,n)};r.exp({hasMetadata:function(e,t){return s(e,o(t),arguments.length<3?void 0:l(arguments[2]))}})},function(e,t,n){var r=n(42),o=n(2),i=r.has,a=r.key;r.exp({hasOwnMetadata:function(e,t){return i(e,o(t),arguments.length<3?void 0:a(arguments[2]))}})},function(e,t,n){var r=n(42),o=n(2),i=n(20),a=r.key,l=r.set;r.exp({metadata:function(e,t){return function(n,r){l(e,t,(void 0!==r?o:i)(n),a(r))}}})},function(e,t,n){var r=n(0);r(r.P+r.R,"Set",{toJSON:n(226)("Set")})},function(e,t,n){"use strict";var r=n(0),o=n(162)(!0);r(r.P,"String",{at:function(e){return o(this,e)}})},function(e,t,n){"use strict";var r=n(0),o=n(31),i=n(15),a=n(114),l=n(112),s=RegExp.prototype,c=function(e,t){this._r=e,this._s=t};n(154)(c,"RegExp String",function(){var e=this._r.exec(this._s);return{value:e,done:null===e}}),r(r.P,"String",{matchAll:function(e){if(o(this),!a(e))throw TypeError(e+" is not a regexp!");var t=String(this),n="flags"in s?String(e.flags):l.call(e),r=new RegExp(e.source,~n.indexOf("g")?n:"g"+n);return r.lastIndex=i(e.lastIndex),new c(r,t)}})},function(e,t,n){"use strict";var r=n(0),o=n(242);r(r.P,"String",{padEnd:function(e){return o(this,e,arguments.length>1?arguments[1]:void 0,!1)}})},function(e,t,n){"use strict";var r=n(0),o=n(242);r(r.P,"String",{padStart:function(e){return o(this,e,arguments.length>1?arguments[1]:void 0,!0)}})},function(e,t,n){"use strict";n(81)("trimLeft",function(e){return function(){return e(this,1)}},"trimStart")},function(e,t,n){"use strict";n(81)("trimRight",function(e){return function(){return e(this,2)}},"trimEnd")},function(e,t,n){n(168)("asyncIterator")},function(e,t,n){n(168)("observable")},function(e,t,n){var r=n(0);r(r.S,"System",{global:n(3)})},function(e,t,n){for(var r=n(170),o=n(22),i=n(3),a=n(21),l=n(79),s=n(8),c=s("iterator"),u=s("toStringTag"),d=l.Array,p=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],f=0;f<5;f++){var m,h=p[f],g=i[h],b=g&&g.prototype;if(b){b[c]||a(b,c,d),b[u]||a(b,u,h),l[h]=d;for(m in r)b[m]||o(b,m,r[m],!0)}}},function(e,t,n){var r=n(0),o=n(166);r(r.G+r.B,{setImmediate:o.set,clearImmediate:o.clear})},function(e,t,n){var r=n(3),o=n(0),i=n(113),a=n(375),l=r.navigator,s=!!l&&/MSIE .\./.test(l.userAgent),c=function(e){return s?function(t,n){return e(i(a,[].slice.call(arguments,2),"function"==typeof t?t:Function(t)),n)}:e};o(o.G+o.B+o.F*s,{setTimeout:c(r.setTimeout),setInterval:c(r.setInterval)})},function(e,t,n){n(498),n(437),n(439),n(438),n(441),n(443),n(448),n(442),n(440),n(450),n(449),n(445),n(446),n(444),n(436),n(447),n(451),n(452),n(404),n(406),n(405),n(454),n(453),n(424),n(434),n(435),n(425),n(426),n(427),n(428),n(429),n(430),n(431),n(432),n(433),n(407),n(408),n(409),n(410),n(411),n(412),n(413),n(414),n(415),n(416),n(417),n(418),n(419),n(420),n(421),n(422),n(423),n(485),n(490),n(497),n(488),n(480),n(481),n(486),n(491),n(493),n(476),n(477),n(478),n(479),n(482),n(483),n(484),n(487),n(489),n(492),n(494),n(495),n(496),n(399),n(401),n(400),n(403),n(402),n(388),n(386),n(392),n(389),n(395),n(397),n(385),n(391),n(382),n(396),n(380),n(394),n(393),n(387),n(390),n(379),n(381),n(384),n(383),n(398),n(170),n(470),n(475),n(245),n(471),n(472),n(473),n(474),n(455),n(244),n(246),n(247),n(510),n(499),n(500),n(505),n(508),n(509),n(503),n(506),n(504),n(507),n(501),n(502),n(456),n(457),n(458),n(459),n(460),n(463),n(461),n(462),n(464),n(465),n(466),n(467),n(469),n(468),n(511),n(537),n(540),n(539),n(541),n(542),n(538),n(543),n(544),n(522),n(525),n(521),n(519),n(520),n(523),n(524),n(514),n(536),n(545),n(513),n(515),n(517),n(516),n(518),n(527),n(528),n(530),n(529),n(532),n(531),n(533),n(534),n(535),n(512),n(526),n(548),n(547),n(546),e.exports=n(40)},function(e,t,n){t=e.exports=n(55)(void 0),t.push([e.i,'html{color:rgba(0,0,0,.87)}::-moz-selection{background:#b3d4fc;text-shadow:none}::selection{background:#b3d4fc;text-shadow:none}hr{display:block;height:1px;border:0;border-top:1px solid #ccc;margin:1em 0;padding:0}audio,canvas,iframe,img,svg,video{vertical-align:middle}fieldset{border:0;margin:0;padding:0}textarea{resize:vertical}.browserupgrade{margin:.2em 0;background:#ccc;color:#000;padding:.2em 0}.hidden{display:none!important}.visuallyhidden{border:0;clip:rect(0 0 0 0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.visuallyhidden.focusable:active,.visuallyhidden.focusable:focus{clip:auto;height:auto;margin:0;overflow:visible;position:static;width:auto}.invisible{visibility:hidden}.clearfix:after,.clearfix:before{content:" ";display:table}.clearfix:after{clear:both}@media print{*,:after,:before,:first-letter{background:transparent!important;color:#000!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href)")"}abbr[title]:after{content:" (" attr(title)")"}a[href^="#"]:after,a[href^="javascript:"]:after{content:""}blockquote,pre{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}img,tr{page-break-inside:avoid}img{max-width:100%!important}h2,h3,p{orphans:3;widows:3}h2,h3{page-break-after:avoid}}.mdl-accordion,.mdl-button,.mdl-card,.mdl-checkbox,.mdl-dropdown-menu,.mdl-icon-toggle,.mdl-item,.mdl-radio,.mdl-slider,.mdl-switch,.mdl-tabs__tab,a{-webkit-tap-highlight-color:transparent;-webkit-tap-highlight-color:rgba(255,255,255,0)}html{height:100%;-ms-touch-action:manipulation;touch-action:manipulation}body,html{width:100%}body{min-height:100%;margin:0}main{display:block}[hidden]{display:none!important}body,html{font-family:Helvetica,Arial,sans-serif;font-size:14px;font-weight:400;line-height:20px}h1,h2,h3,h4,h5,h6,p{padding:0}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small{font-family:Roboto,Helvetica,Arial,sans-serif;font-weight:400;line-height:1.35;letter-spacing:-.02em;opacity:.54;font-size:.6em}h1{font-size:56px;line-height:1.35;letter-spacing:-.02em;margin:24px 0}h1,h2{font-family:Roboto,Helvetica,Arial,sans-serif;font-weight:400}h2{font-size:45px;line-height:48px}h2,h3{margin:24px 0}h3{font-size:34px;line-height:40px}h3,h4{font-family:Roboto,Helvetica,Arial,sans-serif;font-weight:400}h4{font-size:24px;line-height:32px;-moz-osx-font-smoothing:grayscale;margin:24px 0 16px}h5{font-size:20px;font-weight:500;line-height:1;letter-spacing:.02em}h5,h6{font-family:Roboto,Helvetica,Arial,sans-serif;margin:24px 0 16px}h6{font-size:16px;letter-spacing:.04em}h6,p{font-weight:400;line-height:24px}p{font-size:14px;letter-spacing:0;margin:0 0 16px}a{color:#ff4081;font-weight:500}blockquote{font-family:Roboto,Helvetica,Arial,sans-serif;position:relative;font-size:24px;font-weight:300;font-style:italic;line-height:1.35;letter-spacing:.08em}blockquote:before{position:absolute;left:-.5em;content:"\\201C"}blockquote:after{content:"\\201D";margin-left:-.05em}mark{background-color:#f4ff81}dt{font-weight:700}address{font-size:12px;line-height:1;font-style:normal}address,ol,ul{font-weight:400;letter-spacing:0}ol,ul{font-size:14px;line-height:24px}.mdl-typography--display-4,.mdl-typography--display-4-color-contrast{font-family:Roboto,Helvetica,Arial,sans-serif;font-size:112px;font-weight:300;line-height:1;letter-spacing:-.04em}.mdl-typography--display-4-color-contrast{opacity:.54}.mdl-typography--display-3,.mdl-typography--display-3-color-contrast{font-family:Roboto,Helvetica,Arial,sans-serif;font-size:56px;font-weight:400;line-height:1.35;letter-spacing:-.02em}.mdl-typography--display-3-color-contrast{opacity:.54}.mdl-typography--display-2,.mdl-typography--display-2-color-contrast{font-family:Roboto,Helvetica,Arial,sans-serif;font-size:45px;font-weight:400;line-height:48px}.mdl-typography--display-2-color-contrast{opacity:.54}.mdl-typography--display-1,.mdl-typography--display-1-color-contrast{font-family:Roboto,Helvetica,Arial,sans-serif;font-size:34px;font-weight:400;line-height:40px}.mdl-typography--display-1-color-contrast{opacity:.54}.mdl-typography--headline,.mdl-typography--headline-color-contrast{font-family:Roboto,Helvetica,Arial,sans-serif;font-size:24px;font-weight:400;line-height:32px;-moz-osx-font-smoothing:grayscale}.mdl-typography--headline-color-contrast{opacity:.87}.mdl-typography--title,.mdl-typography--title-color-contrast{font-family:Roboto,Helvetica,Arial,sans-serif;font-size:20px;font-weight:500;line-height:1;letter-spacing:.02em}.mdl-typography--title-color-contrast{opacity:.87}.mdl-typography--subhead,.mdl-typography--subhead-color-contrast{font-family:Roboto,Helvetica,Arial,sans-serif;font-size:16px;font-weight:400;line-height:24px;letter-spacing:.04em}.mdl-typography--subhead-color-contrast{opacity:.87}.mdl-typography--body-2,.mdl-typography--body-2-color-contrast{font-size:14px;font-weight:700;line-height:24px;letter-spacing:0}.mdl-typography--body-2-color-contrast{opacity:.87}.mdl-typography--body-1,.mdl-typography--body-1-color-contrast{font-size:14px;font-weight:400;line-height:24px;letter-spacing:0}.mdl-typography--body-1-color-contrast{opacity:.87}.mdl-typography--body-2-force-preferred-font,.mdl-typography--body-2-force-preferred-font-color-contrast{font-family:Roboto,Helvetica,Arial,sans-serif;font-size:14px;font-weight:500;line-height:24px;letter-spacing:0}.mdl-typography--body-2-force-preferred-font-color-contrast{opacity:.87}.mdl-typography--body-1-force-preferred-font,.mdl-typography--body-1-force-preferred-font-color-contrast{font-family:Roboto,Helvetica,Arial,sans-serif;font-size:14px;font-weight:400;line-height:24px;letter-spacing:0}.mdl-typography--body-1-force-preferred-font-color-contrast{opacity:.87}.mdl-typography--caption,.mdl-typography--caption-force-preferred-font{font-size:12px;font-weight:400;line-height:1;letter-spacing:0}.mdl-typography--caption-force-preferred-font{font-family:Roboto,Helvetica,Arial,sans-serif}.mdl-typography--caption-color-contrast,.mdl-typography--caption-force-preferred-font-color-contrast{font-size:12px;font-weight:400;line-height:1;letter-spacing:0;opacity:.54}.mdl-typography--caption-force-preferred-font-color-contrast,.mdl-typography--menu{font-family:Roboto,Helvetica,Arial,sans-serif}.mdl-typography--menu{font-size:14px;font-weight:500;line-height:1;letter-spacing:0}.mdl-typography--menu-color-contrast{opacity:.87}.mdl-typography--button,.mdl-typography--button-color-contrast,.mdl-typography--menu-color-contrast{font-family:Roboto,Helvetica,Arial,sans-serif;font-size:14px;font-weight:500;line-height:1;letter-spacing:0}.mdl-typography--button,.mdl-typography--button-color-contrast{text-transform:uppercase}.mdl-typography--button-color-contrast{opacity:.87}.mdl-typography--text-left{text-align:left}.mdl-typography--text-right{text-align:right}.mdl-typography--text-center{text-align:center}.mdl-typography--text-justify{text-align:justify}.mdl-typography--text-nowrap{white-space:nowrap}.mdl-typography--text-lowercase{text-transform:lowercase}.mdl-typography--text-uppercase{text-transform:uppercase}.mdl-typography--text-capitalize{text-transform:capitalize}.mdl-typography--font-thin{font-weight:200!important}.mdl-typography--font-light{font-weight:300!important}.mdl-typography--font-regular{font-weight:400!important}.mdl-typography--font-medium{font-weight:500!important}.mdl-typography--font-bold{font-weight:700!important}.mdl-typography--font-black{font-weight:900!important}.material-icons{font-family:Material Icons;font-weight:400;font-style:normal;font-size:24px;line-height:1;letter-spacing:normal;text-transform:none;display:inline-block;word-wrap:normal;-moz-font-feature-settings:"liga";font-feature-settings:"liga";-webkit-font-feature-settings:"liga";-webkit-font-smoothing:antialiased}.mdl-color-text--red{color:#f44336!important}.mdl-color--red{background-color:#f44336!important}.mdl-color-text--red-50{color:#ffebee!important}.mdl-color--red-50{background-color:#ffebee!important}.mdl-color-text--red-100{color:#ffcdd2!important}.mdl-color--red-100{background-color:#ffcdd2!important}.mdl-color-text--red-200{color:#ef9a9a!important}.mdl-color--red-200{background-color:#ef9a9a!important}.mdl-color-text--red-300{color:#e57373!important}.mdl-color--red-300{background-color:#e57373!important}.mdl-color-text--red-400{color:#ef5350!important}.mdl-color--red-400{background-color:#ef5350!important}.mdl-color-text--red-500{color:#f44336!important}.mdl-color--red-500{background-color:#f44336!important}.mdl-color-text--red-600{color:#e53935!important}.mdl-color--red-600{background-color:#e53935!important}.mdl-color-text--red-700{color:#d32f2f!important}.mdl-color--red-700{background-color:#d32f2f!important}.mdl-color-text--red-800{color:#c62828!important}.mdl-color--red-800{background-color:#c62828!important}.mdl-color-text--red-900{color:#b71c1c!important}.mdl-color--red-900{background-color:#b71c1c!important}.mdl-color-text--red-A100{color:#ff8a80!important}.mdl-color--red-A100{background-color:#ff8a80!important}.mdl-color-text--red-A200{color:#ff5252!important}.mdl-color--red-A200{background-color:#ff5252!important}.mdl-color-text--red-A400{color:#ff1744!important}.mdl-color--red-A400{background-color:#ff1744!important}.mdl-color-text--red-A700{color:#d50000!important}.mdl-color--red-A700{background-color:#d50000!important}.mdl-color-text--pink{color:#e91e63!important}.mdl-color--pink{background-color:#e91e63!important}.mdl-color-text--pink-50{color:#fce4ec!important}.mdl-color--pink-50{background-color:#fce4ec!important}.mdl-color-text--pink-100{color:#f8bbd0!important}.mdl-color--pink-100{background-color:#f8bbd0!important}.mdl-color-text--pink-200{color:#f48fb1!important}.mdl-color--pink-200{background-color:#f48fb1!important}.mdl-color-text--pink-300{color:#f06292!important}.mdl-color--pink-300{background-color:#f06292!important}.mdl-color-text--pink-400{color:#ec407a!important}.mdl-color--pink-400{background-color:#ec407a!important}.mdl-color-text--pink-500{color:#e91e63!important}.mdl-color--pink-500{background-color:#e91e63!important}.mdl-color-text--pink-600{color:#d81b60!important}.mdl-color--pink-600{background-color:#d81b60!important}.mdl-color-text--pink-700{color:#c2185b!important}.mdl-color--pink-700{background-color:#c2185b!important}.mdl-color-text--pink-800{color:#ad1457!important}.mdl-color--pink-800{background-color:#ad1457!important}.mdl-color-text--pink-900{color:#880e4f!important}.mdl-color--pink-900{background-color:#880e4f!important}.mdl-color-text--pink-A100{color:#ff80ab!important}.mdl-color--pink-A100{background-color:#ff80ab!important}.mdl-color-text--pink-A200{color:#ff4081!important}.mdl-color--pink-A200{background-color:#ff4081!important}.mdl-color-text--pink-A400{color:#f50057!important}.mdl-color--pink-A400{background-color:#f50057!important}.mdl-color-text--pink-A700{color:#c51162!important}.mdl-color--pink-A700{background-color:#c51162!important}.mdl-color-text--purple{color:#9c27b0!important}.mdl-color--purple{background-color:#9c27b0!important}.mdl-color-text--purple-50{color:#f3e5f5!important}.mdl-color--purple-50{background-color:#f3e5f5!important}.mdl-color-text--purple-100{color:#e1bee7!important}.mdl-color--purple-100{background-color:#e1bee7!important}.mdl-color-text--purple-200{color:#ce93d8!important}.mdl-color--purple-200{background-color:#ce93d8!important}.mdl-color-text--purple-300{color:#ba68c8!important}.mdl-color--purple-300{background-color:#ba68c8!important}.mdl-color-text--purple-400{color:#ab47bc!important}.mdl-color--purple-400{background-color:#ab47bc!important}.mdl-color-text--purple-500{color:#9c27b0!important}.mdl-color--purple-500{background-color:#9c27b0!important}.mdl-color-text--purple-600{color:#8e24aa!important}.mdl-color--purple-600{background-color:#8e24aa!important}.mdl-color-text--purple-700{color:#7b1fa2!important}.mdl-color--purple-700{background-color:#7b1fa2!important}.mdl-color-text--purple-800{color:#6a1b9a!important}.mdl-color--purple-800{background-color:#6a1b9a!important}.mdl-color-text--purple-900{color:#4a148c!important}.mdl-color--purple-900{background-color:#4a148c!important}.mdl-color-text--purple-A100{color:#ea80fc!important}.mdl-color--purple-A100{background-color:#ea80fc!important}.mdl-color-text--purple-A200{color:#e040fb!important}.mdl-color--purple-A200{background-color:#e040fb!important}.mdl-color-text--purple-A400{color:#d500f9!important}.mdl-color--purple-A400{background-color:#d500f9!important}.mdl-color-text--purple-A700{color:#a0f!important}.mdl-color--purple-A700{background-color:#a0f!important}.mdl-color-text--deep-purple{color:#673ab7!important}.mdl-color--deep-purple{background-color:#673ab7!important}.mdl-color-text--deep-purple-50{color:#ede7f6!important}.mdl-color--deep-purple-50{background-color:#ede7f6!important}.mdl-color-text--deep-purple-100{color:#d1c4e9!important}.mdl-color--deep-purple-100{background-color:#d1c4e9!important}.mdl-color-text--deep-purple-200{color:#b39ddb!important}.mdl-color--deep-purple-200{background-color:#b39ddb!important}.mdl-color-text--deep-purple-300{color:#9575cd!important}.mdl-color--deep-purple-300{background-color:#9575cd!important}.mdl-color-text--deep-purple-400{color:#7e57c2!important}.mdl-color--deep-purple-400{background-color:#7e57c2!important}.mdl-color-text--deep-purple-500{color:#673ab7!important}.mdl-color--deep-purple-500{background-color:#673ab7!important}.mdl-color-text--deep-purple-600{color:#5e35b1!important}.mdl-color--deep-purple-600{background-color:#5e35b1!important}.mdl-color-text--deep-purple-700{color:#512da8!important}.mdl-color--deep-purple-700{background-color:#512da8!important}.mdl-color-text--deep-purple-800{color:#4527a0!important}.mdl-color--deep-purple-800{background-color:#4527a0!important}.mdl-color-text--deep-purple-900{color:#311b92!important}.mdl-color--deep-purple-900{background-color:#311b92!important}.mdl-color-text--deep-purple-A100{color:#b388ff!important}.mdl-color--deep-purple-A100{background-color:#b388ff!important}.mdl-color-text--deep-purple-A200{color:#7c4dff!important}.mdl-color--deep-purple-A200{background-color:#7c4dff!important}.mdl-color-text--deep-purple-A400{color:#651fff!important}.mdl-color--deep-purple-A400{background-color:#651fff!important}.mdl-color-text--deep-purple-A700{color:#6200ea!important}.mdl-color--deep-purple-A700{background-color:#6200ea!important}.mdl-color-text--indigo{color:#3f51b5!important}.mdl-color--indigo{background-color:#3f51b5!important}.mdl-color-text--indigo-50{color:#e8eaf6!important}.mdl-color--indigo-50{background-color:#e8eaf6!important}.mdl-color-text--indigo-100{color:#c5cae9!important}.mdl-color--indigo-100{background-color:#c5cae9!important}.mdl-color-text--indigo-200{color:#9fa8da!important}.mdl-color--indigo-200{background-color:#9fa8da!important}.mdl-color-text--indigo-300{color:#7986cb!important}.mdl-color--indigo-300{background-color:#7986cb!important}.mdl-color-text--indigo-400{color:#5c6bc0!important}.mdl-color--indigo-400{background-color:#5c6bc0!important}.mdl-color-text--indigo-500{color:#3f51b5!important}.mdl-color--indigo-500{background-color:#3f51b5!important}.mdl-color-text--indigo-600{color:#3949ab!important}.mdl-color--indigo-600{background-color:#3949ab!important}.mdl-color-text--indigo-700{color:#303f9f!important}.mdl-color--indigo-700{background-color:#303f9f!important}.mdl-color-text--indigo-800{color:#283593!important}.mdl-color--indigo-800{background-color:#283593!important}.mdl-color-text--indigo-900{color:#1a237e!important}.mdl-color--indigo-900{background-color:#1a237e!important}.mdl-color-text--indigo-A100{color:#8c9eff!important}.mdl-color--indigo-A100{background-color:#8c9eff!important}.mdl-color-text--indigo-A200{color:#536dfe!important}.mdl-color--indigo-A200{background-color:#536dfe!important}.mdl-color-text--indigo-A400{color:#3d5afe!important}.mdl-color--indigo-A400{background-color:#3d5afe!important}.mdl-color-text--indigo-A700{color:#304ffe!important}.mdl-color--indigo-A700{background-color:#304ffe!important}.mdl-color-text--blue{color:#2196f3!important}.mdl-color--blue{background-color:#2196f3!important}.mdl-color-text--blue-50{color:#e3f2fd!important}.mdl-color--blue-50{background-color:#e3f2fd!important}.mdl-color-text--blue-100{color:#bbdefb!important}.mdl-color--blue-100{background-color:#bbdefb!important}.mdl-color-text--blue-200{color:#90caf9!important}.mdl-color--blue-200{background-color:#90caf9!important}.mdl-color-text--blue-300{color:#64b5f6!important}.mdl-color--blue-300{background-color:#64b5f6!important}.mdl-color-text--blue-400{color:#42a5f5!important}.mdl-color--blue-400{background-color:#42a5f5!important}.mdl-color-text--blue-500{color:#2196f3!important}.mdl-color--blue-500{background-color:#2196f3!important}.mdl-color-text--blue-600{color:#1e88e5!important}.mdl-color--blue-600{background-color:#1e88e5!important}.mdl-color-text--blue-700{color:#1976d2!important}.mdl-color--blue-700{background-color:#1976d2!important}.mdl-color-text--blue-800{color:#1565c0!important}.mdl-color--blue-800{background-color:#1565c0!important}.mdl-color-text--blue-900{color:#0d47a1!important}.mdl-color--blue-900{background-color:#0d47a1!important}.mdl-color-text--blue-A100{color:#82b1ff!important}.mdl-color--blue-A100{background-color:#82b1ff!important}.mdl-color-text--blue-A200{color:#448aff!important}.mdl-color--blue-A200{background-color:#448aff!important}.mdl-color-text--blue-A400{color:#2979ff!important}.mdl-color--blue-A400{background-color:#2979ff!important}.mdl-color-text--blue-A700{color:#2962ff!important}.mdl-color--blue-A700{background-color:#2962ff!important}.mdl-color-text--light-blue{color:#03a9f4!important}.mdl-color--light-blue{background-color:#03a9f4!important}.mdl-color-text--light-blue-50{color:#e1f5fe!important}.mdl-color--light-blue-50{background-color:#e1f5fe!important}.mdl-color-text--light-blue-100{color:#b3e5fc!important}.mdl-color--light-blue-100{background-color:#b3e5fc!important}.mdl-color-text--light-blue-200{color:#81d4fa!important}.mdl-color--light-blue-200{background-color:#81d4fa!important}.mdl-color-text--light-blue-300{color:#4fc3f7!important}.mdl-color--light-blue-300{background-color:#4fc3f7!important}.mdl-color-text--light-blue-400{color:#29b6f6!important}.mdl-color--light-blue-400{background-color:#29b6f6!important}.mdl-color-text--light-blue-500{color:#03a9f4!important}.mdl-color--light-blue-500{background-color:#03a9f4!important}.mdl-color-text--light-blue-600{color:#039be5!important}.mdl-color--light-blue-600{background-color:#039be5!important}.mdl-color-text--light-blue-700{color:#0288d1!important}.mdl-color--light-blue-700{background-color:#0288d1!important}.mdl-color-text--light-blue-800{color:#0277bd!important}.mdl-color--light-blue-800{background-color:#0277bd!important}.mdl-color-text--light-blue-900{color:#01579b!important}.mdl-color--light-blue-900{background-color:#01579b!important}.mdl-color-text--light-blue-A100{color:#80d8ff!important}.mdl-color--light-blue-A100{background-color:#80d8ff!important}.mdl-color-text--light-blue-A200{color:#40c4ff!important}.mdl-color--light-blue-A200{background-color:#40c4ff!important}.mdl-color-text--light-blue-A400{color:#00b0ff!important}.mdl-color--light-blue-A400{background-color:#00b0ff!important}.mdl-color-text--light-blue-A700{color:#0091ea!important}.mdl-color--light-blue-A700{background-color:#0091ea!important}.mdl-color-text--cyan{color:#00bcd4!important}.mdl-color--cyan{background-color:#00bcd4!important}.mdl-color-text--cyan-50{color:#e0f7fa!important}.mdl-color--cyan-50{background-color:#e0f7fa!important}.mdl-color-text--cyan-100{color:#b2ebf2!important}.mdl-color--cyan-100{background-color:#b2ebf2!important}.mdl-color-text--cyan-200{color:#80deea!important}.mdl-color--cyan-200{background-color:#80deea!important}.mdl-color-text--cyan-300{color:#4dd0e1!important}.mdl-color--cyan-300{background-color:#4dd0e1!important}.mdl-color-text--cyan-400{color:#26c6da!important}.mdl-color--cyan-400{background-color:#26c6da!important}.mdl-color-text--cyan-500{color:#00bcd4!important}.mdl-color--cyan-500{background-color:#00bcd4!important}.mdl-color-text--cyan-600{color:#00acc1!important}.mdl-color--cyan-600{background-color:#00acc1!important}.mdl-color-text--cyan-700{color:#0097a7!important}.mdl-color--cyan-700{background-color:#0097a7!important}.mdl-color-text--cyan-800{color:#00838f!important}.mdl-color--cyan-800{background-color:#00838f!important}.mdl-color-text--cyan-900{color:#006064!important}.mdl-color--cyan-900{background-color:#006064!important}.mdl-color-text--cyan-A100{color:#84ffff!important}.mdl-color--cyan-A100{background-color:#84ffff!important}.mdl-color-text--cyan-A200{color:#18ffff!important}.mdl-color--cyan-A200{background-color:#18ffff!important}.mdl-color-text--cyan-A400{color:#00e5ff!important}.mdl-color--cyan-A400{background-color:#00e5ff!important}.mdl-color-text--cyan-A700{color:#00b8d4!important}.mdl-color--cyan-A700{background-color:#00b8d4!important}.mdl-color-text--teal{color:#009688!important}.mdl-color--teal{background-color:#009688!important}.mdl-color-text--teal-50{color:#e0f2f1!important}.mdl-color--teal-50{background-color:#e0f2f1!important}.mdl-color-text--teal-100{color:#b2dfdb!important}.mdl-color--teal-100{background-color:#b2dfdb!important}.mdl-color-text--teal-200{color:#80cbc4!important}.mdl-color--teal-200{background-color:#80cbc4!important}.mdl-color-text--teal-300{color:#4db6ac!important}.mdl-color--teal-300{background-color:#4db6ac!important}.mdl-color-text--teal-400{color:#26a69a!important}.mdl-color--teal-400{background-color:#26a69a!important}.mdl-color-text--teal-500{color:#009688!important}.mdl-color--teal-500{background-color:#009688!important}.mdl-color-text--teal-600{color:#00897b!important}.mdl-color--teal-600{background-color:#00897b!important}.mdl-color-text--teal-700{color:#00796b!important}.mdl-color--teal-700{background-color:#00796b!important}.mdl-color-text--teal-800{color:#00695c!important}.mdl-color--teal-800{background-color:#00695c!important}.mdl-color-text--teal-900{color:#004d40!important}.mdl-color--teal-900{background-color:#004d40!important}.mdl-color-text--teal-A100{color:#a7ffeb!important}.mdl-color--teal-A100{background-color:#a7ffeb!important}.mdl-color-text--teal-A200{color:#64ffda!important}.mdl-color--teal-A200{background-color:#64ffda!important}.mdl-color-text--teal-A400{color:#1de9b6!important}.mdl-color--teal-A400{background-color:#1de9b6!important}.mdl-color-text--teal-A700{color:#00bfa5!important}.mdl-color--teal-A700{background-color:#00bfa5!important}.mdl-color-text--green{color:#4caf50!important}.mdl-color--green{background-color:#4caf50!important}.mdl-color-text--green-50{color:#e8f5e9!important}.mdl-color--green-50{background-color:#e8f5e9!important}.mdl-color-text--green-100{color:#c8e6c9!important}.mdl-color--green-100{background-color:#c8e6c9!important}.mdl-color-text--green-200{color:#a5d6a7!important}.mdl-color--green-200{background-color:#a5d6a7!important}.mdl-color-text--green-300{color:#81c784!important}.mdl-color--green-300{background-color:#81c784!important}.mdl-color-text--green-400{color:#66bb6a!important}.mdl-color--green-400{background-color:#66bb6a!important}.mdl-color-text--green-500{color:#4caf50!important}.mdl-color--green-500{background-color:#4caf50!important}.mdl-color-text--green-600{color:#43a047!important}.mdl-color--green-600{background-color:#43a047!important}.mdl-color-text--green-700{color:#388e3c!important}.mdl-color--green-700{background-color:#388e3c!important}.mdl-color-text--green-800{color:#2e7d32!important}.mdl-color--green-800{background-color:#2e7d32!important}.mdl-color-text--green-900{color:#1b5e20!important}.mdl-color--green-900{background-color:#1b5e20!important}.mdl-color-text--green-A100{color:#b9f6ca!important}.mdl-color--green-A100{background-color:#b9f6ca!important}.mdl-color-text--green-A200{color:#69f0ae!important}.mdl-color--green-A200{background-color:#69f0ae!important}.mdl-color-text--green-A400{color:#00e676!important}.mdl-color--green-A400{background-color:#00e676!important}.mdl-color-text--green-A700{color:#00c853!important}.mdl-color--green-A700{background-color:#00c853!important}.mdl-color-text--light-green{color:#8bc34a!important}.mdl-color--light-green{background-color:#8bc34a!important}.mdl-color-text--light-green-50{color:#f1f8e9!important}.mdl-color--light-green-50{background-color:#f1f8e9!important}.mdl-color-text--light-green-100{color:#dcedc8!important}.mdl-color--light-green-100{background-color:#dcedc8!important}.mdl-color-text--light-green-200{color:#c5e1a5!important}.mdl-color--light-green-200{background-color:#c5e1a5!important}.mdl-color-text--light-green-300{color:#aed581!important}.mdl-color--light-green-300{background-color:#aed581!important}.mdl-color-text--light-green-400{color:#9ccc65!important}.mdl-color--light-green-400{background-color:#9ccc65!important}.mdl-color-text--light-green-500{color:#8bc34a!important}.mdl-color--light-green-500{background-color:#8bc34a!important}.mdl-color-text--light-green-600{color:#7cb342!important}.mdl-color--light-green-600{background-color:#7cb342!important}.mdl-color-text--light-green-700{color:#689f38!important}.mdl-color--light-green-700{background-color:#689f38!important}.mdl-color-text--light-green-800{color:#558b2f!important}.mdl-color--light-green-800{background-color:#558b2f!important}.mdl-color-text--light-green-900{color:#33691e!important}.mdl-color--light-green-900{background-color:#33691e!important}.mdl-color-text--light-green-A100{color:#ccff90!important}.mdl-color--light-green-A100{background-color:#ccff90!important}.mdl-color-text--light-green-A200{color:#b2ff59!important}.mdl-color--light-green-A200{background-color:#b2ff59!important}.mdl-color-text--light-green-A400{color:#76ff03!important}.mdl-color--light-green-A400{background-color:#76ff03!important}.mdl-color-text--light-green-A700{color:#64dd17!important}.mdl-color--light-green-A700{background-color:#64dd17!important}.mdl-color-text--lime{color:#cddc39!important}.mdl-color--lime{background-color:#cddc39!important}.mdl-color-text--lime-50{color:#f9fbe7!important}.mdl-color--lime-50{background-color:#f9fbe7!important}.mdl-color-text--lime-100{color:#f0f4c3!important}.mdl-color--lime-100{background-color:#f0f4c3!important}.mdl-color-text--lime-200{color:#e6ee9c!important}.mdl-color--lime-200{background-color:#e6ee9c!important}.mdl-color-text--lime-300{color:#dce775!important}.mdl-color--lime-300{background-color:#dce775!important}.mdl-color-text--lime-400{color:#d4e157!important}.mdl-color--lime-400{background-color:#d4e157!important}.mdl-color-text--lime-500{color:#cddc39!important}.mdl-color--lime-500{background-color:#cddc39!important}.mdl-color-text--lime-600{color:#c0ca33!important}.mdl-color--lime-600{background-color:#c0ca33!important}.mdl-color-text--lime-700{color:#afb42b!important}.mdl-color--lime-700{background-color:#afb42b!important}.mdl-color-text--lime-800{color:#9e9d24!important}.mdl-color--lime-800{background-color:#9e9d24!important}.mdl-color-text--lime-900{color:#827717!important}.mdl-color--lime-900{background-color:#827717!important}.mdl-color-text--lime-A100{color:#f4ff81!important}.mdl-color--lime-A100{background-color:#f4ff81!important}.mdl-color-text--lime-A200{color:#eeff41!important}.mdl-color--lime-A200{background-color:#eeff41!important}.mdl-color-text--lime-A400{color:#c6ff00!important}.mdl-color--lime-A400{background-color:#c6ff00!important}.mdl-color-text--lime-A700{color:#aeea00!important}.mdl-color--lime-A700{background-color:#aeea00!important}.mdl-color-text--yellow{color:#ffeb3b!important}.mdl-color--yellow{background-color:#ffeb3b!important}.mdl-color-text--yellow-50{color:#fffde7!important}.mdl-color--yellow-50{background-color:#fffde7!important}.mdl-color-text--yellow-100{color:#fff9c4!important}.mdl-color--yellow-100{background-color:#fff9c4!important}.mdl-color-text--yellow-200{color:#fff59d!important}.mdl-color--yellow-200{background-color:#fff59d!important}.mdl-color-text--yellow-300{color:#fff176!important}.mdl-color--yellow-300{background-color:#fff176!important}.mdl-color-text--yellow-400{color:#ffee58!important}.mdl-color--yellow-400{background-color:#ffee58!important}.mdl-color-text--yellow-500{color:#ffeb3b!important}.mdl-color--yellow-500{background-color:#ffeb3b!important}.mdl-color-text--yellow-600{color:#fdd835!important}.mdl-color--yellow-600{background-color:#fdd835!important}.mdl-color-text--yellow-700{color:#fbc02d!important}.mdl-color--yellow-700{background-color:#fbc02d!important}.mdl-color-text--yellow-800{color:#f9a825!important}.mdl-color--yellow-800{background-color:#f9a825!important}.mdl-color-text--yellow-900{color:#f57f17!important}.mdl-color--yellow-900{background-color:#f57f17!important}.mdl-color-text--yellow-A100{color:#ffff8d!important}.mdl-color--yellow-A100{background-color:#ffff8d!important}.mdl-color-text--yellow-A200{color:#ff0!important}.mdl-color--yellow-A200{background-color:#ff0!important}.mdl-color-text--yellow-A400{color:#ffea00!important}.mdl-color--yellow-A400{background-color:#ffea00!important}.mdl-color-text--yellow-A700{color:#ffd600!important}.mdl-color--yellow-A700{background-color:#ffd600!important}.mdl-color-text--amber{color:#ffc107!important}.mdl-color--amber{background-color:#ffc107!important}.mdl-color-text--amber-50{color:#fff8e1!important}.mdl-color--amber-50{background-color:#fff8e1!important}.mdl-color-text--amber-100{color:#ffecb3!important}.mdl-color--amber-100{background-color:#ffecb3!important}.mdl-color-text--amber-200{color:#ffe082!important}.mdl-color--amber-200{background-color:#ffe082!important}.mdl-color-text--amber-300{color:#ffd54f!important}.mdl-color--amber-300{background-color:#ffd54f!important}.mdl-color-text--amber-400{color:#ffca28!important}.mdl-color--amber-400{background-color:#ffca28!important}.mdl-color-text--amber-500{color:#ffc107!important}.mdl-color--amber-500{background-color:#ffc107!important}.mdl-color-text--amber-600{color:#ffb300!important}.mdl-color--amber-600{background-color:#ffb300!important}.mdl-color-text--amber-700{color:#ffa000!important}.mdl-color--amber-700{background-color:#ffa000!important}.mdl-color-text--amber-800{color:#ff8f00!important}.mdl-color--amber-800{background-color:#ff8f00!important}.mdl-color-text--amber-900{color:#ff6f00!important}.mdl-color--amber-900{background-color:#ff6f00!important}.mdl-color-text--amber-A100{color:#ffe57f!important}.mdl-color--amber-A100{background-color:#ffe57f!important}.mdl-color-text--amber-A200{color:#ffd740!important}.mdl-color--amber-A200{background-color:#ffd740!important}.mdl-color-text--amber-A400{color:#ffc400!important}.mdl-color--amber-A400{background-color:#ffc400!important}.mdl-color-text--amber-A700{color:#ffab00!important}.mdl-color--amber-A700{background-color:#ffab00!important}.mdl-color-text--orange{color:#ff9800!important}.mdl-color--orange{background-color:#ff9800!important}.mdl-color-text--orange-50{color:#fff3e0!important}.mdl-color--orange-50{background-color:#fff3e0!important}.mdl-color-text--orange-100{color:#ffe0b2!important}.mdl-color--orange-100{background-color:#ffe0b2!important}.mdl-color-text--orange-200{color:#ffcc80!important}.mdl-color--orange-200{background-color:#ffcc80!important}.mdl-color-text--orange-300{color:#ffb74d!important}.mdl-color--orange-300{background-color:#ffb74d!important}.mdl-color-text--orange-400{color:#ffa726!important}.mdl-color--orange-400{background-color:#ffa726!important}.mdl-color-text--orange-500{color:#ff9800!important}.mdl-color--orange-500{background-color:#ff9800!important}.mdl-color-text--orange-600{color:#fb8c00!important}.mdl-color--orange-600{background-color:#fb8c00!important}.mdl-color-text--orange-700{color:#f57c00!important}.mdl-color--orange-700{background-color:#f57c00!important}.mdl-color-text--orange-800{color:#ef6c00!important}.mdl-color--orange-800{background-color:#ef6c00!important}.mdl-color-text--orange-900{color:#e65100!important}.mdl-color--orange-900{background-color:#e65100!important}.mdl-color-text--orange-A100{color:#ffd180!important}.mdl-color--orange-A100{background-color:#ffd180!important}.mdl-color-text--orange-A200{color:#ffab40!important}.mdl-color--orange-A200{background-color:#ffab40!important}.mdl-color-text--orange-A400{color:#ff9100!important}.mdl-color--orange-A400{background-color:#ff9100!important}.mdl-color-text--orange-A700{color:#ff6d00!important}.mdl-color--orange-A700{background-color:#ff6d00!important}.mdl-color-text--deep-orange{color:#ff5722!important}.mdl-color--deep-orange{background-color:#ff5722!important}.mdl-color-text--deep-orange-50{color:#fbe9e7!important}.mdl-color--deep-orange-50{background-color:#fbe9e7!important}.mdl-color-text--deep-orange-100{color:#ffccbc!important}.mdl-color--deep-orange-100{background-color:#ffccbc!important}.mdl-color-text--deep-orange-200{color:#ffab91!important}.mdl-color--deep-orange-200{background-color:#ffab91!important}.mdl-color-text--deep-orange-300{color:#ff8a65!important}.mdl-color--deep-orange-300{background-color:#ff8a65!important}.mdl-color-text--deep-orange-400{color:#ff7043!important}.mdl-color--deep-orange-400{background-color:#ff7043!important}.mdl-color-text--deep-orange-500{color:#ff5722!important}.mdl-color--deep-orange-500{background-color:#ff5722!important}.mdl-color-text--deep-orange-600{color:#f4511e!important}.mdl-color--deep-orange-600{background-color:#f4511e!important}.mdl-color-text--deep-orange-700{color:#e64a19!important}.mdl-color--deep-orange-700{background-color:#e64a19!important}.mdl-color-text--deep-orange-800{color:#d84315!important}.mdl-color--deep-orange-800{background-color:#d84315!important}.mdl-color-text--deep-orange-900{color:#bf360c!important}.mdl-color--deep-orange-900{background-color:#bf360c!important}.mdl-color-text--deep-orange-A100{color:#ff9e80!important}.mdl-color--deep-orange-A100{background-color:#ff9e80!important}.mdl-color-text--deep-orange-A200{color:#ff6e40!important}.mdl-color--deep-orange-A200{background-color:#ff6e40!important}.mdl-color-text--deep-orange-A400{color:#ff3d00!important}.mdl-color--deep-orange-A400{background-color:#ff3d00!important}.mdl-color-text--deep-orange-A700{color:#dd2c00!important}.mdl-color--deep-orange-A700{background-color:#dd2c00!important}.mdl-color-text--brown{color:#795548!important}.mdl-color--brown{background-color:#795548!important}.mdl-color-text--brown-50{color:#efebe9!important}.mdl-color--brown-50{background-color:#efebe9!important}.mdl-color-text--brown-100{color:#d7ccc8!important}.mdl-color--brown-100{background-color:#d7ccc8!important}.mdl-color-text--brown-200{color:#bcaaa4!important}.mdl-color--brown-200{background-color:#bcaaa4!important}.mdl-color-text--brown-300{color:#a1887f!important}.mdl-color--brown-300{background-color:#a1887f!important}.mdl-color-text--brown-400{color:#8d6e63!important}.mdl-color--brown-400{background-color:#8d6e63!important}.mdl-color-text--brown-500{color:#795548!important}.mdl-color--brown-500{background-color:#795548!important}.mdl-color-text--brown-600{color:#6d4c41!important}.mdl-color--brown-600{background-color:#6d4c41!important}.mdl-color-text--brown-700{color:#5d4037!important}.mdl-color--brown-700{background-color:#5d4037!important}.mdl-color-text--brown-800{color:#4e342e!important}.mdl-color--brown-800{background-color:#4e342e!important}.mdl-color-text--brown-900{color:#3e2723!important}.mdl-color--brown-900{background-color:#3e2723!important}.mdl-color-text--grey{color:#9e9e9e!important}.mdl-color--grey{background-color:#9e9e9e!important}.mdl-color-text--grey-50{color:#fafafa!important}.mdl-color--grey-50{background-color:#fafafa!important}.mdl-color-text--grey-100{color:#f5f5f5!important}.mdl-color--grey-100{background-color:#f5f5f5!important}.mdl-color-text--grey-200{color:#eee!important}.mdl-color--grey-200{background-color:#eee!important}.mdl-color-text--grey-300{color:#e0e0e0!important}.mdl-color--grey-300{background-color:#e0e0e0!important}.mdl-color-text--grey-400{color:#bdbdbd!important}.mdl-color--grey-400{background-color:#bdbdbd!important}.mdl-color-text--grey-500{color:#9e9e9e!important}.mdl-color--grey-500{background-color:#9e9e9e!important}.mdl-color-text--grey-600{color:#757575!important}.mdl-color--grey-600{background-color:#757575!important}.mdl-color-text--grey-700{color:#616161!important}.mdl-color--grey-700{background-color:#616161!important}.mdl-color-text--grey-800{color:#424242!important}.mdl-color--grey-800{background-color:#424242!important}.mdl-color-text--grey-900{color:#212121!important}.mdl-color--grey-900{background-color:#212121!important}.mdl-color-text--blue-grey{color:#607d8b!important}.mdl-color--blue-grey{background-color:#607d8b!important}.mdl-color-text--blue-grey-50{color:#eceff1!important}.mdl-color--blue-grey-50{background-color:#eceff1!important}.mdl-color-text--blue-grey-100{color:#cfd8dc!important}.mdl-color--blue-grey-100{background-color:#cfd8dc!important}.mdl-color-text--blue-grey-200{color:#b0bec5!important}.mdl-color--blue-grey-200{background-color:#b0bec5!important}.mdl-color-text--blue-grey-300{color:#90a4ae!important}.mdl-color--blue-grey-300{background-color:#90a4ae!important}.mdl-color-text--blue-grey-400{color:#78909c!important}.mdl-color--blue-grey-400{background-color:#78909c!important}.mdl-color-text--blue-grey-500{color:#607d8b!important}.mdl-color--blue-grey-500{background-color:#607d8b!important}.mdl-color-text--blue-grey-600{color:#546e7a!important}.mdl-color--blue-grey-600{background-color:#546e7a!important}.mdl-color-text--blue-grey-700{color:#455a64!important}.mdl-color--blue-grey-700{background-color:#455a64!important}.mdl-color-text--blue-grey-800{color:#37474f!important}.mdl-color--blue-grey-800{background-color:#37474f!important}.mdl-color-text--blue-grey-900{color:#263238!important}.mdl-color--blue-grey-900{background-color:#263238!important}.mdl-color--black{background-color:#000!important}.mdl-color-text--black{color:#000!important}.mdl-color--white{background-color:#fff!important}.mdl-color-text--white{color:#fff!important}.mdl-color--primary{background-color:#3f51b5!important}.mdl-color--primary-contrast{background-color:#fff!important}.mdl-color--primary-dark{background-color:#303f9f!important}.mdl-color--accent{background-color:#ff4081!important}.mdl-color--accent-contrast{background-color:#fff!important}.mdl-color-text--primary{color:#3f51b5!important}.mdl-color-text--primary-contrast{color:#fff!important}.mdl-color-text--primary-dark{color:#303f9f!important}.mdl-color-text--accent{color:#ff4081!important}.mdl-color-text--accent-contrast{color:#fff!important}.mdl-ripple{background:#000;border-radius:50%;height:50px;left:0;opacity:0;pointer-events:none;position:absolute;top:0;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%);width:50px;overflow:hidden}.mdl-ripple.is-animating{transition:transform .3s cubic-bezier(0,0,.2,1),width .3s cubic-bezier(0,0,.2,1),height .3s cubic-bezier(0,0,.2,1),opacity .6s cubic-bezier(0,0,.2,1);transition:transform .3s cubic-bezier(0,0,.2,1),width .3s cubic-bezier(0,0,.2,1),height .3s cubic-bezier(0,0,.2,1),opacity .6s cubic-bezier(0,0,.2,1),-webkit-transform .3s cubic-bezier(0,0,.2,1)}.mdl-ripple.is-visible{opacity:.3}.mdl-animation--default,.mdl-animation--fast-out-slow-in{transition-timing-function:cubic-bezier(.4,0,.2,1)}.mdl-animation--linear-out-slow-in{transition-timing-function:cubic-bezier(0,0,.2,1)}.mdl-animation--fast-out-linear-in{transition-timing-function:cubic-bezier(.4,0,1,1)}.mdl-badge{position:relative;white-space:nowrap;margin-right:24px}.mdl-badge:not([data-badge]){margin-right:auto}.mdl-badge[data-badge]:after{content:attr(data-badge);display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:row;-ms-flex-direction:row;flex-direction:row;-webkit-flex-wrap:wrap;-ms-flex-wrap:wrap;flex-wrap:wrap;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center;-webkit-align-content:center;-ms-flex-line-pack:center;align-content:center;-webkit-align-items:center;-ms-flex-align:center;align-items:center;position:absolute;top:-11px;right:-24px;font-family:Roboto,Helvetica,Arial,sans-serif;font-weight:600;font-size:12px;width:22px;height:22px;border-radius:50%;background:#ff4081;color:#fff}.mdl-button .mdl-badge[data-badge]:after{top:-10px;right:-5px}.mdl-badge.mdl-badge--no-background[data-badge]:after{color:#ff4081;background:hsla(0,0%,100%,.2);box-shadow:0 0 1px gray}.mdl-badge.mdl-badge--overlap{margin-right:10px}.mdl-badge.mdl-badge--overlap:after{right:-10px}.mdl-button{background:0 0;border:none;border-radius:2px;color:#000;position:relative;height:36px;margin:0;min-width:64px;padding:0 16px;display:inline-block;font-family:Roboto,Helvetica,Arial,sans-serif;font-size:14px;font-weight:500;text-transform:uppercase;letter-spacing:0;overflow:hidden;will-change:box-shadow;transition:box-shadow .2s cubic-bezier(.4,0,1,1),background-color .2s cubic-bezier(.4,0,.2,1),color .2s cubic-bezier(.4,0,.2,1);outline:none;cursor:pointer;text-decoration:none;text-align:center;line-height:36px;vertical-align:middle}.mdl-button::-moz-focus-inner{border:0}.mdl-button:hover{background-color:hsla(0,0%,62%,.2)}.mdl-button:focus:not(:active){background-color:rgba(0,0,0,.12)}.mdl-button:active{background-color:hsla(0,0%,62%,.4)}.mdl-button.mdl-button--colored{color:#3f51b5}.mdl-button.mdl-button--colored:focus:not(:active){background-color:rgba(0,0,0,.12)}input.mdl-button[type=submit]{-webkit-appearance:none}.mdl-button--raised{background:hsla(0,0%,62%,.2);box-shadow:0 2px 2px 0 rgba(0,0,0,.14),0 3px 1px -2px rgba(0,0,0,.2),0 1px 5px 0 rgba(0,0,0,.12)}.mdl-button--raised:active{box-shadow:0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12),0 2px 4px -1px rgba(0,0,0,.2);background-color:hsla(0,0%,62%,.4)}.mdl-button--raised:focus:not(:active){box-shadow:0 0 8px rgba(0,0,0,.18),0 8px 16px rgba(0,0,0,.36);background-color:hsla(0,0%,62%,.4)}.mdl-button--raised.mdl-button--colored{background:#3f51b5;color:#fff}.mdl-button--raised.mdl-button--colored:active,.mdl-button--raised.mdl-button--colored:focus:not(:active),.mdl-button--raised.mdl-button--colored:hover{background-color:#3f51b5}.mdl-button--raised.mdl-button--colored .mdl-ripple{background:#fff}.mdl-button--fab{border-radius:50%;font-size:24px;height:56px;margin:auto;min-width:56px;width:56px;padding:0;overflow:hidden;background:hsla(0,0%,62%,.2);box-shadow:0 1px 1.5px 0 rgba(0,0,0,.12),0 1px 1px 0 rgba(0,0,0,.24);position:relative;line-height:normal}.mdl-button--fab .material-icons{position:absolute;top:50%;left:50%;-webkit-transform:translate(-12px,-12px);transform:translate(-12px,-12px);line-height:24px;width:24px}.mdl-button--fab.mdl-button--mini-fab{height:40px;min-width:40px;width:40px}.mdl-button--fab .mdl-button__ripple-container{border-radius:50%;-webkit-mask-image:-webkit-radial-gradient(circle,#fff,#000)}.mdl-button--fab:active{box-shadow:0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12),0 2px 4px -1px rgba(0,0,0,.2);background-color:hsla(0,0%,62%,.4)}.mdl-button--fab:focus:not(:active){box-shadow:0 0 8px rgba(0,0,0,.18),0 8px 16px rgba(0,0,0,.36);background-color:hsla(0,0%,62%,.4)}.mdl-button--fab.mdl-button--colored{background:#ff4081;color:#fff}.mdl-button--fab.mdl-button--colored:active,.mdl-button--fab.mdl-button--colored:focus:not(:active),.mdl-button--fab.mdl-button--colored:hover{background-color:#ff4081}.mdl-button--fab.mdl-button--colored .mdl-ripple{background:#fff}.mdl-button--icon{border-radius:50%;font-size:24px;height:32px;margin-left:0;margin-right:0;min-width:32px;width:32px;padding:0;overflow:hidden;color:inherit;line-height:normal}.mdl-button--icon .material-icons{position:absolute;top:50%;left:50%;-webkit-transform:translate(-12px,-12px);transform:translate(-12px,-12px);line-height:24px;width:24px}.mdl-button--icon.mdl-button--mini-icon{height:24px;min-width:24px;width:24px}.mdl-button--icon.mdl-button--mini-icon .material-icons{top:0;left:0}.mdl-button--icon .mdl-button__ripple-container{border-radius:50%;-webkit-mask-image:-webkit-radial-gradient(circle,#fff,#000)}.mdl-button__ripple-container{display:block;height:100%;left:0;position:absolute;top:0;width:100%;z-index:0;overflow:hidden}.mdl-button.mdl-button--disabled .mdl-button__ripple-container .mdl-ripple,.mdl-button[disabled] .mdl-button__ripple-container .mdl-ripple{background-color:transparent}.mdl-button--primary.mdl-button--primary{color:#3f51b5}.mdl-button--primary.mdl-button--primary .mdl-ripple{background:#fff}.mdl-button--primary.mdl-button--primary.mdl-button--fab,.mdl-button--primary.mdl-button--primary.mdl-button--raised{color:#fff;background-color:#3f51b5}.mdl-button--accent.mdl-button--accent{color:#ff4081}.mdl-button--accent.mdl-button--accent .mdl-ripple{background:#fff}.mdl-button--accent.mdl-button--accent.mdl-button--fab,.mdl-button--accent.mdl-button--accent.mdl-button--raised{color:#fff;background-color:#ff4081}.mdl-button.mdl-button--disabled.mdl-button--disabled,.mdl-button[disabled][disabled]{color:rgba(0,0,0,.26);cursor:default;background-color:transparent}.mdl-button--fab.mdl-button--disabled.mdl-button--disabled,.mdl-button--fab[disabled][disabled]{background-color:rgba(0,0,0,.12);color:rgba(0,0,0,.26)}.mdl-button--raised.mdl-button--disabled.mdl-button--disabled,.mdl-button--raised[disabled][disabled]{background-color:rgba(0,0,0,.12);color:rgba(0,0,0,.26);box-shadow:none}.mdl-button--colored.mdl-button--disabled.mdl-button--disabled,.mdl-button--colored[disabled][disabled]{color:rgba(0,0,0,.26)}.mdl-button .material-icons{vertical-align:middle}.mdl-card{display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:column;-ms-flex-direction:column;flex-direction:column;font-size:16px;font-weight:400;min-height:200px;overflow:hidden;width:330px;z-index:1;position:relative;background:#fff;border-radius:2px;box-sizing:border-box}.mdl-card__media{background-color:#ff4081;background-repeat:repeat;background-position:50% 50%;background-size:cover;background-origin:padding-box;background-attachment:scroll;box-sizing:border-box}.mdl-card__title{-webkit-align-items:center;-ms-flex-align:center;align-items:center;color:#000;display:block;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-justify-content:stretch;-ms-flex-pack:stretch;justify-content:stretch;line-height:normal;padding:16px;-webkit-perspective-origin:165px 56px;perspective-origin:165px 56px;-webkit-transform-origin:165px 56px;transform-origin:165px 56px;box-sizing:border-box}.mdl-card__title.mdl-card--border{border-bottom:1px solid rgba(0,0,0,.1)}.mdl-card__title-text{-webkit-align-self:flex-end;-ms-flex-item-align:end;align-self:flex-end;color:inherit;display:block;display:-webkit-flex;display:-ms-flexbox;display:flex;font-size:24px;font-weight:300;line-height:normal;overflow:hidden;-webkit-transform-origin:149px 48px;transform-origin:149px 48px;margin:0}.mdl-card__subtitle-text{font-size:14px;color:rgba(0,0,0,.54);margin:0}.mdl-card__supporting-text{color:rgba(0,0,0,.54);font-size:1rem;line-height:18px;overflow:hidden;padding:16px;width:90%}.mdl-card__actions{font-size:16px;line-height:normal;width:100%;background-color:transparent;padding:8px;box-sizing:border-box}.mdl-card__actions.mdl-card--border{border-top:1px solid rgba(0,0,0,.1)}.mdl-card--expand{-webkit-flex-grow:1;-ms-flex-positive:1;flex-grow:1}.mdl-card__menu{position:absolute;right:16px;top:16px}.mdl-checkbox{position:relative;z-index:1;vertical-align:middle;display:inline-block;box-sizing:border-box;width:100%;height:24px;margin:0;padding:0}.mdl-checkbox.is-upgraded{padding-left:24px}.mdl-checkbox__input{line-height:24px}.mdl-checkbox.is-upgraded .mdl-checkbox__input{position:absolute;width:0;height:0;margin:0;padding:0;opacity:0;-ms-appearance:none;-moz-appearance:none;-webkit-appearance:none;appearance:none;border:none}.mdl-checkbox__box-outline{position:absolute;top:3px;left:0;display:inline-block;box-sizing:border-box;width:16px;height:16px;margin:0;cursor:pointer;overflow:hidden;border:2px solid rgba(0,0,0,.54);border-radius:2px;z-index:2}.mdl-checkbox.is-checked .mdl-checkbox__box-outline{border:2px solid #3f51b5}.mdl-checkbox.is-disabled .mdl-checkbox__box-outline,fieldset[disabled] .mdl-checkbox .mdl-checkbox__box-outline{border:2px solid rgba(0,0,0,.26);cursor:auto}.mdl-checkbox__focus-helper{position:absolute;top:3px;left:0;display:inline-block;box-sizing:border-box;width:16px;height:16px;border-radius:50%;background-color:transparent}.mdl-checkbox.is-focused .mdl-checkbox__focus-helper{box-shadow:0 0 0 8px rgba(0,0,0,.1);background-color:rgba(0,0,0,.1)}.mdl-checkbox.is-focused.is-checked .mdl-checkbox__focus-helper{box-shadow:0 0 0 8px rgba(63,81,181,.26);background-color:rgba(63,81,181,.26)}.mdl-checkbox__tick-outline{position:absolute;top:0;left:0;height:100%;width:100%;-webkit-mask:url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgdmVyc2lvbj0iMS4xIgogICB2aWV3Qm94PSIwIDAgMSAxIgogICBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJ4TWluWU1pbiBtZWV0Ij4KICA8ZGVmcz4KICAgIDxjbGlwUGF0aCBpZD0iY2xpcCI+CiAgICAgIDxwYXRoCiAgICAgICAgIGQ9Ik0gMCwwIDAsMSAxLDEgMSwwIDAsMCB6IE0gMC44NTM0Mzc1LDAuMTY3MTg3NSAwLjk1OTY4NzUsMC4yNzMxMjUgMC40MjkzNzUsMC44MDM0Mzc1IDAuMzIzMTI1LDAuOTA5Njg3NSAwLjIxNzE4NzUsMC44MDM0Mzc1IDAuMDQwMzEyNSwwLjYyNjg3NSAwLjE0NjU2MjUsMC41MjA2MjUgMC4zMjMxMjUsMC42OTc1IDAuODUzNDM3NSwwLjE2NzE4NzUgeiIKICAgICAgICAgc3R5bGU9ImZpbGw6I2ZmZmZmZjtmaWxsLW9wYWNpdHk6MTtzdHJva2U6bm9uZSIgLz4KICAgIDwvY2xpcFBhdGg+CiAgICA8bWFzayBpZD0ibWFzayIgbWFza1VuaXRzPSJvYmplY3RCb3VuZGluZ0JveCIgbWFza0NvbnRlbnRVbml0cz0ib2JqZWN0Qm91bmRpbmdCb3giPgogICAgICA8cGF0aAogICAgICAgICBkPSJNIDAsMCAwLDEgMSwxIDEsMCAwLDAgeiBNIDAuODUzNDM3NSwwLjE2NzE4NzUgMC45NTk2ODc1LDAuMjczMTI1IDAuNDI5Mzc1LDAuODAzNDM3NSAwLjMyMzEyNSwwLjkwOTY4NzUgMC4yMTcxODc1LDAuODAzNDM3NSAwLjA0MDMxMjUsMC42MjY4NzUgMC4xNDY1NjI1LDAuNTIwNjI1IDAuMzIzMTI1LDAuNjk3NSAwLjg1MzQzNzUsMC4xNjcxODc1IHoiCiAgICAgICAgIHN0eWxlPSJmaWxsOiNmZmZmZmY7ZmlsbC1vcGFjaXR5OjE7c3Ryb2tlOm5vbmUiIC8+CiAgICA8L21hc2s+CiAgPC9kZWZzPgogIDxyZWN0CiAgICAgd2lkdGg9IjEiCiAgICAgaGVpZ2h0PSIxIgogICAgIHg9IjAiCiAgICAgeT0iMCIKICAgICBjbGlwLXBhdGg9InVybCgjY2xpcCkiCiAgICAgc3R5bGU9ImZpbGw6IzAwMDAwMDtmaWxsLW9wYWNpdHk6MTtzdHJva2U6bm9uZSIgLz4KPC9zdmc+Cg==");mask:url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgdmVyc2lvbj0iMS4xIgogICB2aWV3Qm94PSIwIDAgMSAxIgogICBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJ4TWluWU1pbiBtZWV0Ij4KICA8ZGVmcz4KICAgIDxjbGlwUGF0aCBpZD0iY2xpcCI+CiAgICAgIDxwYXRoCiAgICAgICAgIGQ9Ik0gMCwwIDAsMSAxLDEgMSwwIDAsMCB6IE0gMC44NTM0Mzc1LDAuMTY3MTg3NSAwLjk1OTY4NzUsMC4yNzMxMjUgMC40MjkzNzUsMC44MDM0Mzc1IDAuMzIzMTI1LDAuOTA5Njg3NSAwLjIxNzE4NzUsMC44MDM0Mzc1IDAuMDQwMzEyNSwwLjYyNjg3NSAwLjE0NjU2MjUsMC41MjA2MjUgMC4zMjMxMjUsMC42OTc1IDAuODUzNDM3NSwwLjE2NzE4NzUgeiIKICAgICAgICAgc3R5bGU9ImZpbGw6I2ZmZmZmZjtmaWxsLW9wYWNpdHk6MTtzdHJva2U6bm9uZSIgLz4KICAgIDwvY2xpcFBhdGg+CiAgICA8bWFzayBpZD0ibWFzayIgbWFza1VuaXRzPSJvYmplY3RCb3VuZGluZ0JveCIgbWFza0NvbnRlbnRVbml0cz0ib2JqZWN0Qm91bmRpbmdCb3giPgogICAgICA8cGF0aAogICAgICAgICBkPSJNIDAsMCAwLDEgMSwxIDEsMCAwLDAgeiBNIDAuODUzNDM3NSwwLjE2NzE4NzUgMC45NTk2ODc1LDAuMjczMTI1IDAuNDI5Mzc1LDAuODAzNDM3NSAwLjMyMzEyNSwwLjkwOTY4NzUgMC4yMTcxODc1LDAuODAzNDM3NSAwLjA0MDMxMjUsMC42MjY4NzUgMC4xNDY1NjI1LDAuNTIwNjI1IDAuMzIzMTI1LDAuNjk3NSAwLjg1MzQzNzUsMC4xNjcxODc1IHoiCiAgICAgICAgIHN0eWxlPSJmaWxsOiNmZmZmZmY7ZmlsbC1vcGFjaXR5OjE7c3Ryb2tlOm5vbmUiIC8+CiAgICA8L21hc2s+CiAgPC9kZWZzPgogIDxyZWN0CiAgICAgd2lkdGg9IjEiCiAgICAgaGVpZ2h0PSIxIgogICAgIHg9IjAiCiAgICAgeT0iMCIKICAgICBjbGlwLXBhdGg9InVybCgjY2xpcCkiCiAgICAgc3R5bGU9ImZpbGw6IzAwMDAwMDtmaWxsLW9wYWNpdHk6MTtzdHJva2U6bm9uZSIgLz4KPC9zdmc+Cg==");background:0 0;transition-duration:.28s;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-property:background}.mdl-checkbox.is-checked .mdl-checkbox__tick-outline{background:#3f51b5 url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgdmVyc2lvbj0iMS4xIgogICB2aWV3Qm94PSIwIDAgMSAxIgogICBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJ4TWluWU1pbiBtZWV0Ij4KICA8cGF0aAogICAgIGQ9Ik0gMC4wNDAzODA1OSwwLjYyNjc3NjcgMC4xNDY0NDY2MSwwLjUyMDcxMDY4IDAuNDI5Mjg5MzIsMC44MDM1NTMzOSAwLjMyMzIyMzMsMC45MDk2MTk0MSB6IE0gMC4yMTcxNTcyOSwwLjgwMzU1MzM5IDAuODUzNTUzMzksMC4xNjcxNTcyOSAwLjk1OTYxOTQxLDAuMjczMjIzMyAwLjMyMzIyMzMsMC45MDk2MTk0MSB6IgogICAgIGlkPSJyZWN0Mzc4MCIKICAgICBzdHlsZT0iZmlsbDojZmZmZmZmO2ZpbGwtb3BhY2l0eToxO3N0cm9rZTpub25lIiAvPgo8L3N2Zz4K")}.mdl-checkbox.is-checked.is-disabled .mdl-checkbox__tick-outline,fieldset[disabled] .mdl-checkbox.is-checked .mdl-checkbox__tick-outline{background:rgba(0,0,0,.26)url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgdmVyc2lvbj0iMS4xIgogICB2aWV3Qm94PSIwIDAgMSAxIgogICBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJ4TWluWU1pbiBtZWV0Ij4KICA8cGF0aAogICAgIGQ9Ik0gMC4wNDAzODA1OSwwLjYyNjc3NjcgMC4xNDY0NDY2MSwwLjUyMDcxMDY4IDAuNDI5Mjg5MzIsMC44MDM1NTMzOSAwLjMyMzIyMzMsMC45MDk2MTk0MSB6IE0gMC4yMTcxNTcyOSwwLjgwMzU1MzM5IDAuODUzNTUzMzksMC4xNjcxNTcyOSAwLjk1OTYxOTQxLDAuMjczMjIzMyAwLjMyMzIyMzMsMC45MDk2MTk0MSB6IgogICAgIGlkPSJyZWN0Mzc4MCIKICAgICBzdHlsZT0iZmlsbDojZmZmZmZmO2ZpbGwtb3BhY2l0eToxO3N0cm9rZTpub25lIiAvPgo8L3N2Zz4K")}.mdl-checkbox__label{position:relative;cursor:pointer;font-size:16px;line-height:24px;margin:0}.mdl-checkbox.is-disabled .mdl-checkbox__label,fieldset[disabled] .mdl-checkbox .mdl-checkbox__label{color:rgba(0,0,0,.26);cursor:auto}.mdl-checkbox__ripple-container{position:absolute;z-index:2;top:-6px;left:-10px;box-sizing:border-box;width:36px;height:36px;border-radius:50%;cursor:pointer;overflow:hidden;-webkit-mask-image:-webkit-radial-gradient(circle,#fff,#000)}.mdl-checkbox__ripple-container .mdl-ripple{background:#3f51b5}.mdl-checkbox.is-disabled .mdl-checkbox__ripple-container,fieldset[disabled] .mdl-checkbox .mdl-checkbox__ripple-container{cursor:auto}.mdl-checkbox.is-disabled .mdl-checkbox__ripple-container .mdl-ripple,fieldset[disabled] .mdl-checkbox .mdl-checkbox__ripple-container .mdl-ripple{background:0 0}.mdl-chip{height:32px;font-family:Roboto,Helvetica,Arial,sans-serif;line-height:32px;padding:0 12px;border:0;border-radius:16px;background-color:#dedede;display:inline-block;color:rgba(0,0,0,.87);margin:2px 0;font-size:0;white-space:nowrap}.mdl-chip__text{font-size:13px;vertical-align:middle;display:inline-block}.mdl-chip__action{height:24px;width:24px;background:0 0;opacity:.54;cursor:pointer;padding:0;margin:0 0 0 4px;font-size:13px;text-decoration:none;color:rgba(0,0,0,.87);border:none;outline:none}.mdl-chip__action,.mdl-chip__contact{display:inline-block;vertical-align:middle;overflow:hidden;text-align:center}.mdl-chip__contact{height:32px;width:32px;border-radius:16px;margin-right:8px;font-size:18px;line-height:32px}.mdl-chip:focus{outline:0;box-shadow:0 2px 2px 0 rgba(0,0,0,.14),0 3px 1px -2px rgba(0,0,0,.2),0 1px 5px 0 rgba(0,0,0,.12)}.mdl-chip:active{background-color:#d6d6d6}.mdl-chip--deletable{padding-right:4px}.mdl-chip--contact{padding-left:0}.mdl-data-table{position:relative;border:1px solid rgba(0,0,0,.12);border-collapse:collapse;white-space:nowrap;font-size:13px;background-color:#fff}.mdl-data-table thead{padding-bottom:3px}.mdl-data-table thead .mdl-data-table__select{margin-top:0}.mdl-data-table tbody tr{position:relative;height:48px;transition-duration:.28s;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-property:background-color}.mdl-data-table tbody tr.is-selected{background-color:#e0e0e0}.mdl-data-table tbody tr:hover{background-color:#eee}.mdl-data-table td{text-align:right}.mdl-data-table th{padding:0 18px 12px;text-align:right}.mdl-data-table td:first-of-type,.mdl-data-table th:first-of-type{padding-left:24px}.mdl-data-table td:last-of-type,.mdl-data-table th:last-of-type{padding-right:24px}.mdl-data-table td{position:relative;height:48px;border-top:1px solid rgba(0,0,0,.12);border-bottom:1px solid rgba(0,0,0,.12);padding:12px 18px;box-sizing:border-box}.mdl-data-table td,.mdl-data-table td .mdl-data-table__select{vertical-align:middle}.mdl-data-table th{position:relative;vertical-align:bottom;text-overflow:ellipsis;font-weight:700;line-height:24px;letter-spacing:0;height:48px;font-size:12px;color:rgba(0,0,0,.54);padding-bottom:8px;box-sizing:border-box}.mdl-data-table th.mdl-data-table__header--sorted-ascending,.mdl-data-table th.mdl-data-table__header--sorted-descending{color:rgba(0,0,0,.87)}.mdl-data-table th.mdl-data-table__header--sorted-ascending:before,.mdl-data-table th.mdl-data-table__header--sorted-descending:before{font-family:Material Icons;font-weight:400;font-style:normal;line-height:1;letter-spacing:normal;text-transform:none;display:inline-block;word-wrap:normal;-moz-font-feature-settings:"liga";font-feature-settings:"liga";-webkit-font-feature-settings:"liga";-webkit-font-smoothing:antialiased;font-size:16px;content:"\\E5D8";margin-right:5px;vertical-align:sub}.mdl-data-table th.mdl-data-table__header--sorted-ascending:hover,.mdl-data-table th.mdl-data-table__header--sorted-descending:hover{cursor:pointer}.mdl-data-table th.mdl-data-table__header--sorted-ascending:hover:before,.mdl-data-table th.mdl-data-table__header--sorted-descending:hover:before{color:rgba(0,0,0,.26)}.mdl-data-table th.mdl-data-table__header--sorted-descending:before{content:"\\E5DB"}.mdl-data-table__select{width:16px}.mdl-data-table__cell--non-numeric.mdl-data-table__cell--non-numeric{text-align:left}.mdl-dialog{border:none;box-shadow:0 9px 46px 8px rgba(0,0,0,.14),0 11px 15px -7px rgba(0,0,0,.12),0 24px 38px 3px rgba(0,0,0,.2);width:280px}.mdl-dialog__title{padding:24px 24px 0;margin:0;font-size:2.5rem}.mdl-dialog__actions{padding:8px 8px 8px 24px;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:row-reverse;-ms-flex-direction:row-reverse;flex-direction:row-reverse;-webkit-flex-wrap:wrap;-ms-flex-wrap:wrap;flex-wrap:wrap}.mdl-dialog__actions>*{margin-right:8px;height:36px}.mdl-dialog__actions>:first-child{margin-right:0}.mdl-dialog__actions--full-width{padding:0 0 8px}.mdl-dialog__actions--full-width>*{height:48px;-webkit-flex:0 0 100%;-ms-flex:0 0 100%;flex:0 0 100%;padding-right:16px;margin-right:0;text-align:right}.mdl-dialog__content{padding:20px 24px 24px;color:rgba(0,0,0,.54)}.mdl-mega-footer{padding:16px 40px;color:#9e9e9e;background-color:#424242}.mdl-mega-footer--bottom-section:after,.mdl-mega-footer--middle-section:after,.mdl-mega-footer--top-section:after,.mdl-mega-footer__bottom-section:after,.mdl-mega-footer__middle-section:after,.mdl-mega-footer__top-section:after{content:"";display:block;clear:both}.mdl-mega-footer--left-section,.mdl-mega-footer--right-section,.mdl-mega-footer__left-section,.mdl-mega-footer__right-section{margin-bottom:16px}.mdl-mega-footer--right-section a,.mdl-mega-footer__right-section a{display:block;margin-bottom:16px;color:inherit;text-decoration:none}@media screen and (min-width:760px){.mdl-mega-footer--left-section,.mdl-mega-footer__left-section{float:left}.mdl-mega-footer--right-section,.mdl-mega-footer__right-section{float:right}.mdl-mega-footer--right-section a,.mdl-mega-footer__right-section a{display:inline-block;margin-left:16px;line-height:36px;vertical-align:middle}}.mdl-mega-footer--social-btn,.mdl-mega-footer__social-btn{width:36px;height:36px;padding:0;margin:0;background-color:#9e9e9e;border:none}.mdl-mega-footer--drop-down-section,.mdl-mega-footer__drop-down-section{display:block;position:relative}@media screen and (min-width:760px){.mdl-mega-footer--drop-down-section,.mdl-mega-footer__drop-down-section{width:33%}.mdl-mega-footer--drop-down-section:first-child,.mdl-mega-footer--drop-down-section:nth-child(2),.mdl-mega-footer__drop-down-section:first-child,.mdl-mega-footer__drop-down-section:nth-child(2){float:left}.mdl-mega-footer--drop-down-section:nth-child(3),.mdl-mega-footer__drop-down-section:nth-child(3){float:right}.mdl-mega-footer--drop-down-section:nth-child(3):after,.mdl-mega-footer__drop-down-section:nth-child(3):after{clear:right}.mdl-mega-footer--drop-down-section:nth-child(4),.mdl-mega-footer__drop-down-section:nth-child(4){clear:right;float:right}.mdl-mega-footer--middle-section:after,.mdl-mega-footer__middle-section:after{content:"";display:block;clear:both}.mdl-mega-footer--bottom-section,.mdl-mega-footer__bottom-section{padding-top:0}}@media screen and (min-width:1024px){.mdl-mega-footer--drop-down-section,.mdl-mega-footer--drop-down-section:nth-child(3),.mdl-mega-footer--drop-down-section:nth-child(4),.mdl-mega-footer__drop-down-section,.mdl-mega-footer__drop-down-section:nth-child(3),.mdl-mega-footer__drop-down-section:nth-child(4){width:24%;float:left}}.mdl-mega-footer--heading-checkbox,.mdl-mega-footer__heading-checkbox{position:absolute;width:100%;height:55.8px;padding:32px;margin:-16px 0 0;cursor:pointer;z-index:1;opacity:0}.mdl-mega-footer--heading-checkbox+.mdl-mega-footer--heading:after,.mdl-mega-footer--heading-checkbox+.mdl-mega-footer__heading:after,.mdl-mega-footer__heading-checkbox+.mdl-mega-footer--heading:after,.mdl-mega-footer__heading-checkbox+.mdl-mega-footer__heading:after{font-family:Material Icons;content:"\\E5CE"}.mdl-mega-footer--heading-checkbox:checked+.mdl-mega-footer--heading+.mdl-mega-footer--link-list,.mdl-mega-footer--heading-checkbox:checked+.mdl-mega-footer__heading+.mdl-mega-footer__link-list,.mdl-mega-footer--heading-checkbox:checked~.mdl-mega-footer--link-list,.mdl-mega-footer--heading-checkbox:checked~.mdl-mega-footer__link-list,.mdl-mega-footer__heading-checkbox:checked+.mdl-mega-footer--heading+.mdl-mega-footer--link-list,.mdl-mega-footer__heading-checkbox:checked+.mdl-mega-footer__heading+.mdl-mega-footer__link-list,.mdl-mega-footer__heading-checkbox:checked~.mdl-mega-footer--link-list,.mdl-mega-footer__heading-checkbox:checked~.mdl-mega-footer__link-list{display:none}.mdl-mega-footer--heading-checkbox:checked+.mdl-mega-footer--heading:after,.mdl-mega-footer--heading-checkbox:checked+.mdl-mega-footer__heading:after,.mdl-mega-footer__heading-checkbox:checked+.mdl-mega-footer--heading:after,.mdl-mega-footer__heading-checkbox:checked+.mdl-mega-footer__heading:after{font-family:Material Icons;content:"\\E5CF"}.mdl-mega-footer--heading,.mdl-mega-footer__heading{position:relative;width:100%;padding-right:39.8px;margin-bottom:16px;box-sizing:border-box;font-size:14px;line-height:23.8px;font-weight:500;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;color:#e0e0e0}.mdl-mega-footer--heading:after,.mdl-mega-footer__heading:after{content:"";position:absolute;top:0;right:0;display:block;width:23.8px;height:23.8px;background-size:cover}.mdl-mega-footer--link-list,.mdl-mega-footer__link-list{list-style:none;padding:0;margin:0 0 32px}.mdl-mega-footer--link-list:after,.mdl-mega-footer__link-list:after{clear:both;display:block;content:""}.mdl-mega-footer--link-list li,.mdl-mega-footer__link-list li{font-size:14px;font-weight:400;letter-spacing:0;line-height:20px}.mdl-mega-footer--link-list a,.mdl-mega-footer__link-list a{color:inherit;text-decoration:none;white-space:nowrap}@media screen and (min-width:760px){.mdl-mega-footer--heading-checkbox,.mdl-mega-footer__heading-checkbox{display:none}.mdl-mega-footer--heading-checkbox+.mdl-mega-footer--heading:after,.mdl-mega-footer--heading-checkbox+.mdl-mega-footer__heading:after,.mdl-mega-footer__heading-checkbox+.mdl-mega-footer--heading:after,.mdl-mega-footer__heading-checkbox+.mdl-mega-footer__heading:after{content:""}.mdl-mega-footer--heading-checkbox:checked+.mdl-mega-footer--heading+.mdl-mega-footer--link-list,.mdl-mega-footer--heading-checkbox:checked+.mdl-mega-footer__heading+.mdl-mega-footer__link-list,.mdl-mega-footer--heading-checkbox:checked~.mdl-mega-footer--link-list,.mdl-mega-footer--heading-checkbox:checked~.mdl-mega-footer__link-list,.mdl-mega-footer__heading-checkbox:checked+.mdl-mega-footer--heading+.mdl-mega-footer--link-list,.mdl-mega-footer__heading-checkbox:checked+.mdl-mega-footer__heading+.mdl-mega-footer__link-list,.mdl-mega-footer__heading-checkbox:checked~.mdl-mega-footer--link-list,.mdl-mega-footer__heading-checkbox:checked~.mdl-mega-footer__link-list{display:block}.mdl-mega-footer--heading-checkbox:checked+.mdl-mega-footer--heading:after,.mdl-mega-footer--heading-checkbox:checked+.mdl-mega-footer__heading:after,.mdl-mega-footer__heading-checkbox:checked+.mdl-mega-footer--heading:after,.mdl-mega-footer__heading-checkbox:checked+.mdl-mega-footer__heading:after{content:""}}.mdl-mega-footer--bottom-section,.mdl-mega-footer__bottom-section{padding-top:16px;margin-bottom:16px}.mdl-logo{margin-bottom:16px;color:#fff}.mdl-mega-footer--bottom-section .mdl-mega-footer--link-list li,.mdl-mega-footer__bottom-section .mdl-mega-footer__link-list li{float:left;margin-bottom:0;margin-right:16px}@media screen and (min-width:760px){.mdl-logo{float:left;margin-bottom:0;margin-right:16px}}.mdl-mini-footer{display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-flow:row wrap;-ms-flex-flow:row wrap;flex-flow:row wrap;-webkit-justify-content:space-between;-ms-flex-pack:justify;justify-content:space-between;padding:32px 16px;color:#9e9e9e;background-color:#424242}.mdl-mini-footer:after{content:"";display:block}.mdl-mini-footer .mdl-logo{line-height:36px}.mdl-mini-footer--link-list,.mdl-mini-footer__link-list{display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-flow:row nowrap;-ms-flex-flow:row nowrap;flex-flow:row nowrap;list-style:none;margin:0;padding:0}.mdl-mini-footer--link-list li,.mdl-mini-footer__link-list li{margin-bottom:0;margin-right:16px}@media screen and (min-width:760px){.mdl-mini-footer--link-list li,.mdl-mini-footer__link-list li{line-height:36px}}.mdl-mini-footer--link-list a,.mdl-mini-footer__link-list a{color:inherit;text-decoration:none;white-space:nowrap}.mdl-mini-footer--left-section,.mdl-mini-footer__left-section{display:inline-block;-webkit-order:0;-ms-flex-order:0;order:0}.mdl-mini-footer--right-section,.mdl-mini-footer__right-section{display:inline-block;-webkit-order:1;-ms-flex-order:1;order:1}.mdl-mini-footer--social-btn,.mdl-mini-footer__social-btn{width:36px;height:36px;padding:0;margin:0;background-color:#9e9e9e;border:none}.mdl-icon-toggle{position:relative;z-index:1;vertical-align:middle;display:inline-block;height:32px;margin:0;padding:0}.mdl-icon-toggle__input{line-height:32px}.mdl-icon-toggle.is-upgraded .mdl-icon-toggle__input{position:absolute;width:0;height:0;margin:0;padding:0;opacity:0;-ms-appearance:none;-moz-appearance:none;-webkit-appearance:none;appearance:none;border:none}.mdl-icon-toggle__label{display:inline-block;position:relative;cursor:pointer;height:32px;width:32px;min-width:32px;color:#616161;border-radius:50%;padding:0;margin-left:0;margin-right:0;text-align:center;background-color:transparent;will-change:background-color;transition:background-color .2s cubic-bezier(.4,0,.2,1),color .2s cubic-bezier(.4,0,.2,1)}.mdl-icon-toggle__label.material-icons{line-height:32px;font-size:24px}.mdl-icon-toggle.is-checked .mdl-icon-toggle__label{color:#3f51b5}.mdl-icon-toggle.is-disabled .mdl-icon-toggle__label{color:rgba(0,0,0,.26);cursor:auto;transition:none}.mdl-icon-toggle.is-focused .mdl-icon-toggle__label{background-color:rgba(0,0,0,.12)}.mdl-icon-toggle.is-focused.is-checked .mdl-icon-toggle__label{background-color:rgba(63,81,181,.26)}.mdl-icon-toggle__ripple-container{position:absolute;z-index:2;top:-2px;left:-2px;box-sizing:border-box;width:36px;height:36px;border-radius:50%;cursor:pointer;overflow:hidden;-webkit-mask-image:-webkit-radial-gradient(circle,#fff,#000)}.mdl-icon-toggle__ripple-container .mdl-ripple{background:#616161}.mdl-icon-toggle.is-disabled .mdl-icon-toggle__ripple-container{cursor:auto}.mdl-icon-toggle.is-disabled .mdl-icon-toggle__ripple-container .mdl-ripple{background:0 0}.mdl-list{display:block;padding:8px 0;list-style:none}.mdl-list__item{font-family:Roboto,Helvetica,Arial,sans-serif;font-size:16px;font-weight:400;letter-spacing:.04em;line-height:1;min-height:48px;-webkit-flex-direction:row;-ms-flex-direction:row;flex-direction:row;-webkit-flex-wrap:nowrap;-ms-flex-wrap:nowrap;flex-wrap:nowrap;padding:16px;cursor:default;color:rgba(0,0,0,.87);overflow:hidden}.mdl-list__item,.mdl-list__item .mdl-list__item-primary-content{box-sizing:border-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-align-items:center;-ms-flex-align:center;align-items:center}.mdl-list__item .mdl-list__item-primary-content{-webkit-order:0;-ms-flex-order:0;order:0;-webkit-flex-grow:2;-ms-flex-positive:2;flex-grow:2;text-decoration:none}.mdl-list__item .mdl-list__item-primary-content .mdl-list__item-icon{margin-right:32px}.mdl-list__item .mdl-list__item-primary-content .mdl-list__item-avatar{margin-right:16px}.mdl-list__item .mdl-list__item-secondary-content{display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-flow:column;-ms-flex-flow:column;flex-flow:column;-webkit-align-items:flex-end;-ms-flex-align:end;align-items:flex-end;margin-left:16px}.mdl-list__item .mdl-list__item-secondary-content .mdl-list__item-secondary-action label{display:inline}.mdl-list__item .mdl-list__item-secondary-content .mdl-list__item-secondary-info{font-size:12px;font-weight:400;line-height:1;letter-spacing:0;color:rgba(0,0,0,.54)}.mdl-list__item .mdl-list__item-secondary-content .mdl-list__item-sub-header{padding:0 0 0 16px}.mdl-list__item-icon,.mdl-list__item-icon.material-icons{height:24px;width:24px;font-size:24px;box-sizing:border-box;color:#757575}.mdl-list__item-avatar,.mdl-list__item-avatar.material-icons{height:40px;width:40px;box-sizing:border-box;border-radius:50%;background-color:#757575;font-size:40px;color:#fff}.mdl-list__item--two-line{height:72px}.mdl-list__item--two-line .mdl-list__item-primary-content{height:36px;line-height:20px;display:block}.mdl-list__item--two-line .mdl-list__item-primary-content .mdl-list__item-avatar{float:left}.mdl-list__item--two-line .mdl-list__item-primary-content .mdl-list__item-icon{float:left;margin-top:6px}.mdl-list__item--two-line .mdl-list__item-primary-content .mdl-list__item-secondary-content{height:36px}.mdl-list__item--two-line .mdl-list__item-primary-content .mdl-list__item-sub-title{font-size:14px;font-weight:400;letter-spacing:0;line-height:18px;color:rgba(0,0,0,.54);display:block;padding:0}.mdl-list__item--three-line{height:88px}.mdl-list__item--three-line .mdl-list__item-primary-content{height:52px;line-height:20px;display:block}.mdl-list__item--three-line .mdl-list__item-primary-content .mdl-list__item-avatar,.mdl-list__item--three-line .mdl-list__item-primary-content .mdl-list__item-icon{float:left}.mdl-list__item--three-line .mdl-list__item-secondary-content{height:52px}.mdl-list__item--three-line .mdl-list__item-text-body{font-size:14px;font-weight:400;letter-spacing:0;line-height:18px;height:52px;color:rgba(0,0,0,.54);display:block;padding:0}.mdl-menu__container{display:block;margin:0;padding:0;border:none;position:absolute;overflow:visible;height:0;width:0;visibility:hidden;z-index:-1}.mdl-menu__container.is-animating,.mdl-menu__container.is-visible{z-index:999;visibility:visible}.mdl-menu__outline{display:block;background:#fff;margin:0;padding:0;border:none;border-radius:2px;position:absolute;top:0;left:0;overflow:hidden;opacity:0;-webkit-transform:scale(0);transform:scale(0);-webkit-transform-origin:0 0;transform-origin:0 0;box-shadow:0 2px 2px 0 rgba(0,0,0,.14),0 3px 1px -2px rgba(0,0,0,.2),0 1px 5px 0 rgba(0,0,0,.12);will-change:transform;transition:transform .3s cubic-bezier(.4,0,.2,1),opacity .2s cubic-bezier(.4,0,.2,1);transition:transform .3s cubic-bezier(.4,0,.2,1),opacity .2s cubic-bezier(.4,0,.2,1),-webkit-transform .3s cubic-bezier(.4,0,.2,1);z-index:-1}.mdl-menu__container.is-visible .mdl-menu__outline{opacity:1;-webkit-transform:scale(1);transform:scale(1);z-index:999}.mdl-menu__outline.mdl-menu--bottom-right{-webkit-transform-origin:100% 0;transform-origin:100% 0}.mdl-menu__outline.mdl-menu--top-left{-webkit-transform-origin:0 100%;transform-origin:0 100%}.mdl-menu__outline.mdl-menu--top-right{-webkit-transform-origin:100% 100%;transform-origin:100% 100%}.mdl-menu{position:absolute;list-style:none;top:0;left:0;height:auto;width:auto;min-width:124px;padding:8px 0;margin:0;opacity:0;clip:rect(0 0 0 0);z-index:-1}.mdl-menu__container.is-visible .mdl-menu{opacity:1;z-index:999}.mdl-menu.is-animating{transition:opacity .2s cubic-bezier(.4,0,.2,1),clip .3s cubic-bezier(.4,0,.2,1)}.mdl-menu.mdl-menu--bottom-right{left:auto;right:0}.mdl-menu.mdl-menu--top-left{top:auto;bottom:0}.mdl-menu.mdl-menu--top-right{top:auto;left:auto;bottom:0;right:0}.mdl-menu.mdl-menu--unaligned{top:auto;left:auto}.mdl-menu__item{display:block;border:none;color:rgba(0,0,0,.87);background-color:transparent;text-align:left;margin:0;padding:0 16px;outline-color:#bdbdbd;position:relative;overflow:hidden;font-size:14px;font-weight:400;letter-spacing:0;text-decoration:none;cursor:pointer;height:48px;line-height:48px;white-space:nowrap;opacity:0;transition:opacity .2s cubic-bezier(.4,0,.2,1);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.mdl-menu__container.is-visible .mdl-menu__item{opacity:1}.mdl-menu__item::-moz-focus-inner{border:0}.mdl-menu__item--full-bleed-divider{border-bottom:1px solid rgba(0,0,0,.12)}.mdl-menu__item[data-mdl-disabled],.mdl-menu__item[disabled]{color:#bdbdbd;background-color:transparent;cursor:auto}.mdl-menu__item[data-mdl-disabled]:focus,.mdl-menu__item[data-mdl-disabled]:hover,.mdl-menu__item[disabled]:focus,.mdl-menu__item[disabled]:hover{background-color:transparent}.mdl-menu__item[data-mdl-disabled] .mdl-ripple,.mdl-menu__item[disabled] .mdl-ripple{background:0 0}.mdl-menu__item:hover{background-color:#eee}.mdl-menu__item:focus{outline:none;background-color:#eee}.mdl-menu__item:active{background-color:#e0e0e0}.mdl-menu__item--ripple-container{display:block;height:100%;left:0;position:absolute;top:0;width:100%;z-index:0;overflow:hidden}.mdl-progress{display:block;position:relative;height:4px;width:500px;max-width:100%}.mdl-progress>.bar{display:block;position:absolute;top:0;bottom:0;width:0;transition:width .2s cubic-bezier(.4,0,.2,1)}.mdl-progress>.progressbar{background-color:#3f51b5;z-index:1;left:0}.mdl-progress>.bufferbar{background-image:linear-gradient(90deg,hsla(0,0%,100%,.7),hsla(0,0%,100%,.7)),linear-gradient(90deg,#3f51b5,#3f51b5);z-index:0;left:0}.mdl-progress>.auxbar{right:0}@supports (-webkit-appearance:none){.mdl-progress:not(.mdl-progress--indeterminate):not(.mdl-progress--indeterminate)>.auxbar,.mdl-progress:not(.mdl-progress__indeterminate):not(.mdl-progress__indeterminate)>.auxbar{background-image:linear-gradient(90deg,hsla(0,0%,100%,.7),hsla(0,0%,100%,.7)),linear-gradient(90deg,#3f51b5,#3f51b5);-webkit-mask:url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIj8+Cjxzdmcgd2lkdGg9IjEyIiBoZWlnaHQ9IjQiIHZpZXdQb3J0PSIwIDAgMTIgNCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgogIDxlbGxpcHNlIGN4PSIyIiBjeT0iMiIgcng9IjIiIHJ5PSIyIj4KICAgIDxhbmltYXRlIGF0dHJpYnV0ZU5hbWU9ImN4IiBmcm9tPSIyIiB0bz0iLTEwIiBkdXI9IjAuNnMiIHJlcGVhdENvdW50PSJpbmRlZmluaXRlIiAvPgogIDwvZWxsaXBzZT4KICA8ZWxsaXBzZSBjeD0iMTQiIGN5PSIyIiByeD0iMiIgcnk9IjIiIGNsYXNzPSJsb2FkZXIiPgogICAgPGFuaW1hdGUgYXR0cmlidXRlTmFtZT0iY3giIGZyb209IjE0IiB0bz0iMiIgZHVyPSIwLjZzIiByZXBlYXRDb3VudD0iaW5kZWZpbml0ZSIgLz4KICA8L2VsbGlwc2U+Cjwvc3ZnPgo=");mask:url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIj8+Cjxzdmcgd2lkdGg9IjEyIiBoZWlnaHQ9IjQiIHZpZXdQb3J0PSIwIDAgMTIgNCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgogIDxlbGxpcHNlIGN4PSIyIiBjeT0iMiIgcng9IjIiIHJ5PSIyIj4KICAgIDxhbmltYXRlIGF0dHJpYnV0ZU5hbWU9ImN4IiBmcm9tPSIyIiB0bz0iLTEwIiBkdXI9IjAuNnMiIHJlcGVhdENvdW50PSJpbmRlZmluaXRlIiAvPgogIDwvZWxsaXBzZT4KICA8ZWxsaXBzZSBjeD0iMTQiIGN5PSIyIiByeD0iMiIgcnk9IjIiIGNsYXNzPSJsb2FkZXIiPgogICAgPGFuaW1hdGUgYXR0cmlidXRlTmFtZT0iY3giIGZyb209IjE0IiB0bz0iMiIgZHVyPSIwLjZzIiByZXBlYXRDb3VudD0iaW5kZWZpbml0ZSIgLz4KICA8L2VsbGlwc2U+Cjwvc3ZnPgo=")}}.mdl-progress:not(.mdl-progress--indeterminate)>.auxbar,.mdl-progress:not(.mdl-progress__indeterminate)>.auxbar{background-image:linear-gradient(90deg,hsla(0,0%,100%,.9),hsla(0,0%,100%,.9)),linear-gradient(90deg,#3f51b5,#3f51b5)}.mdl-progress.mdl-progress--indeterminate>.bar1,.mdl-progress.mdl-progress__indeterminate>.bar1{-webkit-animation-name:indeterminate1;animation-name:indeterminate1}.mdl-progress.mdl-progress--indeterminate>.bar1,.mdl-progress.mdl-progress--indeterminate>.bar3,.mdl-progress.mdl-progress__indeterminate>.bar1,.mdl-progress.mdl-progress__indeterminate>.bar3{background-color:#3f51b5;-webkit-animation-duration:2s;animation-duration:2s;-webkit-animation-iteration-count:infinite;animation-iteration-count:infinite;-webkit-animation-timing-function:linear;animation-timing-function:linear}.mdl-progress.mdl-progress--indeterminate>.bar3,.mdl-progress.mdl-progress__indeterminate>.bar3{background-image:none;-webkit-animation-name:indeterminate2;animation-name:indeterminate2}@-webkit-keyframes indeterminate1{0%{left:0;width:0}50%{left:25%;width:75%}75%{left:100%;width:0}}@keyframes indeterminate1{0%{left:0;width:0}50%{left:25%;width:75%}75%{left:100%;width:0}}@-webkit-keyframes indeterminate2{0%,50%{left:0;width:0}75%{left:0;width:25%}to{left:100%;width:0}}@keyframes indeterminate2{0%,50%{left:0;width:0}75%{left:0;width:25%}to{left:100%;width:0}}.mdl-navigation{display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-wrap:nowrap;-ms-flex-wrap:nowrap;flex-wrap:nowrap;box-sizing:border-box}.mdl-navigation__link{color:#424242;text-decoration:none;margin:0;font-size:14px;font-weight:400;line-height:24px;letter-spacing:0;opacity:.87}.mdl-navigation__link .material-icons{vertical-align:middle}.mdl-layout{position:absolute;width:100%;height:100%}.mdl-layout.is-small-screen .mdl-layout--large-screen-only,.mdl-layout:not(.is-small-screen) .mdl-layout--small-screen-only{display:none}.mdl-layout__inner-container{width:100%;height:100%;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:column;-ms-flex-direction:column;flex-direction:column;overflow-y:auto;overflow-x:hidden;position:relative;-webkit-overflow-scrolling:touch}.mdl-layout-title,.mdl-layout__title{display:block;position:relative;font-family:Roboto,Helvetica,Arial,sans-serif;font-size:20px;line-height:1;letter-spacing:.02em;font-weight:400;box-sizing:border-box}.mdl-layout-spacer{-webkit-flex-grow:1;-ms-flex-positive:1;flex-grow:1}.mdl-layout__drawer{display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:column;-ms-flex-direction:column;flex-direction:column;-webkit-flex-wrap:nowrap;-ms-flex-wrap:nowrap;flex-wrap:nowrap;width:240px;height:100%;max-height:100%;position:absolute;top:0;left:0;box-shadow:0 2px 2px 0 rgba(0,0,0,.14),0 3px 1px -2px rgba(0,0,0,.2),0 1px 5px 0 rgba(0,0,0,.12);box-sizing:border-box;border-right:1px solid #e0e0e0;background:#fafafa;-webkit-transform:translateX(-250px);transform:translateX(-250px);-webkit-transform-style:preserve-3d;transform-style:preserve-3d;will-change:transform;transition-duration:.2s;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-property:transform;transition-property:transform,-webkit-transform;color:#424242;overflow:visible;overflow-y:auto;z-index:5}.mdl-layout__drawer.is-visible{-webkit-transform:translateX(0);transform:translateX(0)}.mdl-layout__drawer.is-visible~.mdl-layout__content.mdl-layout__content{overflow:hidden}.mdl-layout__drawer>*{-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0}.mdl-layout__drawer>.mdl-layout-title,.mdl-layout__drawer>.mdl-layout__title{line-height:64px;padding-left:40px}@media screen and (max-width:1024px){.mdl-layout__drawer>.mdl-layout-title,.mdl-layout__drawer>.mdl-layout__title{line-height:56px;padding-left:16px}}.mdl-layout__drawer .mdl-navigation{-webkit-flex-direction:column;-ms-flex-direction:column;flex-direction:column;-webkit-align-items:stretch;-ms-flex-align:stretch;-ms-grid-row-align:stretch;align-items:stretch;padding-top:16px}.mdl-layout__drawer .mdl-navigation .mdl-navigation__link{display:block;-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0;padding:16px 40px;margin:0;color:#757575}@media screen and (max-width:1024px){.mdl-layout__drawer .mdl-navigation .mdl-navigation__link{padding:16px}}.mdl-layout__drawer .mdl-navigation .mdl-navigation__link:hover{background-color:#e0e0e0}.mdl-layout__drawer .mdl-navigation .mdl-navigation__link--current{background-color:#e0e0e0;color:#000}@media screen and (min-width:1025px){.mdl-layout--fixed-drawer>.mdl-layout__inner-container>.mdl-layout__drawer{-webkit-transform:translateX(0);transform:translateX(0)}}.mdl-layout__drawer-button{display:block;position:absolute;height:48px;width:48px;border:0;-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0;overflow:hidden;text-align:center;cursor:pointer;font-size:26px;line-height:56px;font-family:Helvetica,Arial,sans-serif;margin:8px 12px;top:0;left:0;color:#fff;z-index:4}.mdl-layout__header .mdl-layout__drawer-button{position:absolute;color:#fff;background-color:inherit}@media screen and (max-width:1024px){.mdl-layout__header .mdl-layout__drawer-button{margin:4px}}@media screen and (max-width:1024px){.mdl-layout__drawer-button{margin:4px;color:rgba(0,0,0,.5)}}@media screen and (min-width:1025px){.mdl-layout__drawer-button{line-height:54px}.mdl-layout--fixed-drawer>.mdl-layout__inner-container>.mdl-layout__drawer-button,.mdl-layout--no-desktop-drawer-button .mdl-layout__drawer-button,.mdl-layout--no-drawer-button .mdl-layout__drawer-button{display:none}}.mdl-layout__header{display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:column;-ms-flex-direction:column;flex-direction:column;-webkit-flex-wrap:nowrap;-ms-flex-wrap:nowrap;flex-wrap:nowrap;-webkit-justify-content:flex-start;-ms-flex-pack:start;justify-content:flex-start;box-sizing:border-box;-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0;width:100%;margin:0;padding:0;border:none;min-height:64px;max-height:1000px;z-index:3;background-color:#3f51b5;color:#fff;box-shadow:0 2px 2px 0 rgba(0,0,0,.14),0 3px 1px -2px rgba(0,0,0,.2),0 1px 5px 0 rgba(0,0,0,.12);transition-duration:.2s;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-property:max-height,box-shadow}@media screen and (max-width:1024px){.mdl-layout__header{min-height:56px}}.mdl-layout--fixed-drawer.is-upgraded:not(.is-small-screen)>.mdl-layout__inner-container>.mdl-layout__header{margin-left:240px;width:calc(100% - 240px)}@media screen and (min-width:1025px){.mdl-layout--fixed-drawer>.mdl-layout__inner-container>.mdl-layout__header .mdl-layout__header-row{padding-left:40px}}.mdl-layout__header>.mdl-layout-icon{position:absolute;left:40px;top:16px;height:32px;width:32px;overflow:hidden;z-index:3;display:block}@media screen and (max-width:1024px){.mdl-layout__header>.mdl-layout-icon{left:16px;top:12px}}.mdl-layout.has-drawer .mdl-layout__header>.mdl-layout-icon{display:none}.mdl-layout__header.is-compact{max-height:64px}@media screen and (max-width:1024px){.mdl-layout__header.is-compact{max-height:56px}}.mdl-layout__header.is-compact.has-tabs{height:112px}@media screen and (max-width:1024px){.mdl-layout__header.is-compact.has-tabs{min-height:104px}}@media screen and (max-width:1024px){.mdl-layout__header{display:none}.mdl-layout--fixed-header>.mdl-layout__inner-container>.mdl-layout__header{display:-webkit-flex;display:-ms-flexbox;display:flex}}.mdl-layout__header--transparent.mdl-layout__header--transparent{background-color:transparent;box-shadow:none}.mdl-layout__header--scroll,.mdl-layout__header--seamed{box-shadow:none}.mdl-layout__header--waterfall{box-shadow:none;overflow:hidden}.mdl-layout__header--waterfall.is-casting-shadow{box-shadow:0 2px 2px 0 rgba(0,0,0,.14),0 3px 1px -2px rgba(0,0,0,.2),0 1px 5px 0 rgba(0,0,0,.12)}.mdl-layout__header--waterfall.mdl-layout__header--waterfall-hide-top{-webkit-justify-content:flex-end;-ms-flex-pack:end;justify-content:flex-end}.mdl-layout__header-row{display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:row;-ms-flex-direction:row;flex-direction:row;-webkit-flex-wrap:nowrap;-ms-flex-wrap:nowrap;flex-wrap:nowrap;-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0;box-sizing:border-box;-webkit-align-self:stretch;-ms-flex-item-align:stretch;align-self:stretch;-webkit-align-items:center;-ms-flex-align:center;align-items:center;height:64px;margin:0;padding:0 40px 0 80px}.mdl-layout--no-drawer-button .mdl-layout__header-row{padding-left:40px}@media screen and (min-width:1025px){.mdl-layout--no-desktop-drawer-button .mdl-layout__header-row{padding-left:40px}}@media screen and (max-width:1024px){.mdl-layout__header-row{height:56px;padding:0 16px 0 72px}.mdl-layout--no-drawer-button .mdl-layout__header-row{padding-left:16px}}.mdl-layout__header-row>*{-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0}.mdl-layout__header--scroll .mdl-layout__header-row{width:100%}.mdl-layout__header-row .mdl-navigation{margin:0;padding:0;height:64px;-webkit-flex-direction:row;-ms-flex-direction:row;flex-direction:row;-webkit-align-items:center;-ms-flex-align:center;-ms-grid-row-align:center;align-items:center}@media screen and (max-width:1024px){.mdl-layout__header-row .mdl-navigation{height:56px}}.mdl-layout__header-row .mdl-navigation__link{display:block;color:#fff;line-height:64px;padding:0 24px}@media screen and (max-width:1024px){.mdl-layout__header-row .mdl-navigation__link{line-height:56px;padding:0 16px}}.mdl-layout__obfuscator{background-color:transparent;position:absolute;top:0;left:0;height:100%;width:100%;z-index:4;visibility:hidden;transition-property:background-color;transition-duration:.2s;transition-timing-function:cubic-bezier(.4,0,.2,1)}.mdl-layout__obfuscator.is-visible{background-color:rgba(0,0,0,.5);visibility:visible}@supports (pointer-events:auto){.mdl-layout__obfuscator{background-color:rgba(0,0,0,.5);opacity:0;transition-property:opacity;visibility:visible;pointer-events:none}.mdl-layout__obfuscator.is-visible{pointer-events:auto;opacity:1}}.mdl-layout__content{-ms-flex:0 1 auto;position:relative;display:inline-block;overflow-y:auto;overflow-x:hidden;-webkit-flex-grow:1;-ms-flex-positive:1;flex-grow:1;z-index:1;-webkit-overflow-scrolling:touch}.mdl-layout--fixed-drawer>.mdl-layout__inner-container>.mdl-layout__content{margin-left:240px}.mdl-layout.has-scrolling-header .mdl-layout__content{overflow:visible}@media screen and (max-width:1024px){.mdl-layout--fixed-drawer>.mdl-layout__inner-container>.mdl-layout__content{margin-left:0}.mdl-layout.has-scrolling-header .mdl-layout__content{overflow-y:auto;overflow-x:hidden}}.mdl-layout__tab-bar{height:96px;margin:0;width:calc(100% - 112px);padding:0 0 0 56px;display:-webkit-flex;display:-ms-flexbox;display:flex;background-color:#3f51b5;overflow-y:hidden;overflow-x:scroll}.mdl-layout__tab-bar::-webkit-scrollbar{display:none}.mdl-layout--no-drawer-button .mdl-layout__tab-bar{padding-left:16px;width:calc(100% - 32px)}@media screen and (min-width:1025px){.mdl-layout--no-desktop-drawer-button .mdl-layout__tab-bar{padding-left:16px;width:calc(100% - 32px)}}@media screen and (max-width:1024px){.mdl-layout__tab-bar{width:calc(100% - 60px);padding:0 0 0 60px}.mdl-layout--no-drawer-button .mdl-layout__tab-bar{width:calc(100% - 8px);padding-left:4px}}.mdl-layout--fixed-tabs .mdl-layout__tab-bar{padding:0;overflow:hidden;width:100%}.mdl-layout__tab-bar-container{position:relative;height:48px;width:100%;border:none;margin:0;z-index:2;-webkit-flex-grow:0;-ms-flex-positive:0;flex-grow:0;-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0;overflow:hidden}.mdl-layout__container>.mdl-layout__tab-bar-container{position:absolute;top:0;left:0}.mdl-layout__tab-bar-button{display:inline-block;position:absolute;top:0;height:48px;width:56px;z-index:4;text-align:center;background-color:#3f51b5;color:transparent;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.mdl-layout--no-desktop-drawer-button .mdl-layout__tab-bar-button,.mdl-layout--no-drawer-button .mdl-layout__tab-bar-button{width:16px}.mdl-layout--no-desktop-drawer-button .mdl-layout__tab-bar-button .material-icons,.mdl-layout--no-drawer-button .mdl-layout__tab-bar-button .material-icons{position:relative;left:-4px}@media screen and (max-width:1024px){.mdl-layout__tab-bar-button{width:60px}}.mdl-layout--fixed-tabs .mdl-layout__tab-bar-button{display:none}.mdl-layout__tab-bar-button .material-icons{line-height:48px}.mdl-layout__tab-bar-button.is-active{color:#fff}.mdl-layout__tab-bar-left-button{left:0}.mdl-layout__tab-bar-right-button{right:0}.mdl-layout__tab{margin:0;border:none;padding:0 24px;float:left;position:relative;display:block;-webkit-flex-grow:0;-ms-flex-positive:0;flex-grow:0;-webkit-flex-shrink:0;-ms-flex-negative:0;flex-shrink:0;text-decoration:none;height:48px;line-height:48px;text-align:center;font-weight:500;font-size:14px;text-transform:uppercase;color:hsla(0,0%,100%,.6);overflow:hidden}@media screen and (max-width:1024px){.mdl-layout__tab{padding:0 12px}}.mdl-layout--fixed-tabs .mdl-layout__tab{float:none;-webkit-flex-grow:1;-ms-flex-positive:1;flex-grow:1;padding:0}.mdl-layout.is-upgraded .mdl-layout__tab.is-active{color:#fff}.mdl-layout.is-upgraded .mdl-layout__tab.is-active:after{height:2px;width:100%;display:block;content:" ";bottom:0;left:0;position:absolute;background:#ff4081;-webkit-animation:border-expand .2s cubic-bezier(.4,0,.4,1).01s alternate forwards;animation:border-expand .2s cubic-bezier(.4,0,.4,1).01s alternate forwards;transition:all 1s cubic-bezier(.4,0,1,1)}.mdl-layout__tab .mdl-layout__tab-ripple-container{display:block;position:absolute;height:100%;width:100%;left:0;top:0;z-index:1;overflow:hidden}.mdl-layout__tab .mdl-layout__tab-ripple-container .mdl-ripple{background-color:#fff}.mdl-layout__tab-panel{display:block}.mdl-layout.is-upgraded .mdl-layout__tab-panel{display:none}.mdl-layout.is-upgraded .mdl-layout__tab-panel.is-active{display:block}.mdl-radio{position:relative;font-size:16px;line-height:24px;display:inline-block;box-sizing:border-box;margin:0;padding-left:0}.mdl-radio.is-upgraded{padding-left:24px}.mdl-radio__button{line-height:24px}.mdl-radio.is-upgraded .mdl-radio__button{position:absolute;width:0;height:0;margin:0;padding:0;opacity:0;-ms-appearance:none;-moz-appearance:none;-webkit-appearance:none;appearance:none;border:none}.mdl-radio__outer-circle{position:absolute;top:4px;left:0;display:inline-block;box-sizing:border-box;width:16px;height:16px;margin:0;cursor:pointer;border:2px solid rgba(0,0,0,.54);border-radius:50%;z-index:2}.mdl-radio.is-checked .mdl-radio__outer-circle{border:2px solid #3f51b5}.mdl-radio.is-disabled .mdl-radio__outer-circle,.mdl-radio__outer-circle fieldset[disabled] .mdl-radio{border:2px solid rgba(0,0,0,.26);cursor:auto}.mdl-radio__inner-circle{position:absolute;z-index:1;margin:0;top:8px;left:4px;box-sizing:border-box;width:8px;height:8px;cursor:pointer;transition-duration:.28s;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-property:transform;transition-property:transform,-webkit-transform;-webkit-transform:scale3d(0,0,0);transform:scale3d(0,0,0);border-radius:50%;background:#3f51b5}.mdl-radio.is-checked .mdl-radio__inner-circle{-webkit-transform:scaleX(1);transform:scaleX(1)}.mdl-radio.is-disabled .mdl-radio__inner-circle,fieldset[disabled] .mdl-radio .mdl-radio__inner-circle{background:rgba(0,0,0,.26);cursor:auto}.mdl-radio.is-focused .mdl-radio__inner-circle{box-shadow:0 0 0 10px rgba(0,0,0,.1)}.mdl-radio__label{cursor:pointer}.mdl-radio.is-disabled .mdl-radio__label,fieldset[disabled] .mdl-radio .mdl-radio__label{color:rgba(0,0,0,.26);cursor:auto}.mdl-radio__ripple-container{position:absolute;z-index:2;top:-9px;left:-13px;box-sizing:border-box;width:42px;height:42px;border-radius:50%;cursor:pointer;overflow:hidden;-webkit-mask-image:-webkit-radial-gradient(circle,#fff,#000)}.mdl-radio__ripple-container .mdl-ripple{background:#3f51b5}.mdl-radio.is-disabled .mdl-radio__ripple-container,fieldset[disabled] .mdl-radio .mdl-radio__ripple-container{cursor:auto}.mdl-radio.is-disabled .mdl-radio__ripple-container .mdl-ripple,fieldset[disabled] .mdl-radio .mdl-radio__ripple-container .mdl-ripple{background:0 0}:root .mdl-slider.mdl-slider.is-upgraded,_:-ms-input-placeholder{-ms-appearance:none;height:32px;margin:0}.mdl-slider{width:calc(100% - 40px);margin:0 20px}.mdl-slider.is-upgraded{-webkit-appearance:none;-moz-appearance:none;appearance:none;height:2px;background:0 0;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;outline:0;padding:0;color:#3f51b5;-webkit-align-self:center;-ms-flex-item-align:center;align-self:center;z-index:1;cursor:pointer}.mdl-slider.is-upgraded::-moz-focus-outer{border:0}.mdl-slider.is-upgraded::-ms-tooltip{display:none}.mdl-slider.is-upgraded::-webkit-slider-runnable-track{background:0 0}.mdl-slider.is-upgraded::-moz-range-track{background:0 0;border:none}.mdl-slider.is-upgraded::-ms-track{background:0 0;color:transparent;height:2px;width:100%;border:none}.mdl-slider.is-upgraded::-ms-fill-lower{padding:0;background:linear-gradient(90deg,transparent,transparent 16px,#3f51b5 0,#3f51b5 0)}.mdl-slider.is-upgraded::-ms-fill-upper{padding:0;background:linear-gradient(270deg,transparent,transparent 16px,rgba(0,0,0,.26) 16px,rgba(0,0,0,.26) 0)}.mdl-slider.is-upgraded::-webkit-slider-thumb{-webkit-appearance:none;width:12px;height:12px;box-sizing:border-box;border-radius:50%;background:#3f51b5;border:none;transition:transform .18s cubic-bezier(.4,0,.2,1),border .18s cubic-bezier(.4,0,.2,1),box-shadow .18s cubic-bezier(.4,0,.2,1),background .28s cubic-bezier(.4,0,.2,1);transition:transform .18s cubic-bezier(.4,0,.2,1),border .18s cubic-bezier(.4,0,.2,1),box-shadow .18s cubic-bezier(.4,0,.2,1),background .28s cubic-bezier(.4,0,.2,1),-webkit-transform .18s cubic-bezier(.4,0,.2,1)}.mdl-slider.is-upgraded::-moz-range-thumb{-moz-appearance:none;width:12px;height:12px;box-sizing:border-box;border-radius:50%;background-image:none;background:#3f51b5;border:none}.mdl-slider.is-upgraded:focus:not(:active)::-webkit-slider-thumb{box-shadow:0 0 0 10px rgba(63,81,181,.26)}.mdl-slider.is-upgraded:focus:not(:active)::-moz-range-thumb{box-shadow:0 0 0 10px rgba(63,81,181,.26)}.mdl-slider.is-upgraded:active::-webkit-slider-thumb{background-image:none;background:#3f51b5;-webkit-transform:scale(1.5);transform:scale(1.5)}.mdl-slider.is-upgraded:active::-moz-range-thumb{background-image:none;background:#3f51b5;transform:scale(1.5)}.mdl-slider.is-upgraded::-ms-thumb{width:32px;height:32px;border:none;border-radius:50%;background:#3f51b5;transform:scale(.375);transition:transform .18s cubic-bezier(.4,0,.2,1),background .28s cubic-bezier(.4,0,.2,1);transition:transform .18s cubic-bezier(.4,0,.2,1),background .28s cubic-bezier(.4,0,.2,1),-webkit-transform .18s cubic-bezier(.4,0,.2,1)}.mdl-slider.is-upgraded:focus:not(:active)::-ms-thumb{background:radial-gradient(circle closest-side,#3f51b5 0,#3f51b5 37.5%,rgba(63,81,181,.26) 37.5%,rgba(63,81,181,.26) 100%);transform:scale(1)}.mdl-slider.is-upgraded:active::-ms-thumb{background:#3f51b5;transform:scale(.5625)}.mdl-slider.is-upgraded.is-lowest-value::-webkit-slider-thumb{border:2px solid rgba(0,0,0,.26);background:0 0}.mdl-slider.is-upgraded.is-lowest-value::-moz-range-thumb{border:2px solid rgba(0,0,0,.26);background:0 0}.mdl-slider.is-upgraded.is-lowest-value+.mdl-slider__background-flex>.mdl-slider__background-upper{left:6px}.mdl-slider.is-upgraded.is-lowest-value:focus:not(:active)::-webkit-slider-thumb{box-shadow:0 0 0 10px rgba(0,0,0,.12);background:rgba(0,0,0,.12)}.mdl-slider.is-upgraded.is-lowest-value:focus:not(:active)::-moz-range-thumb{box-shadow:0 0 0 10px rgba(0,0,0,.12);background:rgba(0,0,0,.12)}.mdl-slider.is-upgraded.is-lowest-value:active::-webkit-slider-thumb{border:1.6px solid rgba(0,0,0,.26);-webkit-transform:scale(1.5);transform:scale(1.5)}.mdl-slider.is-upgraded.is-lowest-value:active+.mdl-slider__background-flex>.mdl-slider__background-upper{left:9px}.mdl-slider.is-upgraded.is-lowest-value:active::-moz-range-thumb{border:1.5px solid rgba(0,0,0,.26);transform:scale(1.5)}.mdl-slider.is-upgraded.is-lowest-value::-ms-thumb{background:radial-gradient(circle closest-side,transparent 0,transparent 66.67%,rgba(0,0,0,.26) 66.67%,rgba(0,0,0,.26) 100%)}.mdl-slider.is-upgraded.is-lowest-value:focus:not(:active)::-ms-thumb{background:radial-gradient(circle closest-side,rgba(0,0,0,.12) 0,rgba(0,0,0,.12) 25%,rgba(0,0,0,.26) 25%,rgba(0,0,0,.26) 37.5%,rgba(0,0,0,.12) 37.5%,rgba(0,0,0,.12)100%);transform:scale(1)}.mdl-slider.is-upgraded.is-lowest-value:active::-ms-thumb{transform:scale(.5625);background:radial-gradient(circle closest-side,transparent 0,transparent 77.78%,rgba(0,0,0,.26) 77.78%,rgba(0,0,0,.26) 100%)}.mdl-slider.is-upgraded.is-lowest-value::-ms-fill-lower{background:0 0}.mdl-slider.is-upgraded.is-lowest-value::-ms-fill-upper{margin-left:6px}.mdl-slider.is-upgraded.is-lowest-value:active::-ms-fill-upper{margin-left:9px}.mdl-slider.is-upgraded:disabled::-webkit-slider-thumb,.mdl-slider.is-upgraded:disabled:active::-webkit-slider-thumb,.mdl-slider.is-upgraded:disabled:focus::-webkit-slider-thumb{-webkit-transform:scale(.667);transform:scale(.667);background:rgba(0,0,0,.26)}.mdl-slider.is-upgraded:disabled::-moz-range-thumb,.mdl-slider.is-upgraded:disabled:active::-moz-range-thumb,.mdl-slider.is-upgraded:disabled:focus::-moz-range-thumb{transform:scale(.667);background:rgba(0,0,0,.26)}.mdl-slider.is-upgraded:disabled+.mdl-slider__background-flex>.mdl-slider__background-lower{background-color:rgba(0,0,0,.26);left:-6px}.mdl-slider.is-upgraded:disabled+.mdl-slider__background-flex>.mdl-slider__background-upper{left:6px}.mdl-slider.is-upgraded.is-lowest-value:disabled::-webkit-slider-thumb,.mdl-slider.is-upgraded.is-lowest-value:disabled:active::-webkit-slider-thumb,.mdl-slider.is-upgraded.is-lowest-value:disabled:focus::-webkit-slider-thumb{border:3px solid rgba(0,0,0,.26);background:0 0;-webkit-transform:scale(.667);transform:scale(.667)}.mdl-slider.is-upgraded.is-lowest-value:disabled::-moz-range-thumb,.mdl-slider.is-upgraded.is-lowest-value:disabled:active::-moz-range-thumb,.mdl-slider.is-upgraded.is-lowest-value:disabled:focus::-moz-range-thumb{border:3px solid rgba(0,0,0,.26);background:0 0;transform:scale(.667)}.mdl-slider.is-upgraded.is-lowest-value:disabled:active+.mdl-slider__background-flex>.mdl-slider__background-upper{left:6px}.mdl-slider.is-upgraded:disabled::-ms-thumb,.mdl-slider.is-upgraded:disabled:active::-ms-thumb,.mdl-slider.is-upgraded:disabled:focus::-ms-thumb{transform:scale(.25);background:rgba(0,0,0,.26)}.mdl-slider.is-upgraded.is-lowest-value:disabled::-ms-thumb,.mdl-slider.is-upgraded.is-lowest-value:disabled:active::-ms-thumb,.mdl-slider.is-upgraded.is-lowest-value:disabled:focus::-ms-thumb{transform:scale(.25);background:radial-gradient(circle closest-side,transparent 0,transparent 50%,rgba(0,0,0,.26) 50%,rgba(0,0,0,.26) 100%)}.mdl-slider.is-upgraded:disabled::-ms-fill-lower{margin-right:6px;background:linear-gradient(90deg,transparent,transparent 25px,rgba(0,0,0,.26) 25px,rgba(0,0,0,.26) 0)}.mdl-slider.is-upgraded.is-lowest-value:disabled:active::-ms-fill-upper,.mdl-slider.is-upgraded:disabled::-ms-fill-upper{margin-left:6px}.mdl-slider__ie-container{height:18px;overflow:visible;border:none;margin:none;padding:none}.mdl-slider__container{height:18px;position:relative;-webkit-flex-direction:row;-ms-flex-direction:row;flex-direction:row}.mdl-slider__background-flex,.mdl-slider__container{background:0 0;display:-webkit-flex;display:-ms-flexbox;display:flex}.mdl-slider__background-flex{position:absolute;height:2px;width:calc(100% - 52px);top:50%;left:0;margin:0 26px;overflow:hidden;border:0;padding:0;-webkit-transform:translateY(-1px);transform:translateY(-1px)}.mdl-slider__background-lower{background:#3f51b5}.mdl-slider__background-lower,.mdl-slider__background-upper{-webkit-flex:0;-ms-flex:0;flex:0;position:relative;border:0;padding:0}.mdl-slider__background-upper{background:rgba(0,0,0,.26);transition:left .18s cubic-bezier(.4,0,.2,1)}.mdl-snackbar{position:fixed;bottom:0;left:50%;cursor:default;background-color:#323232;z-index:3;display:block;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-justify-content:space-between;-ms-flex-pack:justify;justify-content:space-between;font-family:Roboto,Helvetica,Arial,sans-serif;will-change:transform;-webkit-transform:translateY(80px);transform:translateY(80px);transition:transform .25s cubic-bezier(.4,0,1,1);transition:transform .25s cubic-bezier(.4,0,1,1),-webkit-transform .25s cubic-bezier(.4,0,1,1);pointer-events:none}@media (max-width:479px){.mdl-snackbar{width:100%;left:0;min-height:48px;max-height:80px}}@media (min-width:480px){.mdl-snackbar{min-width:288px;max-width:568px;border-radius:2px;-webkit-transform:translate(-50%,80px);transform:translate(-50%,80px)}}.mdl-snackbar--active{-webkit-transform:translate(0);transform:translate(0);pointer-events:auto;transition:transform .25s cubic-bezier(0,0,.2,1);transition:transform .25s cubic-bezier(0,0,.2,1),-webkit-transform .25s cubic-bezier(0,0,.2,1)}@media (min-width:480px){.mdl-snackbar--active{-webkit-transform:translate(-50%);transform:translate(-50%)}}.mdl-snackbar__text{padding:14px 12px 14px 24px;vertical-align:middle;color:#fff;float:left}.mdl-snackbar__action{background:0 0;border:none;color:#ff4081;float:right;padding:14px 24px 14px 12px;font-family:Roboto,Helvetica,Arial,sans-serif;font-size:14px;font-weight:500;text-transform:uppercase;line-height:1;letter-spacing:0;overflow:hidden;outline:none;opacity:0;pointer-events:none;cursor:pointer;text-decoration:none;text-align:center;-webkit-align-self:center;-ms-flex-item-align:center;align-self:center}.mdl-snackbar__action::-moz-focus-inner{border:0}.mdl-snackbar__action:not([aria-hidden]){opacity:1;pointer-events:auto}.mdl-spinner{display:inline-block;position:relative;width:28px;height:28px}.mdl-spinner:not(.is-upgraded).is-active:after{content:"Loading..."}.mdl-spinner.is-upgraded.is-active{-webkit-animation:mdl-spinner__container-rotate 1.56823529412s linear infinite;animation:mdl-spinner__container-rotate 1.56823529412s linear infinite}@-webkit-keyframes mdl-spinner__container-rotate{to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@keyframes mdl-spinner__container-rotate{to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}.mdl-spinner__layer{position:absolute;width:100%;height:100%;opacity:0}.mdl-spinner__layer-1{border-color:#42a5f5}.mdl-spinner--single-color .mdl-spinner__layer-1{border-color:#3f51b5}.mdl-spinner.is-active .mdl-spinner__layer-1{-webkit-animation:mdl-spinner__fill-unfill-rotate 5332ms cubic-bezier(.4,0,.2,1)infinite both,mdl-spinner__layer-1-fade-in-out 5332ms cubic-bezier(.4,0,.2,1)infinite both;animation:mdl-spinner__fill-unfill-rotate 5332ms cubic-bezier(.4,0,.2,1)infinite both,mdl-spinner__layer-1-fade-in-out 5332ms cubic-bezier(.4,0,.2,1)infinite both}.mdl-spinner__layer-2{border-color:#f44336}.mdl-spinner--single-color .mdl-spinner__layer-2{border-color:#3f51b5}.mdl-spinner.is-active .mdl-spinner__layer-2{-webkit-animation:mdl-spinner__fill-unfill-rotate 5332ms cubic-bezier(.4,0,.2,1)infinite both,mdl-spinner__layer-2-fade-in-out 5332ms cubic-bezier(.4,0,.2,1)infinite both;animation:mdl-spinner__fill-unfill-rotate 5332ms cubic-bezier(.4,0,.2,1)infinite both,mdl-spinner__layer-2-fade-in-out 5332ms cubic-bezier(.4,0,.2,1)infinite both}.mdl-spinner__layer-3{border-color:#fdd835}.mdl-spinner--single-color .mdl-spinner__layer-3{border-color:#3f51b5}.mdl-spinner.is-active .mdl-spinner__layer-3{-webkit-animation:mdl-spinner__fill-unfill-rotate 5332ms cubic-bezier(.4,0,.2,1)infinite both,mdl-spinner__layer-3-fade-in-out 5332ms cubic-bezier(.4,0,.2,1)infinite both;animation:mdl-spinner__fill-unfill-rotate 5332ms cubic-bezier(.4,0,.2,1)infinite both,mdl-spinner__layer-3-fade-in-out 5332ms cubic-bezier(.4,0,.2,1)infinite both}.mdl-spinner__layer-4{border-color:#4caf50}.mdl-spinner--single-color .mdl-spinner__layer-4{border-color:#3f51b5}.mdl-spinner.is-active .mdl-spinner__layer-4{-webkit-animation:mdl-spinner__fill-unfill-rotate 5332ms cubic-bezier(.4,0,.2,1)infinite both,mdl-spinner__layer-4-fade-in-out 5332ms cubic-bezier(.4,0,.2,1)infinite both;animation:mdl-spinner__fill-unfill-rotate 5332ms cubic-bezier(.4,0,.2,1)infinite both,mdl-spinner__layer-4-fade-in-out 5332ms cubic-bezier(.4,0,.2,1)infinite both}@-webkit-keyframes mdl-spinner__fill-unfill-rotate{12.5%{-webkit-transform:rotate(135deg);transform:rotate(135deg)}25%{-webkit-transform:rotate(270deg);transform:rotate(270deg)}37.5%{-webkit-transform:rotate(405deg);transform:rotate(405deg)}50%{-webkit-transform:rotate(540deg);transform:rotate(540deg)}62.5%{-webkit-transform:rotate(675deg);transform:rotate(675deg)}75%{-webkit-transform:rotate(810deg);transform:rotate(810deg)}87.5%{-webkit-transform:rotate(945deg);transform:rotate(945deg)}to{-webkit-transform:rotate(3turn);transform:rotate(3turn)}}@keyframes mdl-spinner__fill-unfill-rotate{12.5%{-webkit-transform:rotate(135deg);transform:rotate(135deg)}25%{-webkit-transform:rotate(270deg);transform:rotate(270deg)}37.5%{-webkit-transform:rotate(405deg);transform:rotate(405deg)}50%{-webkit-transform:rotate(540deg);transform:rotate(540deg)}62.5%{-webkit-transform:rotate(675deg);transform:rotate(675deg)}75%{-webkit-transform:rotate(810deg);transform:rotate(810deg)}87.5%{-webkit-transform:rotate(945deg);transform:rotate(945deg)}to{-webkit-transform:rotate(3turn);transform:rotate(3turn)}}@-webkit-keyframes mdl-spinner__layer-1-fade-in-out{0%,25%{opacity:.99}26%,89%{opacity:0}90%,to{opacity:.99}}@keyframes mdl-spinner__layer-1-fade-in-out{0%,25%{opacity:.99}26%,89%{opacity:0}90%,to{opacity:.99}}@-webkit-keyframes mdl-spinner__layer-2-fade-in-out{0%,15%{opacity:0}25%,50%{opacity:.99}51%{opacity:0}}@keyframes mdl-spinner__layer-2-fade-in-out{0%,15%{opacity:0}25%,50%{opacity:.99}51%{opacity:0}}@-webkit-keyframes mdl-spinner__layer-3-fade-in-out{0%,40%{opacity:0}50%,75%{opacity:.99}76%{opacity:0}}@keyframes mdl-spinner__layer-3-fade-in-out{0%,40%{opacity:0}50%,75%{opacity:.99}76%{opacity:0}}@-webkit-keyframes mdl-spinner__layer-4-fade-in-out{0%,65%{opacity:0}75%,90%{opacity:.99}to{opacity:0}}@keyframes mdl-spinner__layer-4-fade-in-out{0%,65%{opacity:0}75%,90%{opacity:.99}to{opacity:0}}.mdl-spinner__gap-patch{position:absolute;box-sizing:border-box;top:0;left:45%;width:10%;height:100%;overflow:hidden;border-color:inherit}.mdl-spinner__gap-patch .mdl-spinner__circle{width:1000%;left:-450%}.mdl-spinner__circle-clipper{display:inline-block;position:relative;width:50%;height:100%;overflow:hidden;border-color:inherit}.mdl-spinner__circle-clipper .mdl-spinner__circle{width:200%}.mdl-spinner__circle{box-sizing:border-box;height:100%;border-width:3px;border-style:solid;border-color:inherit;border-bottom-color:transparent!important;border-radius:50%;-webkit-animation:none;animation:none;position:absolute;top:0;right:0;bottom:0;left:0}.mdl-spinner__left .mdl-spinner__circle{border-right-color:transparent!important;-webkit-transform:rotate(129deg);transform:rotate(129deg)}.mdl-spinner.is-active .mdl-spinner__left .mdl-spinner__circle{-webkit-animation:mdl-spinner__left-spin 1333ms cubic-bezier(.4,0,.2,1)infinite both;animation:mdl-spinner__left-spin 1333ms cubic-bezier(.4,0,.2,1)infinite both}.mdl-spinner__right .mdl-spinner__circle{left:-100%;border-left-color:transparent!important;-webkit-transform:rotate(-129deg);transform:rotate(-129deg)}.mdl-spinner.is-active .mdl-spinner__right .mdl-spinner__circle{-webkit-animation:mdl-spinner__right-spin 1333ms cubic-bezier(.4,0,.2,1)infinite both;animation:mdl-spinner__right-spin 1333ms cubic-bezier(.4,0,.2,1)infinite both}@-webkit-keyframes mdl-spinner__left-spin{0%{-webkit-transform:rotate(130deg);transform:rotate(130deg)}50%{-webkit-transform:rotate(-5deg);transform:rotate(-5deg)}to{-webkit-transform:rotate(130deg);transform:rotate(130deg)}}@keyframes mdl-spinner__left-spin{0%{-webkit-transform:rotate(130deg);transform:rotate(130deg)}50%{-webkit-transform:rotate(-5deg);transform:rotate(-5deg)}to{-webkit-transform:rotate(130deg);transform:rotate(130deg)}}@-webkit-keyframes mdl-spinner__right-spin{0%{-webkit-transform:rotate(-130deg);transform:rotate(-130deg)}50%{-webkit-transform:rotate(5deg);transform:rotate(5deg)}to{-webkit-transform:rotate(-130deg);transform:rotate(-130deg)}}@keyframes mdl-spinner__right-spin{0%{-webkit-transform:rotate(-130deg);transform:rotate(-130deg)}50%{-webkit-transform:rotate(5deg);transform:rotate(5deg)}to{-webkit-transform:rotate(-130deg);transform:rotate(-130deg)}}.mdl-switch{position:relative;z-index:1;vertical-align:middle;display:inline-block;box-sizing:border-box;width:100%;height:24px;margin:0;padding:0;overflow:visible;-webkit-touch-callout:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.mdl-switch.is-upgraded{padding-left:28px}.mdl-switch__input{line-height:24px}.mdl-switch.is-upgraded .mdl-switch__input{position:absolute;width:0;height:0;margin:0;padding:0;opacity:0;-ms-appearance:none;-moz-appearance:none;-webkit-appearance:none;appearance:none;border:none}.mdl-switch__track{background:rgba(0,0,0,.26);position:absolute;left:0;top:5px;height:14px;width:36px;border-radius:14px;cursor:pointer}.mdl-switch.is-checked .mdl-switch__track{background:rgba(63,81,181,.5)}.mdl-switch.is-disabled .mdl-switch__track,.mdl-switch__track fieldset[disabled] .mdl-switch{background:rgba(0,0,0,.12);cursor:auto}.mdl-switch__thumb{background:#fafafa;position:absolute;left:0;top:2px;height:20px;width:20px;border-radius:50%;cursor:pointer;box-shadow:0 2px 2px 0 rgba(0,0,0,.14),0 3px 1px -2px rgba(0,0,0,.2),0 1px 5px 0 rgba(0,0,0,.12);transition-duration:.28s;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-property:left}.mdl-switch.is-checked .mdl-switch__thumb{background:#3f51b5;left:16px;box-shadow:0 3px 4px 0 rgba(0,0,0,.14),0 3px 3px -2px rgba(0,0,0,.2),0 1px 8px 0 rgba(0,0,0,.12)}.mdl-switch.is-disabled .mdl-switch__thumb,.mdl-switch__thumb fieldset[disabled] .mdl-switch{background:#bdbdbd;cursor:auto}.mdl-switch__focus-helper{position:absolute;top:50%;left:50%;-webkit-transform:translate(-4px,-4px);transform:translate(-4px,-4px);display:inline-block;box-sizing:border-box;width:8px;height:8px;border-radius:50%;background-color:transparent}.mdl-switch.is-focused .mdl-switch__focus-helper{box-shadow:0 0 0 20px rgba(0,0,0,.1);background-color:rgba(0,0,0,.1)}.mdl-switch.is-focused.is-checked .mdl-switch__focus-helper{box-shadow:0 0 0 20px rgba(63,81,181,.26);background-color:rgba(63,81,181,.26)}.mdl-switch__label{position:relative;cursor:pointer;font-size:16px;line-height:24px;margin:0;left:24px}.mdl-switch.is-disabled .mdl-switch__label,.mdl-switch__label fieldset[disabled] .mdl-switch{color:#bdbdbd;cursor:auto}.mdl-switch__ripple-container{position:absolute;z-index:2;top:-12px;left:-14px;box-sizing:border-box;width:48px;height:48px;border-radius:50%;cursor:pointer;overflow:hidden;-webkit-mask-image:-webkit-radial-gradient(circle,#fff,#000);transition-duration:.4s;transition-timing-function:step-end;transition-property:left}.mdl-switch__ripple-container .mdl-ripple{background:#3f51b5}.mdl-switch.is-disabled .mdl-switch__ripple-container,.mdl-switch__ripple-container fieldset[disabled] .mdl-switch{cursor:auto}.mdl-switch.is-disabled .mdl-switch__ripple-container .mdl-ripple,fieldset[disabled] .mdl-switch .mdl-switch__ripple-container .mdl-ripple{background:0 0}.mdl-switch.is-checked .mdl-switch__ripple-container{left:2px}.mdl-tabs{display:block;width:100%}.mdl-tabs__tab-bar{display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-direction:row;-ms-flex-direction:row;flex-direction:row;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center;-webkit-align-content:space-between;-ms-flex-line-pack:justify;align-content:space-between;-webkit-align-items:flex-start;-ms-flex-align:start;align-items:flex-start;height:48px;padding:0;margin:0;border-bottom:1px solid #e0e0e0}.mdl-tabs__tab{margin:0;border:none;padding:0 24px;float:left;position:relative;display:block;text-decoration:none;height:48px;line-height:48px;text-align:center;font-weight:500;font-size:14px;text-transform:uppercase;color:rgba(0,0,0,.54);overflow:hidden}.mdl-tabs.is-upgraded .mdl-tabs__tab.is-active{color:rgba(0,0,0,.87)}.mdl-tabs.is-upgraded .mdl-tabs__tab.is-active:after{height:2px;width:100%;display:block;content:" ";bottom:0;left:0;position:absolute;background:#3f51b5;-webkit-animation:border-expand .2s cubic-bezier(.4,0,.4,1).01s alternate forwards;animation:border-expand .2s cubic-bezier(.4,0,.4,1).01s alternate forwards;transition:all 1s cubic-bezier(.4,0,1,1)}.mdl-tabs__tab .mdl-tabs__ripple-container{display:block;position:absolute;height:100%;width:100%;left:0;top:0;z-index:1;overflow:hidden}.mdl-tabs__tab .mdl-tabs__ripple-container .mdl-ripple{background:#3f51b5}.mdl-tabs__panel{display:block}.mdl-tabs.is-upgraded .mdl-tabs__panel{display:none}.mdl-tabs.is-upgraded .mdl-tabs__panel.is-active{display:block}@-webkit-keyframes border-expand{0%{opacity:0;width:0}to{opacity:1;width:100%}}@keyframes border-expand{0%{opacity:0;width:0}to{opacity:1;width:100%}}.mdl-textfield{position:relative;font-size:16px;display:inline-block;box-sizing:border-box;width:300px;max-width:100%;margin:0;padding:20px 0}.mdl-textfield .mdl-button{position:absolute;bottom:20px}.mdl-textfield--align-right{text-align:right}.mdl-textfield--full-width{width:100%}.mdl-textfield--expandable{min-width:32px;width:auto;min-height:32px}.mdl-textfield--expandable .mdl-button--icon{top:16px}.mdl-textfield__input{border:none;border-bottom:1px solid rgba(0,0,0,.12);display:block;font-size:16px;font-family:Helvetica,Arial,sans-serif;margin:0;padding:4px 0;width:100%;background:0 0;text-align:left;color:inherit}.mdl-textfield__input[type=number]{-moz-appearance:textfield}.mdl-textfield__input[type=number]::-webkit-inner-spin-button,.mdl-textfield__input[type=number]::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}.mdl-textfield.is-focused .mdl-textfield__input{outline:none}.mdl-textfield.is-invalid .mdl-textfield__input{border-color:#d50000;box-shadow:none}.mdl-textfield.is-disabled .mdl-textfield__input,fieldset[disabled] .mdl-textfield .mdl-textfield__input{background-color:transparent;border-bottom:1px dotted rgba(0,0,0,.12);color:rgba(0,0,0,.26)}.mdl-textfield textarea.mdl-textfield__input{display:block}.mdl-textfield__label{bottom:0;color:rgba(0,0,0,.26);font-size:16px;left:0;right:0;pointer-events:none;position:absolute;display:block;top:24px;width:100%;overflow:hidden;white-space:nowrap;text-align:left}.mdl-textfield.has-placeholder .mdl-textfield__label,.mdl-textfield.is-dirty .mdl-textfield__label{visibility:hidden}.mdl-textfield--floating-label .mdl-textfield__label{transition-duration:.2s;transition-timing-function:cubic-bezier(.4,0,.2,1)}.mdl-textfield--floating-label.has-placeholder .mdl-textfield__label{transition:none}.mdl-textfield.is-disabled.is-disabled .mdl-textfield__label,fieldset[disabled] .mdl-textfield .mdl-textfield__label{color:rgba(0,0,0,.26)}.mdl-textfield--floating-label.has-placeholder .mdl-textfield__label,.mdl-textfield--floating-label.is-dirty .mdl-textfield__label,.mdl-textfield--floating-label.is-focused .mdl-textfield__label{color:#3f51b5;font-size:12px;top:4px;visibility:visible}.mdl-textfield--floating-label.has-placeholder .mdl-textfield__expandable-holder .mdl-textfield__label,.mdl-textfield--floating-label.is-dirty .mdl-textfield__expandable-holder .mdl-textfield__label,.mdl-textfield--floating-label.is-focused .mdl-textfield__expandable-holder .mdl-textfield__label{top:-16px}.mdl-textfield--floating-label.is-invalid .mdl-textfield__label{color:#d50000;font-size:12px}.mdl-textfield__label:after{background-color:#3f51b5;bottom:20px;content:"";height:2px;left:45%;position:absolute;transition-duration:.2s;transition-timing-function:cubic-bezier(.4,0,.2,1);visibility:hidden;width:10px}.mdl-textfield.is-focused .mdl-textfield__label:after{left:0;visibility:visible;width:100%}.mdl-textfield.is-invalid .mdl-textfield__label:after{background-color:#d50000}.mdl-textfield__error{color:#d50000;position:absolute;font-size:12px;margin-top:3px;visibility:hidden;display:block}.mdl-textfield.is-invalid .mdl-textfield__error{visibility:visible}.mdl-textfield__expandable-holder{position:relative;margin-left:32px;transition-duration:.2s;transition-timing-function:cubic-bezier(.4,0,.2,1);display:inline-block;max-width:.1px}.mdl-textfield.is-dirty .mdl-textfield__expandable-holder,.mdl-textfield.is-focused .mdl-textfield__expandable-holder{max-width:600px}.mdl-textfield__expandable-holder .mdl-textfield__label:after{bottom:0}.mdl-tooltip{-webkit-transform:scale(0);transform:scale(0);-webkit-transform-origin:top center;transform-origin:top center;z-index:999;background:rgba(97,97,97,.9);border-radius:2px;color:#fff;display:inline-block;font-size:10px;font-weight:500;line-height:14px;max-width:170px;position:fixed;top:-500px;left:-500px;padding:8px;text-align:center}.mdl-tooltip.is-active{-webkit-animation:pulse .2s cubic-bezier(0,0,.2,1)forwards;animation:pulse .2s cubic-bezier(0,0,.2,1)forwards}.mdl-tooltip--large{line-height:14px;font-size:14px;padding:16px}@-webkit-keyframes pulse{0%{-webkit-transform:scale(0);transform:scale(0);opacity:0}50%{-webkit-transform:scale(.99);transform:scale(.99)}to{-webkit-transform:scale(1);transform:scale(1);opacity:1;visibility:visible}}@keyframes pulse{0%{-webkit-transform:scale(0);transform:scale(0);opacity:0}50%{-webkit-transform:scale(.99);transform:scale(.99)}to{-webkit-transform:scale(1);transform:scale(1);opacity:1;visibility:visible}}.mdl-shadow--2dp{box-shadow:0 2px 2px 0 rgba(0,0,0,.14),0 3px 1px -2px rgba(0,0,0,.2),0 1px 5px 0 rgba(0,0,0,.12)}.mdl-shadow--3dp{box-shadow:0 3px 4px 0 rgba(0,0,0,.14),0 3px 3px -2px rgba(0,0,0,.2),0 1px 8px 0 rgba(0,0,0,.12)}.mdl-shadow--4dp{box-shadow:0 4px 5px 0 rgba(0,0,0,.14),0 1px 10px 0 rgba(0,0,0,.12),0 2px 4px -1px rgba(0,0,0,.2)}.mdl-shadow--6dp{box-shadow:0 6px 10px 0 rgba(0,0,0,.14),0 1px 18px 0 rgba(0,0,0,.12),0 3px 5px -1px rgba(0,0,0,.2)}.mdl-shadow--8dp{box-shadow:0 8px 10px 1px rgba(0,0,0,.14),0 3px 14px 2px rgba(0,0,0,.12),0 5px 5px -3px rgba(0,0,0,.2)}.mdl-shadow--16dp{box-shadow:0 16px 24px 2px rgba(0,0,0,.14),0 6px 30px 5px rgba(0,0,0,.12),0 8px 10px -5px rgba(0,0,0,.2)}.mdl-shadow--24dp{box-shadow:0 9px 46px 8px rgba(0,0,0,.14),0 11px 15px -7px rgba(0,0,0,.12),0 24px 38px 3px rgba(0,0,0,.2)}.mdl-grid{display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-flex-flow:row wrap;-ms-flex-flow:row wrap;flex-flow:row wrap;margin:0 auto;-webkit-align-items:stretch;-ms-flex-align:stretch;align-items:stretch}.mdl-grid.mdl-grid--no-spacing{padding:0}.mdl-cell{box-sizing:border-box}.mdl-cell--top{-webkit-align-self:flex-start;-ms-flex-item-align:start;align-self:flex-start}.mdl-cell--middle{-webkit-align-self:center;-ms-flex-item-align:center;align-self:center}.mdl-cell--bottom{-webkit-align-self:flex-end;-ms-flex-item-align:end;align-self:flex-end}.mdl-cell--stretch{-webkit-align-self:stretch;-ms-flex-item-align:stretch;align-self:stretch}.mdl-grid.mdl-grid--no-spacing>.mdl-cell{margin:0}.mdl-cell--order-1{-webkit-order:1;-ms-flex-order:1;order:1}.mdl-cell--order-2{-webkit-order:2;-ms-flex-order:2;order:2}.mdl-cell--order-3{-webkit-order:3;-ms-flex-order:3;order:3}.mdl-cell--order-4{-webkit-order:4;-ms-flex-order:4;order:4}.mdl-cell--order-5{-webkit-order:5;-ms-flex-order:5;order:5}.mdl-cell--order-6{-webkit-order:6;-ms-flex-order:6;order:6}.mdl-cell--order-7{-webkit-order:7;-ms-flex-order:7;order:7}.mdl-cell--order-8{-webkit-order:8;-ms-flex-order:8;order:8}.mdl-cell--order-9{-webkit-order:9;-ms-flex-order:9;order:9}.mdl-cell--order-10{-webkit-order:10;-ms-flex-order:10;order:10}.mdl-cell--order-11{-webkit-order:11;-ms-flex-order:11;order:11}.mdl-cell--order-12{-webkit-order:12;-ms-flex-order:12;order:12}@media (max-width:479px){.mdl-grid{padding:8px}.mdl-cell{margin:8px;width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell{width:100%}.mdl-cell--hide-phone{display:none!important}.mdl-cell--order-1-phone.mdl-cell--order-1-phone{-webkit-order:1;-ms-flex-order:1;order:1}.mdl-cell--order-2-phone.mdl-cell--order-2-phone{-webkit-order:2;-ms-flex-order:2;order:2}.mdl-cell--order-3-phone.mdl-cell--order-3-phone{-webkit-order:3;-ms-flex-order:3;order:3}.mdl-cell--order-4-phone.mdl-cell--order-4-phone{-webkit-order:4;-ms-flex-order:4;order:4}.mdl-cell--order-5-phone.mdl-cell--order-5-phone{-webkit-order:5;-ms-flex-order:5;order:5}.mdl-cell--order-6-phone.mdl-cell--order-6-phone{-webkit-order:6;-ms-flex-order:6;order:6}.mdl-cell--order-7-phone.mdl-cell--order-7-phone{-webkit-order:7;-ms-flex-order:7;order:7}.mdl-cell--order-8-phone.mdl-cell--order-8-phone{-webkit-order:8;-ms-flex-order:8;order:8}.mdl-cell--order-9-phone.mdl-cell--order-9-phone{-webkit-order:9;-ms-flex-order:9;order:9}.mdl-cell--order-10-phone.mdl-cell--order-10-phone{-webkit-order:10;-ms-flex-order:10;order:10}.mdl-cell--order-11-phone.mdl-cell--order-11-phone{-webkit-order:11;-ms-flex-order:11;order:11}.mdl-cell--order-12-phone.mdl-cell--order-12-phone{-webkit-order:12;-ms-flex-order:12;order:12}.mdl-cell--1-col,.mdl-cell--1-col-phone.mdl-cell--1-col-phone{width:calc(25% - 16px)}.mdl-grid--no-spacing>.mdl-cell--1-col,.mdl-grid--no-spacing>.mdl-cell--1-col-phone.mdl-cell--1-col-phone{width:25%}.mdl-cell--2-col,.mdl-cell--2-col-phone.mdl-cell--2-col-phone{width:calc(50% - 16px)}.mdl-grid--no-spacing>.mdl-cell--2-col,.mdl-grid--no-spacing>.mdl-cell--2-col-phone.mdl-cell--2-col-phone{width:50%}.mdl-cell--3-col,.mdl-cell--3-col-phone.mdl-cell--3-col-phone{width:calc(75% - 16px)}.mdl-grid--no-spacing>.mdl-cell--3-col,.mdl-grid--no-spacing>.mdl-cell--3-col-phone.mdl-cell--3-col-phone{width:75%}.mdl-cell--4-col,.mdl-cell--4-col-phone.mdl-cell--4-col-phone{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--4-col,.mdl-grid--no-spacing>.mdl-cell--4-col-phone.mdl-cell--4-col-phone{width:100%}.mdl-cell--5-col,.mdl-cell--5-col-phone.mdl-cell--5-col-phone{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--5-col,.mdl-grid--no-spacing>.mdl-cell--5-col-phone.mdl-cell--5-col-phone{width:100%}.mdl-cell--6-col,.mdl-cell--6-col-phone.mdl-cell--6-col-phone{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--6-col,.mdl-grid--no-spacing>.mdl-cell--6-col-phone.mdl-cell--6-col-phone{width:100%}.mdl-cell--7-col,.mdl-cell--7-col-phone.mdl-cell--7-col-phone{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--7-col,.mdl-grid--no-spacing>.mdl-cell--7-col-phone.mdl-cell--7-col-phone{width:100%}.mdl-cell--8-col,.mdl-cell--8-col-phone.mdl-cell--8-col-phone{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--8-col,.mdl-grid--no-spacing>.mdl-cell--8-col-phone.mdl-cell--8-col-phone{width:100%}.mdl-cell--9-col,.mdl-cell--9-col-phone.mdl-cell--9-col-phone{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--9-col,.mdl-grid--no-spacing>.mdl-cell--9-col-phone.mdl-cell--9-col-phone{width:100%}.mdl-cell--10-col,.mdl-cell--10-col-phone.mdl-cell--10-col-phone{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--10-col,.mdl-grid--no-spacing>.mdl-cell--10-col-phone.mdl-cell--10-col-phone{width:100%}.mdl-cell--11-col,.mdl-cell--11-col-phone.mdl-cell--11-col-phone{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--11-col,.mdl-grid--no-spacing>.mdl-cell--11-col-phone.mdl-cell--11-col-phone{width:100%}.mdl-cell--12-col,.mdl-cell--12-col-phone.mdl-cell--12-col-phone{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--12-col,.mdl-grid--no-spacing>.mdl-cell--12-col-phone.mdl-cell--12-col-phone{width:100%}.mdl-cell--1-offset,.mdl-cell--1-offset-phone.mdl-cell--1-offset-phone{margin-left:calc(25% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--1-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--1-offset-phone.mdl-cell--1-offset-phone{margin-left:25%}.mdl-cell--2-offset,.mdl-cell--2-offset-phone.mdl-cell--2-offset-phone{margin-left:calc(50% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--2-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--2-offset-phone.mdl-cell--2-offset-phone{margin-left:50%}.mdl-cell--3-offset,.mdl-cell--3-offset-phone.mdl-cell--3-offset-phone{margin-left:calc(75% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--3-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--3-offset-phone.mdl-cell--3-offset-phone{margin-left:75%}}@media (min-width:480px) and (max-width:839px){.mdl-grid{padding:8px}.mdl-cell{margin:8px;width:calc(50% - 16px)}.mdl-grid--no-spacing>.mdl-cell{width:50%}.mdl-cell--hide-tablet{display:none!important}.mdl-cell--order-1-tablet.mdl-cell--order-1-tablet{-webkit-order:1;-ms-flex-order:1;order:1}.mdl-cell--order-2-tablet.mdl-cell--order-2-tablet{-webkit-order:2;-ms-flex-order:2;order:2}.mdl-cell--order-3-tablet.mdl-cell--order-3-tablet{-webkit-order:3;-ms-flex-order:3;order:3}.mdl-cell--order-4-tablet.mdl-cell--order-4-tablet{-webkit-order:4;-ms-flex-order:4;order:4}.mdl-cell--order-5-tablet.mdl-cell--order-5-tablet{-webkit-order:5;-ms-flex-order:5;order:5}.mdl-cell--order-6-tablet.mdl-cell--order-6-tablet{-webkit-order:6;-ms-flex-order:6;order:6}.mdl-cell--order-7-tablet.mdl-cell--order-7-tablet{-webkit-order:7;-ms-flex-order:7;order:7}.mdl-cell--order-8-tablet.mdl-cell--order-8-tablet{-webkit-order:8;-ms-flex-order:8;order:8}.mdl-cell--order-9-tablet.mdl-cell--order-9-tablet{-webkit-order:9;-ms-flex-order:9;order:9}.mdl-cell--order-10-tablet.mdl-cell--order-10-tablet{-webkit-order:10;-ms-flex-order:10;order:10}.mdl-cell--order-11-tablet.mdl-cell--order-11-tablet{-webkit-order:11;-ms-flex-order:11;order:11}.mdl-cell--order-12-tablet.mdl-cell--order-12-tablet{-webkit-order:12;-ms-flex-order:12;order:12}.mdl-cell--1-col,.mdl-cell--1-col-tablet.mdl-cell--1-col-tablet{width:calc(12.5% - 16px)}.mdl-grid--no-spacing>.mdl-cell--1-col,.mdl-grid--no-spacing>.mdl-cell--1-col-tablet.mdl-cell--1-col-tablet{width:12.5%}.mdl-cell--2-col,.mdl-cell--2-col-tablet.mdl-cell--2-col-tablet{width:calc(25% - 16px)}.mdl-grid--no-spacing>.mdl-cell--2-col,.mdl-grid--no-spacing>.mdl-cell--2-col-tablet.mdl-cell--2-col-tablet{width:25%}.mdl-cell--3-col,.mdl-cell--3-col-tablet.mdl-cell--3-col-tablet{width:calc(37.5% - 16px)}.mdl-grid--no-spacing>.mdl-cell--3-col,.mdl-grid--no-spacing>.mdl-cell--3-col-tablet.mdl-cell--3-col-tablet{width:37.5%}.mdl-cell--4-col,.mdl-cell--4-col-tablet.mdl-cell--4-col-tablet{width:calc(50% - 16px)}.mdl-grid--no-spacing>.mdl-cell--4-col,.mdl-grid--no-spacing>.mdl-cell--4-col-tablet.mdl-cell--4-col-tablet{width:50%}.mdl-cell--5-col,.mdl-cell--5-col-tablet.mdl-cell--5-col-tablet{width:calc(62.5% - 16px)}.mdl-grid--no-spacing>.mdl-cell--5-col,.mdl-grid--no-spacing>.mdl-cell--5-col-tablet.mdl-cell--5-col-tablet{width:62.5%}.mdl-cell--6-col,.mdl-cell--6-col-tablet.mdl-cell--6-col-tablet{width:calc(75% - 16px)}.mdl-grid--no-spacing>.mdl-cell--6-col,.mdl-grid--no-spacing>.mdl-cell--6-col-tablet.mdl-cell--6-col-tablet{width:75%}.mdl-cell--7-col,.mdl-cell--7-col-tablet.mdl-cell--7-col-tablet{width:calc(87.5% - 16px)}.mdl-grid--no-spacing>.mdl-cell--7-col,.mdl-grid--no-spacing>.mdl-cell--7-col-tablet.mdl-cell--7-col-tablet{width:87.5%}.mdl-cell--8-col,.mdl-cell--8-col-tablet.mdl-cell--8-col-tablet{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--8-col,.mdl-grid--no-spacing>.mdl-cell--8-col-tablet.mdl-cell--8-col-tablet{width:100%}.mdl-cell--9-col,.mdl-cell--9-col-tablet.mdl-cell--9-col-tablet{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--9-col,.mdl-grid--no-spacing>.mdl-cell--9-col-tablet.mdl-cell--9-col-tablet{width:100%}.mdl-cell--10-col,.mdl-cell--10-col-tablet.mdl-cell--10-col-tablet{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--10-col,.mdl-grid--no-spacing>.mdl-cell--10-col-tablet.mdl-cell--10-col-tablet{width:100%}.mdl-cell--11-col,.mdl-cell--11-col-tablet.mdl-cell--11-col-tablet{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--11-col,.mdl-grid--no-spacing>.mdl-cell--11-col-tablet.mdl-cell--11-col-tablet{width:100%}.mdl-cell--12-col,.mdl-cell--12-col-tablet.mdl-cell--12-col-tablet{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--12-col,.mdl-grid--no-spacing>.mdl-cell--12-col-tablet.mdl-cell--12-col-tablet{width:100%}.mdl-cell--1-offset,.mdl-cell--1-offset-tablet.mdl-cell--1-offset-tablet{margin-left:calc(12.5% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--1-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--1-offset-tablet.mdl-cell--1-offset-tablet{margin-left:12.5%}.mdl-cell--2-offset,.mdl-cell--2-offset-tablet.mdl-cell--2-offset-tablet{margin-left:calc(25% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--2-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--2-offset-tablet.mdl-cell--2-offset-tablet{margin-left:25%}.mdl-cell--3-offset,.mdl-cell--3-offset-tablet.mdl-cell--3-offset-tablet{margin-left:calc(37.5% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--3-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--3-offset-tablet.mdl-cell--3-offset-tablet{margin-left:37.5%}.mdl-cell--4-offset,.mdl-cell--4-offset-tablet.mdl-cell--4-offset-tablet{margin-left:calc(50% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--4-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--4-offset-tablet.mdl-cell--4-offset-tablet{margin-left:50%}.mdl-cell--5-offset,.mdl-cell--5-offset-tablet.mdl-cell--5-offset-tablet{margin-left:calc(62.5% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--5-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--5-offset-tablet.mdl-cell--5-offset-tablet{margin-left:62.5%}.mdl-cell--6-offset,.mdl-cell--6-offset-tablet.mdl-cell--6-offset-tablet{margin-left:calc(75% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--6-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--6-offset-tablet.mdl-cell--6-offset-tablet{margin-left:75%}.mdl-cell--7-offset,.mdl-cell--7-offset-tablet.mdl-cell--7-offset-tablet{margin-left:calc(87.5% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--7-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--7-offset-tablet.mdl-cell--7-offset-tablet{margin-left:87.5%}}@media (min-width:840px){.mdl-grid{padding:8px}.mdl-cell{margin:8px;width:calc(33.3333333333% - 16px)}.mdl-grid--no-spacing>.mdl-cell{width:33.3333333333%}.mdl-cell--hide-desktop{display:none!important}.mdl-cell--order-1-desktop.mdl-cell--order-1-desktop{-webkit-order:1;-ms-flex-order:1;order:1}.mdl-cell--order-2-desktop.mdl-cell--order-2-desktop{-webkit-order:2;-ms-flex-order:2;order:2}.mdl-cell--order-3-desktop.mdl-cell--order-3-desktop{-webkit-order:3;-ms-flex-order:3;order:3}.mdl-cell--order-4-desktop.mdl-cell--order-4-desktop{-webkit-order:4;-ms-flex-order:4;order:4}.mdl-cell--order-5-desktop.mdl-cell--order-5-desktop{-webkit-order:5;-ms-flex-order:5;order:5}.mdl-cell--order-6-desktop.mdl-cell--order-6-desktop{-webkit-order:6;-ms-flex-order:6;order:6}.mdl-cell--order-7-desktop.mdl-cell--order-7-desktop{-webkit-order:7;-ms-flex-order:7;order:7}.mdl-cell--order-8-desktop.mdl-cell--order-8-desktop{-webkit-order:8;-ms-flex-order:8;order:8}.mdl-cell--order-9-desktop.mdl-cell--order-9-desktop{-webkit-order:9;-ms-flex-order:9;order:9}.mdl-cell--order-10-desktop.mdl-cell--order-10-desktop{-webkit-order:10;-ms-flex-order:10;order:10}.mdl-cell--order-11-desktop.mdl-cell--order-11-desktop{-webkit-order:11;-ms-flex-order:11;order:11}.mdl-cell--order-12-desktop.mdl-cell--order-12-desktop{-webkit-order:12;-ms-flex-order:12;order:12}.mdl-cell--1-col,.mdl-cell--1-col-desktop.mdl-cell--1-col-desktop{width:calc(8.3333333333% - 16px)}.mdl-grid--no-spacing>.mdl-cell--1-col,.mdl-grid--no-spacing>.mdl-cell--1-col-desktop.mdl-cell--1-col-desktop{width:8.3333333333%}.mdl-cell--2-col,.mdl-cell--2-col-desktop.mdl-cell--2-col-desktop{width:calc(16.6666666667% - 16px)}.mdl-grid--no-spacing>.mdl-cell--2-col,.mdl-grid--no-spacing>.mdl-cell--2-col-desktop.mdl-cell--2-col-desktop{width:16.6666666667%}.mdl-cell--3-col,.mdl-cell--3-col-desktop.mdl-cell--3-col-desktop{width:calc(25% - 16px)}.mdl-grid--no-spacing>.mdl-cell--3-col,.mdl-grid--no-spacing>.mdl-cell--3-col-desktop.mdl-cell--3-col-desktop{width:25%}.mdl-cell--4-col,.mdl-cell--4-col-desktop.mdl-cell--4-col-desktop{width:calc(33.3333333333% - 16px)}.mdl-grid--no-spacing>.mdl-cell--4-col,.mdl-grid--no-spacing>.mdl-cell--4-col-desktop.mdl-cell--4-col-desktop{width:33.3333333333%}.mdl-cell--5-col,.mdl-cell--5-col-desktop.mdl-cell--5-col-desktop{width:calc(41.6666666667% - 16px)}.mdl-grid--no-spacing>.mdl-cell--5-col,.mdl-grid--no-spacing>.mdl-cell--5-col-desktop.mdl-cell--5-col-desktop{width:41.6666666667%}.mdl-cell--6-col,.mdl-cell--6-col-desktop.mdl-cell--6-col-desktop{width:calc(50% - 16px)}.mdl-grid--no-spacing>.mdl-cell--6-col,.mdl-grid--no-spacing>.mdl-cell--6-col-desktop.mdl-cell--6-col-desktop{width:50%}.mdl-cell--7-col,.mdl-cell--7-col-desktop.mdl-cell--7-col-desktop{width:calc(58.3333333333% - 16px)}.mdl-grid--no-spacing>.mdl-cell--7-col,.mdl-grid--no-spacing>.mdl-cell--7-col-desktop.mdl-cell--7-col-desktop{width:58.3333333333%}.mdl-cell--8-col,.mdl-cell--8-col-desktop.mdl-cell--8-col-desktop{width:calc(66.6666666667% - 16px)}.mdl-grid--no-spacing>.mdl-cell--8-col,.mdl-grid--no-spacing>.mdl-cell--8-col-desktop.mdl-cell--8-col-desktop{width:66.6666666667%}.mdl-cell--9-col,.mdl-cell--9-col-desktop.mdl-cell--9-col-desktop{width:calc(75% - 16px)}.mdl-grid--no-spacing>.mdl-cell--9-col,.mdl-grid--no-spacing>.mdl-cell--9-col-desktop.mdl-cell--9-col-desktop{width:75%}.mdl-cell--10-col,.mdl-cell--10-col-desktop.mdl-cell--10-col-desktop{width:calc(83.3333333333% - 16px)}.mdl-grid--no-spacing>.mdl-cell--10-col,.mdl-grid--no-spacing>.mdl-cell--10-col-desktop.mdl-cell--10-col-desktop{width:83.3333333333%}.mdl-cell--11-col,.mdl-cell--11-col-desktop.mdl-cell--11-col-desktop{width:calc(91.6666666667% - 16px)}.mdl-grid--no-spacing>.mdl-cell--11-col,.mdl-grid--no-spacing>.mdl-cell--11-col-desktop.mdl-cell--11-col-desktop{width:91.6666666667%}.mdl-cell--12-col,.mdl-cell--12-col-desktop.mdl-cell--12-col-desktop{width:calc(100% - 16px)}.mdl-grid--no-spacing>.mdl-cell--12-col,.mdl-grid--no-spacing>.mdl-cell--12-col-desktop.mdl-cell--12-col-desktop{width:100%}.mdl-cell--1-offset,.mdl-cell--1-offset-desktop.mdl-cell--1-offset-desktop{margin-left:calc(8.3333333333% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--1-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--1-offset-desktop.mdl-cell--1-offset-desktop{margin-left:8.3333333333%}.mdl-cell--2-offset,.mdl-cell--2-offset-desktop.mdl-cell--2-offset-desktop{margin-left:calc(16.6666666667% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--2-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--2-offset-desktop.mdl-cell--2-offset-desktop{margin-left:16.6666666667%}.mdl-cell--3-offset,.mdl-cell--3-offset-desktop.mdl-cell--3-offset-desktop{margin-left:calc(25% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--3-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--3-offset-desktop.mdl-cell--3-offset-desktop{margin-left:25%}.mdl-cell--4-offset,.mdl-cell--4-offset-desktop.mdl-cell--4-offset-desktop{margin-left:calc(33.3333333333% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--4-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--4-offset-desktop.mdl-cell--4-offset-desktop{margin-left:33.3333333333%}.mdl-cell--5-offset,.mdl-cell--5-offset-desktop.mdl-cell--5-offset-desktop{margin-left:calc(41.6666666667% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--5-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--5-offset-desktop.mdl-cell--5-offset-desktop{margin-left:41.6666666667%}.mdl-cell--6-offset,.mdl-cell--6-offset-desktop.mdl-cell--6-offset-desktop{margin-left:calc(50% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--6-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--6-offset-desktop.mdl-cell--6-offset-desktop{margin-left:50%}.mdl-cell--7-offset,.mdl-cell--7-offset-desktop.mdl-cell--7-offset-desktop{margin-left:calc(58.3333333333% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--7-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--7-offset-desktop.mdl-cell--7-offset-desktop{margin-left:58.3333333333%}.mdl-cell--8-offset,.mdl-cell--8-offset-desktop.mdl-cell--8-offset-desktop{margin-left:calc(66.6666666667% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--8-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--8-offset-desktop.mdl-cell--8-offset-desktop{margin-left:66.6666666667%}.mdl-cell--9-offset,.mdl-cell--9-offset-desktop.mdl-cell--9-offset-desktop{margin-left:calc(75% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--9-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--9-offset-desktop.mdl-cell--9-offset-desktop{margin-left:75%}.mdl-cell--10-offset,.mdl-cell--10-offset-desktop.mdl-cell--10-offset-desktop{margin-left:calc(83.3333333333% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--10-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--10-offset-desktop.mdl-cell--10-offset-desktop{margin-left:83.3333333333%}.mdl-cell--11-offset,.mdl-cell--11-offset-desktop.mdl-cell--11-offset-desktop{margin-left:calc(91.6666666667% + 8px)}.mdl-grid.mdl-grid--no-spacing>.mdl-cell--11-offset,.mdl-grid.mdl-grid--no-spacing>.mdl-cell--11-offset-desktop.mdl-cell--11-offset-desktop{margin-left:91.6666666667%}}',""])},function(e,t,n){t=e.exports=n(55)(void 0),t.push([e.i,'.ReactTable{position:relative;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;border:1px solid rgba(0,0,0,.1)}.ReactTable *{box-sizing:border-box}.ReactTable .rt-table{-ms-flex:1;flex:1;-ms-flex-direction:column;flex-direction:column;-webkit-box-align:stretch;-ms-flex-align:stretch;align-items:stretch;width:100%;border-collapse:collapse;overflow:auto}.ReactTable .rt-table,.ReactTable .rt-thead{-webkit-box-flex:1;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal}.ReactTable .rt-thead{-ms-flex:1 0 auto;flex:1 0 auto;-ms-flex-direction:column;flex-direction:column;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.ReactTable .rt-thead.-headerGroups{background:rgba(0,0,0,.03)}.ReactTable .rt-thead.-filters,.ReactTable .rt-thead.-headerGroups{border-bottom:1px solid rgba(0,0,0,.05)}.ReactTable .rt-thead.-filters .rt-th{border-right:1px solid rgba(0,0,0,.02)}.ReactTable .rt-thead.-header{box-shadow:0 2px 15px 0 rgba(0,0,0,.15)}.ReactTable .rt-thead .rt-tr{text-align:center}.ReactTable .rt-thead .rt-td,.ReactTable .rt-thead .rt-th{padding:5px;line-height:normal;position:relative;border-right:1px solid rgba(0,0,0,.05);-webkit-transition:box-shadow .3s cubic-bezier(.175,.885,.32,1.275);transition:box-shadow .3s cubic-bezier(.175,.885,.32,1.275);box-shadow:inset 0 0 0 0 transparent}.ReactTable .rt-thead .rt-td.-sort-asc,.ReactTable .rt-thead .rt-th.-sort-asc{box-shadow:inset 0 3px 0 0 rgba(0,0,0,.6)}.ReactTable .rt-thead .rt-td.-sort-desc,.ReactTable .rt-thead .rt-th.-sort-desc{box-shadow:inset 0 -3px 0 0 rgba(0,0,0,.6)}.ReactTable .rt-thead .rt-td.-cursor-pointer,.ReactTable .rt-thead .rt-th.-cursor-pointer{cursor:pointer}.ReactTable .rt-thead .rt-td:last-child,.ReactTable .rt-thead .rt-th:last-child{border-right:0}.ReactTable .rt-thead .rt-resizable-header{overflow:visible}.ReactTable .rt-thead .rt-resizable-header:last-child{overflow:hidden}.ReactTable .rt-thead .rt-resizable-header-content{overflow:hidden;text-overflow:ellipsis}.ReactTable .rt-thead .rt-header-pivot{border-right-color:#f7f7f7}.ReactTable .rt-thead .rt-header-pivot:after,.ReactTable .rt-thead .rt-header-pivot:before{left:100%;top:50%;border:solid transparent;content:" ";height:0;width:0;position:absolute;pointer-events:none}.ReactTable .rt-thead .rt-header-pivot:after{border-color:hsla(0,0%,100%,0);border-left-color:#fff;border-width:8px;margin-top:-8px}.ReactTable .rt-thead .rt-header-pivot:before{border-color:hsla(0,0%,40%,0);border-left-color:#f7f7f7;border-width:10px;margin-top:-10px}.ReactTable .rt-tbody{-webkit-box-flex:99999;-ms-flex:99999 1 auto;flex:99999 1 auto;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;overflow:auto}.ReactTable .rt-tbody .rt-tr-group{border-bottom:1px solid rgba(0,0,0,.05)}.ReactTable .rt-tbody .rt-tr-group:last-child{border-bottom:0}.ReactTable .rt-tbody .rt-td{border-right:1px solid rgba(0,0,0,.02)}.ReactTable .rt-tbody .rt-td:last-child{border-right:0}.ReactTable .rt-tbody .rt-expandable{cursor:pointer}.ReactTable .rt-tr-group{-webkit-box-flex:1;-ms-flex:1 0 auto;flex:1 0 auto;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;-webkit-box-align:stretch;-ms-flex-align:stretch;align-items:stretch}.ReactTable .rt-tr{-webkit-box-flex:1;-ms-flex:1 0 auto;flex:1 0 auto;display:-webkit-inline-box;display:-ms-inline-flexbox;display:inline-flex}.ReactTable .rt-td,.ReactTable .rt-th{-webkit-box-flex:1;-ms-flex:1 0 0px;flex:1 0 0;white-space:nowrap;text-overflow:ellipsis;padding:7px 5px;overflow:hidden;-webkit-transition:.3s ease;transition:.3s ease;-webkit-transition-property:width,min-width,padding,opacity;transition-property:width,min-width,padding,opacity}.ReactTable .rt-td.-hidden,.ReactTable .rt-th.-hidden{width:0!important;min-width:0!important;padding:0!important;border:0!important;opacity:0!important}.ReactTable .rt-expander{display:inline-block;position:relative;margin:0;color:transparent;margin:0 10px}.ReactTable .rt-expander:after{content:"";position:absolute;width:0;height:0;top:50%;left:50%;-webkit-transform:translate(-50%,-50%) rotate(-90deg);transform:translate(-50%,-50%) rotate(-90deg);border-left:5.04px solid transparent;border-right:5.04px solid transparent;border-top:7px solid rgba(0,0,0,.8);-webkit-transition:all .3s cubic-bezier(.175,.885,.32,1.275);transition:all .3s cubic-bezier(.175,.885,.32,1.275);cursor:pointer}.ReactTable .rt-expander.-open:after{-webkit-transform:translate(-50%,-50%) rotate(0);transform:translate(-50%,-50%) rotate(0)}.ReactTable .rt-resizer{display:inline-block;position:absolute;width:36px;top:0;bottom:0;right:-18px;cursor:col-resize;z-index:10}.ReactTable .rt-tfoot{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;box-shadow:0 0 15px 0 rgba(0,0,0,.15)}.ReactTable .rt-tfoot .rt-td{border-right:1px solid rgba(0,0,0,.05)}.ReactTable .rt-tfoot .rt-td:last-child{border-right:0}.ReactTable.-striped .rt-tr.-odd{background:rgba(0,0,0,.03)}.ReactTable.-highlight .rt-tbody .rt-tr:not(.-padRow):hover{background:rgba(0,0,0,.05)}.ReactTable .-pagination{z-index:1;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-pack:justify;-ms-flex-pack:justify;justify-content:space-between;-webkit-box-align:stretch;-ms-flex-align:stretch;align-items:stretch;-ms-flex-wrap:wrap;flex-wrap:wrap;padding:3px;box-shadow:0 0 15px 0 rgba(0,0,0,.1);border-top:2px solid rgba(0,0,0,.1)}.ReactTable .-pagination .-btn{-webkit-appearance:none;-moz-appearance:none;appearance:none;display:block;width:100%;height:100%;border:0;border-radius:3px;padding:6px;font-size:1em;color:rgba(0,0,0,.6);background:rgba(0,0,0,.1);-webkit-transition:all .1s ease;transition:all .1s ease;cursor:pointer;outline:none}.ReactTable .-pagination .-btn[disabled]{opacity:.5;cursor:default}.ReactTable .-pagination .-btn:not([disabled]):hover{background:rgba(0,0,0,.3);color:#fff}.ReactTable .-pagination .-next,.ReactTable .-pagination .-previous{-webkit-box-flex:1;-ms-flex:1;flex:1;text-align:center}.ReactTable .-pagination .-center{-webkit-box-flex:1.5;-ms-flex:1.5;flex:1.5;text-align:center;margin-bottom:0;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-ms-flex-direction:row;flex-direction:row;-ms-flex-wrap:wrap;flex-wrap:wrap;-webkit-box-align:center;-ms-flex-align:center;align-items:center;-ms-flex-pack:distribute;justify-content:space-around}.ReactTable .-pagination .-pageInfo{display:inline-block;margin:3px 10px;white-space:nowrap}.ReactTable .-pagination .-pageJump{display:inline-block}.ReactTable .-pagination .-pageJump input{width:70px;text-align:center}.ReactTable .-pagination .-pageSizeOptions{margin:3px 10px}.ReactTable .rt-noData{left:50%;top:50%;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%);z-index:1;padding:20px;color:rgba(0,0,0,.5)}.ReactTable .-loading,.ReactTable .rt-noData{display:block;position:absolute;background:hsla(0,0%,100%,.8);-webkit-transition:all .3s ease;transition:all .3s ease;pointer-events:none}.ReactTable .-loading{left:0;right:0;top:0;bottom:0;z-index:2;opacity:0}.ReactTable .-loading>div{position:absolute;display:block;text-align:center;width:100%;top:50%;left:0;font-size:15px;color:rgba(0,0,0,.6);-webkit-transform:translateY(-52%);transform:translateY(-52%);-webkit-transition:all .3s cubic-bezier(.25,.46,.45,.94);transition:all .3s cubic-bezier(.25,.46,.45,.94)}.ReactTable .-loading.-active{opacity:1;pointer-events:all}.ReactTable .-loading.-active>div{-webkit-transform:translateY(50%);transform:translateY(50%)}.ReactTable input,.ReactTable select{border:1px solid rgba(0,0,0,.1);background:#fff;padding:5px 7px;font-size:inherit;border-radius:3px;font-weight:400;outline:none}.ReactTable input:not([type=checkbox]):not([type=radio]),.ReactTable select{-webkit-appearance:none;-moz-appearance:none;appearance:none}.ReactTable input:not([type=checkbox]):not([type=radio])::-ms-expand,.ReactTable select::-ms-expand{display:none}.ReactTable .select-wrap{position:relative;display:inline-block}.ReactTable .select-wrap select{padding:5px 15px 5px 7px;min-width:100px}.ReactTable .select-wrap:after{content:"";position:absolute;right:8px;top:50%;-webkit-transform:translateY(-50%);transform:translateY(-50%);border-color:#999 transparent transparent;border-style:solid;border-width:5px 5px 2.5px}.ReactTable .rt-resizing .rt-td,.ReactTable .rt-resizing .rt-th{-webkit-transition:none!important;transition:none!important;cursor:col-resize;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}',""])},function(e,t,n){t=e.exports=n(55)(!1),t.push([e.i,"._10Ae{padding:40px}._3n1K{color:#fff;text-decoration:none}@media screen and (max-width:1024px){.TXe9{display:-webkit-box;display:-ms-flexbox;display:flex}._10Ae{padding:0 16px}}",""]),t.locals={row:"_10Ae",title:"_3n1K",header:"TXe9"}},function(e,t,n){t=e.exports=n(55)(!1),t.push([e.i,".aS3A{margin:0 auto;max-width:1000px;width:100%}",""]),t.locals={content:"aS3A"}},function(e,t,n){t=e.exports=n(55)(!1),t.push([e.i,".aq1X:empty:not(:focus):before{content:attr(data-ph);color:grey}._2k6k{white-space:normal}",""]),t.locals={editableCell:"aq1X",tableCell:"_2k6k"}},function(e,t,n){t=e.exports=n(55)(!1),t.push([e.i,".wxGp{position:absolute;top:0;left:0;display:-webkit-box;display:-ms-flexbox;display:flex;width:100%;height:100%;text-align:center;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center;-webkit-box-align:center;-ms-flex-align:center;align-items:center}._2f78{padding-bottom:80px}._2cJo{margin:0;font-weight:300;font-size:15em;line-height:1}._2cJo,.mOfQ{color:#607d8b;letter-spacing:.02em}.mOfQ{padding-bottom:.5em;font-weight:400;font-size:2em;font-family:Roboto,Helvetica,Arial,sans-serif;line-height:1em}._27M2{padding-bottom:0;color:rgba(96,125,139,.5);font-size:1.125em;line-height:1.5em}@media only screen and (max-width:280px){._27M2,.wxGp{width:95%}.mOfQ{margin:0 0 .3em;font-size:1.5em}}@media screen and (max-width:1024px){._2f78{padding:0 16px}._2cJo{font-size:10em}.mOfQ{font-size:1.5em}}",""]),t.locals={container:"wxGp",content:"_2f78",code:"_2cJo",title:"mOfQ",text:"_27M2"}},function(e,t,n){t=e.exports=n(55)(!1),t.push([e.i,"@media screen and (max-width:1024px){._38pY{padding:0 16px}}",""]),t.locals={content:"_38pY"}},function(e,t,n){var r;!function(){"use strict";/**
* @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
*
* @codingstandard ftlabs-jsv2
* @copyright The Financial Times Limited [All Rights Reserved]
* @license MIT License (see LICENSE.txt)
*/
function o(e,t){function n(e,t){return function(){return e.apply(t,arguments)}}var r;if(t=t||{},this.trackingClick=!1,this.trackingClickStart=0,this.targetElement=null,this.touchStartX=0,this.touchStartY=0,this.lastTouchIdentifier=0,this.touchBoundary=t.touchBoundary||10,this.layer=e,this.tapDelay=t.tapDelay||200,this.tapTimeout=t.tapTimeout||700,!o.notNeeded(e)){for(var i=["onMouse","onClick","onTouchStart","onTouchMove","onTouchEnd","onTouchCancel"],l=this,s=0,c=i.length;s<c;s++)l[i[s]]=n(l[i[s]],l);a&&(e.addEventListener("mouseover",this.onMouse,!0),e.addEventListener("mousedown",this.onMouse,!0),e.addEventListener("mouseup",this.onMouse,!0)),e.addEventListener("click",this.onClick,!0),e.addEventListener("touchstart",this.onTouchStart,!1),e.addEventListener("touchmove",this.onTouchMove,!1),e.addEventListener("touchend",this.onTouchEnd,!1),e.addEventListener("touchcancel",this.onTouchCancel,!1),Event.prototype.stopImmediatePropagation||(e.removeEventListener=function(t,n,r){var o=Node.prototype.removeEventListener;"click"===t?o.call(e,t,n.hijacked||n,r):o.call(e,t,n,r)},e.addEventListener=function(t,n,r){var o=Node.prototype.addEventListener;"click"===t?o.call(e,t,n.hijacked||(n.hijacked=function(e){e.propagationStopped||n(e)}),r):o.call(e,t,n,r)}),"function"==typeof e.onclick&&(r=e.onclick,e.addEventListener("click",function(e){r(e)},!1),e.onclick=null)}}var i=navigator.userAgent.indexOf("Windows Phone")>=0,a=navigator.userAgent.indexOf("Android")>0&&!i,l=/iP(ad|hone|od)/.test(navigator.userAgent)&&!i,s=l&&/OS 4_\d(_\d)?/.test(navigator.userAgent),c=l&&/OS [6-7]_\d/.test(navigator.userAgent),u=navigator.userAgent.indexOf("BB10")>0;o.prototype.needsClick=function(e){switch(e.nodeName.toLowerCase()){case"button":case"select":case"textarea":if(e.disabled)return!0;break;case"input":if(l&&"file"===e.type||e.disabled)return!0;break;case"label":case"iframe":case"video":return!0}return/\bneedsclick\b/.test(e.className)},o.prototype.needsFocus=function(e){switch(e.nodeName.toLowerCase()){case"textarea":return!0;case"select":return!a;case"input":switch(e.type){case"button":case"checkbox":case"file":case"image":case"radio":case"submit":return!1}return!e.disabled&&!e.readOnly;default:return/\bneedsfocus\b/.test(e.className)}},o.prototype.sendClick=function(e,t){var n,r;document.activeElement&&document.activeElement!==e&&document.activeElement.blur(),r=t.changedTouches[0],n=document.createEvent("MouseEvents"),n.initMouseEvent(this.determineEventType(e),!0,!0,window,1,r.screenX,r.screenY,r.clientX,r.clientY,!1,!1,!1,!1,0,null),n.forwardedTouchEvent=!0,e.dispatchEvent(n)},o.prototype.determineEventType=function(e){return a&&"select"===e.tagName.toLowerCase()?"mousedown":"click"},o.prototype.focus=function(e){var t;l&&e.setSelectionRange&&0!==e.type.indexOf("date")&&"time"!==e.type&&"month"!==e.type?(t=e.value.length,e.setSelectionRange(t,t)):e.focus()},o.prototype.updateScrollParent=function(e){var t,n;if(!(t=e.fastClickScrollParent)||!t.contains(e)){n=e;do{if(n.scrollHeight>n.offsetHeight){t=n,e.fastClickScrollParent=n;break}n=n.parentElement}while(n)}t&&(t.fastClickLastScrollTop=t.scrollTop)},o.prototype.getTargetElementFromEventTarget=function(e){return e.nodeType===Node.TEXT_NODE?e.parentNode:e},o.prototype.onTouchStart=function(e){var t,n,r;if(e.targetTouches.length>1)return!0;if(t=this.getTargetElementFromEventTarget(e.target),n=e.targetTouches[0],l){if(r=window.getSelection(),r.rangeCount&&!r.isCollapsed)return!0;if(!s){if(n.identifier&&n.identifier===this.lastTouchIdentifier)return e.preventDefault(),!1;this.lastTouchIdentifier=n.identifier,this.updateScrollParent(t)}}return this.trackingClick=!0,this.trackingClickStart=e.timeStamp,this.targetElement=t,this.touchStartX=n.pageX,this.touchStartY=n.pageY,e.timeStamp-this.lastClickTime<this.tapDelay&&e.preventDefault(),!0},o.prototype.touchHasMoved=function(e){var t=e.changedTouches[0],n=this.touchBoundary;return Math.abs(t.pageX-this.touchStartX)>n||Math.abs(t.pageY-this.touchStartY)>n},o.prototype.onTouchMove=function(e){return!this.trackingClick||((this.targetElement!==this.getTargetElementFromEventTarget(e.target)||this.touchHasMoved(e))&&(this.trackingClick=!1,this.targetElement=null),!0)},o.prototype.findControl=function(e){return void 0!==e.control?e.control:e.htmlFor?document.getElementById(e.htmlFor):e.querySelector("button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea")},o.prototype.onTouchEnd=function(e){var t,n,r,o,i,u=this.targetElement;if(!this.trackingClick)return!0;if(e.timeStamp-this.lastClickTime<this.tapDelay)return this.cancelNextClick=!0,!0;if(e.timeStamp-this.trackingClickStart>this.tapTimeout)return!0;if(this.cancelNextClick=!1,this.lastClickTime=e.timeStamp,n=this.trackingClickStart,this.trackingClick=!1,this.trackingClickStart=0,c&&(i=e.changedTouches[0],u=document.elementFromPoint(i.pageX-window.pageXOffset,i.pageY-window.pageYOffset)||u,u.fastClickScrollParent=this.targetElement.fastClickScrollParent),"label"===(r=u.tagName.toLowerCase())){if(t=this.findControl(u)){if(this.focus(u),a)return!1;u=t}}else if(this.needsFocus(u))return e.timeStamp-n>100||l&&window.top!==window&&"input"===r?(this.targetElement=null,!1):(this.focus(u),this.sendClick(u,e),l&&"select"===r||(this.targetElement=null,e.preventDefault()),!1);return!(!l||s||!(o=u.fastClickScrollParent)||o.fastClickLastScrollTop===o.scrollTop)||(this.needsClick(u)||(e.preventDefault(),this.sendClick(u,e)),!1)},o.prototype.onTouchCancel=function(){this.trackingClick=!1,this.targetElement=null},o.prototype.onMouse=function(e){return!this.targetElement||(!!e.forwardedTouchEvent||(!e.cancelable||(!(!this.needsClick(this.targetElement)||this.cancelNextClick)||(e.stopImmediatePropagation?e.stopImmediatePropagation():e.propagationStopped=!0,e.stopPropagation(),e.preventDefault(),!1))))},o.prototype.onClick=function(e){var t;return this.trackingClick?(this.targetElement=null,this.trackingClick=!1,!0):"submit"===e.target.type&&0===e.detail||(t=this.onMouse(e),t||(this.targetElement=null),t)},o.prototype.destroy=function(){var e=this.layer;a&&(e.removeEventListener("mouseover",this.onMouse,!0),e.removeEventListener("mousedown",this.onMouse,!0),e.removeEventListener("mouseup",this.onMouse,!0)),e.removeEventListener("click",this.onClick,!0),e.removeEventListener("touchstart",this.onTouchStart,!1),e.removeEventListener("touchmove",this.onTouchMove,!1),e.removeEventListener("touchend",this.onTouchEnd,!1),e.removeEventListener("touchcancel",this.onTouchCancel,!1)},o.notNeeded=function(e){var t,n,r;if(void 0===window.ontouchstart)return!0;if(n=+(/Chrome\/([0-9]+)/.exec(navigator.userAgent)||[,0])[1]){if(!a)return!0;if(t=document.querySelector("meta[name=viewport]")){if(t.content.indexOf("user-scalable=no")!==-1)return!0;if(n>31&&document.documentElement.scrollWidth<=window.outerWidth)return!0}}if(u&&(r=navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/),r[1]>=10&&r[2]>=3&&(t=document.querySelector("meta[name=viewport]")))){if(t.content.indexOf("user-scalable=no")!==-1)return!0;if(document.documentElement.scrollWidth<=window.outerWidth)return!0}return"none"===e.style.msTouchAction||"manipulation"===e.style.touchAction||(!!(+(/Firefox\/([0-9]+)/.exec(navigator.userAgent)||[,0])[1]>=27&&(t=document.querySelector("meta[name=viewport]"))&&(t.content.indexOf("user-scalable=no")!==-1||document.documentElement.scrollWidth<=window.outerWidth))||("none"===e.style.touchAction||"manipulation"===e.style.touchAction))},o.attach=function(e,t){return new o(e,t)},void 0!==(r=function(){return o}.call(t,n,t,e))&&(e.exports=r)}()},function(e,t,n){"use strict";function r(e){return e.replace(o,function(e,t){return t.toUpperCase()})}var o=/-(.)/g;e.exports=r},function(e,t,n){"use strict";function r(e){return o(e.replace(i,"ms-"))}var o=n(558),i=/^-ms-/;e.exports=r},function(e,t,n){"use strict";function r(e,t){return!(!e||!t)&&(e===t||!o(e)&&(o(t)?r(e,t.parentNode):"contains"in e?e.contains(t):!!e.compareDocumentPosition&&!!(16&e.compareDocumentPosition(t))))}var o=n(568);e.exports=r},function(e,t,n){"use strict";function r(e){var t=e.length;if((Array.isArray(e)||"object"!=typeof e&&"function"!=typeof e)&&a(!1),"number"!=typeof t&&a(!1),0===t||t-1 in e||a(!1),"function"==typeof e.callee&&a(!1),e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(e){}for(var n=Array(t),r=0;r<t;r++)n[r]=e[r];return n}function o(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"length"in e&&!("setInterval"in e)&&"number"!=typeof e.nodeType&&(Array.isArray(e)||"callee"in e||"item"in e)}function i(e){return o(e)?Array.isArray(e)?e.slice():r(e):[e]}var a=n(1);e.exports=i},function(e,t,n){"use strict";function r(e){var t=e.match(u);return t&&t[1].toLowerCase()}function o(e,t){var n=c;c||s(!1);var o=r(e),i=o&&l(o);if(i){n.innerHTML=i[1]+e+i[2];for(var u=i[0];u--;)n=n.lastChild}else n.innerHTML=e;var d=n.getElementsByTagName("script");d.length&&(t||s(!1),a(d).forEach(t));for(var p=Array.from(n.childNodes);n.lastChild;)n.removeChild(n.lastChild);return p}var i=n(19),a=n(561),l=n(563),s=n(1),c=i.canUseDOM?document.createElement("div"):null,u=/^\s*<(\w+)/;e.exports=o},function(e,t,n){"use strict";function r(e){return a||i(!1),p.hasOwnProperty(e)||(e="*"),l.hasOwnProperty(e)||(a.innerHTML="*"===e?"<link />":"<"+e+"></"+e+">",l[e]=!a.firstChild),l[e]?p[e]:null}var o=n(19),i=n(1),a=o.canUseDOM?document.createElement("div"):null,l={},s=[1,'<select multiple="true">',"</select>"],c=[1,"<table>","</table>"],u=[3,"<table><tbody><tr>","</tr></tbody></table>"],d=[1,'<svg xmlns="http://www.w3.org/2000/svg">',"</svg>"],p={"*":[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:s,option:s,caption:c,colgroup:c,tbody:c,tfoot:c,thead:c,td:u,th:u};["circle","clipPath","defs","ellipse","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","text","tspan"].forEach(function(e){p[e]=d,l[e]=!0}),e.exports=r},function(e,t,n){"use strict";function r(e){return e===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}e.exports=r},function(e,t,n){"use strict";function r(e){return e.replace(o,"-$1").toLowerCase()}var o=/([A-Z])/g;e.exports=r},function(e,t,n){"use strict";function r(e){return o(e).replace(i,"-ms-")}var o=n(565),i=/^ms-/;e.exports=r},function(e,t,n){"use strict";function r(e){return!(!e||!("function"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}e.exports=r},function(e,t,n){"use strict";function r(e){return o(e)&&3==e.nodeType}var o=n(567);e.exports=r},function(e,t,n){"use strict";function r(e){var t={};return function(n){return t.hasOwnProperty(n)||(t[n]=e.call(this,n)),t[n]}}e.exports=r},function(e,t,n){"use strict";t.__esModule=!0;t.canUseDOM=!("undefined"==typeof window||!window.document||!window.document.createElement),t.addEventListener=function(e,t,n){return e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent("on"+t,n)},t.removeEventListener=function(e,t,n){return e.removeEventListener?e.removeEventListener(t,n,!1):e.detachEvent("on"+t,n)},t.getConfirmation=function(e,t){return t(window.confirm(e))},t.supportsHistory=function(){var e=window.navigator.userAgent;return(e.indexOf("Android 2.")===-1&&e.indexOf("Android 4.0")===-1||e.indexOf("Mobile Safari")===-1||e.indexOf("Chrome")!==-1||e.indexOf("Windows Phone")!==-1)&&(window.history&&"pushState"in window.history)},t.supportsPopStateOnHashChange=function(){return window.navigator.userAgent.indexOf("Trident")===-1},t.supportsGoWithoutReloadUsingHash=function(){return window.navigator.userAgent.indexOf("Firefox")===-1},t.isExtraneousPopstateEvent=function(e){return void 0===e.state&&navigator.userAgent.indexOf("CriOS")===-1}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0,t.locationsAreEqual=t.createLocation=void 0;var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(691),a=r(i),l=n(708),s=r(l),c=n(251);t.createLocation=function(e,t,n,r){var i=void 0;return"string"==typeof e?(i=(0,c.parsePath)(e),i.state=t):(i=o({},e),void 0===i.pathname&&(i.pathname=""),i.search?"?"!==i.search.charAt(0)&&(i.search="?"+i.search):i.search="",i.hash?"#"!==i.hash.charAt(0)&&(i.hash="#"+i.hash):i.hash="",void 0!==t&&void 0===i.state&&(i.state=t)),i.key=n,r&&(i.pathname?"/"!==i.pathname.charAt(0)&&(i.pathname=(0,a.default)(i.pathname,r.pathname)):i.pathname=r.pathname),i},t.locationsAreEqual=function(e,t){return e.pathname===t.pathname&&e.search===t.search&&e.hash===t.hash&&e.key===t.key&&(0,s.default)(e.state,t.state)}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(296),l=r(a),s=n(252),c=r(s),u=n(571),d=n(251),p=n(573),f=r(p),m=n(570),h="popstate",g="hashchange",b=function(){try{return window.history.state||{}}catch(e){return{}}},y=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(0,c.default)(m.canUseDOM,"Browser history needs a DOM");var t=window.history,n=(0,m.supportsHistory)(),r=!(0,m.supportsPopStateOnHashChange)(),a=e.forceRefresh,s=void 0!==a&&a,p=e.getUserConfirmation,y=void 0===p?m.getConfirmation:p,v=e.keyLength,_=void 0===v?6:v,x=e.basename?(0,d.stripTrailingSlash)((0,d.addLeadingSlash)(e.basename)):"",w=function(e){var t=e||{},n=t.key,r=t.state,o=window.location,a=o.pathname,l=o.search,s=o.hash,c=a+l+s;return x&&(c=(0,d.stripPrefix)(c,x)),i({},(0,d.parsePath)(c),{state:r,key:n})},C=function(){return Math.random().toString(36).substr(2,_)},k=(0,f.default)(),E=function(e){i(V,e),V.length=t.length,k.notifyListeners(V.location,V.action)},A=function(e){(0,m.isExtraneousPopstateEvent)(e)||T(w(e.state))},S=function(){T(w(b()))},I=!1,T=function(e){if(I)I=!1,E();else{var t="POP";k.confirmTransitionTo(e,t,y,function(n){n?E({action:t,location:e}):P(e)})}},P=function(e){var t=V.location,n=M.indexOf(t.key);n===-1&&(n=0);var r=M.indexOf(e.key);r===-1&&(r=0);var o=n-r;o&&(I=!0,D(o))},O=w(b()),M=[O.key],R=function(e){return x+(0,d.createPath)(e)},N=function(e,r){(0,l.default)(!("object"===(void 0===e?"undefined":o(e))&&void 0!==e.state&&void 0!==r),"You should avoid providing a 2nd state argument to push when the 1st argument is a location-like object that already has state; it is ignored");var i="PUSH",a=(0,u.createLocation)(e,r,C(),V.location);k.confirmTransitionTo(a,i,y,function(e){if(e){var r=R(a),o=a.key,c=a.state;if(n)if(t.pushState({key:o,state:c},null,r),s)window.location.href=r;else{var u=M.indexOf(V.location.key),d=M.slice(0,u===-1?0:u+1);d.push(a.key),M=d,E({action:i,location:a})}else(0,l.default)(void 0===c,"Browser history cannot push state in browsers that do not support HTML5 history"),window.location.href=r}})},L=function(e,r){(0,l.default)(!("object"===(void 0===e?"undefined":o(e))&&void 0!==e.state&&void 0!==r),"You should avoid providing a 2nd state argument to replace when the 1st argument is a location-like object that already has state; it is ignored");var i="REPLACE",a=(0,u.createLocation)(e,r,C(),V.location);k.confirmTransitionTo(a,i,y,function(e){if(e){var r=R(a),o=a.key,c=a.state;if(n)if(t.replaceState({key:o,state:c},null,r),s)window.location.replace(r);else{var u=M.indexOf(V.location.key);u!==-1&&(M[u]=a.key),E({action:i,location:a})}else(0,l.default)(void 0===c,"Browser history cannot replace state in browsers that do not support HTML5 history"),window.location.replace(r)}})},D=function(e){t.go(e)},j=function(){return D(-1)},F=function(){return D(1)},z=0,U=function(e){z+=e,1===z?((0,m.addEventListener)(window,h,A),r&&(0,m.addEventListener)(window,g,S)):0===z&&((0,m.removeEventListener)(window,h,A),r&&(0,m.removeEventListener)(window,g,S))},B=!1,H=function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=k.setPrompt(e);return B||(U(1),B=!0),function(){return B&&(B=!1,U(-1)),t()}},W=function(e){var t=k.appendListener(e);return U(1),function(){U(-1),t()}},V={length:t.length,action:"POP",location:O,createHref:R,push:N,replace:L,go:D,goBack:j,goForward:F,block:H,listen:W};return V};t.default=y},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(296),i=r(o),a=function(){var e=null,t=function(t){return(0,i.default)(null==e,"A history supports only one prompt at a time"),e=t,function(){e===t&&(e=null)}},n=function(t,n,r,o){if(null!=e){var a="function"==typeof e?e(t,n):e;"string"==typeof a?"function"==typeof r?r(a,o):((0,i.default)(!1,"A history needs a getUserConfirmation function in order to use a prompt message"),o(!0)):o(a!==!1)}else o(!0)},r=[];return{setPrompt:t,confirmTransitionTo:n,appendListener:function(e){var t=!0,n=function(){t&&e.apply(void 0,arguments)};return r.push(n),function(){t=!1,r=r.filter(function(e){return e!==n})}},notifyListeners:function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];r.forEach(function(e){return e.apply(void 0,t)})}}};t.default=a},function(e,t,n){"use strict";var r={childContextTypes:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,mixins:!0,propTypes:!0,type:!0},o={name:!0,length:!0,prototype:!0,caller:!0,arguments:!0,arity:!0},i="function"==typeof Object.getOwnPropertySymbols;e.exports=function(e,t,n){if("string"!=typeof t){var a=Object.getOwnPropertyNames(t);i&&(a=a.concat(Object.getOwnPropertySymbols(t)));for(var l=0;l<a.length;++l)if(!(r[a[l]]||o[a[l]]||n&&n[a[l]]))try{e[a[l]]=t[a[l]]}catch(e){}}return e}},function(e,t){t.read=function(e,t,n,r,o){var i,a,l=8*o-r-1,s=(1<<l)-1,c=s>>1,u=-7,d=n?o-1:0,p=n?-1:1,f=e[t+d];for(d+=p,i=f&(1<<-u)-1,f>>=-u,u+=l;u>0;i=256*i+e[t+d],d+=p,u-=8);for(a=i&(1<<-u)-1,i>>=-u,u+=r;u>0;a=256*a+e[t+d],d+=p,u-=8);if(0===i)i=1-c;else{if(i===s)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,r),i-=c}return(f?-1:1)*a*Math.pow(2,i-r)},t.write=function(e,t,n,r,o,i){var a,l,s,c=8*i-o-1,u=(1<<c)-1,d=u>>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,f=r?0:i-1,m=r?1:-1,h=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(l=isNaN(t)?1:0,a=u):(a=Math.floor(Math.log(t)/Math.LN2),t*(s=Math.pow(2,-a))<1&&(a--,s*=2),t+=a+d>=1?p/s:p*Math.pow(2,1-d),t*s>=2&&(a++,s/=2),a+d>=u?(l=0,a=u):a+d>=1?(l=(t*s-1)*Math.pow(2,o),a+=d):(l=t*Math.pow(2,d-1)*Math.pow(2,o),a=0));o>=8;e[n+f]=255&l,f+=m,l/=256,o-=8);for(a=a<<o|l,c+=o;c>0;e[n+f]=255&a,f+=m,a/=256,c-=8);e[n+f-m]|=128*h}},function(e,t){var n={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},function(e,t,n){"use strict";function r(e){return Array.prototype.slice.call(arguments,1).forEach(function(t){t&&Object.keys(t).forEach(function(n){e[n]=t[n]})}),e}function o(e){return Object.prototype.toString.call(e)}function i(e){return"[object String]"===o(e)}function a(e){return"[object Object]"===o(e)}function l(e){return"[object RegExp]"===o(e)}function s(e){return"[object Function]"===o(e)}function c(e){return e.replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function u(e){return Object.keys(e||{}).reduce(function(e,t){return e||y.hasOwnProperty(t)},!1)}function d(e){e.__index__=-1,e.__text_cache__=""}function p(e){return function(t,n){var r=t.slice(n);return e.test(r)?r.match(e)[0].length:0}}function f(){return function(e,t){t.normalize(e)}}function m(e){function t(e){return e.replace("%TLDS%",u.src_tlds)}function o(e,t){throw new Error('(LinkifyIt) Invalid schema "'+e+'": '+t)}var u=e.re=r({},n(578)),m=e.__tlds__.slice();e.__tlds_replaced__||m.push(_),m.push(u.src_xn),u.src_tlds=m.join("|"),u.email_fuzzy=RegExp(t(u.tpl_email_fuzzy),"i"),u.link_fuzzy=RegExp(t(u.tpl_link_fuzzy),"i"),u.link_no_ip_fuzzy=RegExp(t(u.tpl_link_no_ip_fuzzy),"i"),u.host_fuzzy_test=RegExp(t(u.tpl_host_fuzzy_test),"i");var h=[];e.__compiled__={},Object.keys(e.__schemas__).forEach(function(t){var n=e.__schemas__[t];if(null!==n){var r={validate:null,link:null};return e.__compiled__[t]=r,a(n)?(l(n.validate)?r.validate=p(n.validate):s(n.validate)?r.validate=n.validate:o(t,n),void(s(n.normalize)?r.normalize=n.normalize:n.normalize?o(t,n):r.normalize=f())):i(n)?void h.push(t):void o(t,n)}}),h.forEach(function(t){e.__compiled__[e.__schemas__[t]]&&(e.__compiled__[t].validate=e.__compiled__[e.__schemas__[t]].validate,e.__compiled__[t].normalize=e.__compiled__[e.__schemas__[t]].normalize)}),e.__compiled__[""]={validate:null,normalize:f()};var g=Object.keys(e.__compiled__).filter(function(t){return t.length>0&&e.__compiled__[t]}).map(c).join("|");e.re.schema_test=RegExp("(^|(?!_)(?:[><]|"+u.src_ZPCc+"))("+g+")","i"),e.re.schema_search=RegExp("(^|(?!_)(?:[><]|"+u.src_ZPCc+"))("+g+")","ig"),e.re.pretest=RegExp("("+e.re.schema_test.source+")|("+e.re.host_fuzzy_test.source+")|@","i"),d(e)}function h(e,t){var n=e.__index__,r=e.__last_index__,o=e.__text_cache__.slice(n,r);this.schema=e.__schema__.toLowerCase(),this.index=n+t,this.lastIndex=r+t,this.raw=o,this.text=o,this.url=o}function g(e,t){var n=new h(e,t);return e.__compiled__[n.schema].normalize(n,e),n}function b(e,t){if(!(this instanceof b))return new b(e,t);t||u(e)&&(t=e,e={}),this.__opts__=r({},y,t),this.__index__=-1,this.__last_index__=-1,this.__schema__="",this.__text_cache__="",this.__schemas__=r({},v,e),this.__compiled__={},this.__tlds__=x,this.__tlds_replaced__=!1,this.re={},m(this)}var y={fuzzyLink:!0,fuzzyEmail:!0,fuzzyIP:!1},v={"http:":{validate:function(e,t,n){var r=e.slice(t);return n.re.http||(n.re.http=new RegExp("^\\/\\/"+n.re.src_auth+n.re.src_host_port_strict+n.re.src_path,"i")),n.re.http.test(r)?r.match(n.re.http)[0].length:0}},"https:":"http:","ftp:":"http:","//":{validate:function(e,t,n){var r=e.slice(t);return n.re.no_http||(n.re.no_http=new RegExp("^"+n.re.src_auth+"(?:localhost|(?:(?:"+n.re.src_domain+")\\.)+"+n.re.src_domain_root+")"+n.re.src_port+n.re.src_host_terminator+n.re.src_path,"i")),n.re.no_http.test(r)?t>=3&&":"===e[t-3]?0:t>=3&&"/"===e[t-3]?0:r.match(n.re.no_http)[0].length:0}},"mailto:":{validate:function(e,t,n){var r=e.slice(t);return n.re.mailto||(n.re.mailto=new RegExp("^"+n.re.src_email_name+"@"+n.re.src_host_strict,"i")),n.re.mailto.test(r)?r.match(n.re.mailto)[0].length:0}}},_="a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]",x="biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф".split("|");b.prototype.add=function(e,t){return this.__schemas__[e]=t,m(this),this},b.prototype.set=function(e){return this.__opts__=r(this.__opts__,e),this},b.prototype.test=function(e){if(this.__text_cache__=e,this.__index__=-1,!e.length)return!1;var t,n,r,o,i,a,l,s;if(this.re.schema_test.test(e))for(l=this.re.schema_search,l.lastIndex=0;null!==(t=l.exec(e));)if(o=this.testSchemaAt(e,t[2],l.lastIndex)){this.__schema__=t[2],this.__index__=t.index+t[1].length,this.__last_index__=t.index+t[0].length+o;break}return this.__opts__.fuzzyLink&&this.__compiled__["http:"]&&(s=e.search(this.re.host_fuzzy_test))>=0&&(this.__index__<0||s<this.__index__)&&null!==(n=e.match(this.__opts__.fuzzyIP?this.re.link_fuzzy:this.re.link_no_ip_fuzzy))&&(i=n.index+n[1].length,(this.__index__<0||i<this.__index__)&&(this.__schema__="",this.__index__=i,this.__last_index__=n.index+n[0].length)),this.__opts__.fuzzyEmail&&this.__compiled__["mailto:"]&&e.indexOf("@")>=0&&null!==(r=e.match(this.re.email_fuzzy))&&(i=r.index+r[1].length,a=r.index+r[0].length,(this.__index__<0||i<this.__index__||i===this.__index__&&a>this.__last_index__)&&(this.__schema__="mailto:",this.__index__=i,this.__last_index__=a)),this.__index__>=0},b.prototype.pretest=function(e){return this.re.pretest.test(e)},b.prototype.testSchemaAt=function(e,t,n){return this.__compiled__[t.toLowerCase()]?this.__compiled__[t.toLowerCase()].validate(e,n,this):0},b.prototype.match=function(e){var t=0,n=[];this.__index__>=0&&this.__text_cache__===e&&(n.push(g(this,t)),t=this.__last_index__);for(var r=t?e.slice(t):e;this.test(r);)n.push(g(this,t)),r=r.slice(this.__last_index__),t+=this.__last_index__;return n.length?n:null},b.prototype.tlds=function(e,t){return e=Array.isArray(e)?e:[e],t?(this.__tlds__=this.__tlds__.concat(e).sort().filter(function(e,t,n){return e!==n[t-1]}).reverse(),m(this),this):(this.__tlds__=e.slice(),this.__tlds_replaced__=!0,m(this),this)},b.prototype.normalize=function(e){e.schema||(e.url="http://"+e.url),"mailto:"!==e.schema||/^mailto:/i.test(e.url)||(e.url="mailto:"+e.url)},e.exports=b},function(e,t,n){"use strict";var r=t.src_Any=n(707).source,o=t.src_Cc=n(704).source,i=t.src_Z=n(706).source,a=t.src_P=n(705).source,l=t.src_ZPCc=[i,a,o].join("|"),s=t.src_ZCc=[i,o].join("|"),c="(?:(?!>|<|"+l+")"+r+")",u=t.src_ip4="(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";t.src_auth="(?:(?:(?!"+s+"|[@/]).)+@)?";var d=t.src_port="(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?",p=t.src_host_terminator="(?=$|>|<|"+l+")(?!-|_|:\\d|\\.-|\\.(?!$|"+l+"))",f=t.src_path="(?:[/?#](?:(?!"+s+"|[()[\\]{}.,\"'?!\\-<>]).|\\[(?:(?!"+s+"|\\]).)*\\]|\\((?:(?!"+s+"|[)]).)*\\)|\\{(?:(?!"+s+'|[}]).)*\\}|\\"(?:(?!'+s+'|["]).)+\\"|\\\'(?:(?!'+s+"|[']).)+\\'|\\'(?="+c+").|\\.{2,3}[a-zA-Z0-9%/]|\\.(?!"+s+"|[.]).|\\-(?!--(?:[^-]|$))(?:-*)|\\,(?!"+s+").|\\!(?!"+s+"|[!]).|\\?(?!"+s+"|[?]).)+|\\/)?",m=t.src_email_name='[\\-;:&=\\+\\$,\\"\\.a-zA-Z0-9_]+',h=t.src_xn="xn--[a-z0-9\\-]{1,59}",g=t.src_domain_root="(?:"+h+"|"+c+"{1,63})",b=t.src_domain="(?:"+h+"|(?:"+c+")|(?:"+c+"(?:-(?!-)|"+c+"){0,61}"+c+"))",y=t.src_host="(?:(?:(?:(?:"+b+")\\.)*"+g+"))",v=t.tpl_host_fuzzy="(?:"+u+"|(?:(?:(?:"+b+")\\.)+(?:%TLDS%)))",_=t.tpl_host_no_ip_fuzzy="(?:(?:(?:"+b+")\\.)+(?:%TLDS%))";t.src_host_strict=y+p;var x=t.tpl_host_fuzzy_strict=v+p;t.src_host_port_strict=y+d+p;var w=t.tpl_host_port_fuzzy_strict=v+d+p,C=t.tpl_host_port_no_ip_fuzzy_strict=_+d+p;t.tpl_host_fuzzy_test="localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:"+l+"|>|$))",t.tpl_email_fuzzy="(^|<|>|\\(|"+s+")("+m+"@"+x+")",t.tpl_link_fuzzy="(^|(?![.:/\\-_@])(?:[$+<=>^`|]|"+l+"))((?![$+<=>^`|])"+w+f+")",t.tpl_link_no_ip_fuzzy="(^|(?![.:/\\-_@])(?:[$+<=>^`|]|"+l+"))((?![$+<=>^`|])"+C+f+")"},function(e,t,n){"use strict";function r(e){return null==e?void 0===e?s:l:c&&c in Object(e)?n.i(i.a)(e):n.i(a.a)(e)}var o=n(253),i=n(582),a=n(583),l="[object Null]",s="[object Undefined]",c=o.a?o.a.toStringTag:void 0;t.a=r},function(e,t,n){"use strict";(function(e){var n="object"==typeof e&&e&&e.Object===Object&&e;t.a=n}).call(t,n(101))},function(e,t,n){"use strict";var r=n(584),o=n.i(r.a)(Object.getPrototypeOf,Object);t.a=o},function(e,t,n){"use strict";function r(e){var t=a.call(e,s),n=e[s];try{e[s]=void 0;var r=!0}catch(e){}var o=l.call(e);return r&&(t?e[s]=n:delete e[s]),o}var o=n(253),i=Object.prototype,a=i.hasOwnProperty,l=i.toString,s=o.a?o.a.toStringTag:void 0;t.a=r},function(e,t,n){"use strict";function r(e){return i.call(e)}var o=Object.prototype,i=o.toString;t.a=r},function(e,t,n){"use strict";function r(e,t){return function(n){return e(t(n))}}t.a=r},function(e,t,n){"use strict";var r=n(580),o="object"==typeof self&&self&&self.Object===Object&&self,i=r.a||o||Function("return this")();t.a=i},function(e,t,n){"use strict";function r(e){return null!=e&&"object"==typeof e}t.a=r},function(e,t,n){"use strict";var r=n(28),o=n(1),i=n(588);e.exports=function(){function e(e,t,n,r,a,l){l!==i&&o(!1,"Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types")}function t(){return e}e.isRequired=e;var n={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t};return n.checkPropTypes=r,n.PropTypes=n,n}},function(e,t,n){"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},function(e,t,n){"use strict";e.exports=n(603)},function(e,t,n){"use strict";var r={Properties:{"aria-current":0,"aria-details":0,"aria-disabled":0,"aria-hidden":0,"aria-invalid":0,"aria-keyshortcuts":0,"aria-label":0,"aria-roledescription":0,"aria-autocomplete":0,"aria-checked":0,"aria-expanded":0,"aria-haspopup":0,"aria-level":0,"aria-modal":0,"aria-multiline":0,"aria-multiselectable":0,"aria-orientation":0,"aria-placeholder":0,"aria-pressed":0,"aria-readonly":0,"aria-required":0,"aria-selected":0,"aria-sort":0,"aria-valuemax":0,"aria-valuemin":0,"aria-valuenow":0,"aria-valuetext":0,"aria-atomic":0,"aria-busy":0,"aria-live":0,"aria-relevant":0,"aria-dropeffect":0,"aria-grabbed":0,"aria-activedescendant":0,"aria-colcount":0,"aria-colindex":0,"aria-colspan":0,"aria-controls":0,"aria-describedby":0,"aria-errormessage":0,"aria-flowto":0,"aria-labelledby":0,"aria-owns":0,"aria-posinset":0,"aria-rowcount":0,"aria-rowindex":0,"aria-rowspan":0,"aria-setsize":0},DOMAttributeNames:{},DOMPropertyNames:{}};e.exports=r},function(e,t,n){"use strict";var r=n(13),o=n(249),i={focusDOMComponent:function(){o(r.getNodeFromInstance(this))}};e.exports=i},function(e,t,n){"use strict";function r(){var e=window.opera;return"object"==typeof e&&"function"==typeof e.version&&parseInt(e.version(),10)<=12}function o(e){return(e.ctrlKey||e.altKey||e.metaKey)&&!(e.ctrlKey&&e.altKey)}function i(e){switch(e){case"topCompositionStart":return A.compositionStart;case"topCompositionEnd":return A.compositionEnd;case"topCompositionUpdate":return A.compositionUpdate}}function a(e,t){return"topKeyDown"===e&&t.keyCode===v}function l(e,t){switch(e){case"topKeyUp":return y.indexOf(t.keyCode)!==-1;case"topKeyDown":return t.keyCode!==v;case"topKeyPress":case"topMouseDown":case"topBlur":return!0;default:return!1}}function s(e){var t=e.detail;return"object"==typeof t&&"data"in t?t.data:null}function c(e,t,n,r){var o,c;if(_?o=i(e):I?l(e,n)&&(o=A.compositionEnd):a(e,n)&&(o=A.compositionStart),!o)return null;C&&(I||o!==A.compositionStart?o===A.compositionEnd&&I&&(c=I.getData()):I=h.getPooled(r));var u=g.getPooled(o,t,n,r);if(c)u.data=c;else{var d=s(n);null!==d&&(u.data=d)}return f.accumulateTwoPhaseDispatches(u),u}function u(e,t){switch(e){case"topCompositionEnd":return s(t);case"topKeyPress":return t.which!==k?null:(S=!0,E);case"topTextInput":var n=t.data;return n===E&&S?null:n;default:return null}}function d(e,t){if(I){if("topCompositionEnd"===e||!_&&l(e,t)){var n=I.getData();return h.release(I),I=null,n}return null}switch(e){case"topPaste":return null;case"topKeyPress":return t.which&&!o(t)?String.fromCharCode(t.which):null;case"topCompositionEnd":return C?null:t.data;default:return null}}function p(e,t,n,r){var o;if(!(o=w?u(e,n):d(e,n)))return null;var i=b.getPooled(A.beforeInput,t,n,r);return i.data=o,f.accumulateTwoPhaseDispatches(i),i}var f=n(97),m=n(19),h=n(598),g=n(632),b=n(635),y=[9,13,27,32],v=229,_=m.canUseDOM&&"CompositionEvent"in window,x=null;m.canUseDOM&&"documentMode"in document&&(x=document.documentMode);var w=m.canUseDOM&&"TextEvent"in window&&!x&&!r(),C=m.canUseDOM&&(!_||x&&x>8&&x<=11),k=32,E=String.fromCharCode(k),A={beforeInput:{phasedRegistrationNames:{bubbled:"onBeforeInput",captured:"onBeforeInputCapture"},dependencies:["topCompositionEnd","topKeyPress","topTextInput","topPaste"]},compositionEnd:{phasedRegistrationNames:{bubbled:"onCompositionEnd",captured:"onCompositionEndCapture"},dependencies:["topBlur","topCompositionEnd","topKeyDown","topKeyPress","topKeyUp","topMouseDown"]},compositionStart:{phasedRegistrationNames:{bubbled:"onCompositionStart",captured:"onCompositionStartCapture"},dependencies:["topBlur","topCompositionStart","topKeyDown","topKeyPress","topKeyUp","topMouseDown"]},compositionUpdate:{phasedRegistrationNames:{bubbled:"onCompositionUpdate",captured:"onCompositionUpdateCapture"},dependencies:["topBlur","topCompositionUpdate","topKeyDown","topKeyPress","topKeyUp","topMouseDown"]}},S=!1,I=null,T={eventTypes:A,extractEvents:function(e,t,n,r){return[c(e,t,n,r),p(e,t,n,r)]}};e.exports=T},function(e,t,n){"use strict";var r=n(255),o=n(19),i=(n(29),n(559),n(641)),a=n(566),l=n(569),s=(n(4),l(function(e){return a(e)})),c=!1,u="cssFloat";if(o.canUseDOM){var d=document.createElement("div").style;try{d.font=""}catch(e){c=!0}void 0===document.documentElement.style.cssFloat&&(u="styleFloat")}var p={createMarkupForStyles:function(e,t){var n="";for(var r in e)if(e.hasOwnProperty(r)){var o=e[r];null!=o&&(n+=s(r)+":",n+=i(r,o,t)+";")}return n||null},setValueForStyles:function(e,t,n){var o=e.style;for(var a in t)if(t.hasOwnProperty(a)){var l=i(a,t[a],n);if("float"!==a&&"cssFloat"!==a||(a=u),l)o[a]=l;else{var s=c&&r.shorthandPropertyExpansions[a];if(s)for(var d in s)o[d]="";else o[a]=""}}}};e.exports=p},function(e,t,n){"use strict";function r(e){var t=e.nodeName&&e.nodeName.toLowerCase();return"select"===t||"input"===t&&"file"===e.type}function o(e){var t=C.getPooled(S.change,T,e,k(e));v.accumulateTwoPhaseDispatches(t),w.batchedUpdates(i,t)}function i(e){y.enqueueEvents(e),y.processEventQueue(!1)}function a(e,t){I=e,T=t,I.attachEvent("onchange",o)}function l(){I&&(I.detachEvent("onchange",o),I=null,T=null)}function s(e,t){if("topChange"===e)return t}function c(e,t,n){"topFocus"===e?(l(),a(t,n)):"topBlur"===e&&l()}function u(e,t){I=e,T=t,P=e.value,O=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(I,"value",N),I.attachEvent?I.attachEvent("onpropertychange",p):I.addEventListener("propertychange",p,!1)}function d(){I&&(delete I.value,I.detachEvent?I.detachEvent("onpropertychange",p):I.removeEventListener("propertychange",p,!1),I=null,T=null,P=null,O=null)}function p(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==P&&(P=t,o(e))}}function f(e,t){if("topInput"===e)return t}function m(e,t,n){"topFocus"===e?(d(),u(t,n)):"topBlur"===e&&d()}function h(e,t){if(("topSelectionChange"===e||"topKeyUp"===e||"topKeyDown"===e)&&I&&I.value!==P)return P=I.value,T}function g(e){return e.nodeName&&"input"===e.nodeName.toLowerCase()&&("checkbox"===e.type||"radio"===e.type)}function b(e,t){if("topClick"===e)return t}var y=n(96),v=n(97),_=n(19),x=n(13),w=n(33),C=n(44),k=n(186),E=n(188),A=n(277),S={change:{phasedRegistrationNames:{bubbled:"onChange",captured:"onChangeCapture"},dependencies:["topBlur","topChange","topClick","topFocus","topInput","topKeyDown","topKeyUp","topSelectionChange"]}},I=null,T=null,P=null,O=null,M=!1;_.canUseDOM&&(M=E("change")&&(!document.documentMode||document.documentMode>8));var R=!1;_.canUseDOM&&(R=E("input")&&(!document.documentMode||document.documentMode>11));var N={get:function(){return O.get.call(this)},set:function(e){P=""+e,O.set.call(this,e)}},L={eventTypes:S,extractEvents:function(e,t,n,o){var i,a,l=t?x.getNodeFromInstance(t):window;if(r(l)?M?i=s:a=c:A(l)?R?i=f:(i=h,a=m):g(l)&&(i=b),i){var u=i(e,t);if(u){var d=C.getPooled(S.change,u,n,o);return d.type="change",v.accumulateTwoPhaseDispatches(d),d}}a&&a(e,l,t)}};e.exports=L},function(e,t,n){"use strict";var r=n(6),o=n(83),i=n(19),a=n(562),l=n(28),s=(n(1),{dangerouslyReplaceNodeWithMarkup:function(e,t){if(i.canUseDOM||r("56"),t||r("57"),"HTML"===e.nodeName&&r("58"),"string"==typeof t){var n=a(t,l)[0];e.parentNode.replaceChild(n,e)}else o.replaceChildWithTree(e,t)}});e.exports=s},function(e,t,n){"use strict";var r=["ResponderEventPlugin","SimpleEventPlugin","TapEventPlugin","EnterLeaveEventPlugin","ChangeEventPlugin","SelectEventPlugin","BeforeInputEventPlugin"];e.exports=r},function(e,t,n){"use strict";var r=n(97),o=n(13),i=n(122),a={mouseEnter:{registrationName:"onMouseEnter",dependencies:["topMouseOut","topMouseOver"]},mouseLeave:{registrationName:"onMouseLeave",dependencies:["topMouseOut","topMouseOver"]}},l={eventTypes:a,extractEvents:function(e,t,n,l){if("topMouseOver"===e&&(n.relatedTarget||n.fromElement))return null;if("topMouseOut"!==e&&"topMouseOver"!==e)return null;var s;if(l.window===l)s=l;else{var c=l.ownerDocument;s=c?c.defaultView||c.parentWindow:window}var u,d;if("topMouseOut"===e){u=t;var p=n.relatedTarget||n.toElement;d=p?o.getClosestInstanceFromNode(p):null}else u=null,d=t;if(u===d)return null;var f=null==u?s:o.getNodeFromInstance(u),m=null==d?s:o.getNodeFromInstance(d),h=i.getPooled(a.mouseLeave,u,n,l);h.type="mouseleave",h.target=f,h.relatedTarget=m;var g=i.getPooled(a.mouseEnter,d,n,l);return g.type="mouseenter",g.target=m,g.relatedTarget=f,r.accumulateEnterLeaveDispatches(h,g,u,d),[h,g]}};e.exports=l},function(e,t,n){"use strict";function r(e){this._root=e,this._startText=this.getText(),this._fallbackText=null}var o=n(9),i=n(69),a=n(276);o(r.prototype,{destructor:function(){this._root=null,this._startText=null,this._fallbackText=null},getText:function(){return"value"in this._root?this._root.value:this._root[a()]},getData:function(){if(this._fallbackText)return this._fallbackText;var e,t,n=this._startText,r=n.length,o=this.getText(),i=o.length;for(e=0;e<r&&n[e]===o[e];e++);var a=r-e;for(t=1;t<=a&&n[r-t]===o[i-t];t++);var l=t>1?1-t:void 0;return this._fallbackText=o.slice(e,l),this._fallbackText}}),i.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";var r=n(84),o=r.injection.MUST_USE_PROPERTY,i=r.injection.HAS_BOOLEAN_VALUE,a=r.injection.HAS_NUMERIC_VALUE,l=r.injection.HAS_POSITIVE_NUMERIC_VALUE,s=r.injection.HAS_OVERLOADED_BOOLEAN_VALUE,c={isCustomAttribute:RegExp.prototype.test.bind(new RegExp("^(data|aria)-["+r.ATTRIBUTE_NAME_CHAR+"]*$")),Properties:{accept:0,acceptCharset:0,accessKey:0,action:0,allowFullScreen:i,allowTransparency:0,alt:0,as:0,async:i,autoComplete:0,autoPlay:i,capture:i,cellPadding:0,cellSpacing:0,charSet:0,challenge:0,checked:o|i,cite:0,classID:0,className:0,cols:l,colSpan:0,content:0,contentEditable:0,contextMenu:0,controls:i,coords:0,crossOrigin:0,data:0,dateTime:0,default:i,defer:i,dir:0,disabled:i,download:s,draggable:0,encType:0,form:0,formAction:0,formEncType:0,formMethod:0,formNoValidate:i,formTarget:0,frameBorder:0,headers:0,height:0,hidden:i,high:0,href:0,hrefLang:0,htmlFor:0,httpEquiv:0,icon:0,id:0,inputMode:0,integrity:0,is:0,keyParams:0,keyType:0,kind:0,label:0,lang:0,list:0,loop:i,low:0,manifest:0,marginHeight:0,marginWidth:0,max:0,maxLength:0,media:0,mediaGroup:0,method:0,min:0,minLength:0,multiple:o|i,muted:o|i,name:0,nonce:0,noValidate:i,open:i,optimum:0,pattern:0,placeholder:0,playsInline:i,poster:0,preload:0,profile:0,radioGroup:0,readOnly:i,referrerPolicy:0,rel:0,required:i,reversed:i,role:0,rows:l,rowSpan:a,sandbox:0,scope:0,scoped:i,scrolling:0,seamless:i,selected:o|i,shape:0,size:l,sizes:0,span:l,spellCheck:0,src:0,srcDoc:0,srcLang:0,srcSet:0,start:a,step:0,style:0,summary:0,tabIndex:0,target:0,title:0,type:0,useMap:0,value:0,width:0,wmode:0,wrap:0,about:0,datatype:0,inlist:0,prefix:0,property:0,resource:0,typeof:0,vocab:0,autoCapitalize:0,autoCorrect:0,autoSave:0,color:0,itemProp:0,itemScope:i,itemType:0,itemID:0,itemRef:0,results:0,security:0,unselectable:0},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{}};e.exports=c},function(e,t,n){"use strict";(function(t){function r(e,t,n,r){var o=void 0===e[n];null!=t&&o&&(e[n]=i(t,!0))}var o=n(70),i=n(187),a=(n(178),n(189)),l=n(279);n(4);void 0!==t&&t.env;var s={instantiateChildren:function(e,t,n,o){if(null==e)return null;var i={};return l(e,r,i),i},updateChildren:function(e,t,n,r,l,s,c,u,d){if(t||e){var p,f;for(p in t)if(t.hasOwnProperty(p)){f=e&&e[p];var m=f&&f._currentElement,h=t[p];if(null!=f&&a(m,h))o.receiveComponent(f,h,l,u),t[p]=f;else{f&&(r[p]=o.getHostNode(f),o.unmountComponent(f,!1));var g=i(h,!0);t[p]=g;var b=o.mountComponent(g,l,s,c,u,d);n.push(b)}}for(p in e)!e.hasOwnProperty(p)||t&&t.hasOwnProperty(p)||(f=e[p],r[p]=o.getHostNode(f),o.unmountComponent(f,!1))}},unmountChildren:function(e,t){for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];o.unmountComponent(r,t)}}};e.exports=s}).call(t,n(173))},function(e,t,n){"use strict";var r=n(174),o=n(607),i={processChildrenUpdates:o.dangerouslyProcessChildrenUpdates,replaceNodeWithMarkup:r.dangerouslyReplaceNodeWithMarkup};e.exports=i},function(e,t,n){"use strict";function r(e){}function o(e,t){}function i(e){return!(!e.prototype||!e.prototype.isReactComponent)}function a(e){return!(!e.prototype||!e.prototype.isPureReactComponent)}var l=n(6),s=n(9),c=n(71),u=n(180),d=n(45),p=n(181),f=n(98),m=(n(29),n(269)),h=n(70),g=n(82),b=(n(1),n(171)),y=n(189),v=(n(4),{ImpureClass:0,PureClass:1,StatelessFunctional:2});r.prototype.render=function(){var e=f.get(this)._currentElement.type,t=e(this.props,this.context,this.updater);return o(e,t),t};var _=1,x={construct:function(e){this._currentElement=e,this._rootNodeID=0,this._compositeType=null,this._instance=null,this._hostParent=null,this._hostContainerInfo=null,this._updateBatchNumber=null,this._pendingElement=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._renderedNodeType=null,this._renderedComponent=null,this._context=null,this._mountOrder=0,this._topLevelWrapper=null,this._pendingCallbacks=null,this._calledComponentWillUnmount=!1},mountComponent:function(e,t,n,s){this._context=s,this._mountOrder=_++,this._hostParent=t,this._hostContainerInfo=n;var u,d=this._currentElement.props,p=this._processContext(s),m=this._currentElement.type,h=e.getUpdateQueue(),b=i(m),y=this._constructComponent(b,d,p,h);b||null!=y&&null!=y.render?a(m)?this._compositeType=v.PureClass:this._compositeType=v.ImpureClass:(u=y,o(m,u),null===y||y===!1||c.isValidElement(y)||l("105",m.displayName||m.name||"Component"),y=new r(m),this._compositeType=v.StatelessFunctional);y.props=d,y.context=p,y.refs=g,y.updater=h,this._instance=y,f.set(y,this);var x=y.state;void 0===x&&(y.state=x=null),("object"!=typeof x||Array.isArray(x))&&l("106",this.getName()||"ReactCompositeComponent"),this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1;var w;return w=y.unstable_handleError?this.performInitialMountWithErrorHandling(u,t,n,e,s):this.performInitialMount(u,t,n,e,s),y.componentDidMount&&e.getReactMountReady().enqueue(y.componentDidMount,y),w},_constructComponent:function(e,t,n,r){return this._constructComponentWithoutOwner(e,t,n,r)},_constructComponentWithoutOwner:function(e,t,n,r){var o=this._currentElement.type;return e?new o(t,n,r):o(t,n,r)},performInitialMountWithErrorHandling:function(e,t,n,r,o){var i,a=r.checkpoint();try{i=this.performInitialMount(e,t,n,r,o)}catch(l){r.rollback(a),this._instance.unstable_handleError(l),this._pendingStateQueue&&(this._instance.state=this._processPendingState(this._instance.props,this._instance.context)),a=r.checkpoint(),this._renderedComponent.unmountComponent(!0),r.rollback(a),i=this.performInitialMount(e,t,n,r,o)}return i},performInitialMount:function(e,t,n,r,o){var i=this._instance,a=0;i.componentWillMount&&(i.componentWillMount(),this._pendingStateQueue&&(i.state=this._processPendingState(i.props,i.context))),void 0===e&&(e=this._renderValidatedComponent());var l=m.getType(e);this._renderedNodeType=l;var s=this._instantiateReactComponent(e,l!==m.EMPTY);this._renderedComponent=s;var c=h.mountComponent(s,r,t,n,this._processChildContext(o),a);return c},getHostNode:function(){return h.getHostNode(this._renderedComponent)},unmountComponent:function(e){if(this._renderedComponent){var t=this._instance;if(t.componentWillUnmount&&!t._calledComponentWillUnmount)if(t._calledComponentWillUnmount=!0,e){var n=this.getName()+".componentWillUnmount()";p.invokeGuardedCallback(n,t.componentWillUnmount.bind(t))}else t.componentWillUnmount();this._renderedComponent&&(h.unmountComponent(this._renderedComponent,e),this._renderedNodeType=null,this._renderedComponent=null,this._instance=null),this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._pendingCallbacks=null,this._pendingElement=null,this._context=null,this._rootNodeID=0,this._topLevelWrapper=null,f.remove(t)}},_maskContext:function(e){var t=this._currentElement.type,n=t.contextTypes;if(!n)return g;var r={};for(var o in n)r[o]=e[o];return r},_processContext:function(e){var t=this._maskContext(e);return t},_processChildContext:function(e){var t,n=this._currentElement.type,r=this._instance;if(r.getChildContext&&(t=r.getChildContext()),t){"object"!=typeof n.childContextTypes&&l("107",this.getName()||"ReactCompositeComponent");for(var o in t)o in n.childContextTypes||l("108",this.getName()||"ReactCompositeComponent",o);return s({},e,t)}return e},_checkContextTypes:function(e,t,n){},receiveComponent:function(e,t,n){var r=this._currentElement,o=this._context;this._pendingElement=null,this.updateComponent(t,r,e,o,n)},performUpdateIfNecessary:function(e){null!=this._pendingElement?h.receiveComponent(this,this._pendingElement,e,this._context):null!==this._pendingStateQueue||this._pendingForceUpdate?this.updateComponent(e,this._currentElement,this._currentElement,this._context,this._context):this._updateBatchNumber=null},updateComponent:function(e,t,n,r,o){var i=this._instance;null==i&&l("136",this.getName()||"ReactCompositeComponent");var a,s=!1;this._context===o?a=i.context:(a=this._processContext(o),s=!0);var c=t.props,u=n.props;t!==n&&(s=!0),s&&i.componentWillReceiveProps&&i.componentWillReceiveProps(u,a);var d=this._processPendingState(u,a),p=!0;this._pendingForceUpdate||(i.shouldComponentUpdate?p=i.shouldComponentUpdate(u,d,a):this._compositeType===v.PureClass&&(p=!b(c,u)||!b(i.state,d))),this._updateBatchNumber=null,p?(this._pendingForceUpdate=!1,this._performComponentUpdate(n,u,d,a,e,o)):(this._currentElement=n,this._context=o,i.props=u,i.state=d,i.context=a)},_processPendingState:function(e,t){var n=this._instance,r=this._pendingStateQueue,o=this._pendingReplaceState;if(this._pendingReplaceState=!1,this._pendingStateQueue=null,!r)return n.state;if(o&&1===r.length)return r[0];for(var i=s({},o?r[0]:n.state),a=o?1:0;a<r.length;a++){var l=r[a];s(i,"function"==typeof l?l.call(n,i,e,t):l)}return i},_performComponentUpdate:function(e,t,n,r,o,i){var a,l,s,c=this._instance,u=Boolean(c.componentDidUpdate);u&&(a=c.props,l=c.state,s=c.context),c.componentWillUpdate&&c.componentWillUpdate(t,n,r),this._currentElement=e,this._context=i,c.props=t,c.state=n,c.context=r,this._updateRenderedComponent(o,i),u&&o.getReactMountReady().enqueue(c.componentDidUpdate.bind(c,a,l,s),c)},_updateRenderedComponent:function(e,t){var n=this._renderedComponent,r=n._currentElement,o=this._renderValidatedComponent(),i=0;if(y(r,o))h.receiveComponent(n,o,e,this._processChildContext(t));else{var a=h.getHostNode(n);h.unmountComponent(n,!1);var l=m.getType(o);this._renderedNodeType=l;var s=this._instantiateReactComponent(o,l!==m.EMPTY);this._renderedComponent=s;var c=h.mountComponent(s,e,this._hostParent,this._hostContainerInfo,this._processChildContext(t),i);this._replaceNodeWithMarkup(a,c,n)}},_replaceNodeWithMarkup:function(e,t,n){u.replaceNodeWithMarkup(e,t,n)},_renderValidatedComponentWithoutOwnerOrContext:function(){var e=this._instance;return e.render()},_renderValidatedComponent:function(){var e;if(this._compositeType!==v.StatelessFunctional){d.current=this;try{e=this._renderValidatedComponentWithoutOwnerOrContext()}finally{d.current=null}}else e=this._renderValidatedComponentWithoutOwnerOrContext();return null===e||e===!1||c.isValidElement(e)||l("109",this.getName()||"ReactCompositeComponent"),e},attachRef:function(e,t){var n=this.getPublicInstance();null==n&&l("110");var r=t.getPublicInstance();(n.refs===g?n.refs={}:n.refs)[e]=r},detachRef:function(e){delete this.getPublicInstance().refs[e]},getName:function(){var e=this._currentElement.type,t=this._instance&&this._instance.constructor;return e.displayName||t&&t.displayName||e.name||t&&t.name||null},getPublicInstance:function(){var e=this._instance;return this._compositeType===v.StatelessFunctional?null:e},_instantiateReactComponent:null};e.exports=x},function(e,t,n){"use strict";var r=n(13),o=n(262),i=n(268),a=n(70),l=n(33),s=n(271),c=n(642),u=n(275),d=n(650);n(4);o.inject();var p={findDOMNode:c,render:i.render,unmountComponentAtNode:i.unmountComponentAtNode,version:s,unstable_batchedUpdates:l.batchedUpdates,unstable_renderSubtreeIntoContainer:d};"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject&&__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ComponentTree:{getClosestInstanceFromNode:r.getClosestInstanceFromNode,getNodeFromInstance:function(e){return e._renderedComponent&&(e=u(e)),e?r.getNodeFromInstance(e):null}},Mount:i,Reconciler:a});e.exports=p},function(e,t,n){"use strict";function r(e){if(e){var t=e._currentElement._owner||null;if(t){var n=t.getName();if(n)return" This DOM node was rendered by `"+n+"`."}}return""}function o(e,t){t&&(K[e._tag]&&(null!=t.children||null!=t.dangerouslySetInnerHTML)&&h("137",e._tag,e._currentElement._owner?" Check the render method of "+e._currentElement._owner.getName()+".":""),null!=t.dangerouslySetInnerHTML&&(null!=t.children&&h("60"),"object"==typeof t.dangerouslySetInnerHTML&&H in t.dangerouslySetInnerHTML||h("61")),null!=t.style&&"object"!=typeof t.style&&h("62",r(e)))}function i(e,t,n,r){if(!(r instanceof R)){var o=e._hostContainerInfo;F(t,o._node&&o._node.nodeType===V?o._node:o._ownerDocument),r.getReactMountReady().enqueue(a,{inst:e,registrationName:t,listener:n})}}function a(){var e=this;C.putListener(e.inst,e.registrationName,e.listener)}function l(){var e=this;I.postMountWrapper(e)}function s(){var e=this;O.postMountWrapper(e)}function c(){var e=this;T.postMountWrapper(e)}function u(){var e=this;e._rootNodeID||h("63");var t=j(e);switch(t||h("64"),e._tag){case"iframe":case"object":e._wrapperState.listeners=[E.trapBubbledEvent("topLoad","load",t)];break;case"video":case"audio":e._wrapperState.listeners=[];for(var n in G)G.hasOwnProperty(n)&&e._wrapperState.listeners.push(E.trapBubbledEvent(n,G[n],t));break;case"source":e._wrapperState.listeners=[E.trapBubbledEvent("topError","error",t)];break;case"img":e._wrapperState.listeners=[E.trapBubbledEvent("topError","error",t),E.trapBubbledEvent("topLoad","load",t)];break;case"form":e._wrapperState.listeners=[E.trapBubbledEvent("topReset","reset",t),E.trapBubbledEvent("topSubmit","submit",t)];break;case"input":case"select":case"textarea":e._wrapperState.listeners=[E.trapBubbledEvent("topInvalid","invalid",t)]}}function d(){P.postUpdateWrapper(this)}function p(e){Q.call(X,e)||(Z.test(e)||h("65",e),X[e]=!0)}function f(e,t){return e.indexOf("-")>=0||null!=t.is}function m(e){var t=e.type;p(t),this._currentElement=e,this._tag=t.toLowerCase(),this._namespaceURI=null,this._renderedChildren=null,this._previousStyle=null,this._previousStyleCopy=null,this._hostNode=null,this._hostParent=null,this._rootNodeID=0,this._domID=0,this._hostContainerInfo=null,this._wrapperState=null,this._topLevelWrapper=null,this._flags=0}var h=n(6),g=n(9),b=n(591),y=n(593),v=n(83),_=n(175),x=n(84),w=n(257),C=n(96),k=n(176),E=n(121),A=n(258),S=n(13),I=n(608),T=n(609),P=n(260),O=n(613),M=(n(29),n(619)),R=n(270),N=(n(28),n(124)),L=(n(1),n(188),n(171),n(190),n(4),A),D=C.deleteListener,j=S.getNodeFromInstance,F=E.listenTo,z=k.registrationNameModules,U={string:!0,number:!0},B="style",H="__html",W={children:null,dangerouslySetInnerHTML:null,suppressContentEditableWarning:null},V=11,G={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"},Y={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},q={listing:!0,pre:!0,textarea:!0},K=g({menuitem:!0},Y),Z=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,X={},Q={}.hasOwnProperty,J=1;m.displayName="ReactDOMComponent",m.Mixin={mountComponent:function(e,t,n,r){this._rootNodeID=J++,this._domID=n._idCounter++,this._hostParent=t,this._hostContainerInfo=n;var i=this._currentElement.props;switch(this._tag){case"audio":case"form":case"iframe":case"img":case"link":case"object":case"source":case"video":this._wrapperState={listeners:null},e.getReactMountReady().enqueue(u,this);break;case"input":I.mountWrapper(this,i,t),i=I.getHostProps(this,i),e.getReactMountReady().enqueue(u,this);break;case"option":T.mountWrapper(this,i,t),i=T.getHostProps(this,i);break;case"select":P.mountWrapper(this,i,t),i=P.getHostProps(this,i),e.getReactMountReady().enqueue(u,this);break;case"textarea":O.mountWrapper(this,i,t),i=O.getHostProps(this,i),e.getReactMountReady().enqueue(u,this)}o(this,i);var a,d;null!=t?(a=t._namespaceURI,d=t._tag):n._tag&&(a=n._namespaceURI,d=n._tag),(null==a||a===_.svg&&"foreignobject"===d)&&(a=_.html),a===_.html&&("svg"===this._tag?a=_.svg:"math"===this._tag&&(a=_.mathml)),this._namespaceURI=a;var p;if(e.useCreateElement){var f,m=n._ownerDocument;if(a===_.html)if("script"===this._tag){var h=m.createElement("div"),g=this._currentElement.type;h.innerHTML="<"+g+"></"+g+">",f=h.removeChild(h.firstChild)}else f=i.is?m.createElement(this._currentElement.type,i.is):m.createElement(this._currentElement.type);else f=m.createElementNS(a,this._currentElement.type);S.precacheNode(this,f),this._flags|=L.hasCachedChildNodes,this._hostParent||w.setAttributeForRoot(f),this._updateDOMProperties(null,i,e);var y=v(f);this._createInitialChildren(e,i,r,y),p=y}else{var x=this._createOpenTagMarkupAndPutListeners(e,i),C=this._createContentMarkup(e,i,r);p=!C&&Y[this._tag]?x+"/>":x+">"+C+"</"+this._currentElement.type+">"}switch(this._tag){case"input":e.getReactMountReady().enqueue(l,this),i.autoFocus&&e.getReactMountReady().enqueue(b.focusDOMComponent,this);break;case"textarea":e.getReactMountReady().enqueue(s,this),i.autoFocus&&e.getReactMountReady().enqueue(b.focusDOMComponent,this);break;case"select":i.autoFocus&&e.getReactMountReady().enqueue(b.focusDOMComponent,this);break;case"button":i.autoFocus&&e.getReactMountReady().enqueue(b.focusDOMComponent,this);break;case"option":e.getReactMountReady().enqueue(c,this)}return p},_createOpenTagMarkupAndPutListeners:function(e,t){var n="<"+this._currentElement.type;for(var r in t)if(t.hasOwnProperty(r)){var o=t[r];if(null!=o)if(z.hasOwnProperty(r))o&&i(this,r,o,e);else{r===B&&(o&&(o=this._previousStyleCopy=g({},t.style)),o=y.createMarkupForStyles(o,this));var a=null;null!=this._tag&&f(this._tag,t)?W.hasOwnProperty(r)||(a=w.createMarkupForCustomAttribute(r,o)):a=w.createMarkupForProperty(r,o),a&&(n+=" "+a)}}return e.renderToStaticMarkup?n:(this._hostParent||(n+=" "+w.createMarkupForRoot()),n+=" "+w.createMarkupForID(this._domID))},_createContentMarkup:function(e,t,n){var r="",o=t.dangerouslySetInnerHTML;if(null!=o)null!=o.__html&&(r=o.__html);else{var i=U[typeof t.children]?t.children:null,a=null!=i?null:t.children;if(null!=i)r=N(i);else if(null!=a){var l=this.mountChildren(a,e,n);r=l.join("")}}return q[this._tag]&&"\n"===r.charAt(0)?"\n"+r:r},_createInitialChildren:function(e,t,n,r){var o=t.dangerouslySetInnerHTML;if(null!=o)null!=o.__html&&v.queueHTML(r,o.__html);else{var i=U[typeof t.children]?t.children:null,a=null!=i?null:t.children;if(null!=i)""!==i&&v.queueText(r,i);else if(null!=a)for(var l=this.mountChildren(a,e,n),s=0;s<l.length;s++)v.queueChild(r,l[s])}},receiveComponent:function(e,t,n){var r=this._currentElement;this._currentElement=e,this.updateComponent(t,r,e,n)},updateComponent:function(e,t,n,r){var i=t.props,a=this._currentElement.props;switch(this._tag){case"input":i=I.getHostProps(this,i),a=I.getHostProps(this,a);break;case"option":i=T.getHostProps(this,i),a=T.getHostProps(this,a);break;case"select":i=P.getHostProps(this,i),a=P.getHostProps(this,a);break;case"textarea":i=O.getHostProps(this,i),a=O.getHostProps(this,a)}switch(o(this,a),this._updateDOMProperties(i,a,e),this._updateDOMChildren(i,a,e,r),this._tag){case"input":I.updateWrapper(this);break;case"textarea":O.updateWrapper(this);break;case"select":e.getReactMountReady().enqueue(d,this)}},_updateDOMProperties:function(e,t,n){var r,o,a;for(r in e)if(!t.hasOwnProperty(r)&&e.hasOwnProperty(r)&&null!=e[r])if(r===B){var l=this._previousStyleCopy;for(o in l)l.hasOwnProperty(o)&&(a=a||{},a[o]="");this._previousStyleCopy=null}else z.hasOwnProperty(r)?e[r]&&D(this,r):f(this._tag,e)?W.hasOwnProperty(r)||w.deleteValueForAttribute(j(this),r):(x.properties[r]||x.isCustomAttribute(r))&&w.deleteValueForProperty(j(this),r);for(r in t){var s=t[r],c=r===B?this._previousStyleCopy:null!=e?e[r]:void 0;if(t.hasOwnProperty(r)&&s!==c&&(null!=s||null!=c))if(r===B)if(s?s=this._previousStyleCopy=g({},s):this._previousStyleCopy=null,c){for(o in c)!c.hasOwnProperty(o)||s&&s.hasOwnProperty(o)||(a=a||{},a[o]="");for(o in s)s.hasOwnProperty(o)&&c[o]!==s[o]&&(a=a||{},a[o]=s[o])}else a=s;else if(z.hasOwnProperty(r))s?i(this,r,s,n):c&&D(this,r);else if(f(this._tag,t))W.hasOwnProperty(r)||w.setValueForAttribute(j(this),r,s);else if(x.properties[r]||x.isCustomAttribute(r)){var u=j(this);null!=s?w.setValueForProperty(u,r,s):w.deleteValueForProperty(u,r)}}a&&y.setValueForStyles(j(this),a,this)},_updateDOMChildren:function(e,t,n,r){var o=U[typeof e.children]?e.children:null,i=U[typeof t.children]?t.children:null,a=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,l=t.dangerouslySetInnerHTML&&t.dangerouslySetInnerHTML.__html,s=null!=o?null:e.children,c=null!=i?null:t.children,u=null!=o||null!=a,d=null!=i||null!=l;null!=s&&null==c?this.updateChildren(null,n,r):u&&!d&&this.updateTextContent(""),null!=i?o!==i&&this.updateTextContent(""+i):null!=l?a!==l&&this.updateMarkup(""+l):null!=c&&this.updateChildren(c,n,r)},getHostNode:function(){return j(this)},unmountComponent:function(e){switch(this._tag){case"audio":case"form":case"iframe":case"img":case"link":case"object":case"source":case"video":var t=this._wrapperState.listeners;if(t)for(var n=0;n<t.length;n++)t[n].remove();break;case"html":case"head":case"body":h("66",this._tag)}this.unmountChildren(e),S.uncacheNode(this),C.deleteAllListeners(this),this._rootNodeID=0,this._domID=0,this._wrapperState=null},getPublicInstance:function(){return j(this)}},g(m.prototype,m.Mixin,M.Mixin),e.exports=m},function(e,t,n){"use strict";var r=n(9),o=n(83),i=n(13),a=function(e){this._currentElement=null,this._hostNode=null,this._hostParent=null,this._hostContainerInfo=null,this._domID=0};r(a.prototype,{mountComponent:function(e,t,n,r){var a=n._idCounter++;this._domID=a,this._hostParent=t,this._hostContainerInfo=n;var l=" react-empty: "+this._domID+" ";if(e.useCreateElement){var s=n._ownerDocument,c=s.createComment(l);return i.precacheNode(this,c),o(c)}return e.renderToStaticMarkup?"":"<!--"+l+"-->"},receiveComponent:function(){},getHostNode:function(){return i.getNodeFromInstance(this)},unmountComponent:function(){i.uncacheNode(this)}}),e.exports=a},function(e,t,n){"use strict";var r={useCreateElement:!0,useFiber:!1};e.exports=r},function(e,t,n){"use strict";var r=n(174),o=n(13),i={dangerouslyProcessChildrenUpdates:function(e,t){var n=o.getNodeFromInstance(e);r.processUpdates(n,t)}};e.exports=i},function(e,t,n){"use strict";function r(){this._rootNodeID&&d.updateWrapper(this)}function o(e){var t=this._currentElement.props,n=s.executeOnChange(t,e);u.asap(r,this);var o=t.name;if("radio"===t.type&&null!=o){for(var a=c.getNodeFromInstance(this),l=a;l.parentNode;)l=l.parentNode;for(var d=l.querySelectorAll("input[name="+JSON.stringify(""+o)+'][type="radio"]'),p=0;p<d.length;p++){var f=d[p];if(f!==a&&f.form===a.form){var m=c.getInstanceFromNode(f);m||i("90"),u.asap(r,m)}}}return n}var i=n(6),a=n(9),l=n(257),s=n(179),c=n(13),u=n(33),d=(n(1),n(4),{getHostProps:function(e,t){var n=s.getValue(t),r=s.getChecked(t);return a({type:void 0,step:void 0,min:void 0,max:void 0},t,{defaultChecked:void 0,defaultValue:void 0,value:null!=n?n:e._wrapperState.initialValue,checked:null!=r?r:e._wrapperState.initialChecked,onChange:e._wrapperState.onChange})},mountWrapper:function(e,t){var n=t.defaultValue;e._wrapperState={initialChecked:null!=t.checked?t.checked:t.defaultChecked,initialValue:null!=t.value?t.value:n,listeners:null,onChange:o.bind(e)}},updateWrapper:function(e){var t=e._currentElement.props,n=t.checked;null!=n&&l.setValueForProperty(c.getNodeFromInstance(e),"checked",n||!1);var r=c.getNodeFromInstance(e),o=s.getValue(t);if(null!=o){var i=""+o;i!==r.value&&(r.value=i)}else null==t.value&&null!=t.defaultValue&&r.defaultValue!==""+t.defaultValue&&(r.defaultValue=""+t.defaultValue),null==t.checked&&null!=t.defaultChecked&&(r.defaultChecked=!!t.defaultChecked)},postMountWrapper:function(e){var t=e._currentElement.props,n=c.getNodeFromInstance(e);switch(t.type){case"submit":case"reset":break;case"color":case"date":case"datetime":case"datetime-local":case"month":case"time":case"week":n.value="",n.value=n.defaultValue;break;default:n.value=n.value}var r=n.name;""!==r&&(n.name=""),n.defaultChecked=!n.defaultChecked,n.defaultChecked=!n.defaultChecked,""!==r&&(n.name=r)}});e.exports=d},function(e,t,n){"use strict";function r(e){var t="";return i.Children.forEach(e,function(e){null!=e&&("string"==typeof e||"number"==typeof e?t+=e:s||(s=!0))}),t}var o=n(9),i=n(71),a=n(13),l=n(260),s=(n(4),!1),c={mountWrapper:function(e,t,n){var o=null;if(null!=n){var i=n;"optgroup"===i._tag&&(i=i._hostParent),null!=i&&"select"===i._tag&&(o=l.getSelectValueContext(i))}var a=null;if(null!=o){var s;if(s=null!=t.value?t.value+"":r(t.children),a=!1,Array.isArray(o)){for(var c=0;c<o.length;c++)if(""+o[c]===s){a=!0;break}}else a=""+o===s}e._wrapperState={selected:a}},postMountWrapper:function(e){var t=e._currentElement.props;if(null!=t.value){a.getNodeFromInstance(e).setAttribute("value",t.value)}},getHostProps:function(e,t){var n=o({selected:void 0,children:void 0},t);null!=e._wrapperState.selected&&(n.selected=e._wrapperState.selected);var i=r(t.children);return i&&(n.children=i),n}};e.exports=c},function(e,t,n){"use strict";function r(e,t,n,r){return e===n&&t===r}function o(e){var t=document.selection,n=t.createRange(),r=n.text.length,o=n.duplicate();o.moveToElementText(e),o.setEndPoint("EndToStart",n);var i=o.text.length;return{start:i,end:i+r}}function i(e){var t=window.getSelection&&window.getSelection();if(!t||0===t.rangeCount)return null;var n=t.anchorNode,o=t.anchorOffset,i=t.focusNode,a=t.focusOffset,l=t.getRangeAt(0);try{l.startContainer.nodeType,l.endContainer.nodeType}catch(e){return null}var s=r(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),c=s?0:l.toString().length,u=l.cloneRange();u.selectNodeContents(e),u.setEnd(l.startContainer,l.startOffset);var d=r(u.startContainer,u.startOffset,u.endContainer,u.endOffset),p=d?0:u.toString().length,f=p+c,m=document.createRange();m.setStart(n,o),m.setEnd(i,a);var h=m.collapsed;return{start:h?f:p,end:h?p:f}}function a(e,t){var n,r,o=document.selection.createRange().duplicate();void 0===t.end?(n=t.start,r=n):t.start>t.end?(n=t.end,r=t.start):(n=t.start,r=t.end),o.moveToElementText(e),o.moveStart("character",n),o.setEndPoint("EndToStart",o),o.moveEnd("character",r-n),o.select()}function l(e,t){if(window.getSelection){var n=window.getSelection(),r=e[u()].length,o=Math.min(t.start,r),i=void 0===t.end?o:Math.min(t.end,r);if(!n.extend&&o>i){var a=i;i=o,o=a}var l=c(e,o),s=c(e,i);if(l&&s){var d=document.createRange();d.setStart(l.node,l.offset),n.removeAllRanges(),o>i?(n.addRange(d),n.extend(s.node,s.offset)):(d.setEnd(s.node,s.offset),n.addRange(d))}}}var s=n(19),c=n(647),u=n(276),d=s.canUseDOM&&"selection"in document&&!("getSelection"in window),p={getOffsets:d?o:i,setOffsets:d?a:l};e.exports=p},function(e,t,n){"use strict";var r=n(262),o=n(625),i=n(271);r.inject();var a={renderToString:o.renderToString,renderToStaticMarkup:o.renderToStaticMarkup,version:i};e.exports=a},function(e,t,n){"use strict";var r=n(6),o=n(9),i=n(174),a=n(83),l=n(13),s=n(124),c=(n(1),n(190),function(e){this._currentElement=e,this._stringText=""+e,this._hostNode=null,this._hostParent=null,this._domID=0,this._mountIndex=0,this._closingComment=null,this._commentNodes=null});o(c.prototype,{mountComponent:function(e,t,n,r){var o=n._idCounter++,i=" react-text: "+o+" ",c=" /react-text ";if(this._domID=o,this._hostParent=t,e.useCreateElement){var u=n._ownerDocument,d=u.createComment(i),p=u.createComment(c),f=a(u.createDocumentFragment());return a.queueChild(f,a(d)),this._stringText&&a.queueChild(f,a(u.createTextNode(this._stringText))),a.queueChild(f,a(p)),l.precacheNode(this,d),this._closingComment=p,f}var m=s(this._stringText);return e.renderToStaticMarkup?m:"<!--"+i+"-->"+m+"<!--"+c+"-->"},receiveComponent:function(e,t){if(e!==this._currentElement){this._currentElement=e;var n=""+e;if(n!==this._stringText){this._stringText=n;var r=this.getHostNode();i.replaceDelimitedText(r[0],r[1],n)}}},getHostNode:function(){var e=this._commentNodes;if(e)return e;if(!this._closingComment)for(var t=l.getNodeFromInstance(this),n=t.nextSibling;;){if(null==n&&r("67",this._domID),8===n.nodeType&&" /react-text "===n.nodeValue){this._closingComment=n;break}n=n.nextSibling}return e=[this._hostNode,this._closingComment],this._commentNodes=e,e},unmountComponent:function(){this._closingComment=null,this._commentNodes=null,l.uncacheNode(this)}}),e.exports=c},function(e,t,n){"use strict";function r(){this._rootNodeID&&u.updateWrapper(this)}function o(e){var t=this._currentElement.props,n=l.executeOnChange(t,e);return c.asap(r,this),n}var i=n(6),a=n(9),l=n(179),s=n(13),c=n(33),u=(n(1),n(4),{getHostProps:function(e,t){return null!=t.dangerouslySetInnerHTML&&i("91"),a({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue,onChange:e._wrapperState.onChange})},mountWrapper:function(e,t){var n=l.getValue(t),r=n;if(null==n){var a=t.defaultValue,s=t.children;null!=s&&(null!=a&&i("92"),Array.isArray(s)&&(s.length<=1||i("93"),s=s[0]),a=""+s),null==a&&(a=""),r=a}e._wrapperState={initialValue:""+r,listeners:null,onChange:o.bind(e)}},updateWrapper:function(e){var t=e._currentElement.props,n=s.getNodeFromInstance(e),r=l.getValue(t);if(null!=r){var o=""+r;o!==n.value&&(n.value=o),null==t.defaultValue&&(n.defaultValue=o)}null!=t.defaultValue&&(n.defaultValue=t.defaultValue)},postMountWrapper:function(e){var t=s.getNodeFromInstance(e),n=t.textContent;n===e._wrapperState.initialValue&&(t.value=n)}});e.exports=u},function(e,t,n){"use strict";function r(e,t){"_hostNode"in e||s("33"),"_hostNode"in t||s("33");for(var n=0,r=e;r;r=r._hostParent)n++;for(var o=0,i=t;i;i=i._hostParent)o++;for(;n-o>0;)e=e._hostParent,n--;for(;o-n>0;)t=t._hostParent,o--;for(var a=n;a--;){if(e===t)return e;e=e._hostParent,t=t._hostParent}return null}function o(e,t){"_hostNode"in e||s("35"),"_hostNode"in t||s("35");for(;t;){if(t===e)return!0;t=t._hostParent}return!1}function i(e){return"_hostNode"in e||s("36"),e._hostParent}function a(e,t,n){for(var r=[];e;)r.push(e),e=e._hostParent;var o;for(o=r.length;o-- >0;)t(r[o],"captured",n);for(o=0;o<r.length;o++)t(r[o],"bubbled",n)}function l(e,t,n,o,i){for(var a=e&&t?r(e,t):null,l=[];e&&e!==a;)l.push(e),e=e._hostParent;for(var s=[];t&&t!==a;)s.push(t),t=t._hostParent;var c;for(c=0;c<l.length;c++)n(l[c],"bubbled",o);for(c=s.length;c-- >0;)n(s[c],"captured",i)}var s=n(6);n(1);e.exports={isAncestor:o,getLowestCommonAncestor:r,getParentInstance:i,traverseTwoPhase:a,traverseEnterLeave:l}},function(e,t,n){"use strict";var r="function"==typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103;e.exports=r},function(e,t,n){"use strict";function r(e){o.enqueueEvents(e),o.processEventQueue(!1)}var o=n(96),i={handleTopLevel:function(e,t,n,i){r(o.extractEvents(e,t,n,i))}};e.exports=i},function(e,t,n){"use strict";function r(e){for(;e._hostParent;)e=e._hostParent;var t=d.getNodeFromInstance(e),n=t.parentNode;return d.getClosestInstanceFromNode(n)}function o(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function i(e){var t=f(e.nativeEvent),n=d.getClosestInstanceFromNode(t),o=n;do{e.ancestors.push(o),o=o&&r(o)}while(o);for(var i=0;i<e.ancestors.length;i++)n=e.ancestors[i],h._handleTopLevel(e.topLevelType,n,e.nativeEvent,f(e.nativeEvent))}function a(e){e(m(window))}var l=n(9),s=n(248),c=n(19),u=n(69),d=n(13),p=n(33),f=n(186),m=n(564);l(o.prototype,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),u.addPoolingTo(o,u.twoArgumentPooler);var h={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:c.canUseDOM?window:null,setHandleTopLevel:function(e){h._handleTopLevel=e},setEnabled:function(e){h._enabled=!!e},isEnabled:function(){return h._enabled},trapBubbledEvent:function(e,t,n){return n?s.listen(n,t,h.dispatchEvent.bind(null,e)):null},trapCapturedEvent:function(e,t,n){return n?s.capture(n,t,h.dispatchEvent.bind(null,e)):null},monitorScrollValue:function(e){var t=a.bind(null,e);s.listen(window,"scroll",t)},dispatchEvent:function(e,t){if(h._enabled){var n=o.getPooled(e,t);try{p.batchedUpdates(i,n)}finally{o.release(n)}}}};e.exports=h},function(e,t,n){"use strict";var r=n(84),o=n(96),i=n(177),a=n(180),l=n(263),s=n(121),c=n(265),u=n(33),d={Component:a.injection,DOMProperty:r.injection,EmptyComponent:l.injection,EventPluginHub:o.injection,EventPluginUtils:i.injection,EventEmitter:s.injection,HostComponent:c.injection,Updates:u.injection};e.exports=d},function(e,t,n){"use strict";function r(e,t,n){return{type:"INSERT_MARKUP",content:e,fromIndex:null,fromNode:null,toIndex:n,afterNode:t}}function o(e,t,n){return{type:"MOVE_EXISTING",content:null,fromIndex:e._mountIndex,fromNode:p.getHostNode(e),toIndex:n,afterNode:t}}function i(e,t){return{type:"REMOVE_NODE",content:null,fromIndex:e._mountIndex,fromNode:t,toIndex:null,afterNode:null}}function a(e){return{type:"SET_MARKUP",content:e,fromIndex:null,fromNode:null,toIndex:null,afterNode:null}}function l(e){return{type:"TEXT_CONTENT",content:e,fromIndex:null,fromNode:null,toIndex:null,afterNode:null}}function s(e,t){return t&&(e=e||[],e.push(t)),e}function c(e,t){d.processChildrenUpdates(e,t)}var u=n(6),d=n(180),p=(n(98),n(29),n(45),n(70)),f=n(600),m=(n(28),n(643)),h=(n(1),{Mixin:{_reconcilerInstantiateChildren:function(e,t,n){return f.instantiateChildren(e,t,n)},_reconcilerUpdateChildren:function(e,t,n,r,o,i){var a,l=0;return a=m(t,l),f.updateChildren(e,a,n,r,o,this,this._hostContainerInfo,i,l),a},mountChildren:function(e,t,n){var r=this._reconcilerInstantiateChildren(e,t,n);this._renderedChildren=r;var o=[],i=0;for(var a in r)if(r.hasOwnProperty(a)){var l=r[a],s=0,c=p.mountComponent(l,t,this,this._hostContainerInfo,n,s);l._mountIndex=i++,o.push(c)}return o},updateTextContent:function(e){var t=this._renderedChildren;f.unmountChildren(t,!1);for(var n in t)t.hasOwnProperty(n)&&u("118");c(this,[l(e)])},updateMarkup:function(e){var t=this._renderedChildren;f.unmountChildren(t,!1);for(var n in t)t.hasOwnProperty(n)&&u("118");c(this,[a(e)])},updateChildren:function(e,t,n){this._updateChildren(e,t,n)},_updateChildren:function(e,t,n){var r=this._renderedChildren,o={},i=[],a=this._reconcilerUpdateChildren(r,e,i,o,t,n);if(a||r){var l,u=null,d=0,f=0,m=0,h=null;for(l in a)if(a.hasOwnProperty(l)){var g=r&&r[l],b=a[l];g===b?(u=s(u,this.moveChild(g,h,d,f)),f=Math.max(g._mountIndex,f),g._mountIndex=d):(g&&(f=Math.max(g._mountIndex,f)),u=s(u,this._mountChildAtIndex(b,i[m],h,d,t,n)),m++),d++,h=p.getHostNode(b)}for(l in o)o.hasOwnProperty(l)&&(u=s(u,this._unmountChild(r[l],o[l])));u&&c(this,u),this._renderedChildren=a}},unmountChildren:function(e){var t=this._renderedChildren;f.unmountChildren(t,e),this._renderedChildren=null},moveChild:function(e,t,n,r){if(e._mountIndex<r)return o(e,t,n)},createChild:function(e,t,n){return r(n,t,e._mountIndex)},removeChild:function(e,t){return i(e,t)},_mountChildAtIndex:function(e,t,n,r,o,i){return e._mountIndex=r,this.createChild(e,n,t)},_unmountChild:function(e,t){var n=this.removeChild(e,t);return e._mountIndex=null,n}}});e.exports=h},function(e,t,n){"use strict";function r(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)}var o=n(6),i=(n(1),{addComponentAsRefTo:function(e,t,n){r(n)||o("119"),n.attachRef(t,e)},removeComponentAsRefFrom:function(e,t,n){r(n)||o("120");var i=n.getPublicInstance();i&&i.refs[t]===e.getPublicInstance()&&n.detachRef(t)}});e.exports=i},function(e,t,n){"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=i.getPooled(null),this.useCreateElement=e}var o=n(9),i=n(256),a=n(69),l=n(121),s=n(266),c=(n(29),n(123)),u=n(182),d={initialize:s.getSelectionInformation,close:s.restoreSelection},p={initialize:function(){var e=l.isEnabled();return l.setEnabled(!1),e},close:function(e){l.setEnabled(e)}},f={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},m=[d,p,f],h={getTransactionWrappers:function(){return m},getReactMountReady:function(){return this.reactMountReady},getUpdateQueue:function(){return u},checkpoint:function(){return this.reactMountReady.checkpoint()},rollback:function(e){this.reactMountReady.rollback(e)},destructor:function(){i.release(this.reactMountReady),this.reactMountReady=null}};o(r.prototype,c,h),a.addPoolingTo(r),e.exports=r},function(e,t,n){"use strict";function r(e,t,n){"function"==typeof e?e(t.getPublicInstance()):i.addComponentAsRefTo(t,e,n)}function o(e,t,n){"function"==typeof e?e(null):i.removeComponentAsRefFrom(t,e,n)}var i=n(620),a={};a.attachRefs=function(e,t){if(null!==t&&"object"==typeof t){var n=t.ref;null!=n&&r(n,e,t._owner)}},a.shouldUpdateRefs=function(e,t){var n=null,r=null;null!==e&&"object"==typeof e&&(n=e.ref,r=e._owner);var o=null,i=null;return null!==t&&"object"==typeof t&&(o=t.ref,i=t._owner),n!==o||"string"==typeof o&&i!==r},a.detachRefs=function(e,t){if(null!==t&&"object"==typeof t){var n=t.ref;null!=n&&o(n,e,t._owner)}},e.exports=a},function(e,t,n){"use strict";var r={isBatchingUpdates:!1,batchedUpdates:function(e){}};e.exports=r},function(e,t,n){"use strict";function r(e,t){var n;try{return m.injection.injectBatchingStrategy(p),n=f.getPooled(t),b++,n.perform(function(){var r=g(e,!0),o=d.mountComponent(r,n,null,s(),h,0);return t||(o=u.addChecksumToMarkup(o)),o},null)}finally{b--,f.release(n),b||m.injection.injectBatchingStrategy(c)}}function o(e){return l.isValidElement(e)||a("46"),r(e,!1)}function i(e){return l.isValidElement(e)||a("47"),r(e,!0)}var a=n(6),l=n(71),s=n(259),c=n(261),u=(n(29),n(267)),d=n(70),p=n(624),f=n(270),m=n(33),h=n(82),g=n(187),b=(n(1),0);e.exports={renderToString:o,renderToStaticMarkup:i}},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){}var i=n(182),a=(n(4),function(){function e(t){r(this,e),this.transaction=t}return e.prototype.isMounted=function(e){return!1},e.prototype.enqueueCallback=function(e,t,n){this.transaction.isInTransaction()&&i.enqueueCallback(e,t,n)},e.prototype.enqueueForceUpdate=function(e){this.transaction.isInTransaction()?i.enqueueForceUpdate(e):o(e,"forceUpdate")},e.prototype.enqueueReplaceState=function(e,t){this.transaction.isInTransaction()?i.enqueueReplaceState(e,t):o(e,"replaceState")},e.prototype.enqueueSetState=function(e,t){this.transaction.isInTransaction()?i.enqueueSetState(e,t):o(e,"setState")},e}());e.exports=a},function(e,t,n){"use strict";var r={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},o={accentHeight:"accent-height",accumulate:0,additive:0,alignmentBaseline:"alignment-baseline",allowReorder:"allowReorder",alphabetic:0,amplitude:0,arabicForm:"arabic-form",ascent:0,attributeName:"attributeName",attributeType:"attributeType",autoReverse:"autoReverse",azimuth:0,baseFrequency:"baseFrequency",baseProfile:"baseProfile",baselineShift:"baseline-shift",bbox:0,begin:0,bias:0,by:0,calcMode:"calcMode",capHeight:"cap-height",clip:0,clipPath:"clip-path",clipRule:"clip-rule",clipPathUnits:"clipPathUnits",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",contentScriptType:"contentScriptType",contentStyleType:"contentStyleType",cursor:0,cx:0,cy:0,d:0,decelerate:0,descent:0,diffuseConstant:"diffuseConstant",direction:0,display:0,divisor:0,dominantBaseline:"dominant-baseline",dur:0,dx:0,dy:0,edgeMode:"edgeMode",elevation:0,enableBackground:"enable-background",end:0,exponent:0,externalResourcesRequired:"externalResourcesRequired",fill:0,fillOpacity:"fill-opacity",fillRule:"fill-rule",filter:0,filterRes:"filterRes",filterUnits:"filterUnits",floodColor:"flood-color",floodOpacity:"flood-opacity",focusable:0,fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",format:0,from:0,fx:0,fy:0,g1:0,g2:0,glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",glyphRef:"glyphRef",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",hanging:0,horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",ideographic:0,imageRendering:"image-rendering",in:0,in2:0,intercept:0,k:0,k1:0,k2:0,k3:0,k4:0,kernelMatrix:"kernelMatrix",kernelUnitLength:"kernelUnitLength",kerning:0,keyPoints:"keyPoints",keySplines:"keySplines",keyTimes:"keyTimes",lengthAdjust:"lengthAdjust",letterSpacing:"letter-spacing",lightingColor:"lighting-color",limitingConeAngle:"limitingConeAngle",local:0,markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",markerHeight:"markerHeight",markerUnits:"markerUnits",markerWidth:"markerWidth",mask:0,maskContentUnits:"maskContentUnits",maskUnits:"maskUnits",mathematical:0,mode:0,numOctaves:"numOctaves",offset:0,opacity:0,operator:0,order:0,orient:0,orientation:0,origin:0,overflow:0,overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pathLength:"pathLength",patternContentUnits:"patternContentUnits",patternTransform:"patternTransform",patternUnits:"patternUnits",pointerEvents:"pointer-events",points:0,pointsAtX:"pointsAtX",pointsAtY:"pointsAtY",pointsAtZ:"pointsAtZ",preserveAlpha:"preserveAlpha",preserveAspectRatio:"preserveAspectRatio",primitiveUnits:"primitiveUnits",r:0,radius:0,refX:"refX",refY:"refY",renderingIntent:"rendering-intent",repeatCount:"repeatCount",repeatDur:"repeatDur",requiredExtensions:"requiredExtensions",requiredFeatures:"requiredFeatures",restart:0,result:0,rotate:0,rx:0,ry:0,scale:0,seed:0,shapeRendering:"shape-rendering",slope:0,spacing:0,specularConstant:"specularConstant",specularExponent:"specularExponent",speed:0,spreadMethod:"spreadMethod",startOffset:"startOffset",stdDeviation:"stdDeviation",stemh:0,stemv:0,stitchTiles:"stitchTiles",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",string:0,stroke:0,strokeDasharray:"stroke-dasharray",strokeDashoffset:"stroke-dashoffset",strokeLinecap:"stroke-linecap",strokeLinejoin:"stroke-linejoin",strokeMiterlimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",surfaceScale:"surfaceScale",systemLanguage:"systemLanguage",tableValues:"tableValues",targetX:"targetX",targetY:"targetY",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",textLength:"textLength",to:0,transform:0,u1:0,u2:0,underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicode:0,unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",values:0,vectorEffect:"vector-effect",version:0,vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",viewBox:"viewBox",viewTarget:"viewTarget",visibility:0,widths:0,wordSpacing:"word-spacing",writingMode:"writing-mode",x:0,xHeight:"x-height",x1:0,x2:0,xChannelSelector:"xChannelSelector",xlinkActuate:"xlink:actuate",xlinkArcrole:"xlink:arcrole",xlinkHref:"xlink:href",xlinkRole:"xlink:role",xlinkShow:"xlink:show",xlinkTitle:"xlink:title",xlinkType:"xlink:type",xmlBase:"xml:base",xmlns:0,xmlnsXlink:"xmlns:xlink",xmlLang:"xml:lang",xmlSpace:"xml:space",y:0,y1:0,y2:0,yChannelSelector:"yChannelSelector",z:0,zoomAndPan:"zoomAndPan"},i={Properties:{},DOMAttributeNamespaces:{xlinkActuate:r.xlink,xlinkArcrole:r.xlink,xlinkHref:r.xlink,xlinkRole:r.xlink,xlinkShow:r.xlink,xlinkTitle:r.xlink,xlinkType:r.xlink,xmlBase:r.xml,xmlLang:r.xml,xmlSpace:r.xml},DOMAttributeNames:{}};Object.keys(o).forEach(function(e){i.Properties[e]=0,o[e]&&(i.DOMAttributeNames[e]=o[e])}),e.exports=i},function(e,t,n){"use strict";function r(e){if("selectionStart"in e&&s.hasSelectionCapabilities(e))return{start:e.selectionStart,end:e.selectionEnd};if(window.getSelection){var t=window.getSelection();return{anchorNode:t.anchorNode,anchorOffset:t.anchorOffset,focusNode:t.focusNode,focusOffset:t.focusOffset}}if(document.selection){var n=document.selection.createRange();return{parentElement:n.parentElement(),text:n.text,top:n.boundingTop,left:n.boundingLeft}}}function o(e,t){if(y||null==h||h!==u())return null;var n=r(h);if(!b||!p(b,n)){b=n;var o=c.getPooled(m.select,g,e,t);return o.type="select",o.target=h,i.accumulateTwoPhaseDispatches(o),o}return null}var i=n(97),a=n(19),l=n(13),s=n(266),c=n(44),u=n(250),d=n(277),p=n(171),f=a.canUseDOM&&"documentMode"in document&&document.documentMode<=11,m={select:{phasedRegistrationNames:{bubbled:"onSelect",captured:"onSelectCapture"},dependencies:["topBlur","topContextMenu","topFocus","topKeyDown","topKeyUp","topMouseDown","topMouseUp","topSelectionChange"]}},h=null,g=null,b=null,y=!1,v=!1,_={eventTypes:m,extractEvents:function(e,t,n,r){if(!v)return null;var i=t?l.getNodeFromInstance(t):window;switch(e){case"topFocus":(d(i)||"true"===i.contentEditable)&&(h=i,g=t,b=null);break;case"topBlur":h=null,g=null,b=null;break;case"topMouseDown":y=!0;break;case"topContextMenu":case"topMouseUp":return y=!1,o(n,r);case"topSelectionChange":if(f)break;case"topKeyDown":case"topKeyUp":return o(n,r)}return null},didPutListener:function(e,t,n){"onSelect"===t&&(v=!0)}};e.exports=_},function(e,t,n){"use strict";function r(e){return"."+e._rootNodeID}function o(e){return"button"===e||"input"===e||"select"===e||"textarea"===e}var i=n(6),a=n(248),l=n(97),s=n(13),c=n(630),u=n(631),d=n(44),p=n(634),f=n(636),m=n(122),h=n(633),g=n(637),b=n(638),y=n(99),v=n(639),_=n(28),x=n(184),w=(n(1),{}),C={};["abort","animationEnd","animationIteration","animationStart","blur","canPlay","canPlayThrough","click","contextMenu","copy","cut","doubleClick","drag","dragEnd","dragEnter","dragExit","dragLeave","dragOver","dragStart","drop","durationChange","emptied","encrypted","ended","error","focus","input","invalid","keyDown","keyPress","keyUp","load","loadedData","loadedMetadata","loadStart","mouseDown","mouseMove","mouseOut","mouseOver","mouseUp","paste","pause","play","playing","progress","rateChange","reset","scroll","seeked","seeking","stalled","submit","suspend","timeUpdate","touchCancel","touchEnd","touchMove","touchStart","transitionEnd","volumeChange","waiting","wheel"].forEach(function(e){var t=e[0].toUpperCase()+e.slice(1),n="on"+t,r="top"+t,o={phasedRegistrationNames:{bubbled:n,captured:n+"Capture"},dependencies:[r]};w[e]=o,C[r]=o});var k={},E={eventTypes:w,extractEvents:function(e,t,n,r){var o=C[e];if(!o)return null;var a;switch(e){case"topAbort":case"topCanPlay":case"topCanPlayThrough":case"topDurationChange":case"topEmptied":case"topEncrypted":case"topEnded":case"topError":case"topInput":case"topInvalid":case"topLoad":case"topLoadedData":case"topLoadedMetadata":case"topLoadStart":case"topPause":case"topPlay":case"topPlaying":case"topProgress":case"topRateChange":case"topReset":case"topSeeked":case"topSeeking":case"topStalled":case"topSubmit":case"topSuspend":case"topTimeUpdate":case"topVolumeChange":case"topWaiting":a=d;break;case"topKeyPress":if(0===x(n))return null;case"topKeyDown":case"topKeyUp":a=f;break;case"topBlur":case"topFocus":a=p;break;case"topClick":if(2===n.button)return null;case"topDoubleClick":case"topMouseDown":case"topMouseMove":case"topMouseUp":case"topMouseOut":case"topMouseOver":case"topContextMenu":a=m;break;case"topDrag":case"topDragEnd":case"topDragEnter":case"topDragExit":case"topDragLeave":case"topDragOver":case"topDragStart":case"topDrop":a=h;break;case"topTouchCancel":case"topTouchEnd":case"topTouchMove":case"topTouchStart":a=g;break;case"topAnimationEnd":case"topAnimationIteration":case"topAnimationStart":a=c;break;case"topTransitionEnd":a=b;break;case"topScroll":a=y;break;case"topWheel":a=v;break;case"topCopy":case"topCut":case"topPaste":a=u}a||i("86",e);var s=a.getPooled(o,t,n,r);return l.accumulateTwoPhaseDispatches(s),s},didPutListener:function(e,t,n){if("onClick"===t&&!o(e._tag)){var i=r(e),l=s.getNodeFromInstance(e);k[i]||(k[i]=a.listen(l,"click",_))}},willDeleteListener:function(e,t){if("onClick"===t&&!o(e._tag)){var n=r(e);k[n].remove(),delete k[n]}}};e.exports=E},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(44),i={animationName:null,elapsedTime:null,pseudoElement:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(44),i={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(44),i={data:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(122),i={dataTransfer:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(99),i={relatedTarget:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(44),i={data:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(99),i=n(184),a=n(644),l=n(185),s={key:a,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:l,charCode:function(e){return"keypress"===e.type?i(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?i(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}};o.augmentClass(r,s),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(99),i=n(185),a={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:i};o.augmentClass(r,a),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(44),i={propertyName:null,elapsedTime:null,pseudoElement:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return o.call(this,e,t,n,r)}var o=n(122),i={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null};o.augmentClass(r,i),e.exports=r},function(e,t,n){"use strict";function r(e){for(var t=1,n=0,r=0,i=e.length,a=i&-4;r<a;){for(var l=Math.min(r+4096,a);r<l;r+=4)n+=(t+=e.charCodeAt(r))+(t+=e.charCodeAt(r+1))+(t+=e.charCodeAt(r+2))+(t+=e.charCodeAt(r+3));t%=o,n%=o}for(;r<i;r++)n+=t+=e.charCodeAt(r);return t%=o,n%=o,t|n<<16}var o=65521;e.exports=r},function(e,t,n){"use strict";function r(e,t,n){if(null==t||"boolean"==typeof t||""===t)return"";if(isNaN(t)||0===t||i.hasOwnProperty(e)&&i[e])return""+t;if("string"==typeof t){t=t.trim()}return t+"px"}var o=n(255),i=(n(4),o.isUnitlessNumber);e.exports=r},function(e,t,n){"use strict";function r(e){if(null==e)return null;if(1===e.nodeType)return e;var t=a.get(e);if(t)return t=l(t),t?i.getNodeFromInstance(t):null;"function"==typeof e.render?o("44"):o("45",Object.keys(e))}var o=n(6),i=(n(45),n(13)),a=n(98),l=n(275);n(1),n(4);e.exports=r},function(e,t,n){"use strict";(function(t){function r(e,t,n,r){if(e&&"object"==typeof e){var o=e,i=void 0===o[n];i&&null!=t&&(o[n]=t)}}function o(e,t){if(null==e)return e;var n={};return i(e,r,n),n}var i=(n(178),n(279));n(4);void 0!==t&&t.env,e.exports=o}).call(t,n(173))},function(e,t,n){"use strict";function r(e){if(e.key){var t=i[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=o(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?a[e.keyCode]||"Unidentified":""}var o=n(184),i={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},a={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"};e.exports=r},function(e,t,n){"use strict";function r(e){var t=e&&(o&&e[o]||e[i]);if("function"==typeof t)return t}var o="function"==typeof Symbol&&Symbol.iterator,i="@@iterator";e.exports=r},function(e,t,n){"use strict";function r(){return o++}var o=1;e.exports=r},function(e,t,n){"use strict";function r(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function o(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function i(e,t){for(var n=r(e),i=0,a=0;n;){if(3===n.nodeType){if(a=i+n.textContent.length,i<=t&&a>=t)return{node:n,offset:t-i};i=a}n=r(o(n))}}e.exports=i},function(e,t,n){"use strict";function r(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n["ms"+e]="MS"+t,n["O"+e]="o"+t.toLowerCase(),n}function o(e){if(l[e])return l[e];if(!a[e])return e;var t=a[e];for(var n in t)if(t.hasOwnProperty(n)&&n in s)return l[e]=t[n];return""}var i=n(19),a={animationend:r("Animation","AnimationEnd"),animationiteration:r("Animation","AnimationIteration"),animationstart:r("Animation","AnimationStart"),transitionend:r("Transition","TransitionEnd")},l={},s={};i.canUseDOM&&(s=document.createElement("div").style,"AnimationEvent"in window||(delete a.animationend.animation,delete a.animationiteration.animation,delete a.animationstart.animation),"TransitionEvent"in window||delete a.transitionend.transition),e.exports=o},function(e,t,n){"use strict";function r(e){return'"'+o(e)+'"'}var o=n(124);e.exports=r},function(e,t,n){"use strict";var r=n(268);e.exports=r.renderSubtreeIntoContainer},function(e,t,n){"use strict";e.exports=n(611)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0}),t.linkify=void 0;var l=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=n(10),c=r(s),u=n(577),d=r(u),p=n(703),f=r(p),m=n(120),h=r(m),g=t.linkify=new d.default;g.tlds(f.default);var b=function(e){function t(){var e,n,r,a;o(this,t);for(var l=arguments.length,s=Array(l),c=0;c<l;c++)s[c]=arguments[c];return n=r=i(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),r.parseCounter=0,a=n,i(r,a)}return a(t,e),l(t,[{key:"getMatches",value:function(e){return g.match(e)}},{key:"parseString",value:function(e){var n=this,r=[];if(""===e)return r;var o=this.getMatches(e);if(!o)return e;var i=0;return o.forEach(function(o,a){o.index>i&&r.push(e.substring(i,o.index));var l={href:o.url,key:"parse"+n.parseCounter+"match"+a};for(var s in n.props.properties){var u=n.props.properties[s];u===t.MATCH&&(u=o.url),l[s]=u}r.push(c.default.createElement(n.props.component,l,o.text)),i=o.lastIndex}),i<e.length&&r.push(e.substring(i)),1===r.length?r[0]:r}},{key:"parse",value:function(e){var t=this,n=e;return"string"==typeof e?n=this.parseString(e):c.default.isValidElement(e)&&"a"!==e.type&&"button"!==e.type?n=c.default.cloneElement(e,{key:"parse"+ ++this.parseCounter},this.parse(e.props.children)):e instanceof Array&&(n=e.map(function(e){return t.parse(e)})),n}},{key:"render",value:function(){this.parseCounter=0;var e=this.parse(this.props.children);return c.default.createElement("span",{className:this.props.className},e)}}]),t}(c.default.Component);b.MATCH="LINKIFY_MATCH",b.propTypes={className:h.default.string,component:h.default.any,properties:h.default.object,urlRegex:h.default.object,emailRegex:h.default.object},b.defaultProps={className:"Linkify",component:"a",properties:{}},t.default=b},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=n(10),l=(n.n(a),n(282));n(192);n.d(t,"a",function(){return s});var s=function(e){function t(n,i){r(this,t);var a=o(this,e.call(this,n,i));return a.store=n.store,a}return i(t,e),t.prototype.getChildContext=function(){return{store:this.store,storeSubscription:null}},t.prototype.render=function(){return a.Children.only(this.props.children)},t}(a.Component);s.propTypes={store:l.a.isRequired,children:a.PropTypes.element.isRequired},s.childContextTypes={store:l.a.isRequired,storeSubscription:l.b},s.displayName="Provider"},function(e,t,n){"use strict";function r(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function o(e,t,n){for(var r=t.length-1;r>=0;r--){var o=t[r](e);if(o)return o}return function(t,r){throw new Error("Invalid value of type "+typeof e+" for "+n+" argument when connecting component "+r.wrappedComponentName+".")}}function i(e,t){return e===t}function a(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.connectHOC,n=void 0===t?l.a:t,a=e.mapStateToPropsFactories,m=void 0===a?u.a:a,h=e.mapDispatchToPropsFactories,g=void 0===h?c.a:h,b=e.mergePropsFactories,y=void 0===b?d.a:b,v=e.selectorFactory,_=void 0===v?p.a:v;return function(e,t,a){var l=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},c=l.pure,u=void 0===c||c,d=l.areStatesEqual,p=void 0===d?i:d,h=l.areOwnPropsEqual,b=void 0===h?s.a:h,v=l.areStatePropsEqual,x=void 0===v?s.a:v,w=l.areMergedPropsEqual,C=void 0===w?s.a:w,k=r(l,["pure","areStatesEqual","areOwnPropsEqual","areStatePropsEqual","areMergedPropsEqual"]),E=o(e,m,"mapStateToProps"),A=o(t,g,"mapDispatchToProps"),S=o(a,y,"mergeProps");return n(_,f({methodName:"connect",getDisplayName:function(e){return"Connect("+e+")"},shouldHandleStateChanges:Boolean(e),initMapStateToProps:E,initMapDispatchToProps:A,initMergeProps:S,pure:u,areStatesEqual:p,areOwnPropsEqual:b,areStatePropsEqual:x,areMergedPropsEqual:C},k))}}var l=n(280),s=n(661),c=n(655),u=n(656),d=n(657),p=n(658),f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t.a=a()},function(e,t,n){"use strict";function r(e){return"function"==typeof e?n.i(l.a)(e,"mapDispatchToProps"):void 0}function o(e){return e?void 0:n.i(l.b)(function(e){return{dispatch:e}})}function i(e){return e&&"object"==typeof e?n.i(l.b)(function(t){return n.i(a.b)(e,t)}):void 0}var a=n(294),l=n(281);t.a=[r,o,i]},function(e,t,n){"use strict";function r(e){return"function"==typeof e?n.i(i.a)(e,"mapStateToProps"):void 0}function o(e){return e?void 0:n.i(i.b)(function(){return{}})}var i=n(281);t.a=[r,o]},function(e,t,n){"use strict";function r(e,t,n){return l({},n,e,t)}function o(e){return function(t,n){var r=(n.displayName,n.pure),o=n.areMergedPropsEqual,i=!1,a=void 0;return function(t,n,l){var s=e(t,n,l);return i?r&&o(s,a)||(a=s):(i=!0,a=s),a}}}function i(e){return"function"==typeof e?o(e):void 0}function a(e){return e?void 0:function(){return r}}var l=(n(283),Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e});t.a=[i,a]},function(e,t,n){"use strict";function r(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function o(e,t,n,r){return function(o,i){return n(e(o,i),t(r,i),i)}}function i(e,t,n,r,o){function i(o,i){return m=o,h=i,g=e(m,h),b=t(r,h),y=n(g,b,h),f=!0,y}function a(){return g=e(m,h),t.dependsOnOwnProps&&(b=t(r,h)),y=n(g,b,h)}function l(){return e.dependsOnOwnProps&&(g=e(m,h)),t.dependsOnOwnProps&&(b=t(r,h)),y=n(g,b,h)}function s(){var t=e(m,h),r=!p(t,g);return g=t,r&&(y=n(g,b,h)),y}function c(e,t){var n=!d(t,h),r=!u(e,m);return m=e,h=t,n&&r?a():n?l():r?s():y}var u=o.areStatesEqual,d=o.areOwnPropsEqual,p=o.areStatePropsEqual,f=!1,m=void 0,h=void 0,g=void 0,b=void 0,y=void 0;return function(e,t){return f?c(e,t):i(e,t)}}function a(e,t){var n=t.initMapStateToProps,a=t.initMapDispatchToProps,l=t.initMergeProps,s=r(t,["initMapStateToProps","initMapDispatchToProps","initMergeProps"]),c=n(e,s),u=a(e,s),d=l(e,s);return(s.pure?i:o)(c,u,d,e,s)}n(659);t.a=a},function(e,t,n){"use strict";n(192)},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(){var e=[],t=[];return{clear:function(){t=i,e=i},notify:function(){for(var n=e=t,r=0;r<n.length;r++)n[r]()},subscribe:function(n){var r=!0;return t===e&&(t=e.slice()),t.push(n),function(){r&&e!==i&&(r=!1,t===e&&(t=e.slice()),t.splice(t.indexOf(n),1))}}}}n.d(t,"a",function(){return l});var i=null,a={notify:function(){}},l=function(){function e(t,n,o){r(this,e),this.store=t,this.parentSub=n,this.onStateChange=o,this.unsubscribe=null,this.listeners=a}return e.prototype.addNestedSub=function(e){return this.trySubscribe(),this.listeners.subscribe(e)},e.prototype.notifyNestedSubs=function(){this.listeners.notify()},e.prototype.isSubscribed=function(){return Boolean(this.unsubscribe)},e.prototype.trySubscribe=function(){this.unsubscribe||(this.unsubscribe=this.parentSub?this.parentSub.addNestedSub(this.onStateChange):this.store.subscribe(this.onStateChange),this.listeners=o())},e.prototype.tryUnsubscribe=function(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null,this.listeners.clear(),this.listeners=a)},e}()},function(e,t,n){"use strict";function r(e,t){return e===t?0!==e||0!==t||1/e==1/t:e!==e&&t!==t}function o(e,t){if(r(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length)return!1;for(var a=0;a<n.length;a++)if(!i.call(t,n[a])||!r(e[n[a]],t[n[a]]))return!1;return!0}t.a=o;var i=Object.prototype.hasOwnProperty},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(10),l=r(a),s=n(88),c=r(s),u=n(193),d=r(u),p=n(666),f=r(p),m=function(){return{}};t.default={data:[],loading:!1,showPagination:!0,showPaginationTop:!1,showPaginationBottom:!0,showPageSizeOptions:!0,pageSizeOptions:[5,10,20,25,50,100],defaultPageSize:20,showPageJump:!0,collapseOnSortingChange:!0,collapseOnPageChange:!0,collapseOnDataChange:!0,freezeWhenExpanded:!1,sortable:!0,resizable:!0,filterable:!1,defaultSortDesc:!1,defaultSorted:[],defaultFiltered:[],defaultResized:[],defaultExpanded:{},defaultFilterMethod:function(e,t,n){var r=e.pivotId||e.id;return void 0===t[r]||String(t[r]).startsWith(e.value)},defaultSortMethod:function(e,t){return e=null===e||void 0===e?"":e,t=null===t||void 0===t?"":t,e="string"==typeof e?e.toLowerCase():e,t="string"==typeof t?t.toLowerCase():t,e>t?1:e<t?-1:0},onPageChange:void 0,onPageSizeChange:void 0,onSortedChange:void 0,onFilteredChange:void 0,onResizedChange:void 0,onExpandedChange:void 0,pivotBy:void 0,pivotValKey:"_pivotVal",pivotIDKey:"_pivotID",subRowsKey:"_subRows",aggregatedKey:"_aggregated",nestingLevelKey:"_nestingLevel",originalKey:"_original",indexKey:"_index",groupedByPivotKey:"_groupedByPivot",onFetchData:function(){return null},className:"",style:{},getProps:m,getTableProps:m,getTheadGroupProps:m,getTheadGroupTrProps:m,getTheadGroupThProps:m,getTheadProps:m,getTheadTrProps:m,getTheadThProps:m,getTheadFilterProps:m,getTheadFilterTrProps:m,getTheadFilterThProps:m,getTbodyProps:m,getTrGroupProps:m,getTrProps:m,getTdProps:m,getTfootProps:m,getTfootTrProps:m,getTfootTdProps:m,getPaginationProps:m,getLoadingProps:m,getNoDataProps:m,getResizerProps:m,column:{Cell:void 0,Header:void 0,Footer:void 0,Aggregated:void 0,Pivot:void 0,PivotValue:void 0,Expander:void 0,Filter:void 0,sortable:void 0,resizable:void 0,filterable:void 0,show:!0,minWidth:100,className:"",style:{},getProps:m,aggregate:void 0,headerClassName:"",headerStyle:{},getHeaderProps:m,footerClassName:"",footerStyle:{},getFooterProps:m,filterMethod:void 0,sortMethod:void 0},expanderDefaults:{sortable:!1,resizable:!1,filterable:!1,width:35},pivotDefaults:{},previousText:"Previous",nextText:"Next",loadingText:"Loading...",noDataText:"No rows found",pageText:"Page",ofText:"of",rowsText:"rows",TableComponent:d.default.makeTemplateComponent("rt-table"),TheadComponent:d.default.makeTemplateComponent("rt-thead"),TbodyComponent:d.default.makeTemplateComponent("rt-tbody"),TrGroupComponent:d.default.makeTemplateComponent("rt-tr-group"),TrComponent:d.default.makeTemplateComponent("rt-tr"),ThComponent:function(e){var t=e.toggleSort,n=e.className,r=e.children,a=o(e,["toggleSort","className","children"]);return l.default.createElement("div",i({className:(0,c.default)(n,"rt-th"),onClick:function(e){t&&t(e)}},a),r)},TdComponent:d.default.makeTemplateComponent("rt-td"),TfootComponent:d.default.makeTemplateComponent("rt-tfoot"),FilterComponent:function(e){var t=e.filter,n=e.onChange;return l.default.createElement("input",{type:"text",style:{width:"100%"},value:t?t.value:"",onChange:function(e){return n(e.target.value)}})},ExpanderComponent:function(e){var t=e.isExpanded;return l.default.createElement("div",{className:(0,c.default)("rt-expander",t&&"-open")},"•")},PivotValueComponent:function(e){var t=e.subRows,n=e.value;return l.default.createElement("span",null,n," ",t&&"("+t.length+")")},AggregatedComponent:function(e){var t=e.subRows,n=e.column,r=t.filter(function(e){return void 0!==e[n.id]}).map(function(e,r){return l.default.createElement("span",{key:r},e[n.id],r<t.length-1?", ":"")});return l.default.createElement("span",null,r)},PivotComponent:void 0,PaginationComponent:f.default,PreviousComponent:void 0,NextComponent:void 0,LoadingComponent:function(e){var t=e.className,n=e.loading,r=e.loadingText,a=o(e,["className","loading","loadingText"]);return l.default.createElement("div",i({className:(0,c.default)("-loading",{"-active":n},t)},a),l.default.createElement("div",{className:"-loading-inner"},r))},NoDataComponent:d.default.makeTemplateComponent("rt-noData"),ResizerComponent:d.default.makeTemplateComponent("rt-resizer"),PadRowComponent:function(){return l.default.createElement("span",null," ")}}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0}),t.ReactTableDefaults=void 0;var l=function(){function e(e,t){var n=[],r=!0,o=!1,i=void 0;try{for(var a,l=e[Symbol.iterator]();!(r=(a=l.next()).done)&&(n.push(a.value),!t||n.length!==t);r=!0);}catch(e){o=!0,i=e}finally{try{!r&&l.return&&l.return()}finally{if(o)throw i}}return n}return function(t,n){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,n);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},c=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=n(10),d=r(u),p=n(88),f=r(p),m=n(193),h=r(m),g=n(664),b=r(g),y=n(665),v=r(y),_=n(662),x=r(_),w=(t.ReactTableDefaults=x.default,function(e){function t(e){o(this,t);var n=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return n.getResolvedState=n.getResolvedState.bind(n),n.getDataModel=n.getDataModel.bind(n),n.getSortedData=n.getSortedData.bind(n),n.fireFetchData=n.fireFetchData.bind(n),n.getPropOrState=n.getPropOrState.bind(n),n.getStateOrProp=n.getStateOrProp.bind(n),n.filterData=n.filterData.bind(n),n.sortData=n.sortData.bind(n),n.getMinRows=n.getMinRows.bind(n),n.onPageChange=n.onPageChange.bind(n),n.onPageSizeChange=n.onPageSizeChange.bind(n),n.sortColumn=n.sortColumn.bind(n),n.filterColumn=n.filterColumn.bind(n),n.resizeColumnStart=n.resizeColumnStart.bind(n),n.resizeColumnEnd=n.resizeColumnEnd.bind(n),n.resizeColumnMoving=n.resizeColumnMoving.bind(n),n.state={page:0,pageSize:e.defaultPageSize,sorted:e.defaultSorted,expanded:e.defaultExpanded,filtered:e.defaultFiltered,resized:e.defaultResized,currentlyResizing:!1,skipNextSort:!1},n}return a(t,e),c(t,[{key:"render",value:function(){var e=this,t=this.getResolvedState(),n=t.children,r=t.className,o=t.style,i=t.getProps,a=t.getTableProps,c=t.getTheadGroupProps,u=t.getTheadGroupTrProps,p=t.getTheadGroupThProps,m=t.getTheadProps,g=t.getTheadTrProps,b=t.getTheadThProps,y=t.getTheadFilterProps,v=t.getTheadFilterTrProps,_=t.getTheadFilterThProps,w=t.getTbodyProps,C=t.getTrGroupProps,k=t.getTrProps,E=t.getTdProps,A=t.getTfootProps,S=t.getTfootTrProps,I=t.getTfootTdProps,T=t.getPaginationProps,P=t.getLoadingProps,O=t.getNoDataProps,M=t.getResizerProps,R=t.showPagination,N=t.showPaginationTop,L=t.showPaginationBottom,D=t.manual,j=t.loadingText,F=t.noDataText,z=t.sortable,U=t.resizable,B=t.filterable,H=t.pivotIDKey,W=t.pivotValKey,V=t.pivotBy,G=t.subRowsKey,Y=t.aggregatedKey,q=t.originalKey,K=t.indexKey,Z=t.groupedByPivotKey,X=t.loading,Q=t.pageSize,J=t.page,$=t.sorted,ee=t.filtered,te=t.resized,ne=t.expanded,re=t.pages,oe=t.onExpandedChange,ie=t.TableComponent,ae=t.TheadComponent,le=t.TbodyComponent,se=t.TrGroupComponent,ce=t.TrComponent,ue=t.ThComponent,de=t.TdComponent,pe=t.TfootComponent,fe=t.PaginationComponent,me=t.LoadingComponent,he=t.SubComponent,ge=t.NoDataComponent,be=t.ResizerComponent,ye=t.ExpanderComponent,ve=t.PivotValueComponent,_e=t.PivotComponent,xe=t.AggregatedComponent,we=t.FilterComponent,Ce=t.PadRowComponent,ke=t.resolvedData,Ee=t.allVisibleColumns,Ae=t.headerGroups,Se=t.hasHeaderGroups,Ie=t.sortedData,Te=t.currentlyResizing,Pe=Q*J,Oe=Pe+Q,Me=D?ke:Ie.slice(Pe,Oe),Re=this.getMinRows(),Ne=h.default.range(Math.max(Re-Me.length,0)),Le=Ee.some(function(e){return e.Footer}),De=B||Ee.some(function(e){return e.filterable});Me=l(function e(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1;return[t.map(function(t,o){r++;var i=s({},t,{_viewIndex:r}),a=n.concat([o]);if(i[G]&&h.default.get(ne,a)){var c=e(i[G],a,r),u=l(c,2);i[G]=u[0],r=u[1]}return i}),r]}(Me),1)[0];var je=J>0,Fe=J+1<re,ze=h.default.sum(Ee.map(function(e){var t=te.find(function(t){return t.id===e.id})||{};return h.default.getFirstDefined(t.value,e.width,e.minWidth)})),Ue=-1,Be=s({},t,{startRow:Pe,endRow:Oe,pageRows:Me,minRows:Re,padRows:Ne,hasColumnFooter:Le,canPrevious:je,canNext:Fe,rowMinWidth:ze}),He=function(){var t=h.default.splitProps(c(Be,void 0,void 0,e)),n=h.default.splitProps(u(Be,void 0,void 0,e));return d.default.createElement(ae,s({className:(0,f.default)("-headerGroups",t.className),style:s({},t.style,{minWidth:ze+"px"})},t.rest),d.default.createElement(ce,s({className:n.className,style:n.style},n.rest),Ae.map(We)))},We=function(t,n){var r=function(e){return(te.find(function(t){return t.id===e.id})||{}).value},o=h.default.sum(t.columns.map(function(e){return e.width||r(e)?0:e.minWidth})),i=h.default.sum(t.columns.map(function(e){return h.default.getFirstDefined(r(e),e.width,e.minWidth)})),a=h.default.sum(t.columns.map(function(e){return h.default.getFirstDefined(r(e),e.width,e.maxWidth)})),l=h.default.splitProps(p(Be,void 0,t,e)),c=h.default.splitProps(t.getHeaderProps(Be,void 0,t,e)),u=[t.headerClassName,l.className,c.className],m=s({},t.headerStyle,l.style,c.style),g=s({},l.rest,c.rest),b={flex:o+" 0 auto",width:i+"px",maxWidth:a+"px"};return d.default.createElement(ue,s({key:n+"-"+t.id,className:(0,f.default)(u),style:s({},m,b)},g),h.default.normalizeComponent(t.Header,{data:Ie,column:t}))},Ve=function(){var t=h.default.splitProps(m(Be,void 0,void 0,e)),n=h.default.splitProps(g(Be,void 0,void 0,e));return d.default.createElement(ae,s({className:(0,f.default)("-header",t.className),style:s({},t.style,{minWidth:ze+"px"})},t.rest),d.default.createElement(ce,s({className:n.className,style:n.style},n.rest),Ee.map(Ge)))},Ge=function(t,n){var r=te.find(function(e){return e.id===t.id})||{},o=$.find(function(e){return e.id===t.id}),i="function"==typeof t.show?t.show():t.show,a=h.default.getFirstDefined(r.value,t.width,t.minWidth),l=h.default.getFirstDefined(r.value,t.width,t.maxWidth),c=h.default.splitProps(b(Be,void 0,t,e)),u=h.default.splitProps(t.getHeaderProps(Be,void 0,t,e)),p=[t.headerClassName,c.className,u.className],m=s({},t.headerStyle,c.style,u.style),g=s({},c.rest,u.rest),y=h.default.getFirstDefined(t.resizable,U,!1),v=y?d.default.createElement(be,s({onMouseDown:function(n){return e.resizeColumnStart(t,n,!1)},onTouchStart:function(n){return e.resizeColumnStart(t,n,!0)}},it)):null,_=h.default.getFirstDefined(t.sortable,z,!1);return d.default.createElement(ue,s({key:n+"-"+t.id,className:(0,f.default)(p,"rt-resizable-header",o?o.desc?"-sort-desc":"-sort-asc":"",_&&"-cursor-pointer",!i&&"-hidden",V&&V.slice(0,-1).includes(t.id)&&"rt-header-pivot"),style:s({},m,{flex:a+" 0 auto",width:a+"px",maxWidth:l+"px"}),toggleSort:function(n){_&&e.sortColumn(t,n.shiftKey)}},g),d.default.createElement("div",{className:"rt-resizable-header-content"},h.default.normalizeComponent(t.Header,{data:Ie,column:t})),v)},Ye=function(){var t=h.default.splitProps(y(Be,void 0,void 0,e)),n=h.default.splitProps(v(Be,void 0,void 0,e));return d.default.createElement(ae,s({className:(0,f.default)("-filters",t.className),style:s({},t.style,{minWidth:ze+"px"})},t.rest),d.default.createElement(ce,s({className:n.className,style:n.style},n.rest),Ee.map(qe)))},qe=function(t,n){var r=te.find(function(e){return e.id===t.id})||{},o=h.default.getFirstDefined(r.value,t.width,t.minWidth),i=h.default.getFirstDefined(r.value,t.width,t.maxWidth),a=h.default.splitProps(_(Be,void 0,t,e)),l=h.default.splitProps(t.getHeaderProps(Be,void 0,t,e)),c=[t.headerClassName,a.className,l.className],u=s({},t.headerStyle,a.style,l.style),p=s({},a.rest,l.rest),m=ee.find(function(e){return e.id===t.id}),g=t.Filter||we,b=h.default.getFirstDefined(t.filterable,B,!1);return d.default.createElement(ue,s({key:n+"-"+t.id,className:(0,f.default)(c),style:s({},u,{flex:o+" 0 auto",width:o+"px",maxWidth:i+"px"})},p),b?h.default.normalizeComponent(g,{column:t,filter:m,onChange:function(n){return e.filterColumn(t,n)}},x.default.column.Filter):null)},Ke=function t(n,r){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],i={original:n[q],row:n,index:n[K],viewIndex:++Ue,level:o.length,nestingPath:o.concat([r]),aggregated:n[Y],groupedByPivot:n[Z],subRows:n[G]},a=h.default.get(ne,i.nestingPath),l=C(Be,i,void 0,e),c=h.default.splitProps(k(Be,i,void 0,e));return d.default.createElement(se,s({key:i.nestingPath.join("_")},l),d.default.createElement(ce,s({className:(0,f.default)(c.className,n._viewIndex%2?"-even":"-odd"),style:c.style},c.rest),Ee.map(function(t,r){var o=te.find(function(e){return e.id===t.id})||{},l="function"==typeof t.show?t.show():t.show,c=h.default.getFirstDefined(o.value,t.width,t.minWidth),u=h.default.getFirstDefined(o.value,t.width,t.maxWidth),p=h.default.splitProps(E(Be,i,t,e)),m=h.default.splitProps(t.getProps(Be,i,t,e)),g=[p.className,t.className,m.className],b=s({},p.style,t.style,m.style),y=s({},i,{isExpanded:a,column:s({},t),value:i.row[t.id],pivoted:t.pivoted,expander:t.expander,resized:te,show:l,width:c,maxWidth:u,tdProps:p,columnProps:m,classes:g,styles:b}),v=y.value,_=void 0,x=void 0,w=void 0,C=function(t){var n=h.default.clone(ne);return n=a?h.default.set(n,y.nestingPath,!1):h.default.set(n,y.nestingPath,{}),e.setStateWithData({expanded:n},function(){oe&&oe(n,y.nestingPath,t)})},k=h.default.normalizeComponent(t.Cell,y,v),A=t.Aggregated||(t.aggregate?t.Cell:xe),S=t.Expander||ye,I=t.PivotValue||ve,T=_e||function(e){return d.default.createElement("div",null,d.default.createElement(S,e),d.default.createElement(I,e))},P=t.Pivot||T;return(y.pivoted||y.expander)&&(y.expandable=!0,_={onClick:C},y.pivoted&&(y.subRows||he||(y.expandable=!1,_={}))),y.pivoted?(x=i.row[H]===t.id&&y.subRows,w=V.indexOf(t.id)>V.indexOf(i.row[H])&&y.subRows,k=x?h.default.normalizeComponent(P,s({},y,{value:n[W]}),n[W]):w?h.default.normalizeComponent(A,y,v):null):y.aggregated&&(k=h.default.normalizeComponent(A,y,v)),y.expander&&(k=h.default.normalizeComponent(S,y,n[W]),V&&(y.groupedByPivot&&(k=null),y.subRows||he||(k=null))),d.default.createElement(de,s({key:r+"-"+t.id,className:(0,f.default)(g,!l&&"hidden",y.expandable&&"rt-expandable",(x||w)&&"rt-pivot"),style:s({},b,{flex:c+" 0 auto",width:c+"px",maxWidth:u+"px"})},p.rest,_),k)})),i.subRows&&a&&i.subRows.map(function(e,n){return t(e,n,i.nestingPath)}),he&&!i.subRows&&a&&he(i))},Ze=function(t,n){var r=C(Be,void 0,void 0,e),o=h.default.splitProps(k(Be,void 0,void 0,e));return d.default.createElement(se,s({key:n},r),d.default.createElement(ce,{className:(0,f.default)("-padRow",(Me.length+n)%2?"-even":"-odd",o.className),style:o.style||{}},Ee.map(Xe)))},Xe=function(t,n){var r=te.find(function(e){return e.id===t.id})||{},o="function"==typeof t.show?t.show():t.show,i=h.default.getFirstDefined(r.value,t.width,t.minWidth),a=i,l=h.default.getFirstDefined(r.value,t.width,t.maxWidth),c=h.default.splitProps(E(Be,void 0,t,e)),u=h.default.splitProps(t.getProps(Be,void 0,t,e)),p=[c.className,t.className,u.className],m=s({},c.style,t.style,u.style);return d.default.createElement(de,s({key:n+"-"+t.id,className:(0,f.default)(p,!o&&"hidden"),style:s({},m,{flex:a+" 0 auto",width:i+"px",maxWidth:l+"px"})},c.rest),h.default.normalizeComponent(Ce))},Qe=function(){var t=A(Be,void 0,void 0,e),n=h.default.splitProps(S(Be,void 0,void 0,e));return d.default.createElement(pe,s({className:t.className,style:s({},t.style,{minWidth:ze+"px"})},t.rest),d.default.createElement(ce,s({className:(0,f.default)(n.className),style:n.style},n.rest),Ee.map(Je)))},Je=function(t,n){var r=te.find(function(e){return e.id===t.id})||{},o="function"==typeof t.show?t.show():t.show,i=h.default.getFirstDefined(r.value,t.width,t.minWidth),a=h.default.getFirstDefined(r.value,t.width,t.maxWidth),l=h.default.splitProps(I(Be,void 0,void 0,e)),c=h.default.splitProps(t.getProps(Be,void 0,t,e)),u=h.default.splitProps(t.getFooterProps(Be,void 0,t,e)),p=[l.className,t.className,c.className,u.className],m=s({},l.style,t.style,c.style,u.style);return d.default.createElement(de,s({key:n+"-"+t.id,className:(0,f.default)(p,!o&&"hidden"),style:s({},m,{flex:i+" 0 auto",width:i+"px",maxWidth:a+"px"})},c.rest,l.rest,u.rest),h.default.normalizeComponent(t.Footer,{data:Ie,column:t}))},$e=function(){var n=h.default.splitProps(T(Be,void 0,void 0,e));return d.default.createElement(fe,s({},t,{pages:re,canPrevious:je,canNext:Fe,onPageChange:e.onPageChange,onPageSizeChange:e.onPageSizeChange,className:n.className,style:n.style},n.rest))},et=h.default.splitProps(i(Be,void 0,void 0,this)),tt=h.default.splitProps(a(Be,void 0,void 0,this)),nt=h.default.splitProps(w(Be,void 0,void 0,this)),rt=P(Be,void 0,void 0,this),ot=O(Be,void 0,void 0,this),it=M(Be,void 0,void 0,this),at=function(){var e=$e();return d.default.createElement("div",s({className:(0,f.default)("ReactTable",r,et.className),style:s({},o,et.style)},et.rest),R&&N?d.default.createElement("div",{className:"pagination-top"},e):null,d.default.createElement(ie,s({className:(0,f.default)(tt.className,Te?"rt-resizing":""),style:tt.style},tt.rest),Se?He():null,Ve(),De?Ye():null,d.default.createElement(le,s({className:(0,f.default)(nt.className),style:s({},nt.style,{minWidth:ze+"px"})},nt.rest),Me.map(function(e,t){return Ke(e,t)}),Ne.map(Ze)),Le?Qe():null),R&&L?d.default.createElement("div",{className:"pagination-bottom"},e):null,!Me.length&&d.default.createElement(ge,ot,h.default.normalizeComponent(F)),d.default.createElement(me,s({loading:X,loadingText:j},rt)))};return n?n(Be,at,this):at()}}]),t}((0,v.default)((0,b.default)(u.Component))));w.defaultProps=x.default,t.default=w},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}();t.default=function(e){return function(e){function t(){return r(this,t),o(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return i(t,e),a(t,[{key:"componentWillMount",value:function(){this.setStateWithData(this.getDataModel(this.getResolvedState()))}},{key:"componentDidMount",value:function(){this.fireFetchData()}},{key:"componentWillReceiveProps",value:function(e,t){var n=this.getResolvedState(),r=this.getResolvedState(e,t);["sorted","filtered","resized","expanded"].forEach(function(e){var t="default"+(e.charAt(0).toUpperCase()+e.slice(1));JSON.stringify(n[t])!==JSON.stringify(r[t])&&(r[e]=r[t])}),["sortable","filterable","resizable"].forEach(function(e){if(n[e]!==r[e]){var t=e.replace("able",""),o=t+"ed",i="default"+(o.charAt(0).toUpperCase()+o.slice(1));r[o]=r[i]}}),n.data===r.data&&n.columns===r.columns&&n.pivotBy===r.pivotBy&&n.sorted===r.sorted&&n.filtered===r.filtered||this.setStateWithData(this.getDataModel(r))}},{key:"setStateWithData",value:function(e,t){var n=this.getResolvedState(),r=this.getResolvedState({},e),o=r.freezeWhenExpanded;if(r.frozen=!1,o)for(var i=Object.keys(r.expanded),a=0;a<i.length;a++)if(r.expanded[i[a]]){r.frozen=!0;break}return(n.frozen&&!r.frozen||n.sorted!==r.sorted||n.filtered!==r.filtered||n.showFilters!==r.showFilters||!r.frozen&&n.resolvedData!==r.resolvedData)&&((n.sorted!==r.sorted&&this.props.collapseOnSortingChange||n.filtered!==r.filtered||n.showFilters!==r.showFilters||!r.frozen&&n.resolvedData!==r.resolvedData&&this.props.collapseOnDataChange)&&(r.expanded={}),Object.assign(r,this.getSortedData(r))),r.sortedData&&(r.pages=r.manual?r.pages:Math.ceil(r.sortedData.length/r.pageSize),r.page=Math.max(r.page>=r.pages?r.pages-1:r.page,0)),this.setState(r,t)}}]),t}(e)}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var c=function(){function e(e,t){var n=[],r=!0,o=!1,i=void 0;try{for(var a,l=e[Symbol.iterator]();!(r=(a=l.next()).done)&&(n.push(a.value),!t||n.length!==t);r=!0);}catch(e){o=!0,i=e}finally{try{!r&&l.return&&l.return()}finally{if(o)throw i}}return n}return function(t,n){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,n);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},d=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),f=n(10),m=r(f),h=n(193),g=r(h);t.default=function(e){return function(e){function t(){return a(this,t),l(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return s(t,e),p(t,[{key:"getResolvedState",value:function(e,t){return d({},g.default.compactObject(this.state),g.default.compactObject(this.props),g.default.compactObject(t),g.default.compactObject(e))}},{key:"getDataModel",value:function(e){var t=this,n=e.columns,r=e.pivotBy,a=void 0===r?[]:r,l=e.data,s=e.pivotIDKey,p=e.pivotValKey,f=e.subRowsKey,h=e.aggregatedKey,b=e.nestingLevelKey,y=e.originalKey,v=e.indexKey,_=e.groupedByPivotKey,x=e.SubComponent,w=!1;n.forEach(function(e){e.columns&&(w=!0)});var C=[].concat(i(n)),k=n.find(function(e){return e.expander||e.columns&&e.columns.some(function(e){return e.expander})});k&&!k.expander&&(k=k.columns.find(function(e){return e.expander})),x&&!k&&(k={expander:!0},C=[k].concat(i(C)));var E=function(e){var n=void 0;if(n=e.expander?d({},t.props.column,t.props.expanderDefaults,e):d({},t.props.column,e),"string"==typeof n.accessor){var r=function(){n.id=n.id||n.accessor;var e=n.accessor;return n.accessor=function(t){return g.default.get(t,e)},{v:n}}();if("object"===(void 0===r?"undefined":u(r)))return r.v}if(n.accessor&&!n.id)throw console.warn(n),new Error("A column id is required if using a non-string accessor for column above.");return n.accessor||(n.accessor=function(e){}),n.maxWidth<n.minWidth&&(n.minWidth=n.maxWidth),n},A=function(e){var t=E(e);return S.push(t),t},S=[],I=C.map(function(e,t){return e.columns?d({},e,{columns:e.columns.map(A)}):A(e)}),T=I.slice(),P=[];T=T.map(function(e,t){if(e.columns){return d({},e,{columns:e.columns.filter(function(e){return!(a.indexOf(e.id)>-1)&&g.default.getFirstDefined(e.show,!0)})})}return e}),T=T.filter(function(e){return e.columns?e.columns.length:!(a.indexOf(e.id)>-1)&&g.default.getFirstDefined(e.show,!0)});var O=T.findIndex(function(e){return e.pivot});a.length&&function(){var e=[];a.forEach(function(t){var n=S.find(function(e){return e.id===t});n&&e.push(n)});var n={header:function(){return m.default.createElement("strong",null,"Group")},columns:e.map(function(e){return d({},t.props.pivotDefaults,e,{pivoted:!0})})};O>=0?(n=d({},T[O],n),T.splice(O,1,n)):T.unshift(n)}();var M=[],R=[],N=function(e,n){M.push(d({},t.props.column,n,{columns:e})),R=[]};T.forEach(function(e,t){if(e.columns)return P=P.concat(e.columns),R.length>0&&N(R),void N(e.columns,e);P.push(e),R.push(e)}),w&&R.length>0&&N(R);var L=function e(t,n){var r,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,a=(r={},o(r,y,t),o(r,v,n),o(r,f,t[f]),o(r,b,i),r);return S.forEach(function(e){e.expander||(a[e.id]=e.accessor(t))}),a[f]&&(a[f]=a[f].map(function(t,n){return e(t,n,i+1)})),a},D=l.map(function(e,t){return L(e,t)}),j=function(e){var t={};return F.forEach(function(n){var r=e.map(function(e){return e[n.id]});t[n.id]=n.aggregate(r,e)}),t},F=P.filter(function(e){return!e.expander&&e.aggregate});return a.length&&function(){D=function e(t,n){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;if(r===n.length)return t;var i=Object.entries(g.default.groupBy(t,n[r])).map(function(e){var t,i=c(e,2),a=i[0],l=i[1];return t={},o(t,s,n[r]),o(t,p,a),o(t,n[r],a),o(t,f,l),o(t,b,r),o(t,_,!0),t});return i=i.map(function(t){var i,a=e(t[f],n,r+1);return d({},t,(i={},o(i,f,a),o(i,h,!0),i),j(a))})}(D,a)}(),d({},e,{resolvedData:D,allVisibleColumns:P,headerGroups:M,allDecoratedColumns:S,hasHeaderGroups:w})}},{key:"getSortedData",value:function(e){var t=e.manual,n=e.sorted,r=e.filtered,o=e.defaultFilterMethod,i=e.resolvedData,a=e.allVisibleColumns,l=e.allDecoratedColumns,s={};return l.filter(function(e){return e.sortMethod}).forEach(function(e){s[e.id]=e.sortMethod}),{sortedData:t?i:this.sortData(this.filterData(i,r,o,a),n,s)}}},{key:"fireFetchData",value:function(){this.props.onFetchData(this.getResolvedState(),this)}},{key:"getPropOrState",value:function(e){return g.default.getFirstDefined(this.props[e],this.state[e])}},{key:"getStateOrProp",value:function(e){return g.default.getFirstDefined(this.state[e],this.props[e])}},{key:"filterData",value:function(e,t,n,r){var i=this,a=e;return t.length&&(a=t.reduce(function(e,t){return e.filter(function(e){var o=void 0;return!(o=r.find(function(e){return e.id===t.id}))||o.filterable===!1||(o.filterMethod||n)(t,e,o)})},a),a=a.map(function(e){return e[i.props.subRowsKey]?d({},e,o({},i.props.subRowsKey,i.filterData(e[i.props.subRowsKey],t,n,r))):e}).filter(function(e){return!e[i.props.subRowsKey]||e[i.props.subRowsKey].length>0})),a}},{key:"sortData",value:function(e,t){var n=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t.length)return e;var o=(this.props.orderByMethod||g.default.orderBy)(e,t.map(function(e){return r[e.id]?function(t,n){return r[e.id](t[e.id],n[e.id])}:function(t,r){return n.props.defaultSortMethod(t[e.id],r[e.id])}}),t.map(function(e){return!e.desc}),this.props.indexKey);return o.forEach(function(e){e[n.props.subRowsKey]&&(e[n.props.subRowsKey]=n.sortData(e[n.props.subRowsKey],t,r))}),o}},{key:"getMinRows",value:function(){return g.default.getFirstDefined(this.props.minRows,this.getStateOrProp("pageSize"))}},{key:"onPageChange",value:function e(t){var n=this,r=this.props,e=r.onPageChange,o=r.collapseOnPageChange,i={page:t};o&&(i.expanded={}),this.setStateWithData(i,function(){e&&e(t),n.fireFetchData()})}},{key:"onPageSizeChange",value:function e(t){var n=this,e=this.props.onPageSizeChange,r=this.getResolvedState(),o=r.pageSize,i=r.page,a=o*i,l=Math.floor(a/t);this.setStateWithData({pageSize:t,page:l},function(){e&&e(t,l),n.fireFetchData()})}},{key:"sortColumn",value:function(e,t){var n=this,r=this.getResolvedState(),o=r.sorted,i=r.skipNextSort,a=r.defaultSortDesc,l=e.hasOwnProperty("defaultSortDesc")?e.defaultSortDesc:a,s=!l;if(i)return void this.setStateWithData({skipNextSort:!1});var c=this.props.onSortedChange,u=g.default.clone(o||[]).map(function(e){return e.desc=g.default.isSortingDesc(e),e});if(g.default.isArray(e))!function(){var n=u.findIndex(function(t){return t.id===e[0].id});if(n>-1){u[n].desc===s?t?u.splice(n,e.length):e.forEach(function(e,t){u[n+t].desc=l}):e.forEach(function(e,t){u[n+t].desc=s}),t||(u=u.slice(n,e.length))}else u=t?u.concat(e.map(function(e){return{id:e.id,desc:l}})):e.map(function(e){return{id:e.id,desc:l}})}();else{var d=u.findIndex(function(t){return t.id===e.id});if(d>-1){var p=u[d];p.desc===s?t?u.splice(d,1):(p.desc=l,u=[p]):(p.desc=s,t||(u=[p]))}else t?u.push({id:e.id,desc:l}):u=[{id:e.id,desc:l}]}this.setStateWithData({page:!o.length&&u.length||!t?0:this.state.page,sorted:u},function(){c&&c(u,e,t),n.fireFetchData()})}},{key:"filterColumn",value:function(e,t){var n=this,r=this.getResolvedState(),o=r.filtered,i=this.props.onFilteredChange,a=(o||[]).filter(function(t){if(t.id!==e.id)return!0});""!==t&&a.push({id:e.id,value:t}),this.setStateWithData({filtered:a},function(){i&&i(a,e,t),n.fireFetchData()})}},{key:"resizeColumnStart",value:function(e,t,n){var r=this,o=t.target.parentElement.getBoundingClientRect().width,i=void 0;i=n?t.changedTouches[0].pageX:t.pageX,this.setStateWithData({currentlyResizing:{id:e.id,startX:i,parentWidth:o}},function(){n?(document.addEventListener("touchmove",r.resizeColumnMoving),document.addEventListener("touchcancel",r.resizeColumnEnd),document.addEventListener("touchend",r.resizeColumnEnd)):(document.addEventListener("mousemove",r.resizeColumnMoving),document.addEventListener("mouseup",r.resizeColumnEnd),document.addEventListener("mouseleave",r.resizeColumnEnd))})}},{key:"resizeColumnEnd",value:function(e){var t="touchend"===e.type||"touchcancel"===e.type;t&&(document.removeEventListener("touchmove",this.resizeColumnMoving),document.removeEventListener("touchcancel",this.resizeColumnEnd),document.removeEventListener("touchend",this.resizeColumnEnd)),document.removeEventListener("mousemove",this.resizeColumnMoving),document.removeEventListener("mouseup",this.resizeColumnEnd),document.removeEventListener("mouseleave",this.resizeColumnEnd),t||this.setStateWithData({skipNextSort:!0,currentlyResizing:!1})}},{key:"resizeColumnMoving",value:function(e){var t=this.props.onResizedChange,n=this.getResolvedState(),r=n.resized,o=n.currentlyResizing,i=r.filter(function(e){return e.id!==o.id}),a=void 0;"touchmove"===e.type?a=e.changedTouches[0].pageX:"mousemove"===e.type&&(a=e.pageX);var l=Math.max(o.parentWidth+a-o.startX,11);i.push({id:o.id,value:l}),this.setStateWithData({resized:i},function(){t&&t(i,e)})}}]),t}(e)}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},c=n(10),u=r(c),d=n(88),p=r(d),f=function(e){return u.default.createElement("button",s({type:"button"},e,{className:"-btn"}),e.children)},m=function(e){function t(e){o(this,t);var n=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return n.getSafePage=n.getSafePage.bind(n),n.changePage=n.changePage.bind(n),n.applyPage=n.applyPage.bind(n),n.state={page:e.page},n}return a(t,e),l(t,[{key:"componentWillReceiveProps",value:function(e){this.setState({page:e.page})}},{key:"getSafePage",value:function(e){return isNaN(e)&&(e=this.props.page),Math.min(Math.max(e,0),this.props.pages-1)}},{key:"changePage",value:function(e){e=this.getSafePage(e),this.setState({page:e}),this.props.page!==e&&this.props.onPageChange(e)}},{key:"applyPage",value:function(e){e&&e.preventDefault();var t=this.state.page;this.changePage(""===t?this.props.page:t)}},{key:"render",value:function(){var e=this,t=this.props,n=t.pages,r=t.page,o=t.showPageSizeOptions,i=t.pageSizeOptions,a=t.pageSize,l=t.showPageJump,s=t.canPrevious,c=t.canNext,d=t.onPageSizeChange,m=t.className,h=t.PreviousComponent,g=void 0===h?f:h,b=t.NextComponent,y=void 0===b?f:b;return u.default.createElement("div",{className:(0,p.default)(m,"-pagination"),style:this.props.paginationStyle},u.default.createElement("div",{className:"-previous"},u.default.createElement(g,{onClick:function(t){s&&e.changePage(r-1)},disabled:!s},this.props.previousText)),u.default.createElement("div",{className:"-center"},u.default.createElement("span",{className:"-pageInfo"},this.props.pageText," ",l?u.default.createElement("div",{className:"-pageJump"},u.default.createElement("input",{type:""===this.state.page?"text":"number",onChange:function(t){var n=t.target.value,r=n-1;if(""===n)return e.setState({page:n});e.setState({page:e.getSafePage(r)})},value:""===this.state.page?"":this.state.page+1,onBlur:this.applyPage,onKeyPress:function(t){13!==t.which&&13!==t.keyCode||e.applyPage()}})):u.default.createElement("span",{className:"-currentPage"},r+1)," ",this.props.ofText," ",u.default.createElement("span",{className:"-totalPages"},n||1)),o&&u.default.createElement("span",{className:"select-wrap -pageSizeOptions"},u.default.createElement("select",{onChange:function(e){return d(Number(e.target.value))},value:a},i.map(function(t,n){return u.default.createElement("option",{key:n,value:t},t," ",e.props.rowsText)})))),u.default.createElement("div",{className:"-next"},u.default.createElement(y,{onClick:function(t){c&&e.changePage(r+1)},disabled:!c},this.props.nextText)))}}]),t}(c.Component);t.default=m},function(e,t,n){"use strict";t.__esModule=!0;var r={number:"number",string:"string",object:"object",array:"array",json:"json",date:"date",boolean:"boolean",numericObject:"numericObject",numericArray:"numericArray"};t.default=r},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0,t.subqueryOmit=t.subquery=t.urlQueryReducer=t.urlQueryMiddleware=t.urlPushInAction=t.urlReplaceInAction=t.urlPushAction=t.urlReplaceAction=t.urlAction=t.pushUrlQueryFromAction=t.pushInUrlQueryFromAction=t.replaceUrlQueryFromAction=t.replaceInUrlQueryFromAction=t.RouterToUrlQuery=t.addUrlProps=t.UrlUpdateTypes=t.UrlQueryParamTypes=t.multiPushInUrlQuery=t.multiReplaceInUrlQuery=t.pushUrlQuery=t.pushInUrlQuery=t.replaceUrlQuery=t.replaceInUrlQuery=t.decode=t.encode=t.Serialize=t.configureUrlQuery=void 0;var i=n(126);Object.defineProperty(t,"encode",{enumerable:!0,get:function(){return i.encode}}),Object.defineProperty(t,"decode",{enumerable:!0,get:function(){return i.decode}});var a=n(194);Object.defineProperty(t,"replaceInUrlQuery",{enumerable:!0,get:function(){return a.replaceInUrlQuery}}),Object.defineProperty(t,"replaceUrlQuery",{enumerable:!0,get:function(){return a.replaceUrlQuery}}),Object.defineProperty(t,"pushInUrlQuery",{enumerable:!0,get:function(){return a.pushInUrlQuery}}),Object.defineProperty(t,"pushUrlQuery",{enumerable:!0,get:function(){return a.pushUrlQuery}}),Object.defineProperty(t,"multiReplaceInUrlQuery",{enumerable:!0,get:function(){return a.multiReplaceInUrlQuery}}),Object.defineProperty(t,"multiPushInUrlQuery",{enumerable:!0,get:function(){return a.multiPushInUrlQuery}});var l=n(285);Object.defineProperty(t,"replaceInUrlQueryFromAction",{enumerable:!0,get:function(){return l.replaceInUrlQueryFromAction}}),Object.defineProperty(t,"replaceUrlQueryFromAction",{enumerable:!0,get:function(){return l.replaceUrlQueryFromAction}}),Object.defineProperty(t,"pushInUrlQueryFromAction",{enumerable:!0,get:function(){return l.pushInUrlQueryFromAction}}),Object.defineProperty(t,"pushUrlQueryFromAction",{enumerable:!0,get:function(){return l.pushUrlQueryFromAction}});var s=n(671);Object.defineProperty(t,"urlReplaceAction",{enumerable:!0,get:function(){return s.urlReplaceAction}}),Object.defineProperty(t,"urlPushAction",{enumerable:!0,get:function(){return s.urlPushAction}}),Object.defineProperty(t,"urlReplaceInAction",{enumerable:!0,get:function(){return s.urlReplaceInAction}}),Object.defineProperty(t,"urlPushInAction",{enumerable:!0,get:function(){return s.urlPushInAction}});var c=n(284),u=o(c),d=r(i),p=n(667),f=o(p),m=n(100),h=o(m),g=n(670),b=o(g),y=n(669),v=o(y),_=o(s),x=n(672),w=o(x),C=n(286),k=o(C),E=n(674),A=o(E),S=n(675),I=o(S);t.configureUrlQuery=u.default,t.Serialize=d,t.UrlQueryParamTypes=f.default,t.UrlUpdateTypes=h.default,t.addUrlProps=b.default,t.RouterToUrlQuery=v.default,t.urlAction=_.default,t.urlQueryMiddleware=w.default,t.urlQueryReducer=k.default,t.subquery=A.default,t.subqueryOmit=I.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}t.__esModule=!0;var l=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=n(10),c=r(s),u=n(120),d=r(u),p=n(284),f=r(p),m=function(e){function t(){return o(this,t),i(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return a(t,e),l(t,[{key:"componentWillMount",value:function(){var e=this.context.router,t=void 0;e.history&&e.history.push&&e.history.replace?t=e.history:e.push&&e.replace?t=e:e.transitionTo&&e.replaceWith&&(t={push:e.transitionTo,replace:e.replaceWith}),(0,f.default)({history:t})}},{key:"render",value:function(){var e=this.props.children;return c.default.Children.only(e)}}]),t}(s.Component);m.propTypes={children:d.default.node},m.contextTypes={router:d.default.object},t.default=m},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function l(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.mapUrlToProps,n=void 0===t?function(e){return e}:t,r=e.mapUrlChangeHandlersToProps,l=e.urlPropsQueryConfig,d=e.addRouterParams,m=e.addUrlChangeHandlers,g=e.changeHandlerName;return function(e){function t(e){var t=void 0;t=b.default.history.location?b.default.history.location:e.location&&(e.location.query||null!=e.location.search)?e.location:window.location;var n=t.query||(0,f.parse)(t.search)||{},r=void 0;return r=w?w(n):n,(d||d!==!1&&b.default.addRouterParams)&&Object.assign(r,e.params,e.match&&e.match.params),r}var _=void 0,w=void 0;l&&(w=(0,h.default)(l));var C=e.displayName||e.name||"Component",k=function(c){function d(){return o(this,d),i(this,(d.__proto__||Object.getPrototypeOf(d)).apply(this,arguments))}return a(d,c),s(d,[{key:"getUrlChangeHandlerProps",value:function(e){var t=this,n=void 0;if(l&&(m||null==m&&b.default.addUrlChangeHandlers))if(_)n=_;else{g||(g=b.default.changeHandlerName),n=Object.keys(l).reduce(function(e,n){var r=l[n],o=r.updateType,i=r.queryParam,a=void 0===i?n:i,s=r.type;return e[g(n)]=function(e){var t=b.default.history.location;t||(t=this.props.location);var n=(0,v.encode)(s,e);if(!t||!t.query||t.query[a]!==n)return(0,y.updateUrlQuerySingle)(o,a,n,t)}.bind(t),e},{});var o=g("urlQueryParams");n[o]=function(e){var t=arguments.length<=1||void 0===arguments[1]?x.default.replaceIn:arguments[1],n=b.default.history.location;n||(n=this.props.location);var r=!0,o=Object.keys(e).reduce(function(t,o){var i=l[o],a=i.queryParam,s=void 0===a?o:a,c=i.type,u=e[o],d=(0,v.encode)(c,u);return t[s]=d,n&&n.query&&n.query[s]!==d&&(r=!1),t},{});if(!(n&&n.query&&r))return(0,y.updateUrlQueryMulti)(t,o,n)}.bind(this),_=n}return r&&(n=r.call(this,e,n)),n}},{key:"render",value:function(){var r=t(this.props);return this.propsWithUrl=Object.assign({},this.props,n(r,this.props)),Object.assign(this.propsWithUrl,this.getUrlChangeHandlerProps(this.propsWithUrl)),u.default.createElement(e,this.propsWithUrl)}}]),d}(c.Component);return k.displayName="AddUrlProps("+C+")",k.WrappedComponent=e,k.propTypes={location:p.default.any},k}}t.__esModule=!0;var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}();t.default=l;var c=n(10),u=r(c),d=n(120),p=r(d),f=n(254),m=n(673),h=r(m),g=n(127),b=r(g),y=n(194),v=n(126),_=n(100),x=r(_)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=arguments.length<=1||void 0===arguments[1]?function(e){return e}:arguments[1],n=arguments.length<=2||void 0===arguments[2]?function(){}:arguments[2];return function(){var r=n.apply(void 0,arguments);return null==r?r={}:"object"!==(void 0===r?"undefined":p(r))&&(r={value:r}),{type:e,meta:d({},r,{urlQuery:!0}),payload:t.apply(void 0,arguments)}}}function i(e){var t=arguments.length<=1||void 0===arguments[1]?function(e){return e}:arguments[1],n=arguments.length<=2||void 0===arguments[2]?h.default.replace:arguments[2];return o(e,function(e){return{encodedQuery:t(e),decodedQuery:e}},function(){return{updateType:n}})}function a(e,t){return i(e,t,h.default.replace)}function l(e,t){return i(e,t,h.default.push)}function s(e,t,n,r){return o(e,function(e){return{queryParam:t,encodedValue:(0,f.encode)(n,e),decodedValue:e,type:n}},function(){return{updateType:r}})}function c(e,t,n){return s(e,t,n,h.default.replaceIn)}function u(e,t,n){return s(e,t,n,h.default.pushIn)}t.__esModule=!0;var d=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e};t.default=o,t.urlUpdateAction=i,t.urlReplaceAction=a,t.urlPushAction=l,t.urlUpdateInAction=s,t.urlReplaceInAction=c,t.urlPushInAction=u;var f=n(126),m=n(100),h=r(m)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(286),i=r(o),a=n(127),l=r(a),s=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];return function(t){var n=t.getState;return function(t){return function(r){if(!r.meta||!r.meta.urlQuery)return t(r);var o=e.reducer||l.default.reducer||i.default,a=null==e.readLocationFromStore?l.default.readLocationFromStore:e.readLocationFromStore;if(a){o(r,a(n()))}else o(r);return e.shortcircuit===!1?t(r):void 0}}}};t.default=s},function(e,t,n){"use strict";function r(e){var t=void 0,n=void 0;return function(r){var i=Object.keys(e).reduce(function(i,a){var l=e[a],s=l.queryParam,c=void 0===s?a:s,u=r[c],d=void 0;return d=t&&void 0!==t[c]&&t[c]===u?n[a]:(0,o.decode)(l.type,u,l.defaultValue),void 0!==d&&l.validate&&!l.validate(d)&&(d=void 0),i[a]=d,i},{});return t=r,n=i,i}}t.__esModule=!0,t.default=r;var o=n(126)},function(e,t,n){"use strict";function r(e){if(!e)return e;for(var t=arguments.length,n=Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return n.reduce(function(t,n){return t[n]=e[n],t},{})}t.__esModule=!0,t.default=r},function(e,t,n){"use strict";function r(e){for(var t=arguments.length,n=Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return e?Object.keys(e).filter(function(e){return!n.includes(e)}).reduce(function(t,n){return t[n]=e[n],t},{}):e}t.__esModule=!0,t.default=r},function(e,t,n){"use strict";function r(e){var t=/[=:]/g,n={"=":"=0",":":"=2"};return"$"+(""+e).replace(t,function(e){return n[e]})}function o(e){var t=/(=0|=2)/g,n={"=0":"=","=2":":"};return(""+("."===e[0]&&"$"===e[1]?e.substring(2):e.substring(1))).replace(t,function(e){return n[e]})}var i={escape:r,unescape:o};e.exports=i},function(e,t,n){"use strict";var r=n(86),o=(n(1),function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)}),i=function(e,t){var n=this;if(n.instancePool.length){var r=n.instancePool.pop();return n.call(r,e,t),r}return new n(e,t)},a=function(e,t,n){var r=this;if(r.instancePool.length){var o=r.instancePool.pop();return r.call(o,e,t,n),o}return new r(e,t,n)},l=function(e,t,n,r){var o=this;if(o.instancePool.length){var i=o.instancePool.pop();return o.call(i,e,t,n,r),i}return new o(e,t,n,r)},s=function(e){var t=this;e instanceof t||r("25"),e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},c=10,u=o,d=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||u,n.poolSize||(n.poolSize=c),n.release=s,n},p={addPoolingTo:d,oneArgumentPooler:o,twoArgumentPooler:i,threeArgumentPooler:a,fourArgumentPooler:l};e.exports=p},function(e,t,n){"use strict";function r(e){return(""+e).replace(_,"$&/")}function o(e,t){this.func=e,this.context=t,this.count=0}function i(e,t,n){var r=e.func,o=e.context;r.call(o,t,e.count++)}function a(e,t,n){if(null==e)return e;var r=o.getPooled(t,n);b(e,i,r),o.release(r)}function l(e,t,n,r){this.result=e,this.keyPrefix=t,this.func=n,this.context=r,this.count=0}function s(e,t,n){var o=e.result,i=e.keyPrefix,a=e.func,l=e.context,s=a.call(l,t,e.count++);Array.isArray(s)?c(s,o,n,g.thatReturnsArgument):null!=s&&(h.isValidElement(s)&&(s=h.cloneAndReplaceKey(s,i+(!s.key||t&&t.key===s.key?"":r(s.key)+"/")+n)),o.push(s))}function c(e,t,n,o,i){var a="";null!=n&&(a=r(n)+"/");var c=l.getPooled(t,a,o,i);b(e,s,c),l.release(c)}function u(e,t,n){if(null==e)return e;var r=[];return c(e,r,null,t,n),r}function d(e,t,n){return null}function p(e,t){return b(e,d,null)}function f(e){var t=[];return c(e,t,null,g.thatReturnsArgument),t}var m=n(677),h=n(85),g=n(28),b=n(686),y=m.twoArgumentPooler,v=m.fourArgumentPooler,_=/\/+/g;o.prototype.destructor=function(){this.func=null,this.context=null,this.count=0},m.addPoolingTo(o,y),l.prototype.destructor=function(){this.result=null,this.keyPrefix=null,this.func=null,this.context=null,this.count=0},m.addPoolingTo(l,v);var x={forEach:a,map:u,mapIntoWithKeyPrefixInternal:c,count:p,toArray:f};e.exports=x},function(e,t,n){"use strict";function r(e){return e}function o(e,t){var n=_.hasOwnProperty(t)?_[t]:null;w.hasOwnProperty(t)&&"OVERRIDE_BASE"!==n&&p("73",t),e&&"DEFINE_MANY"!==n&&"DEFINE_MANY_MERGED"!==n&&p("74",t)}function i(e,t){if(t){"function"==typeof t&&p("75"),h.isValidElement(t)&&p("76");var n=e.prototype,r=n.__reactAutoBindPairs;t.hasOwnProperty(y)&&x.mixins(e,t.mixins);for(var i in t)if(t.hasOwnProperty(i)&&i!==y){var a=t[i],l=n.hasOwnProperty(i);if(o(l,i),x.hasOwnProperty(i))x[i](e,a);else{var u=_.hasOwnProperty(i),d="function"==typeof a,f=d&&!u&&!l&&t.autobind!==!1;if(f)r.push(i,a),n[i]=a;else if(l){var m=_[i];(!u||"DEFINE_MANY_MERGED"!==m&&"DEFINE_MANY"!==m)&&p("77",m,i),"DEFINE_MANY_MERGED"===m?n[i]=s(n[i],a):"DEFINE_MANY"===m&&(n[i]=c(n[i],a))}else n[i]=a}}}else;}function a(e,t){if(t)for(var n in t){var r=t[n];if(t.hasOwnProperty(n)){var o=n in x;o&&p("78",n);var i=n in e;i&&p("79",n),e[n]=r}}}function l(e,t){e&&t&&"object"==typeof e&&"object"==typeof t||p("80");for(var n in t)t.hasOwnProperty(n)&&(void 0!==e[n]&&p("81",n),e[n]=t[n]);return e}function s(e,t){return function(){var n=e.apply(this,arguments),r=t.apply(this,arguments);if(null==n)return r;if(null==r)return n;var o={};return l(o,n),l(o,r),o}}function c(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function u(e,t){var n=t.bind(e);return n}function d(e){for(var t=e.__reactAutoBindPairs,n=0;n<t.length;n+=2){var r=t[n],o=t[n+1];e[r]=u(e,o)}}var p=n(86),f=n(9),m=n(195),h=n(85),g=(n(289),n(196)),b=n(82),y=(n(1),n(4),"mixins"),v=[],_={mixins:"DEFINE_MANY",statics:"DEFINE_MANY",propTypes:"DEFINE_MANY",contextTypes:"DEFINE_MANY",childContextTypes:"DEFINE_MANY",getDefaultProps:"DEFINE_MANY_MERGED",getInitialState:"DEFINE_MANY_MERGED",getChildContext:"DEFINE_MANY_MERGED",render:"DEFINE_ONCE",componentWillMount:"DEFINE_MANY",componentDidMount:"DEFINE_MANY",componentWillReceiveProps:"DEFINE_MANY",shouldComponentUpdate:"DEFINE_ONCE",componentWillUpdate:"DEFINE_MANY",componentDidUpdate:"DEFINE_MANY",componentWillUnmount:"DEFINE_MANY",updateComponent:"OVERRIDE_BASE"},x={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)i(e,t[n])},childContextTypes:function(e,t){e.childContextTypes=f({},e.childContextTypes,t)},contextTypes:function(e,t){e.contextTypes=f({},e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps?e.getDefaultProps=s(e.getDefaultProps,t):e.getDefaultProps=t},propTypes:function(e,t){e.propTypes=f({},e.propTypes,t)},statics:function(e,t){a(e,t)},autobind:function(){}},w={replaceState:function(e,t){this.updater.enqueueReplaceState(this,e),t&&this.updater.enqueueCallback(this,t,"replaceState")},isMounted:function(){return this.updater.isMounted(this)}},C=function(){};f(C.prototype,m.prototype,w);var k={createClass:function(e){var t=r(function(e,n,r){this.__reactAutoBindPairs.length&&d(this),this.props=e,this.context=n,this.refs=b,this.updater=r||g,this.state=null;var o=this.getInitialState?this.getInitialState():null;("object"!=typeof o||Array.isArray(o))&&p("82",t.displayName||"ReactCompositeComponent"),this.state=o});t.prototype=new C,t.prototype.constructor=t,t.prototype.__reactAutoBindPairs=[],v.forEach(i.bind(null,t)),i(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),t.prototype.render||p("83");for(var n in _)t.prototype[n]||(t.prototype[n]=null);return t},injection:{injectMixin:function(e){v.push(e)}}};e.exports=k},function(e,t,n){"use strict";var r=n(85),o=r.createFactory,i={a:o("a"),abbr:o("abbr"),address:o("address"),area:o("area"),article:o("article"),aside:o("aside"),audio:o("audio"),b:o("b"),base:o("base"),bdi:o("bdi"),bdo:o("bdo"),big:o("big"),blockquote:o("blockquote"),body:o("body"),br:o("br"),button:o("button"),canvas:o("canvas"),caption:o("caption"),cite:o("cite"),code:o("code"),col:o("col"),colgroup:o("colgroup"),data:o("data"),datalist:o("datalist"),dd:o("dd"),del:o("del"),details:o("details"),dfn:o("dfn"),dialog:o("dialog"),div:o("div"),dl:o("dl"),dt:o("dt"),em:o("em"),embed:o("embed"),fieldset:o("fieldset"),figcaption:o("figcaption"),figure:o("figure"),footer:o("footer"),form:o("form"),h1:o("h1"),h2:o("h2"),h3:o("h3"),h4:o("h4"),h5:o("h5"),h6:o("h6"),head:o("head"),header:o("header"),hgroup:o("hgroup"),hr:o("hr"),html:o("html"),i:o("i"),iframe:o("iframe"),img:o("img"),input:o("input"),ins:o("ins"),kbd:o("kbd"),keygen:o("keygen"),label:o("label"),legend:o("legend"),li:o("li"),link:o("link"),main:o("main"),map:o("map"),mark:o("mark"),menu:o("menu"),menuitem:o("menuitem"),meta:o("meta"),meter:o("meter"),nav:o("nav"),noscript:o("noscript"),object:o("object"),ol:o("ol"),optgroup:o("optgroup"),option:o("option"),output:o("output"),p:o("p"),param:o("param"),picture:o("picture"),pre:o("pre"),progress:o("progress"),q:o("q"),rp:o("rp"),rt:o("rt"),ruby:o("ruby"),s:o("s"),samp:o("samp"),script:o("script"),section:o("section"),select:o("select"),small:o("small"),source:o("source"),span:o("span"),strong:o("strong"),style:o("style"),sub:o("sub"),summary:o("summary"),sup:o("sup"),table:o("table"),tbody:o("tbody"),td:o("td"),textarea:o("textarea"),tfoot:o("tfoot"),th:o("th"),thead:o("thead"),time:o("time"),title:o("title"),tr:o("tr"),track:o("track"),u:o("u"),ul:o("ul"),var:o("var"),video:o("video"),wbr:o("wbr"),circle:o("circle"),clipPath:o("clipPath"),defs:o("defs"),ellipse:o("ellipse"),g:o("g"),image:o("image"),line:o("line"),linearGradient:o("linearGradient"),mask:o("mask"),path:o("path"),pattern:o("pattern"),polygon:o("polygon"),polyline:o("polyline"),radialGradient:o("radialGradient"),rect:o("rect"),stop:o("stop"),svg:o("svg"),text:o("text"),tspan:o("tspan")};e.exports=i},function(e,t,n){"use strict";function r(e,t){return e===t?0!==e||1/e==1/t:e!==e&&t!==t}function o(e){this.message=e,this.stack=""}function i(e){function t(t,n,r,i,a,l,s){i=i||A,l=l||r;if(null==n[r]){var c=w[a];return t?new o(null===n[r]?"The "+c+" `"+l+"` is marked as required in `"+i+"`, but its value is `null`.":"The "+c+" `"+l+"` is marked as required in `"+i+"`, but its value is `undefined`."):null}return e(n,r,i,a,l)}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}function a(e){function t(t,n,r,i,a,l){var s=t[n];if(y(s)!==e)return new o("Invalid "+w[i]+" `"+a+"` of type `"+v(s)+"` supplied to `"+r+"`, expected `"+e+"`.");return null}return i(t)}function l(){return i(k.thatReturns(null))}function s(e){function t(t,n,r,i,a){if("function"!=typeof e)return new o("Property `"+a+"` of component `"+r+"` has invalid PropType notation inside arrayOf.");var l=t[n];if(!Array.isArray(l)){return new o("Invalid "+w[i]+" `"+a+"` of type `"+y(l)+"` supplied to `"+r+"`, expected an array.")}for(var s=0;s<l.length;s++){var c=e(l,s,r,i,a+"["+s+"]",C);if(c instanceof Error)return c}return null}return i(t)}function c(){function e(e,t,n,r,i){var a=e[t];if(!x.isValidElement(a)){return new o("Invalid "+w[r]+" `"+i+"` of type `"+y(a)+"` supplied to `"+n+"`, expected a single ReactElement.")}return null}return i(e)}function u(e){function t(t,n,r,i,a){if(!(t[n]instanceof e)){var l=w[i],s=e.name||A;return new o("Invalid "+l+" `"+a+"` of type `"+_(t[n])+"` supplied to `"+r+"`, expected instance of `"+s+"`.")}return null}return i(t)}function d(e){function t(t,n,i,a,l){for(var s=t[n],c=0;c<e.length;c++)if(r(s,e[c]))return null;return new o("Invalid "+w[a]+" `"+l+"` of value `"+s+"` supplied to `"+i+"`, expected one of "+JSON.stringify(e)+".")}return Array.isArray(e)?i(t):k.thatReturnsNull}function p(e){function t(t,n,r,i,a){if("function"!=typeof e)return new o("Property `"+a+"` of component `"+r+"` has invalid PropType notation inside objectOf.");var l=t[n],s=y(l);if("object"!==s){return new o("Invalid "+w[i]+" `"+a+"` of type `"+s+"` supplied to `"+r+"`, expected an object.")}for(var c in l)if(l.hasOwnProperty(c)){var u=e(l,c,r,i,a+"."+c,C);if(u instanceof Error)return u}return null}return i(t)}function f(e){function t(t,n,r,i,a){for(var l=0;l<e.length;l++){if(null==(0,e[l])(t,n,r,i,a,C))return null}return new o("Invalid "+w[i]+" `"+a+"` supplied to `"+r+"`.")}return Array.isArray(e)?i(t):k.thatReturnsNull}function m(){function e(e,t,n,r,i){if(!g(e[t])){return new o("Invalid "+w[r]+" `"+i+"` supplied to `"+n+"`, expected a ReactNode.")}return null}return i(e)}function h(e){function t(t,n,r,i,a){var l=t[n],s=y(l);if("object"!==s){return new o("Invalid "+w[i]+" `"+a+"` of type `"+s+"` supplied to `"+r+"`, expected `object`.")}for(var c in e){var u=e[c];if(u){var d=u(l,c,r,i,a+"."+c,C);if(d)return d}}return null}return i(t)}function g(e){switch(typeof e){case"number":case"string":case"undefined":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(g);if(null===e||x.isValidElement(e))return!0;var t=E(e);if(!t)return!1;var n,r=t.call(e);if(t!==e.entries){for(;!(n=r.next()).done;)if(!g(n.value))return!1}else for(;!(n=r.next()).done;){var o=n.value;if(o&&!g(o[1]))return!1}return!0;default:return!1}}function b(e,t){return"symbol"===e||("Symbol"===t["@@toStringTag"]||"function"==typeof Symbol&&t instanceof Symbol)}function y(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":b(t,e)?"symbol":t}function v(e){var t=y(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function _(e){return e.constructor&&e.constructor.name?e.constructor.name:A}var x=n(85),w=n(289),C=n(682),k=n(28),E=n(291),A=(n(4),"<<anonymous>>"),S={array:a("array"),bool:a("boolean"),func:a("function"),number:a("number"),object:a("object"),string:a("string"),symbol:a("symbol"),any:l(),arrayOf:s,element:c(),instanceOf:u,node:m(),objectOf:p,oneOf:d,oneOfType:f,shape:h};o.prototype=Error.prototype,e.exports=S},function(e,t,n){"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},function(e,t,n){"use strict";function r(e,t,n){this.props=e,this.context=t,this.refs=s,this.updater=n||l}function o(){}var i=n(9),a=n(195),l=n(196),s=n(82);o.prototype=a.prototype,r.prototype=new o,r.prototype.constructor=r,i(r.prototype,a.prototype),r.prototype.isPureReactComponent=!0,e.exports=r},function(e,t,n){"use strict";e.exports="15.4.2"},function(e,t,n){"use strict";function r(e){return i.isValidElement(e)||o("143"),e}var o=n(86),i=n(85);n(1);e.exports=r},function(e,t,n){"use strict";function r(e,t){return e&&"object"==typeof e&&null!=e.key?c.escape(e.key):t.toString(36)}function o(e,t,n,i){var p=typeof e;if("undefined"!==p&&"boolean"!==p||(e=null),null===e||"string"===p||"number"===p||"object"===p&&e.$$typeof===l)return n(i,e,""===t?u+r(e,0):t),1;var f,m,h=0,g=""===t?u:t+d;if(Array.isArray(e))for(var b=0;b<e.length;b++)f=e[b],m=g+r(f,b),h+=o(f,m,n,i);else{var y=s(e);if(y){var v,_=y.call(e);if(y!==e.entries)for(var x=0;!(v=_.next()).done;)f=v.value,m=g+r(f,x++),h+=o(f,m,n,i);else for(;!(v=_.next()).done;){var w=v.value;w&&(f=w[1],m=g+c.escape(w[0])+d+r(f,0),h+=o(f,m,n,i))}}else if("object"===p){var C="",k=String(e);a("31","[object Object]"===k?"object with keys {"+Object.keys(e).join(", ")+"}":k,C)}}return h}function i(e,t,n){return null==e?0:o(e,"",t,n)}var a=n(86),l=(n(45),n(288)),s=n(291),c=(n(1),n(676)),u=(n(4),"."),d=":";e.exports=i},function(e,t,n){"use strict";n(292),Object.assign},function(e,t,n){"use strict";function r(e,t){return function(){return t(e.apply(void 0,arguments))}}function o(e,t){if("function"==typeof e)return r(e,t);if("object"!=typeof e||null===e)throw new Error("bindActionCreators expected an object or a function, instead received "+(null===e?"null":typeof e)+'. Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');for(var n=Object.keys(e),o={},i=0;i<n.length;i++){var a=n[i],l=e[a];"function"==typeof l&&(o[a]=r(l,t))}return o}t.a=o},function(e,t,n){"use strict";n(293),n(172),n(295)},function(e,t,n){(function(t,n){!function(t){"use strict";function r(e,t,n,r){var o=t&&t.prototype instanceof i?t:i,a=Object.create(o.prototype),l=new m(r||[]);return a._invoke=u(e,n,l),a}function o(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}function i(){}function a(){}function l(){}function s(e){["next","throw","return"].forEach(function(t){e[t]=function(e){return this._invoke(t,e)}})}function c(e){function t(n,r,i,a){var l=o(e[n],e,r);if("throw"!==l.type){var s=l.arg,c=s.value;return c&&"object"==typeof c&&v.call(c,"__await")?Promise.resolve(c.__await).then(function(e){t("next",e,i,a)},function(e){t("throw",e,i,a)}):Promise.resolve(c).then(function(e){s.value=e,i(s)},a)}a(l.arg)}function r(e,n){function r(){return new Promise(function(r,o){t(e,n,r,o)})}return i=i?i.then(r,r):r()}"object"==typeof n&&n.domain&&(t=n.domain.bind(t));var i;this._invoke=r}function u(e,t,n){var r=E;return function(i,a){if(r===S)throw new Error("Generator is already running");if(r===I){if("throw"===i)throw a;return g()}for(n.method=i,n.arg=a;;){var l=n.delegate;if(l){var s=d(l,n);if(s){if(s===T)continue;return s}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(r===E)throw r=I,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r=S;var c=o(e,t,n);if("normal"===c.type){if(r=n.done?I:A,c.arg===T)continue;return{value:c.arg,done:n.done}}"throw"===c.type&&(r=I,n.method="throw",n.arg=c.arg)}}}function d(e,t){var n=e.iterator[t.method];if(n===b){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=b,d(e,t),"throw"===t.method))return T;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return T}var r=o(n,e.iterator,t.arg);if("throw"===r.type)return t.method="throw",t.arg=r.arg,t.delegate=null,T;var i=r.arg;return i?i.done?(t[e.resultName]=i.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=b),t.delegate=null,T):i:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,T)}function p(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function f(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function m(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(p,this),this.reset(!0)}function h(e){if(e){var t=e[x];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,r=function t(){for(;++n<e.length;)if(v.call(e,n))return t.value=e[n],t.done=!1,t;return t.value=b,t.done=!0,t};return r.next=r}}return{next:g}}function g(){return{value:b,done:!0}}var b,y=Object.prototype,v=y.hasOwnProperty,_="function"==typeof Symbol?Symbol:{},x=_.iterator||"@@iterator",w=_.toStringTag||"@@toStringTag",C="object"==typeof e,k=t.regeneratorRuntime;if(k)return void(C&&(e.exports=k));k=t.regeneratorRuntime=C?e.exports:{},k.wrap=r;var E="suspendedStart",A="suspendedYield",S="executing",I="completed",T={},P={};P[x]=function(){return this};var O=Object.getPrototypeOf,M=O&&O(O(h([])));M&&M!==y&&v.call(M,x)&&(P=M);var R=l.prototype=i.prototype=Object.create(P);a.prototype=R.constructor=l,l.constructor=a,l[w]=a.displayName="GeneratorFunction",k.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===a||"GeneratorFunction"===(t.displayName||t.name))},k.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,l):(e.__proto__=l,w in e||(e[w]="GeneratorFunction")),e.prototype=Object.create(R),e},k.awrap=function(e){return{__await:e}},s(c.prototype),k.AsyncIterator=c,k.async=function(e,t,n,o){var i=new c(r(e,t,n,o));return k.isGeneratorFunction(t)?i:i.next().then(function(e){return e.done?e.value:i.next()})},s(R),R[w]="Generator",R.toString=function(){return"[object Generator]"},k.keys=function(e){var t=[];for(var n in e)t.push(n);return t.reverse(),function n(){for(;t.length;){var r=t.pop();if(r in e)return n.value=r,n.done=!1,n}return n.done=!0,n}},k.values=h,m.prototype={constructor:m,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=b,this.done=!1,this.delegate=null,this.method="next",this.arg=b,this.tryEntries.forEach(f),!e)for(var t in this)"t"===t.charAt(0)&&v.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=b)},stop:function(){this.done=!0;var e=this.tryEntries[0],t=e.completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(e){function t(t,r){return i.type="throw",i.arg=e,n.next=t,r&&(n.method="next",n.arg=b),!!r}if(this.done)throw e;for(var n=this,r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r],i=o.completion;if("root"===o.tryLoc)return t("end");if(o.tryLoc<=this.prev){var a=v.call(o,"catchLoc"),l=v.call(o,"finallyLoc");if(a&&l){if(this.prev<o.catchLoc)return t(o.catchLoc,!0);if(this.prev<o.finallyLoc)return t(o.finallyLoc)}else if(a){if(this.prev<o.catchLoc)return t(o.catchLoc,!0)}else{if(!l)throw new Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return t(o.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&v.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var o=r;break}}o&&("break"===e||"continue"===e)&&o.tryLoc<=t&&t<=o.finallyLoc&&(o=null);var i=o?o.completion:{};return i.type=e,i.arg=t,o?(this.method="next",this.next=o.finallyLoc,T):this.complete(i)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),T},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),f(n),T}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var o=r.arg;f(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:h(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=b),T}}}("object"==typeof t?t:"object"==typeof window?window:"object"==typeof self?self:this)}).call(t,n(101),n(173))},function(e,t,n){"use strict";var r=function(e){return"/"===e.charAt(0)},o=function(e,t){for(var n=t,r=n+1,o=e.length;r<o;n+=1,r+=1)e[n]=e[r];e.pop()},i=function(e){var t=arguments.length<=1||void 0===arguments[1]?"":arguments[1],n=e&&e.split("/")||[],i=t&&t.split("/")||[],a=e&&r(e),l=t&&r(t),s=a||l;if(e&&r(e)?i=n:n.length&&(i.pop(),i=i.concat(n)),!i.length)return"/";var c=void 0;if(i.length){var u=i[i.length-1];c="."===u||".."===u||""===u}else c=!1;for(var d=0,p=i.length;p>=0;p--){var f=i[p];"."===f?o(i,p):".."===f?(o(i,p),d++):d&&(o(i,p),d--)}if(!s)for(;d--;d)i.unshift("..");!s||""===i[0]||i[0]&&r(i[0])||i.unshift("");var m=i.join("/");return c&&"/"!==m.substr(-1)&&(m+="/"),m};e.exports=i},function(e,t,n){"use strict";e.exports=function(e){return encodeURIComponent(e).replace(/[!'()*]/g,function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})}},function(e,t){e.exports=function(e){var t="undefined"!=typeof window&&window.location;if(!t)throw new Error("fixUrls requires window.location");if(!e||"string"!=typeof e)return e;var n=t.protocol+"//"+t.host,r=n+t.pathname.replace(/\/[^\/]*$/,"/");return e.replace(/url *\( *(.+?) *\)/g,function(e,t){var o=t.replace(/^"(.*)"$/,function(e,t){return t}).replace(/^'(.*)'$/,function(e,t){return t});if(/^(#|data:|http:\/\/|https:\/\/|file:\/\/\/)/i.test(o))return e;var i;return i=0===o.indexOf("//")?o:0===o.indexOf("/")?n+o:r+o.replace(/^\.\//,""),"url("+JSON.stringify(i)+")"})}},function(e,t,n){var r=n(551);"string"==typeof r&&(r=[[e.i,r,""]]);n(56)(r,{});r.locals&&(e.exports=r.locals)},function(e,t,n){var r=n(552);"string"==typeof r&&(r=[[e.i,r,""]]);n(56)(r,{});r.locals&&(e.exports=r.locals)},function(e,t,n){var r=n(553);"string"==typeof r&&(r=[[e.i,r,""]]);n(56)(r,{});r.locals&&(e.exports=r.locals)},function(e,t,n){var r=n(554);"string"==typeof r&&(r=[[e.i,r,""]]);n(56)(r,{});r.locals&&(e.exports=r.locals)},function(e,t,n){var r=n(555);"string"==typeof r&&(r=[[e.i,r,""]]);n(56)(r,{});r.locals&&(e.exports=r.locals)},function(e,t,n){var r=n(556);"string"==typeof r&&(r=[[e.i,r,""]]);n(56)(r,{});r.locals&&(e.exports=r.locals)},function(e,t,n){e.exports=n(701)},function(e,t,n){"use strict";(function(e,r){function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var i,a=n(702),l=o(a);i="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==e?e:r;var s=(0,l.default)(i);t.default=s}).call(t,n(101),n(709)(e))},function(e,t,n){"use strict";function r(e){var t,n=e.Symbol;return"function"==typeof n?n.observable?t=n.observable:(t=n("observable"),n.observable=t):t="@@observable",t}Object.defineProperty(t,"__esModule",{value:!0}),t.default=r},function(e,t){e.exports=["aaa","aarp","abarth","abb","abbott","abbvie","abc","able","abogado","abudhabi","ac","academy","accenture","accountant","accountants","aco","active","actor","ad","adac","ads","adult","ae","aeg","aero","aetna","af","afamilycompany","afl","africa","ag","agakhan","agency","ai","aig","aigo","airbus","airforce","airtel","akdn","al","alfaromeo","alibaba","alipay","allfinanz","allstate","ally","alsace","alstom","am","americanexpress","americanfamily","amex","amfam","amica","amsterdam","analytics","android","anquan","anz","ao","aol","apartments","app","apple","aq","aquarelle","ar","arab","aramco","archi","army","arpa","art","arte","as","asda","asia","associates","at","athleta","attorney","au","auction","audi","audible","audio","auspost","author","auto","autos","avianca","aw","aws","ax","axa","az","azure","ba","baby","baidu","banamex","bananarepublic","band","bank","bar","barcelona","barclaycard","barclays","barefoot","bargains","baseball","basketball","bauhaus","bayern","bb","bbc","bbt","bbva","bcg","bcn","bd","be","beats","beauty","beer","bentley","berlin","best","bestbuy","bet","bf","bg","bh","bharti","bi","bible","bid","bike","bing","bingo","bio","biz","bj","black","blackfriday","blanco","blockbuster","blog","bloomberg","blue","bm","bms","bmw","bn","bnl","bnpparibas","bo","boats","boehringer","bofa","bom","bond","boo","book","booking","boots","bosch","bostik","boston","bot","boutique","box","br","bradesco","bridgestone","broadway","broker","brother","brussels","bs","bt","budapest","bugatti","build","builders","business","buy","buzz","bv","bw","by","bz","bzh","ca","cab","cafe","cal","call","calvinklein","cam","camera","camp","cancerresearch","canon","capetown","capital","capitalone","car","caravan","cards","care","career","careers","cars","cartier","casa","case","caseih","cash","casino","cat","catering","catholic","cba","cbn","cbre","cbs","cc","cd","ceb","center","ceo","cern","cf","cfa","cfd","cg","ch","chanel","channel","chase","chat","cheap","chintai","chloe","christmas","chrome","chrysler","church","ci","cipriani","circle","cisco","citadel","citi","citic","city","cityeats","ck","cl","claims","cleaning","click","clinic","clinique","clothing","cloud","club","clubmed","cm","cn","co","coach","codes","coffee","college","cologne","com","comcast","commbank","community","company","compare","computer","comsec","condos","construction","consulting","contact","contractors","cooking","cookingchannel","cool","coop","corsica","country","coupon","coupons","courses","cr","credit","creditcard","creditunion","cricket","crown","crs","cruise","cruises","csc","cu","cuisinella","cv","cw","cx","cy","cymru","cyou","cz","dabur","dad","dance","data","date","dating","datsun","day","dclk","dds","de","deal","dealer","deals","degree","delivery","dell","deloitte","delta","democrat","dental","dentist","desi","design","dev","dhl","diamonds","diet","digital","direct","directory","discount","discover","dish","diy","dj","dk","dm","dnp","do","docs","doctor","dodge","dog","doha","domains","dot","download","drive","dtv","dubai","duck","dunlop","duns","dupont","durban","dvag","dvr","dz","earth","eat","ec","eco","edeka","edu","education","ee","eg","email","emerck","energy","engineer","engineering","enterprises","epost","epson","equipment","er","ericsson","erni","es","esq","estate","esurance","et","etisalat","eu","eurovision","eus","events","everbank","exchange","expert","exposed","express","extraspace","fage","fail","fairwinds","faith","family","fan","fans","farm","farmers","fashion","fast","fedex","feedback","ferrari","ferrero","fi","fiat","fidelity","fido","film","final","finance","financial","fire","firestone","firmdale","fish","fishing","fit","fitness","fj","fk","flickr","flights","flir","florist","flowers","fly","fm","fo","foo","food","foodnetwork","football","ford","forex","forsale","forum","foundation","fox","fr","free","fresenius","frl","frogans","frontdoor","frontier","ftr","fujitsu","fujixerox","fun","fund","furniture","futbol","fyi","ga","gal","gallery","gallo","gallup","game","games","gap","garden","gb","gbiz","gd","gdn","ge","gea","gent","genting","george","gf","gg","ggee","gh","gi","gift","gifts","gives","giving","gl","glade","glass","gle","global","globo","gm","gmail","gmbh","gmo","gmx","gn","godaddy","gold","goldpoint","golf","goo","goodhands","goodyear","goog","google","gop","got","gov","gp","gq","gr","grainger","graphics","gratis","green","gripe","group","gs","gt","gu","guardian","gucci","guge","guide","guitars","guru","gw","gy","hair","hamburg","hangout","haus","hbo","hdfc","hdfcbank","health","healthcare","help","helsinki","here","hermes","hgtv","hiphop","hisamitsu","hitachi","hiv","hk","hkt","hm","hn","hockey","holdings","holiday","homedepot","homegoods","homes","homesense","honda","honeywell","horse","hospital","host","hosting","hot","hoteles","hotels","hotmail","house","how","hr","hsbc","ht","htc","hu","hughes","hyatt","hyundai","ibm","icbc","ice","icu","id","ie","ieee","ifm","ikano","il","im","imamat","imdb","immo","immobilien","in","industries","infiniti","info","ing","ink","institute","insurance","insure","int","intel","international","intuit","investments","io","ipiranga","iq","ir","irish","is","iselect","ismaili","ist","istanbul","it","itau","itv","iveco","iwc","jaguar","java","jcb","jcp","je","jeep","jetzt","jewelry","jio","jlc","jll","jm","jmp","jnj","jo","jobs","joburg","jot","joy","jp","jpmorgan","jprs","juegos","juniper","kaufen","kddi","ke","kerryhotels","kerrylogistics","kerryproperties","kfh","kg","kh","ki","kia","kim","kinder","kindle","kitchen","kiwi","km","kn","koeln","komatsu","kosher","kp","kpmg","kpn","kr","krd","kred","kuokgroup","kw","ky","kyoto","kz","la","lacaixa","ladbrokes","lamborghini","lamer","lancaster","lancia","lancome","land","landrover","lanxess","lasalle","lat","latino","latrobe","law","lawyer","lb","lc","lds","lease","leclerc","lefrak","legal","lego","lexus","lgbt","li","liaison","lidl","life","lifeinsurance","lifestyle","lighting","like","lilly","limited","limo","lincoln","linde","link","lipsy","live","living","lixil","lk","loan","loans","locker","locus","loft","lol","london","lotte","lotto","love","lpl","lplfinancial","lr","ls","lt","ltd","ltda","lu","lundbeck","lupin","luxe","luxury","lv","ly","ma","macys","madrid","maif","maison","makeup","man","management","mango","market","marketing","markets","marriott","marshalls","maserati","mattel","mba","mc","mcd","mcdonalds","mckinsey","md","me","med","media","meet","melbourne","meme","memorial","men","menu","meo","metlife","mg","mh","miami","microsoft","mil","mini","mint","mit","mitsubishi","mk","ml","mlb","mls","mm","mma","mn","mo","mobi","mobile","mobily","moda","moe","moi","mom","monash","money","monster","montblanc","mopar","mormon","mortgage","moscow","moto","motorcycles","mov","movie","movistar","mp","mq","mr","ms","msd","mt","mtn","mtr","mu","museum","mutual","mv","mw","mx","my","mz","na","nab","nadex","nagoya","name","nationwide","natura","navy","nba","nc","ne","nec","net","netbank","netflix","network","neustar","new","newholland","news","next","nextdirect","nexus","nf","nfl","ng","ngo","nhk","ni","nico","nike","nikon","ninja","nissan","nissay","nl","no","nokia","northwesternmutual","norton","now","nowruz","nowtv","np","nr","nra","nrw","ntt","nu","nyc","nz","obi","observer","off","office","okinawa","olayan","olayangroup","oldnavy","ollo","om","omega","one","ong","onl","online","onyourside","ooo","open","oracle","orange","org","organic","origins","osaka","otsuka","ott","ovh","pa","page","pamperedchef","panasonic","panerai","paris","pars","partners","parts","party","passagens","pay","pccw","pe","pet","pf","pfizer","pg","ph","pharmacy","philips","phone","photo","photography","photos","physio","piaget","pics","pictet","pictures","pid","pin","ping","pink","pioneer","pizza","pk","pl","place","play","playstation","plumbing","plus","pm","pn","pnc","pohl","poker","politie","porn","post","pr","pramerica","praxi","press","prime","pro","prod","productions","prof","progressive","promo","properties","property","protection","pru","prudential","ps","pt","pub","pw","pwc","py","qa","qpon","quebec","quest","qvc","racing","radio","raid","re","read","realestate","realtor","realty","recipes","red","redstone","redumbrella","rehab","reise","reisen","reit","reliance","ren","rent","rentals","repair","report","republican","rest","restaurant","review","reviews","rexroth","rich","richardli","ricoh","rightathome","ril","rio","rip","rmit","ro","rocher","rocks","rodeo","rogers","room","rs","rsvp","ru","rugby","ruhr","run","rw","rwe","ryukyu","sa","saarland","safe","safety","sakura","sale","salon","samsclub","samsung","sandvik","sandvikcoromant","sanofi","sap","sapo","sarl","sas","save","saxo","sb","sbi","sbs","sc","sca","scb","schaeffler","schmidt","scholarships","school","schule","schwarz","science","scjohnson","scor","scot","sd","se","seat","secure","security","seek","select","sener","services","ses","seven","sew","sex","sexy","sfr","sg","sh","shangrila","sharp","shaw","shell","shia","shiksha","shoes","shop","shopping","shouji","show","showtime","shriram","si","silk","sina","singles","site","sj","sk","ski","skin","sky","skype","sl","sling","sm","smart","smile","sn","sncf","so","soccer","social","softbank","software","sohu","solar","solutions","song","sony","soy","space","spiegel","spot","spreadbetting","sr","srl","srt","st","stada","staples","star","starhub","statebank","statefarm","statoil","stc","stcgroup","stockholm","storage","store","stream","studio","study","style","su","sucks","supplies","supply","support","surf","surgery","suzuki","sv","swatch","swiftcover","swiss","sx","sy","sydney","symantec","systems","sz","tab","taipei","talk","taobao","target","tatamotors","tatar","tattoo","tax","taxi","tc","tci","td","tdk","team","tech","technology","tel","telecity","telefonica","temasek","tennis","teva","tf","tg","th","thd","theater","theatre","tiaa","tickets","tienda","tiffany","tips","tires","tirol","tj","tjmaxx","tjx","tk","tkmaxx","tl","tm","tmall","tn","to","today","tokyo","tools","top","toray","toshiba","total","tours","town","toyota","toys","tr","trade","trading","training","travel","travelchannel","travelers","travelersinsurance","trust","trv","tt","tube","tui","tunes","tushu","tv","tvs","tw","tz","ua","ubank","ubs","uconnect","ug","uk","unicom","university","uno","uol","ups","us","uy","uz","va","vacations","vana","vanguard","vc","ve","vegas","ventures","verisign","versicherung","vet","vg","vi","viajes","video","vig","viking","villas","vin","vip","virgin","visa","vision","vista","vistaprint","viva","vivo","vlaanderen","vn","vodka","volkswagen","volvo","vote","voting","voto","voyage","vu","vuelos","wales","walmart","walter","wang","wanggou","warman","watch","watches","weather","weatherchannel","webcam","weber","website","wed","wedding","weibo","weir","wf","whoswho","wien","wiki","williamhill","win","windows","wine","winners","wme","wolterskluwer","woodside","work","works","world","wow","ws","wtc","wtf","xbox","xerox","xfinity","xihuan","xin","कॉम","セール","佛山","慈善","集团","在线","한국","大众汽车","点看","คอม","ভারত","八卦","موقع","বাংলা","公益","公司","香格里拉","网站","移动","我爱你","москва","қаз","католик","онлайн","сайт","联通","срб","бг","бел","קום","时尚","微博","淡马锡","ファッション","орг","नेट","ストア","삼성","சிங்கப்பூர்","商标","商店","商城","дети","мкд","ею","ポイント","新闻","工行","家電","كوم","中文网","中信","中国","中國","娱乐","谷歌","భారత్","ලංකා","電訊盈科","购物","クラウド","ભારત","通販","भारत","网店","संगठन","餐厅","网络","ком","укр","香港","诺基亚","食品","飞利浦","台湾","台灣","手表","手机","мон","الجزائر","عمان","ارامكو","ایران","العليان","اتصالات","امارات","بازار","پاکستان","الاردن","موبايلي","بھارت","المغرب","ابوظبي","السعودية","كاثوليك","سودان","همراه","عراق","مليسيا","澳門","닷컴","政府","شبكة","بيتك","عرب","გე","机构","组织机构","健康","ไทย","سورية","рус","рф","珠宝","تونس","大拿","みんな","グーグル","ελ","世界","書籍","ਭਾਰਤ","网址","닷넷","コム","天主教","游戏","vermögensberater","vermögensberatung","企业","信息","嘉里大酒店","嘉里","مصر","قطر","广东","இலங்கை","இந்தியா","հայ","新加坡","فلسطين","政务","xperia","xxx","xyz","yachts","yahoo","yamaxun","yandex","ye","yodobashi","yoga","yokohama","you","youtube","yt","yun","za","zappos","zara","zero","zip","zippo","zm","zone","zuerich","zw"]},function(e,t){e.exports=/[\0-\x1F\x7F-\x9F]/},function(e,t){e.exports=/[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0AF0\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E44\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC9\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDF3C-\uDF3E]|\uD807[\uDC41-\uDC45\uDC70\uDC71]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]/},function(e,t){e.exports=/[ \xA0\u1680\u2000-\u200A\u202F\u205F\u3000]/},function(e,t){e.exports=/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/},function(e,t,n){"use strict";t.__esModule=!0;var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o=function e(t,n){if(t===n)return!0;if(null==t||null==n)return!1;if(Array.isArray(t))return!(!Array.isArray(n)||t.length!==n.length)&&t.every(function(t,r){return e(t,n[r])});var o=void 0===t?"undefined":r(t);if(o!==(void 0===n?"undefined":r(n)))return!1;if("object"===o){var i=t.valueOf(),a=n.valueOf();if(i!==t||a!==n)return e(i,a);var l=Object.keys(t),s=Object.keys(n);return l.length===s.length&&l.every(function(r){return e(t[r],n[r])})}return!1};t.default=o},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t){!function(e){"use strict";function t(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function n(e){return"string"!=typeof e&&(e=String(e)),e}function r(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return b.iterable&&(t[Symbol.iterator]=function(){return t}),t}function o(e){this.map={},e instanceof o?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}function i(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function a(e){return new Promise(function(t,n){e.onload=function(){t(e.result)},e.onerror=function(){n(e.error)}})}function l(e){var t=new FileReader,n=a(t);return t.readAsArrayBuffer(e),n}function s(e){var t=new FileReader,n=a(t);return t.readAsText(e),n}function c(e){for(var t=new Uint8Array(e),n=new Array(t.length),r=0;r<t.length;r++)n[r]=String.fromCharCode(t[r]);return n.join("")}function u(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function d(){return this.bodyUsed=!1,this._initBody=function(e){if(this._bodyInit=e,e)if("string"==typeof e)this._bodyText=e;else if(b.blob&&Blob.prototype.isPrototypeOf(e))this._bodyBlob=e;else if(b.formData&&FormData.prototype.isPrototypeOf(e))this._bodyFormData=e;else if(b.searchParams&&URLSearchParams.prototype.isPrototypeOf(e))this._bodyText=e.toString();else if(b.arrayBuffer&&b.blob&&v(e))this._bodyArrayBuffer=u(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer]);else{if(!b.arrayBuffer||!ArrayBuffer.prototype.isPrototypeOf(e)&&!_(e))throw new Error("unsupported BodyInit type");this._bodyArrayBuffer=u(e)}else this._bodyText="";this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):b.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},b.blob&&(this.blob=function(){var e=i(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?i(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(l)}),this.text=function(){var e=i(this);if(e)return e;if(this._bodyBlob)return s(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(c(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},b.formData&&(this.formData=function(){return this.text().then(m)}),this.json=function(){return this.text().then(JSON.parse)},this}function p(e){var t=e.toUpperCase();return x.indexOf(t)>-1?t:e}function f(e,t){t=t||{};var n=t.body;if(e instanceof f){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new o(e.headers)),this.method=e.method,this.mode=e.mode,n||null==e._bodyInit||(n=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"omit",!t.headers&&this.headers||(this.headers=new o(t.headers)),this.method=p(t.method||this.method||"GET"),this.mode=t.mode||this.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&n)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(n)}function m(e){var t=new FormData;return e.trim().split("&").forEach(function(e){if(e){var n=e.split("="),r=n.shift().replace(/\+/g," "),o=n.join("=").replace(/\+/g," ");t.append(decodeURIComponent(r),decodeURIComponent(o))}}),t}function h(e){var t=new o;return e.split(/\r?\n/).forEach(function(e){var n=e.split(":"),r=n.shift().trim();if(r){var o=n.join(":").trim();t.append(r,o)}}),t}function g(e,t){t||(t={}),this.type="default",this.status="status"in t?t.status:200,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new o(t.headers),this.url=t.url||"",this._initBody(e)}if(!e.fetch){var b={searchParams:"URLSearchParams"in e,iterable:"Symbol"in e&&"iterator"in Symbol,blob:"FileReader"in e&&"Blob"in e&&function(){try{return new Blob,!0}catch(e){return!1}}(),formData:"FormData"in e,arrayBuffer:"ArrayBuffer"in e};if(b.arrayBuffer)var y=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],v=function(e){return e&&DataView.prototype.isPrototypeOf(e)},_=ArrayBuffer.isView||function(e){return e&&y.indexOf(Object.prototype.toString.call(e))>-1};o.prototype.append=function(e,r){e=t(e),r=n(r);var o=this.map[e];this.map[e]=o?o+","+r:r},o.prototype.delete=function(e){delete this.map[t(e)]},o.prototype.get=function(e){return e=t(e),this.has(e)?this.map[e]:null},o.prototype.has=function(e){return this.map.hasOwnProperty(t(e))},o.prototype.set=function(e,r){this.map[t(e)]=n(r)},o.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},o.prototype.keys=function(){var e=[];return this.forEach(function(t,n){e.push(n)}),r(e)},o.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),r(e)},o.prototype.entries=function(){var e=[];return this.forEach(function(t,n){e.push([n,t])}),r(e)},b.iterable&&(o.prototype[Symbol.iterator]=o.prototype.entries);var x=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];f.prototype.clone=function(){return new f(this,{body:this._bodyInit})},d.call(f.prototype),d.call(g.prototype),g.prototype.clone=function(){return new g(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new o(this.headers),url:this.url})},g.error=function(){var e=new g(null,{status:0,statusText:""});return e.type="error",e};var w=[301,302,303,307,308];g.redirect=function(e,t){if(w.indexOf(t)===-1)throw new RangeError("Invalid status code");return new g(null,{status:t,headers:{location:e}})},e.Headers=o,e.Request=f,e.Response=g,e.fetch=function(e,t){return new Promise(function(n,r){var o=new f(e,t),i=new XMLHttpRequest;i.onload=function(){var e={status:i.status,statusText:i.statusText,headers:h(i.getAllResponseHeaders()||"")};e.url="responseURL"in i?i.responseURL:e.headers.get("X-Request-URL"),n(new g("response"in i?i.response:i.responseText,e))},i.onerror=function(){r(new TypeError("Network request failed"))},i.ontimeout=function(){r(new TypeError("Network request failed"))},i.open(o.method,o.url,!0),"include"===o.credentials&&(i.withCredentials=!0),"responseType"in i&&b.blob&&(i.responseType="blob"),o.headers.forEach(function(e,t){i.setRequestHeader(t,e)}),i.send(void 0===o._bodyInit?null:o._bodyInit)})},e.fetch.polyfill=!0}}("undefined"!=typeof self?self:this)},function(e,t){e.exports={title:"HouseRuler",html:'<h2>Welcome!</h2>\n<p>This is a single-page application powered by React and Material Design Lite (MDL).</p>\n<p><a href="https://github.com/kriasoft/react-static-boilerplate">https://github.com/kriasoft/react-static-boilerplate</a></p>\n'}},function(e,t,n){n(299),n(298),e.exports=n(297)}]); |
client/src/components/helpers/ButtonSpacer.js | pahosler/freecodecamp | import React from 'react';
function ButtonSpacer() {
return <div className='button-spacer' style={{ padding: '5px 0' }} />;
}
ButtonSpacer.displayName = 'ButtonSpacer';
export default ButtonSpacer;
|
Realization/frontend/czechidm-core/src/content/dashboards/AssignedTaskDashboard.js | bcvsolutions/CzechIdMng | import React from 'react';
import { connect } from 'react-redux';
import * as Basic from '../../components/basic';
import { WorkflowTaskInstanceManager, SecurityManager } from '../../redux';
import TaskInstanceTable from '../task/TaskInstanceTable';
const uiKeyPrefix = 'task-instance-dashboard-';
/**
* Assigned workflow tasks.
*
* @author Vít Švanda
* @author Radek Tomiška
*/
class AssignedTaskDashboard extends Basic.AbstractContent {
constructor(props, context) {
super(props, context);
this.workflowTaskInstanceManager = new WorkflowTaskInstanceManager();
}
render() {
const { identity, userContext, _total, _showLoading } = this.props;
if (!identity || !SecurityManager.hasAuthority('WORKFLOWTASK_READ')) {
return null;
}
if (identity.id !== userContext.id && !SecurityManager.hasAuthority('WORKFLOWTASK_ADMIN')) {
return null;
}
//
return (
<Basic.Div>
<Basic.ContentHeader
icon="tasks"
text={ this.i18n('content.tasks-assigned.assigned') }/>
{
(_total || !_showLoading)
?
null
:
<Basic.Loading isStatic show />
}
<Basic.Alert
rendered={ !_total && !_showLoading }
level="success"
style={{ paddingTop: 15, paddingBottom: 15 }}
text={ this.i18n('content.tasks-assigned.empty.message') } />
<Basic.Panel className={ _total ? '' : 'hidden' }>
<TaskInstanceTable
uiKey={ `${ uiKeyPrefix }${ identity.username }` }
username={ identity.username }
taskInstanceManager={ this.workflowTaskInstanceManager }
filterOpened={ false }/>
</Basic.Panel>
</Basic.Div>
);
}
}
function select(state, component) {
const uiKey = `${ uiKeyPrefix }${ component.identity ? component.identity.username : '' }`;
const ui = state.data.ui[uiKey];
return {
userContext: state.security.userContext,
_total: ui ? ui.total : null,
_showLoading: ui ? ui.showLoading : null,
i18nReady: state.config.get('i18nReady')
};
}
export default connect(select)(AssignedTaskDashboard);
|
React/ReactNative/ComponentAndLibs/SignalR.js | gsmental/DevToolKit | //https://github.com/aspnet/AspNetCore/tree/master/src/SignalR/clients/ts/signalr
//https://www.npmjs.com/package/@aspnet/signalr
//failed to start the transport 'websockets': null
//solution
//https://github.com/aspnet/AspNetCore/issues/6565
//Install IIS>WebServer>Application Development>WebSocket Protocol
import React, { Component } from 'react';
import { StyleSheet, Text, View, Alert, TextInput, Button, FlatList, List } from 'react-native';
const SignalR = require("@aspnet/signalr");
let connection = new SignalR.HubConnectionBuilder()
.withUrl("https://informme.in/chatHub/")
.build();
connection.start().then(() => connection.invoke("HelloWorld", "SignalR Status", "It is nice to know that SignalR is working on your device"));
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { NickName:'', text: '', messages: [], hubConnection: null, };
}
componentDidMount = () => {
connection.on('HelloWorld', (name, message) => {
var MsgModel = { name: name, message: message }
const messages = this.state.messages.concat([MsgModel]);
this.setState({ messages });
this.setState({ text: '' });
});
}
onPressLearnMore = () => {
connection.invoke("HelloWorld", this.state.NickName, this.state.text);
}
render() {
return (
<View style={styles.container}>
<Text>Welcome to SignalR with React Native App</Text>
<TextInput placeholder="Nick Name"
style={{ height: 40, borderColor: 'gray', borderWidth: 1, width: 300 }}
onChangeText={(NickName) => this.setState({ NickName })}
value={this.state.NickName}
/>
<TextInput placeholder="Type here Message"
style={{ height: 40, borderColor: 'gray', borderWidth: 1, width: 300 }}
onChangeText={(text) => this.setState({ text })}
value={this.state.text}
/>
<Button
onPress={this.onPressLearnMore}
title="Send"
color="#841584"
accessibilityLabel="Learn more about this purple button"
/>
<FlatList
data={this.state.messages}
showsVerticalScrollIndicator={false}
renderItem={({ item }) =>
<View style={styles.flatview}>
<Text style={styles.name}>{item.name}</Text>
<Text style={styles.email}>{item.message}</Text>
</View>
}
keyExtractor={item => item.email}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
marginTop: 50,
},
flatview: {
justifyContent: 'center',
paddingTop: 30,
borderRadius: 2,
},
name: {
fontSize: 18
},
email: {
color: 'red'
},
});
|
src/svg-icons/action/account-balance-wallet.js | barakmitz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAccountBalanceWallet = (props) => (
<SvgIcon {...props}>
<path d="M21 18v1c0 1.1-.9 2-2 2H5c-1.11 0-2-.9-2-2V5c0-1.1.89-2 2-2h14c1.1 0 2 .9 2 2v1h-9c-1.11 0-2 .9-2 2v8c0 1.1.89 2 2 2h9zm-9-2h10V8H12v8zm4-2.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/>
</SvgIcon>
);
ActionAccountBalanceWallet = pure(ActionAccountBalanceWallet);
ActionAccountBalanceWallet.displayName = 'ActionAccountBalanceWallet';
ActionAccountBalanceWallet.muiName = 'SvgIcon';
export default ActionAccountBalanceWallet;
|
src/components/Home/HomeScreen.js | yasavbrain/yasav | import React from 'react';
import I18n from 'yasav/locales/i18n';
import HomeContainer from './containers/HomeContainer';
import { ActivityTypeEnum } from 'yasav/src/const';
export default class HomeScreen extends React.Component {
constructor(props) {
super(props);
this.navigateToActivityList = this.navigateToActivityList.bind(this);
this.navigateToTodoList = this.navigateToTodoList.bind(this);
this.navigateToActivityAddEvent = this.navigateToActivityAddEvent.bind(this);
this.navigateToActivityAddMeeting = this.navigateToActivityAddMeeting.bind(this);
this.navigateToActivityAddContent = this.navigateToActivityAddContent.bind(this);
this.navigateToTodoAdd = this.navigateToTodoAdd.bind(this);
this.navigateToInterlocutorList = this.navigateToInterlocutorList.bind(this);
}
navigateToActivityList() {
this.props.navigation.navigate('ActivityListScreen');
}
navigateToTodoList() {
this.props.navigation.navigate('TodoListScreen');
}
navigateToActivityAddEvent() {
this.props.navigation.navigate('ActivityAddScreen', ActivityTypeEnum.EVENT);
}
navigateToActivityAddMeeting() {
this.props.navigation.navigate('ActivityAddScreen', ActivityTypeEnum.MEETING);
}
navigateToActivityAddContent() {
this.props.navigation.navigate('ActivityAddScreen', ActivityTypeEnum.CONTENT);
}
navigateToTodoAdd() {
this.props.navigation.navigate('TodoAddScreen');
}
navigateToInterlocutorList() {
this.props.navigation.navigate('InterlocutorListScreen');
}
render() {
return (
<HomeContainer
navigateToActivityList={this.navigateToActivityList}
navigateToTodoList={this.navigateToTodoList}
navigateToActivityAddEvent={this.navigateToActivityAddEvent}
navigateToActivityAddMeeting={this.navigateToActivityAddMeeting}
navigateToActivityAddContent={this.navigateToActivityAddContent}
navigateToTodoAdd={this.navigateToTodoAdd}
navigateToInterlocutorList={this.navigateToInterlocutorList}
/>
);
}
}
|
ajax/libs/react-data-grid/0.13.24/react-data-grid-with-addons.min.js | nolsherry/cdnjs | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):"object"==typeof exports?exports.ReactDataGrid=t(require("react")):e.ReactDataGrid=t(e.React)}(this,function(e){return function(e){function t(o){if(r[o])return r[o].exports;var s=r[o]={exports:{},id:o,loaded:!1};return e[o].call(s.exports,s,s.exports,t),s.loaded=!0,s.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){"use strict";e.exports=r(1),e.exports.Editors=r(85),e.exports.Formatters=r(89),e.exports.Toolbar=r(91),e.exports.Row=r(50)},function(e,t,r){"use strict";var o=r(2)["default"],s=r(3)["default"],n=r(18),i=(n.PropTypes,r(19)),l=(r(50),r(42),r(53)),a=r(80),u=r(81),c=r(30),p=r(77),h=r(82),d=r(84),f=r(25);s||(Object.assign=r(83));var m=n.createClass({displayName:"ReactDataGrid",propTypes:{rowHeight:n.PropTypes.number.isRequired,headerRowHeight:n.PropTypes.number,minHeight:n.PropTypes.number.isRequired,minWidth:n.PropTypes.number,enableRowSelect:n.PropTypes.bool,onRowUpdated:n.PropTypes.func,rowGetter:n.PropTypes.func.isRequired,rowsCount:n.PropTypes.number.isRequired,toolbar:n.PropTypes.element,enableCellSelect:n.PropTypes.bool,columns:n.PropTypes.oneOfType([n.PropTypes.object,n.PropTypes.array]).isRequired,onFilter:n.PropTypes.func,onCellCopyPaste:n.PropTypes.func,onCellsDragged:n.PropTypes.func,onAddFilter:n.PropTypes.func},mixins:[h,p.MetricsComputatorMixin,l],getDefaultProps:function(){return{enableCellSelect:!1,tabIndex:-1,rowHeight:35,enableRowSelect:!1,minHeight:350}},getInitialState:function(){var e=this.createColumnMetrics(),t={columnMetrics:e,selectedRows:this.getInitialSelectedRows(),copied:null,expandedRows:[],canFilter:!1,columnFilters:{},sortDirection:null,sortColumn:null,dragged:null,scrollOffset:0};return this.props.enableCellSelect?t.selected={rowIdx:0,idx:0}:t.selected={rowIdx:-1,idx:-1},t},getInitialSelectedRows:function(){for(var e=[],t=0;t<this.props.rowsCount;t++)e.push(!1);return e},componentWillReceiveProps:function(e){e.rowsCount===this.props.rowsCount+1&&this.onAfterAddRow(e.rowsCount+1)},componentDidMount:function(){var e=0,t=this.getDOMNode().querySelector(".react-grid-Canvas");null!=t&&(e=t.offsetWidth-t.clientWidth),this.setState({scrollOffset:e})},render:function(){var e={selected:this.state.selected,dragged:this.state.dragged,onCellClick:this.onCellClick,onCellDoubleClick:this.onCellDoubleClick,onCommit:this.onCellCommit,onCommitCancel:this.setInactive,copied:this.state.copied,handleDragEnterRow:this.handleDragEnter,handleTerminateDrag:this.handleTerminateDrag},t=this.renderToolbar(),r=this.props.minWidth||this.DOMMetrics.gridWidth(),s=r-this.state.scrollOffset;return n.createElement("div",{className:"react-grid-Container",style:{width:r}},t,n.createElement("div",{className:"react-grid-Main"},n.createElement(i,o({ref:"base"},this.props,{headerRows:this.getHeaderRows(),columnMetrics:this.state.columnMetrics,rowGetter:this.props.rowGetter,rowsCount:this.props.rowsCount,rowHeight:this.props.rowHeight,cellMetaData:e,selectedRows:this.state.selectedRows,expandedRows:this.state.expandedRows,rowOffsetHeight:this.getRowOffsetHeight(),sortColumn:this.state.sortColumn,sortDirection:this.state.sortDirection,onSort:this.handleSort,minHeight:this.props.minHeight,totalWidth:s,onViewportKeydown:this.onKeyDown,onViewportDragStart:this.onDragStart,onViewportDragEnd:this.handleDragEnd,onViewportDoubleClick:this.onViewportDoubleClick,onColumnResize:this.onColumnResize}))))},renderToolbar:function(){var e=this.props.toolbar;return n.isValidElement(e)?c(e,{onToggleFilter:this.onToggleFilter,numberOfRows:this.props.rowsCount}):void 0},onSelect:function(e){if(this.props.enableCellSelect)if(this.state.selected.rowIdx===e.rowIdx&&this.state.selected.idx===e.idx&&this.state.selected.active===!0);else{var t=e.idx,r=e.rowIdx;t>=0&&r>=0&&t<f.getSize(this.state.columnMetrics.columns)&&r<this.props.rowsCount&&this.setState({selected:e})}},onCellClick:function(e){this.onSelect({rowIdx:e.rowIdx,idx:e.idx})},onCellDoubleClick:function(e){this.onSelect({rowIdx:e.rowIdx,idx:e.idx}),this.setActive("Enter")},onViewportDoubleClick:function(e){this.setActive()},onPressArrowUp:function(e){this.moveSelectedCell(e,-1,0)},onPressArrowDown:function(e){this.moveSelectedCell(e,1,0)},onPressArrowLeft:function(e){this.moveSelectedCell(e,0,-1)},onPressArrowRight:function(e){this.moveSelectedCell(e,0,1)},onPressTab:function(e){this.moveSelectedCell(e,0,e.shiftKey?-1:1)},onPressEnter:function(e){this.setActive(e.key)},onPressDelete:function(e){this.setActive(e.key)},onPressEscape:function(e){this.setInactive(e.key)},onPressBackspace:function(e){this.setActive(e.key)},onPressChar:function(e){this.isKeyPrintable(e.keyCode)&&this.setActive(e.keyCode)},onPressKeyWithCtrl:function(e){var t={KeyCode_c:99,KeyCode_C:67,KeyCode_V:86,KeyCode_v:118},r=this.state.selected.idx;if(this.canEdit(r))if(e.keyCode==t.KeyCode_c||e.keyCode==t.KeyCode_C){var o=this.getSelectedValue();this.handleCopy({value:o})}else(e.keyCode==t.KeyCode_v||e.keyCode==t.KeyCode_V)&&this.handlePaste()},onDragStart:function(e){var t=this.getSelectedValue();this.handleDragStart({idx:this.state.selected.idx,rowIdx:this.state.selected.rowIdx,value:t}),e&&e.dataTransfer&&e.dataTransfer.setData&&e.dataTransfer.setData("text/plain","dummy")},moveSelectedCell:function(e,t,r){e.preventDefault();var o=this.state.selected.rowIdx+t,s=this.state.selected.idx+r;this.onSelect({idx:s,rowIdx:o})},getSelectedValue:function(){var e=this.state.selected.rowIdx,t=this.state.selected.idx,r=this.getColumn(t).key,o=this.props.rowGetter(e);return d.get(o,r)},setActive:function(e){var t=this.state.selected.rowIdx,r=this.state.selected.idx;if(this.canEdit(r)&&!this.isActive()){var o=s(this.state.selected,{idx:r,rowIdx:t,active:!0,initialKeyCode:e});this.setState({selected:o})}},setInactive:function(){var e=this.state.selected.rowIdx,t=this.state.selected.idx;if(this.canEdit(t)&&this.isActive()){var r=s(this.state.selected,{idx:t,rowIdx:e,active:!1});this.setState({selected:r})}},canEdit:function(e){var t=this.getColumn(e);return this.props.enableCellSelect===!0&&(null!=t.editor||t.editable)},isActive:function(){return this.state.selected.active===!0},onCellCommit:function(e){var t=s({},this.state.selected);t.active=!1,"Tab"===e.key&&(t.idx+=1);var r=this.state.expandedRows;this.setState({selected:t,expandedRows:r}),this.props.onRowUpdated(e)},setupGridColumns:function(){var e=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0],t=e.columns.slice(0);if(e.enableRowSelect){var r={key:"select-row",name:"",formatter:n.createElement(a,null),onCellChange:this.handleRowSelect,filterable:!1,headerRenderer:n.createElement("input",{type:"checkbox",onChange:this.handleCheckboxChange}),width:60,locked:!0},o=t.unshift(r);t=o>0?t:o}return t},handleCheckboxChange:function(e){var t;t=e.currentTarget instanceof HTMLInputElement&&e.currentTarget.checked===!0?!0:!1;for(var r=[],o=0;o<this.props.rowsCount;o++)r.push(t);this.setState({selectedRows:r})},handleRowSelect:function(e,t,r){if(r.stopPropagation(),null!=this.state.selectedRows&&this.state.selectedRows.length>0){var o=this.state.selectedRows.slice();null==o[e]||0==o[e]?o[e]=!0:o[e]=!1,this.setState({selectedRows:o})}},onAfterAddRow:function(e){this.setState({selected:{idx:1,rowIdx:e-2}})},onToggleFilter:function(){this.setState({canFilter:!this.state.canFilter})},getHeaderRows:function(){var e=[{ref:"row",height:this.props.headerRowHeight||this.props.rowHeight}];return this.state.canFilter===!0&&e.push({ref:"filterRow",headerCellRenderer:n.createElement(u,{onChange:this.props.onAddFilter,column:this.props.column}),height:45}),e},getRowOffsetHeight:function(){var e=0;return this.getHeaderRows().forEach(function(t){return e+=parseFloat(t.height,10)}),e},handleSort:function(e,t){this.setState({sortDirection:t,sortColumn:e},function(){this.props.onGridSort(e,t)})},copyPasteEnabled:function(){return null!==this.props.onCellCopyPaste},handleCopy:function(e){if(this.copyPasteEnabled()){var t=e.value,r=this.state.selected,o={idx:r.idx,rowIdx:r.rowIdx};this.setState({textToCopy:t,copied:o})}},handlePaste:function(){if(this.copyPasteEnabled()){var e=this.state.selected,t=this.getColumn(this.state.selected.idx).key;this.props.onCellCopyPaste&&this.props.onCellCopyPaste({cellKey:t,rowIdx:e.rowIdx,value:this.state.textToCopy,fromRow:this.state.copied.rowIdx,toRow:e.rowIdx}),this.setState({copied:null})}},dragEnabled:function(){return null!==this.props.onCellsDragged},handleDragStart:function(e){if(this.dragEnabled()){var t=e.idx,r=e.rowIdx;t>=0&&r>=0&&t<this.getSize()&&r<this.props.rowsCount&&this.setState({dragged:e})}},handleDragEnter:function(e){if(this.dragEnabled()){var t=(this.state.selected,this.state.dragged);t.overRowIdx=e,this.setState({dragged:t})}},handleDragEnd:function(){if(this.dragEnabled()){var e,t,r=this.state.selected,o=this.state.dragged,s=this.getColumn(this.state.selected.idx).key;e=r.rowIdx<o.overRowIdx?r.rowIdx:o.overRowIdx,t=r.rowIdx>o.overRowIdx?r.rowIdx:o.overRowIdx,this.props.onCellsDragged&&this.props.onCellsDragged({cellKey:s,fromRow:e,toRow:t,value:o.value}),this.setState({dragged:{complete:!0}})}},handleTerminateDrag:function(){this.dragEnabled()&&this.setState({dragged:null})}});e.exports=m},function(e,t,r){"use strict";var o=r(3)["default"];t["default"]=o||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},t.__esModule=!0},function(e,t,r){e.exports={"default":r(4),__esModule:!0}},function(e,t,r){r(5),e.exports=r(8).Object.assign},function(e,t,r){var o=r(6);o(o.S+o.F,"Object",{assign:r(11)})},function(e,t,r){var o=r(7),s=r(8),n=r(9),i="prototype",l=function(e,t,r){var a,u,c,p=e&l.F,h=e&l.G,d=e&l.S,f=e&l.P,m=e&l.B,g=e&l.W,y=h?s:s[t]||(s[t]={}),v=h?o:d?o[t]:(o[t]||{})[i];h&&(r=t);for(a in r)u=!p&&v&&a in v,u&&a in y||(c=u?v[a]:r[a],y[a]=h&&"function"!=typeof v[a]?r[a]:m&&u?n(c,o):g&&v[a]==c?function(e){var t=function(t){return this instanceof e?new e(t):e(t)};return t[i]=e[i],t}(c):f&&"function"==typeof c?n(Function.call,c):c,f&&((y[i]||(y[i]={}))[a]=c))};l.F=1,l.G=2,l.S=4,l.P=8,l.B=16,l.W=32,e.exports=l},function(e,t){var r=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=r)},function(e,t){var r=e.exports={version:"1.2.6"};"number"==typeof __e&&(__e=r)},function(e,t,r){var o=r(10);e.exports=function(e,t,r){if(o(e),void 0===t)return e;switch(r){case 1:return function(r){return e.call(t,r)};case 2:return function(r,o){return e.call(t,r,o)};case 3:return function(r,o,s){return e.call(t,r,o,s)}}return function(){return e.apply(t,arguments)}}},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},function(e,t,r){var o=r(12),s=r(13),n=r(15);e.exports=r(17)(function(){var e=Object.assign,t={},r={},o=Symbol(),s="abcdefghijklmnopqrst";return t[o]=7,s.split("").forEach(function(e){r[e]=e}),7!=e({},t)[o]||Object.keys(e({},r)).join("")!=s})?function(e,t){for(var r=s(e),i=arguments,l=i.length,a=1,u=o.getKeys,c=o.getSymbols,p=o.isEnum;l>a;)for(var h,d=n(i[a++]),f=c?u(d).concat(c(d)):u(d),m=f.length,g=0;m>g;)p.call(d,h=f[g++])&&(r[h]=d[h]);return r}:Object.assign},function(e,t){var r=Object;e.exports={create:r.create,getProto:r.getPrototypeOf,isEnum:{}.propertyIsEnumerable,getDesc:r.getOwnPropertyDescriptor,setDesc:r.defineProperty,setDescs:r.defineProperties,getKeys:r.keys,getNames:r.getOwnPropertyNames,getSymbols:r.getOwnPropertySymbols,each:[].forEach}},function(e,t,r){var o=r(14);e.exports=function(e){return Object(o(e))}},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},function(e,t,r){var o=r(16);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==o(e)?e.split(""):Object(e)}},function(e,t){var r={}.toString;e.exports=function(e){return r.call(e).slice(8,-1)}},function(e,t){e.exports=function(e){try{return!!e()}catch(t){return!0}}},function(t,r){t.exports=e},function(e,t,r){"use strict";var o=r(2)["default"],s=r(18),n=s.PropTypes,i=r(20),l=r(47),a=(r(42),r(79)),u=r(77),c=s.createClass({displayName:"Grid",propTypes:{rowGetter:n.oneOfType([n.array,n.func]).isRequired,columns:n.oneOfType([n.array,n.object]),minHeight:n.number,headerRows:n.oneOfType([n.array,n.func]),rowHeight:n.number,rowRenderer:n.func,expandedRows:n.oneOfType([n.array,n.func]),selectedRows:n.oneOfType([n.array,n.func]),rowsCount:n.number,onRows:n.func,sortColumn:s.PropTypes.string,sortDirection:s.PropTypes.oneOf(["ASC","DESC","NONE"]),rowOffsetHeight:n.number.isRequired,onViewportKeydown:n.func.isRequired,onViewportDragStart:n.func.isRequired,onViewportDragEnd:n.func.isRequired,onViewportDoubleClick:n.func.isRequired},mixins:[a,u.MetricsComputatorMixin],getStyle:function(){return{overflow:"hidden",outline:0,position:"relative",minHeight:this.props.minHeight}},render:function(){var e=this.props.headerRows||[{ref:"row"}];return s.createElement("div",o({},this.props,{style:this.getStyle(),className:"react-grid-Grid"}),s.createElement(i,{ref:"header",columnMetrics:this.props.columnMetrics,onColumnResize:this.props.onColumnResize,height:this.props.rowHeight,totalWidth:this.props.totalWidth,headerRows:e,sortColumn:this.props.sortColumn,sortDirection:this.props.sortDirection,onSort:this.props.onSort}),s.createElement("div",{ref:"viewPortContainer",onKeyDown:this.props.onViewportKeydown,onDoubleClick:this.props.onViewportDoubleClick,onDragStart:this.props.onViewportDragStart,onDragEnd:this.props.onViewportDragEnd},s.createElement(l,{ref:"viewport",width:this.props.columnMetrics.width,rowHeight:this.props.rowHeight,rowRenderer:this.props.rowRenderer,rowGetter:this.props.rowGetter,rowsCount:this.props.rowsCount,selectedRows:this.props.selectedRows,expandedRows:this.props.expandedRows,columnMetrics:this.props.columnMetrics,totalWidth:this.props.totalWidth,onScroll:this.onScroll,onRows:this.props.onRows,cellMetaData:this.props.cellMetaData,rowOffsetHeight:this.props.rowOffsetHeight||this.props.rowHeight*e.length,minHeight:this.props.minHeight})))},getDefaultProps:function(){return{rowHeight:35,minHeight:350}}});e.exports=c},function(e,t,r){"use strict";var o=r(2)["default"],s=r(18),n=r(21),i=r(22),l=r(23),a=r(25),u=r(27),c=s.createClass({displayName:"Header",propTypes:{columnMetrics:s.PropTypes.shape({width:s.PropTypes.number.isRequired}).isRequired,totalWidth:s.PropTypes.number,height:s.PropTypes.number.isRequired,headerRows:s.PropTypes.array.isRequired},render:function(){var e=(this.state.resizing||this.props,n({"react-grid-Header":!0,"react-grid-Header--resizing":!!this.state.resizing})),t=this.getHeaderRows();return s.createElement("div",o({},this.props,{style:this.getStyle(),className:e}),t)},shouldComponentUpdate:function(e,t){var r=!l.sameColumns(this.props.columnMetrics.columns,e.columnMetrics.columns,l.sameColumn)||this.props.totalWidth!=e.totalWidth||this.props.headerRows.length!=e.headerRows.length||this.state.resizing!=t.resizing||this.props.sortColumn!=e.sortColumn||this.props.sortDirection!=e.sortDirection;return r},getHeaderRows:function(){var e,t=this.getColumnMetrics();this.state.resizing&&(e=this.state.resizing.column);var r=[];return this.props.headerRows.forEach(function(o,n){var i={position:"absolute",top:this.getCombinedHeaderHeights(n),left:0,width:this.props.totalWidth,overflow:"hidden"};r.push(s.createElement(u,{key:o.ref,ref:o.ref,style:i,onColumnResize:this.onColumnResize,onColumnResizeEnd:this.onColumnResizeEnd,width:t.width,height:o.height||this.props.height,columns:t.columns,resizing:e,headerCellRenderer:o.headerCellRenderer,sortColumn:this.props.sortColumn,sortDirection:this.props.sortDirection,onSort:this.props.onSort}))}.bind(this)),r},getInitialState:function(){return{resizing:null}},componentWillReceiveProps:function(e){this.setState({resizing:null})},onColumnResize:function(e,t){var r=this.state.resizing||this.props,o=this.getColumnPosition(e);if(null!=o){var s={columnMetrics:i(r.columnMetrics)};s.columnMetrics=l.resizeColumn(s.columnMetrics,o,t),s.columnMetrics.totalWidth<r.columnMetrics.totalWidth&&(s.columnMetrics.totalWidth=r.columnMetrics.totalWidth),s.column=a.getColumn(s.columnMetrics.columns,o),this.setState({resizing:s})}},getColumnMetrics:function(){var e;return e=this.state.resizing?this.state.resizing.columnMetrics:this.props.columnMetrics},getColumnPosition:function(e){var t=this.getColumnMetrics(),r=-1;return t.columns.forEach(function(t,o){t.key===e.key&&(r=o)}),-1===r?null:r},onColumnResizeEnd:function(e,t){var r=this.getColumnPosition(e);null!==r&&this.props.onColumnResize&&this.props.onColumnResize(r,t||e.width)},setScrollLeft:function(e){var t=this.refs.row.getDOMNode();t.scrollLeft=e,this.refs.row.setScrollLeft(e)},getCombinedHeaderHeights:function(e){var t=this.props.headerRows.length;"undefined"!=typeof e&&(t=e);for(var r=0,o=0;t>o;o++)r+=this.props.headerRows[o].height||this.props.height;return r},getStyle:function(){return{position:"relative",height:this.getCombinedHeaderHeights(),overflow:"hidden"}}});e.exports=c},function(e,t,r){function o(){for(var e,t="",r=0;r<arguments.length;r++)if(e=arguments[r])if("string"==typeof e||"number"==typeof e)t+=" "+e;else if("[object Array]"===Object.prototype.toString.call(e))t+=" "+o.apply(null,e);else if("object"==typeof e)for(var s in e)e.hasOwnProperty(s)&&e[s]&&(t+=" "+s);return t.substr(1)}var s,n;"undefined"!=typeof e&&e.exports&&(e.exports=o),s=[],n=function(){return o}.apply(t,s),!(void 0!==n&&(e.exports=n))},function(e,t){"use strict";function r(e){var t={};for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);return t}e.exports=r},function(e,t,r){"use strict";function o(e){var t=n(e.columns,e.totalWidth),r=t.filter(function(e){return e.width}).reduce(function(e,t){return e-t.width},e.totalWidth);r-=m();var o=t.filter(function(e){return e.width}).reduce(function(e,t){return e+t.width},0);return t=i(t,r,e.minColumnWidth),t=s(t),{columns:t,width:o,totalWidth:e.totalWidth,minColumnWidth:e.minColumnWidth}}function s(e){var t=0;return e.map(function(e){return e.left=t,t+=e.width,e})}function n(e,t){return e.map(function(e){var r=p({},e);return e.width&&/^([0-9]+)%$/.exec(e.width.toString())&&(r.width=Math.floor(e.width/100*t)),r})}function i(e,t,r){var o=e.filter(function(e){return!e.width});return e.map(function(e,s,n){return e.width||(0>=t?e.width=r:e.width=Math.floor(t/f.getSize(o))),e})}function l(e,t,r){var s=f.getColumn(e.columns,t);e=h(e),e.columns=e.columns.slice(0);var n=h(s);return n.width=Math.max(r,e.minColumnWidth),e=f.spliceColumn(e,t,n),o(e)}function a(e,t){return"undefined"!=typeof Immutable&&e instanceof Immutable.List&&t instanceof Immutable.List}function u(e,t,r){var o,s,n,i={},l={};if(f.getSize(e)!==f.getSize(t))return!1;for(o=0,s=f.getSize(e);s>o;o++)n=e[o],i[n.key]=n;for(o=0,s=f.getSize(t);s>o;o++){n=t[o],l[n.key]=n;var a=i[n.key];if(void 0===a||!r(a,n))return!1}for(o=0,s=f.getSize(e);s>o;o++){n=e[o];var u=l[n.key];if(void 0===u)return!1}return!0}function c(e,t,r){return a(e,t)?e===t:u(e,t,r)}var p=r(3)["default"],h=r(22),d=(r(18).isValidElement,r(24)),f=r(25),m=r(26);e.exports={recalculate:o,resizeColumn:l,sameColumn:d,sameColumns:c}},function(e,t,r){"use strict";var o=r(18).isValidElement;e.exports=function(e,t){var r;for(r in e)if(e.hasOwnProperty(r)){if("function"==typeof e[r]&&"function"==typeof t[r]||o(e[r])&&o(t[r]))continue;if(!t.hasOwnProperty(r)||e[r]!==t[r])return!1}for(r in t)if(t.hasOwnProperty(r)&&!e.hasOwnProperty(r))return!1;return!0}},function(e,t){"use strict";e.exports={getColumn:function(e,t){return Array.isArray(e)?e[t]:"undefined"!=typeof Immutable?e.get(t):void 0},spliceColumn:function(e,t,r){return Array.isArray(e.columns)?e.columns.splice(t,1,r):"undefined"!=typeof Immutable&&(e.columns=e.columns.splice(t,1,r)),e},getSize:function(e){return Array.isArray(e)?e.length:"undefined"!=typeof Immutable?e.size:void 0}}},function(e,t){"use strict";function r(){if(void 0===o){var e=document.createElement("div");e.style.width="50px",e.style.height="50px",e.style.position="absolute",e.style.top="-200px",e.style.left="-200px";var t=document.createElement("div");t.style.height="100px",t.style.width="100%",e.appendChild(t),document.body.appendChild(e);var r=e.clientWidth;e.style.overflowY="scroll";var s=t.clientWidth;document.body.removeChild(e),o=r-s}return o}var o;e.exports=r},function(e,t,r){"use strict";var o=r(2)["default"],s=r(18),n=s.PropTypes,i=r(28),l=r(29),a=r(26),u=(r(42),r(25)),c=r(46),p={overflow:s.PropTypes.string,width:n.oneOfType([n.number,n.string]),height:s.PropTypes.number,position:s.PropTypes.string},h={ASC:"ASC",DESC:"DESC",NONE:"NONE"},d=s.createClass({displayName:"HeaderRow",propTypes:{width:n.oneOfType([n.number,n.string]),height:n.number.isRequired,columns:n.oneOfType([n.array,n.object]),onColumnResize:n.func,onSort:n.func.isRequired,style:n.shape(p)},mixins:[u],render:function(){var e={width:this.props.width?this.props.width+a():"100%",height:this.props.height,whiteSpace:"nowrap",overflowX:"hidden",overflowY:"hidden"},t=this.getCells();return s.createElement("div",o({},this.props,{className:"react-grid-HeaderRow"}),s.createElement("div",{style:e},t))},getHeaderRenderer:function(e){if(e.sortable){var t=this.props.sortColumn===e.key?this.props.sortDirection:h.NONE;return s.createElement(c,{columnKey:e.key,onSort:this.props.onSort,sortDirection:t})}return this.props.headerCellRenderer||e.headerRenderer||this.props.cellRenderer},getCells:function(){for(var e=[],t=[],r=0,o=this.getSize(this.props.columns);o>r;r++){var n=this.getColumn(this.props.columns,r),i=s.createElement(l,{ref:r,key:r,height:this.props.height,column:n,renderer:this.getHeaderRenderer(n),resizing:this.props.resizing===n,onResize:this.props.onColumnResize,onResizeEnd:this.props.onColumnResizeEnd});n.locked?t.push(i):e.push(i)}return e.concat(t)},setScrollLeft:function(e){var t=this;this.props.columns.forEach(function(r,o){r.locked&&t.refs[o].setScrollLeft(e)})},shouldComponentUpdate:function(e){return e.width!==this.props.width||e.height!==this.props.height||e.columns!==this.props.columns||!i(e.style,this.props.style)||this.props.sortColumn!=e.sortColumn||this.props.sortDirection!=e.sortDirection},getStyle:function(){return{overflow:"hidden",width:"100%",height:this.props.height,position:"absolute"}}});e.exports=d},function(e,t){"use strict";function r(e,t){if(e===t)return!0;var r;for(r in e)if(e.hasOwnProperty(r)&&(!t.hasOwnProperty(r)||e[r]!==t[r]))return!1;for(r in t)if(t.hasOwnProperty(r)&&!e.hasOwnProperty(r))return!1;return!0}e.exports=r},function(e,t,r){"use strict";function o(e){return s.createElement("div",{className:"widget-HeaderCell__value"},e.column.name)}var s=r(18),n=r(21),i=r(30),l=s.PropTypes,a=r(42),u=r(44),c=s.createClass({displayName:"HeaderCell",propTypes:{renderer:l.oneOfType([l.func,l.element]).isRequired,column:l.shape(a).isRequired,onResize:l.func.isRequired,height:l.number.isRequired,onResizeEnd:l.func.isRequired},render:function(){var e;this.props.column.resizable&&(e=s.createElement(u,{onDrag:this.onDrag,onDragStart:this.onDragStart,onDragEnd:this.onDragEnd}));var t=n({"react-grid-HeaderCell":!0,"react-grid-HeaderCell--resizing":this.state.resizing,"react-grid-HeaderCell--locked":this.props.column.locked});t=n(t,this.props.className);var r=this.getCell();return s.createElement("div",{className:t,style:this.getStyle()},r,e)},getCell:function(){if(s.isValidElement(this.props.renderer))return i(this.props.renderer,{column:this.props.column});this.props.renderer;return this.props.renderer({column:this.props.column})},getDefaultProps:function(){return{renderer:o}},getInitialState:function(){return{resizing:!1}},setScrollLeft:function(e){var t=s.findDOMNode(this);t.style.webkitTransform="translate3d("+e+"px, 0px, 0px)",t.style.transform="translate3d("+e+"px, 0px, 0px)"},getStyle:function(){return{width:this.props.column.width,left:this.props.column.left,display:"inline-block",position:"absolute",overflow:"hidden",height:this.props.height,margin:0,textOverflow:"ellipsis",whiteSpace:"nowrap"}},onDragStart:function(e){this.setState({resizing:!0}),e&&e.dataTransfer&&e.dataTransfer.setData&&e.dataTransfer.setData("text/plain","dummy")},onDrag:function(e){var t=this.props.onResize||null;if(t){var r=this.getWidthFromMouseEvent(e);r>0&&t(this.props.column,r)}},onDragEnd:function(e){var t=this.getWidthFromMouseEvent(e);this.props.onResizeEnd(this.props.column,t),this.setState({resizing:!1})},getWidthFromMouseEvent:function(e){var t=e.pageX,r=s.findDOMNode(this).getBoundingClientRect().left;return t-r}});s.createClass({displayName:"SimpleCellFormatter",propTypes:{value:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.number,s.PropTypes.object,s.PropTypes.bool]).isRequired},render:function(){return s.createElement("span",null,this.props.value)},shouldComponentUpdate:function(e,t){return e.value!==this.props.value}});e.exports=c},function(e,t,r){(function(t){"use strict";function o(e,r){"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?l(!e.ref,"You are calling cloneWithProps() on a child with a ref. This is dangerous because you're creating a new child which will not be added as a ref to its parent."):null);var o=n.mergeProps(r,e.props);return!o.hasOwnProperty(a)&&e.props.hasOwnProperty(a)&&(o.children=e.props.children),s.createElement(e.type,o)}var s=r(32),n=r(39),i=r(41),l=r(36),a=i({children:null});e.exports=o}).call(t,r(31))},function(e,t){function r(){u=!1,i.length?a=i.concat(a):c=-1,a.length&&o()}function o(){if(!u){var e=setTimeout(r);u=!0;for(var t=a.length;t;){for(i=a,a=[];++c<t;)i&&i[c].run();c=-1,t=a.length}i=null,u=!1,clearTimeout(e)}}function s(e,t){this.fun=e,this.array=t}function n(){}var i,l=e.exports={},a=[],u=!1,c=-1;l.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];a.push(new s(e,t)),1!==a.length||u||setTimeout(o,0)},s.prototype.run=function(){this.fun.apply(null,this.array)},l.title="browser",l.browser=!0,l.env={},l.argv=[],l.version="",l.versions={},l.on=n,l.addListener=n,l.once=n,l.off=n,l.removeListener=n,l.removeAllListeners=n,l.emit=n,l.binding=function(e){throw new Error("process.binding is not supported")},l.cwd=function(){return"/"},l.chdir=function(e){throw new Error("process.chdir is not supported")},l.umask=function(){return 0}},function(e,t,r){(function(t){"use strict";function o(e,r){Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:function(){return this._store?this._store[r]:null},set:function(e){"production"!==t.env.NODE_ENV?a(!1,"Don't set the %s property of the React element. Instead, specify the correct value when initially creating the element.",r):null,this._store[r]=e}})}function s(e){try{var t={props:!0};for(var r in t)o(e,r);c=!0}catch(s){}}var n=r(33),i=r(38),l=r(34),a=r(36),u={key:!0,ref:!0},c=!1,p=function(e,r,o,s,n,i){if(this.type=e,this.key=r,this.ref=o,this._owner=s,this._context=n,"production"!==t.env.NODE_ENV){this._store={props:i,originalProps:l({},i)};try{Object.defineProperty(this._store,"validated",{configurable:!1,enumerable:!1,writable:!0})}catch(a){}if(this._store.validated=!1,c)return void Object.freeze(this)}this.props=i};p.prototype={_isReactElement:!0},"production"!==t.env.NODE_ENV&&s(p.prototype),p.createElement=function(e,t,r){var o,s={},l=null,a=null;if(null!=t){a=void 0===t.ref?null:t.ref,l=void 0===t.key?null:""+t.key;for(o in t)t.hasOwnProperty(o)&&!u.hasOwnProperty(o)&&(s[o]=t[o])}var c=arguments.length-2;if(1===c)s.children=r;else if(c>1){for(var h=Array(c),d=0;c>d;d++)h[d]=arguments[d+2];s.children=h}if(e&&e.defaultProps){var f=e.defaultProps;for(o in f)"undefined"==typeof s[o]&&(s[o]=f[o])}return new p(e,l,a,i.current,n.current,s)},p.createFactory=function(e){var t=p.createElement.bind(null,e);return t.type=e,t},p.cloneAndReplaceProps=function(e,r){var o=new p(e.type,e.key,e.ref,e._owner,e._context,r);return"production"!==t.env.NODE_ENV&&(o._store.validated=e._store.validated),o},p.cloneElement=function(e,t,r){var o,s=l({},e.props),n=e.key,a=e.ref,c=e._owner;if(null!=t){void 0!==t.ref&&(a=t.ref,c=i.current),void 0!==t.key&&(n=""+t.key);for(o in t)t.hasOwnProperty(o)&&!u.hasOwnProperty(o)&&(s[o]=t[o])}var h=arguments.length-2;if(1===h)s.children=r;else if(h>1){for(var d=Array(h),f=0;h>f;f++)d[f]=arguments[f+2];s.children=d}return new p(e.type,n,a,c,e._context,s)},p.isValidElement=function(e){var t=!(!e||!e._isReactElement);return t},e.exports=p}).call(t,r(31))},function(e,t,r){(function(t){"use strict";var o=r(34),s=r(35),n=r(36),i=!1,l={current:s,withContext:function(e,r){"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?n(i,"withContext is deprecated and will be removed in a future version. Use a wrapper component with getChildContext instead."):null,i=!0);var s,a=l.current;l.current=o({},a,e);try{s=r()}finally{l.current=a}return s}};e.exports=l}).call(t,r(31))},function(e,t){"use strict";function r(e,t){if(null==e)throw new TypeError("Object.assign target cannot be null or undefined");for(var r=Object(e),o=Object.prototype.hasOwnProperty,s=1;s<arguments.length;s++){var n=arguments[s];if(null!=n){var i=Object(n);for(var l in i)o.call(i,l)&&(r[l]=i[l])}}return r}e.exports=r},function(e,t,r){(function(t){"use strict";var r={};"production"!==t.env.NODE_ENV&&Object.freeze(r),e.exports=r}).call(t,r(31))},function(e,t,r){(function(t){"use strict";var o=r(37),s=o;"production"!==t.env.NODE_ENV&&(s=function(e,t){for(var r=[],o=2,s=arguments.length;s>o;o++)r.push(arguments[o]);if(void 0===t)throw new Error("`warning(condition, format, ...args)` requires a warning message argument");if(t.length<10||/^[s\W]*$/.test(t))throw new Error("The warning format should be able to uniquely identify this warning. Please, use a more descriptive format than: "+t);if(0!==t.indexOf("Failed Composite propType: ")&&!e){var n=0,i="Warning: "+t.replace(/%s/g,function(){return r[n++]});console.warn(i);try{throw new Error(i)}catch(l){}}}),e.exports=s}).call(t,r(31))},function(e,t){function r(e){return function(){return e}}function o(){}o.thatReturns=r,o.thatReturnsFalse=r(!1),o.thatReturnsTrue=r(!0),o.thatReturnsNull=r(null),o.thatReturnsThis=function(){return this},o.thatReturnsArgument=function(e){return e},e.exports=o},function(e,t){"use strict";var r={current:null};e.exports=r},function(e,t,r){"use strict";function o(e){return function(t,r,o){t.hasOwnProperty(r)?t[r]=e(t[r],o):t[r]=o}}function s(e,t){for(var r in t)if(t.hasOwnProperty(r)){var o=u[r];o&&u.hasOwnProperty(r)?o(e,r,t[r]):e.hasOwnProperty(r)||(e[r]=t[r])}return e}var n=r(34),i=r(37),l=r(40),a=o(function(e,t){return n({},t,e)}),u={children:i,className:o(l),style:a},c={mergeProps:function(e,t){return s(n({},e),t)}};e.exports=c},function(e,t){"use strict";function r(e){e||(e="");var t,r=arguments.length;if(r>1)for(var o=1;r>o;o++)t=arguments[o],t&&(e=(e?e+" ":"")+t);return e}e.exports=r},function(e,t){var r=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};e.exports=r},function(e,t,r){"use strict";var o=(r(43)["default"],r(18)),s={name:o.PropTypes.string.isRequired,key:o.PropTypes.string.isRequired,width:o.PropTypes.number.isRequired};e.exports=s},function(e,t){"use strict";t["default"]=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},t.__esModule=!0},function(e,t,r){"use strict";var o=r(2)["default"],s=r(18),n=(r(21),r(45)),i=(r(30),s.PropTypes,s.createClass({displayName:"ResizeHandle",style:{position:"absolute",top:0,right:0,width:6,height:"100%"},render:function(){return s.createElement(n,o({},this.props,{className:"react-grid-HeaderCell__resizeHandle",style:this.style}))}}));e.exports=i},function(e,t,r){"use strict";var o=r(2)["default"],s=r(18),n=s.PropTypes,i=r(37),l=s.createClass({displayName:"Draggable",propTypes:{
onDragStart:n.func,onDragEnd:n.func,onDrag:n.func,component:n.oneOfType([n.func,n.constructor])},render:function(){this.props.component;return s.createElement("div",o({},this.props,{onMouseDown:this.onMouseDown,className:"react-grid-HeaderCell__draggable"}))},getDefaultProps:function(){return{onDragStart:i.thatReturnsTrue,onDragEnd:i,onDrag:i}},getInitialState:function(){return{drag:null}},onMouseDown:function(e){var t=this.props.onDragStart(e);(null!==t||0===e.button)&&(window.addEventListener("mouseup",this.onMouseUp),window.addEventListener("mousemove",this.onMouseMove),this.setState({drag:t}))},onMouseMove:function(e){null!==this.state.drag&&(e.preventDefault&&e.preventDefault(),this.props.onDrag(e))},onMouseUp:function(e){this.cleanUp(),this.props.onDragEnd(e,this.state.drag),this.setState({drag:null})},componentWillUnmount:function(){this.cleanUp()},cleanUp:function(){window.removeEventListener("mouseup",this.onMouseUp),window.removeEventListener("mousemove",this.onMouseMove)}});e.exports=l},function(e,t,r){"use strict";var o=r(18),s=r(21),n=(r(42),{ASC:"ASC",DESC:"DESC",NONE:"NONE"}),i=o.createClass({displayName:"SortableHeaderCell",propTypes:{columnKey:o.PropTypes.string.isRequired,onSort:o.PropTypes.func.isRequired,sortDirection:o.PropTypes.oneOf(["ASC","DESC","NONE"])},onClick:function(){var e;switch(this.props.sortDirection){case null:case void 0:case n.NONE:e=n.ASC;break;case n.ASC:e=n.DESC;break;case n.DESC:e=n.NONE}this.props.onSort(this.props.columnKey,e)},getSortByText:function(){var e={ASC:"9650",DESC:"9660",NONE:""};return String.fromCharCode(e[this.props.sortDirection])},render:function(){var e=s({"react-grid-HeaderCell-sortable":!0,"react-grid-HeaderCell-sortable--ascending":"ASC"===this.props.sortDirection,"react-grid-HeaderCell-sortable--descending":"DESC"===this.props.sortDirection});return o.createElement("div",{className:e,onClick:this.onClick,style:{cursor:"pointer"}},this.props.column.name,o.createElement("span",{className:"pull-right"},this.getSortByText()))}});e.exports=i},function(e,t,r){"use strict";var o=r(18),s=r(48),n=o.PropTypes,i=r(76),l=o.createClass({displayName:"Viewport",mixins:[i],propTypes:{rowOffsetHeight:n.number.isRequired,totalWidth:n.number.isRequired,columnMetrics:n.object.isRequired,rowGetter:n.oneOfType([n.array,n.func]).isRequired,selectedRows:n.array,expandedRows:n.array,rowRenderer:n.func,rowsCount:n.number.isRequired,rowHeight:n.number.isRequired,onRows:n.func,onScroll:n.func,minHeight:n.number},render:function(){var e={padding:0,bottom:0,left:0,right:0,overflow:"hidden",position:"absolute",top:this.props.rowOffsetHeight};return o.createElement("div",{className:"react-grid-Viewport",style:e},o.createElement(s,{ref:"canvas",totalWidth:this.props.totalWidth,width:this.props.columnMetrics.width,rowGetter:this.props.rowGetter,rowsCount:this.props.rowsCount,selectedRows:this.props.selectedRows,expandedRows:this.props.expandedRows,columns:this.props.columnMetrics.columns,rowRenderer:this.props.rowRenderer,visibleStart:this.state.visibleStart,visibleEnd:this.state.visibleEnd,displayStart:this.state.displayStart,displayEnd:this.state.displayEnd,cellMetaData:this.props.cellMetaData,height:this.state.height,rowHeight:this.props.rowHeight,onScroll:this.onScroll,onRows:this.props.onRows}))},getScroll:function(){return this.refs.canvas.getScroll()},onScroll:function(e){this.updateScroll(e.scrollTop,e.scrollLeft,this.state.height,this.props.rowHeight,this.props.rowsCount),this.props.onScroll&&this.props.onScroll({scrollTop:e.scrollTop,scrollLeft:e.scrollLeft})},setScrollLeft:function(e){this.refs.canvas.setScrollLeft(e)}});e.exports=l},function(e,t,r){"use strict";var o=r(18),s=r(21),n=o.PropTypes,i=r(30),l=r(28),a=r(37),u=r(49),c=r(50),p=(r(42),o.createClass({displayName:"Canvas",mixins:[u],propTypes:{rowRenderer:n.oneOfType([n.func,n.element]),rowHeight:n.number.isRequired,height:n.number.isRequired,displayStart:n.number.isRequired,displayEnd:n.number.isRequired,rowsCount:n.number.isRequired,rowGetter:n.oneOfType([n.func.isRequired,n.array.isRequired]),onRows:n.func,columns:n.oneOfType([n.object,n.array]).isRequired},render:function(){var e=this,t=this.state.displayStart,r=this.state.displayEnd,n=this.props.rowHeight,i=this.props.rowsCount,l=this.getRows(t,r).map(function(r,o){return e.renderRow({key:t+o,ref:o,idx:t+o,row:r,height:n,columns:e.props.columns,isSelected:e.isRowSelected(t+o),expandedRows:e.props.expandedRows,cellMetaData:e.props.cellMetaData})});this._currentRowsLength=l.length,t>0&&l.unshift(this.renderPlaceholder("top",t*n)),i-r>0&&l.push(this.renderPlaceholder("bottom",(i-r)*n));var a={position:"absolute",top:0,left:0,overflowX:"auto",overflowY:"scroll",width:this.props.totalWidth+this.state.scrollbarWidth,height:this.props.height,transform:"translate3d(0, 0, 0)"};return o.createElement("div",{style:a,onScroll:this.onScroll,className:s("react-grid-Canvas",this.props.className,{opaque:this.props.cellMetaData.selected&&this.props.cellMetaData.selected.active})},o.createElement("div",{style:{width:this.props.width,overflow:"hidden"}},l))},renderRow:function(e){var t=this.props.rowRenderer;return"function"==typeof t?o.createElement(t,e):o.isValidElement(this.props.rowRenderer)?i(this.props.rowRenderer,e):void 0},renderPlaceholder:function(e,t){return o.createElement("div",{key:e,style:{height:t}},this.props.columns.map(function(e,t){return o.createElement("div",{style:{width:e.width},key:t})}))},getDefaultProps:function(){return{rowRenderer:c,onRows:a}},isRowSelected:function(e){return this.props.selectedRows&&this.props.selectedRows[e]===!0},_currentRowsLength:0,_currentRowsRange:{start:0,end:0},_scroll:{scrollTop:0,scrollLeft:0},getInitialState:function(){return{shouldUpdate:!0,displayStart:this.props.displayStart,displayEnd:this.props.displayEnd,scrollbarWidth:0}},componentWillMount:function(){this._currentRowsLength=0,this._currentRowsRange={start:0,end:0},this._scroll={scrollTop:0,scrollLeft:0}},componentDidMount:function(){this.onRows()},componentDidUpdate:function(e){this._scroll!=={start:0,end:0}&&this.setScrollLeft(this._scroll.scrollLeft),this.onRows()},componentWillUnmount:function(){this._currentRowsLength=0,this._currentRowsRange={start:0,end:0},this._scroll={scrollTop:0,scrollLeft:0}},componentWillReceiveProps:function(e){e.rowsCount>this.props.rowsCount&&(o.findDOMNode(this).scrollTop=e.rowsCount*this.props.rowHeight);var t=this.getScrollbarWidth(),r=!(e.visibleStart>this.state.displayStart&&e.visibleEnd<this.state.displayEnd&&e.rowsCount===this.props.rowsCount&&e.rowHeight===this.props.rowHeight&&e.columns===this.props.columns&&e.width===this.props.width&&e.cellMetaData===this.props.cellMetaData&&l(e.style,this.props.style));r?this.setState({shouldUpdate:!0,displayStart:e.displayStart,displayEnd:e.displayEnd,scrollbarWidth:t}):this.setState({shouldUpdate:!1,scrollbarWidth:t})},shouldComponentUpdate:function(e,t){return!t||t.shouldUpdate},onRows:function(){this._currentRowsRange!=={start:0,end:0}&&(this.props.onRows(this._currentRowsRange),this._currentRowsRange={start:0,end:0})},getRows:function(e,t){if(this._currentRowsRange={start:e,end:t},Array.isArray(this.props.rowGetter))return this.props.rowGetter.slice(e,t);for(var r=[],o=e;t>o;o++)r.push(this.props.rowGetter(o));return r},getScrollbarWidth:function(){var e=0,t=this.getDOMNode();return e=t.offsetWidth-t.clientWidth},setScrollLeft:function(e){if(0!==this._currentRowsLength){if(!this.refs)return;for(var t=0,r=this._currentRowsLength;r>t;t++)this.refs[t]&&this.refs[t].setScrollLeft&&this.refs[t].setScrollLeft(e)}},getScroll:function(){var e=o.findDOMNode(this),t=e.scrollTop,r=e.scrollLeft;return{scrollTop:t,scrollLeft:r}},onScroll:function(e){this.appendScrollShim();var t=e.target,r=t.scrollTop,o=t.scrollLeft,s={scrollTop:r,scrollLeft:o};this._scroll=s,this.props.onScroll(s)}}));e.exports=p},function(e,t,r){"use strict";var o=r(18),s={appendScrollShim:function(){if(!this._scrollShim){var e=this._scrollShimSize(),t=document.createElement("div");t.classList?t.classList.add("react-grid-ScrollShim"):t.className+=" react-grid-ScrollShim",t.style.position="absolute",t.style.top=0,t.style.left=0,t.style.width=e.width+"px",t.style.height=e.height+"px",o.findDOMNode(this).appendChild(t),this._scrollShim=t}this._scheduleRemoveScrollShim()},_scrollShimSize:function(){return{width:this.props.width,height:this.props.length*this.props.rowHeight}},_scheduleRemoveScrollShim:function(){this._scheduleRemoveScrollShimTimer&&clearTimeout(this._scheduleRemoveScrollShimTimer),this._scheduleRemoveScrollShimTimer=setTimeout(this._removeScrollShim,200)},_removeScrollShim:function(){this._scrollShim&&(this._scrollShim.parentNode.removeChild(this._scrollShim),this._scrollShim=void 0)}};e.exports=s},function(e,t,r){"use strict";var o=r(2)["default"],s=r(18),n=r(21),i=r(51),l=r(23),a=r(25),u=s.createClass({displayName:"Row",propTypes:{height:s.PropTypes.number.isRequired,columns:s.PropTypes.oneOfType([s.PropTypes.object,s.PropTypes.array]).isRequired,row:s.PropTypes.object.isRequired,cellRenderer:s.PropTypes.func,isSelected:s.PropTypes.bool,idx:s.PropTypes.number.isRequired,expandedRows:s.PropTypes.arrayOf(s.PropTypes.object)},mixins:[a],render:function(){var e=n("react-grid-Row","react-grid-Row--"+(this.props.idx%2===0?"even":"odd")),t={height:this.getRowHeight(this.props),overflow:"hidden"},r=this.getCells();return s.createElement("div",o({},this.props,{className:e,style:t,onDragEnter:this.handleDragEnter}),s.isValidElement(this.props.row)?this.props.row:r)},getCells:function(){var e=this,t=[],r=[],o=this.getSelectedColumn();return this.props.columns.forEach(function(n,i){var l=e.props.cellRenderer,a=s.createElement(l,{ref:i,key:n.key+"-"+i,idx:i,rowIdx:e.props.idx,value:e.getCellValue(n.key||i),column:n,height:e.getRowHeight(),formatter:n.formatter,cellMetaData:e.props.cellMetaData,rowData:e.props.row,selectedColumn:o,isRowSelected:e.props.isSelected});n.locked?r.push(a):t.push(a)}),t.concat(r)},getRowHeight:function(){var e=this.props.expandedRows||null;if(e&&this.props.key){var t=e[this.props.key]||null;if(t)return t.height}return this.props.height},getCellValue:function(e){var t;return"select-row"===e?this.props.isSelected:t="function"==typeof this.props.row.get?this.props.row.get(e):this.props.row[e]},renderCell:function(e){return"function"==typeof this.props.cellRenderer&&this.props.cellRenderer.call(this,e),s.isValidElement(this.props.cellRenderer)?cloneWithProps(this.props.cellRenderer,e):this.props.cellRenderer(e)},getDefaultProps:function(){return{cellRenderer:i,isSelected:!1,height:35}},setScrollLeft:function(e){var t=this;this.props.columns.forEach(function(r,o){if(r.locked){if(!t.refs[o])return;t.refs[o].setScrollLeft(e)}})},doesRowContainSelectedCell:function(e){var t=e.cellMetaData.selected;return t&&t.rowIdx===e.idx?!0:!1},willRowBeDraggedOver:function(e){var t=e.cellMetaData.dragged;return null!=t&&(t.rowIdx>=0||t.complete===!0)},hasRowBeenCopied:function(){var e=this.props.cellMetaData.copied;return null!=e&&e.rowIdx===this.props.idx},shouldComponentUpdate:function(e,t){return!l.sameColumns(this.props.columns,e.columns,l.sameColumn)||this.doesRowContainSelectedCell(this.props)||this.doesRowContainSelectedCell(e)||this.willRowBeDraggedOver(e)||e.row!==this.props.row||this.hasRowBeenCopied()||this.props.isSelected!==e.isSelected||e.height!==this.props.height},handleDragEnter:function(){var e=this.props.cellMetaData.handleDragEnterRow;e&&e(this.props.idx)},getSelectedColumn:function(){var e=this.props.cellMetaData.selected;return e&&e.idx?this.getColumn(this.props.columns,e.idx):void 0}});e.exports=u},function(e,t,r){"use strict";var o=r(2)["default"],s=r(18),n=r(21),i=r(30),l=r(52),a=r(42),u=r(74),c=r(75),p=s.createClass({displayName:"Cell",propTypes:{rowIdx:s.PropTypes.number.isRequired,idx:s.PropTypes.number.isRequired,selected:s.PropTypes.shape({idx:s.PropTypes.number.isRequired}),tabIndex:s.PropTypes.number,ref:s.PropTypes.string,column:s.PropTypes.shape(a).isRequired,value:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.number,s.PropTypes.object,s.PropTypes.bool]).isRequired,isExpanded:s.PropTypes.bool,cellMetaData:s.PropTypes.shape(c).isRequired,handleDragStart:s.PropTypes.func,className:s.PropTypes.string,rowData:s.PropTypes.object.isRequired},getDefaultProps:function(){return{tabIndex:-1,ref:"cell",isExpanded:!1}},getInitialState:function(){return{isRowChanging:!1,isCellValueChanging:!1}},componentDidMount:function(){this.checkFocus()},componentDidUpdate:function(e,t){this.checkFocus();var r=this.props.cellMetaData.dragged;r&&r.complete===!0&&this.props.cellMetaData.handleTerminateDrag(),this.state.isRowChanging&&null!=this.props.selectedColumn&&this.applyUpdateClass()},componentWillReceiveProps:function(e){this.setState({isRowChanging:this.props.rowData!==e.rowData,isCellValueChanging:this.props.value!==e.value})},shouldComponentUpdate:function(e,t){return this.props.column.width!==e.column.width||this.props.column.left!==e.column.left||this.props.rowData!==e.rowData||this.props.height!==e.height||this.props.rowIdx!==e.rowIdx||this.isCellSelectionChanging(e)||this.isDraggedCellChanging(e)||this.isCopyCellChanging(e)||this.props.isRowSelected!==e.isRowSelected||this.isSelected()},getStyle:function(){var e={position:"absolute",width:this.props.column.width,height:this.props.height,left:this.props.column.left};return e},render:function(){var e=this.getStyle(),t=this.getCellClass(),r=this.renderCellContent({value:this.props.value,column:this.props.column,rowIdx:this.props.rowIdx,isExpanded:this.props.isExpanded});return s.createElement("div",o({},this.props,{className:t,style:e,onClick:this.onCellClick,onDoubleClick:this.onCellDoubleClick}),r,s.createElement("div",{className:"drag-handle",draggable:"true"}))},renderCellContent:function(e){var t,r=this.getFormatter();return s.isValidElement(r)?(e.dependentValues=this.getFormatterDependencies(),t=i(r,e)):t=u(r)?s.createElement(r,{value:this.props.value,dependentValues:this.getFormatterDependencies()}):s.createElement(h,{value:this.props.value}),s.createElement("div",{ref:"cell",className:"react-grid-Cell__value"},t," ",this.props.cellControls)},isColumnSelected:function(){var e=this.props.cellMetaData;return null==e||null==e.selected?!1:e.selected&&e.selected.idx===this.props.idx},isSelected:function(){var e=this.props.cellMetaData;return null==e||null==e.selected?!1:e.selected&&e.selected.rowIdx===this.props.rowIdx&&e.selected.idx===this.props.idx},isActive:function(){var e=this.props.cellMetaData;return null==e||null==e.selected?!1:this.isSelected()&&e.selected.active===!0},isCellSelectionChanging:function(e){var t=this.props.cellMetaData;if(null==t||null==t.selected)return!1;var r=e.cellMetaData.selected;return t.selected&&r?this.props.idx===r.idx||this.props.idx===t.selected.idx:!0},getFormatter:function(){var e=this.props.column;return this.isActive()?s.createElement(l,{rowData:this.getRowData(),rowIdx:this.props.rowIdx,idx:this.props.idx,cellMetaData:this.props.cellMetaData,column:e,height:this.props.height}):this.props.column.formatter},getRowData:function(){return this.props.rowData.toJSON?this.props.rowData.toJSON():this.props.rowData},getFormatterDependencies:function(){this.props.column.ItemId;return"function"==typeof this.props.column.getRowMetaData?this.props.column.getRowMetaData(this.getRowData(),this.props.column):void 0},onCellClick:function(e){var t=this.props.cellMetaData;null!=t&&null!=t.onCellClick&&t.onCellClick({rowIdx:this.props.rowIdx,idx:this.props.idx})},onCellDoubleClick:function(e){var t=this.props.cellMetaData;null!=t&&null!=t.onCellDoubleClick&&t.onCellDoubleClick({rowIdx:this.props.rowIdx,idx:this.props.idx})},checkFocus:function(){this.isSelected()&&!this.isActive()&&s.findDOMNode(this).focus()},getCellClass:function(){var e=n(this.props.column.cellClass,"react-grid-Cell",this.props.className,this.props.column.locked?"react-grid-Cell--locked":null),t=n({selected:this.isSelected()&&!this.isActive(),editing:this.isActive(),copied:this.isCopied(),"active-drag-cell":this.isSelected()||this.isDraggedOver(),"is-dragged-over-up":this.isDraggedOverUpwards(),"is-dragged-over-down":this.isDraggedOverDownwards(),"was-dragged-over":this.wasDraggedOver()});return n(e,t)},getUpdateCellClass:function(){return this.props.column.getUpdateCellClass?this.props.column.getUpdateCellClass(this.props.selectedColumn,this.props.column,this.state.isCellValueChanging):""},applyUpdateClass:function(){var e=this.getUpdateCellClass();if(null!=e&&""!=e){var t=this.getDOMNode();t.classList?(t.classList.remove(e),t.classList.add(e)):-1===t.className.indexOf(e)&&(t.className=t.className+" "+e)}},setScrollLeft:function(e){var t=this;if(t.isMounted()){var r=s.findDOMNode(this),o="translate3d("+e+"px, 0px, 0px)";r.style.webkitTransform=o,r.style.transform=o}},isCopied:function(){var e=this.props.cellMetaData.copied;return e&&e.rowIdx===this.props.rowIdx&&e.idx===this.props.idx},isDraggedOver:function(){var e=this.props.cellMetaData.dragged;return e&&e.overRowIdx===this.props.rowIdx&&e.idx===this.props.idx},wasDraggedOver:function(){var e=this.props.cellMetaData.dragged;return e&&(e.overRowIdx<this.props.rowIdx&&this.props.rowIdx<e.rowIdx||e.overRowIdx>this.props.rowIdx&&this.props.rowIdx>e.rowIdx)&&e.idx===this.props.idx},isDraggedCellChanging:function(e){var t,r=this.props.cellMetaData.dragged,o=e.cellMetaData.dragged;return r?t=o&&this.props.idx===o.idx||r&&this.props.idx===r.idx:!1},isCopyCellChanging:function(e){var t,r=this.props.cellMetaData.copied,o=e.cellMetaData.copied;return r?t=o&&this.props.idx===o.idx||r&&this.props.idx===r.idx:!1},isDraggedOverUpwards:function(){var e=this.props.cellMetaData.dragged;return!this.isSelected()&&this.isDraggedOver()&&this.props.rowIdx<e.rowIdx},isDraggedOverDownwards:function(){var e=this.props.cellMetaData.dragged;return!this.isSelected()&&this.isDraggedOver()&&this.props.rowIdx>e.rowIdx}}),h=s.createClass({displayName:"SimpleCellFormatter",propTypes:{value:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.number,s.PropTypes.object,s.PropTypes.bool]).isRequired},render:function(){return s.createElement("span",null,this.props.value)},shouldComponentUpdate:function(e,t){return e.value!==this.props.value}});e.exports=p},function(e,t,r){"use strict";var o=r(18),s=r(21),n=r(53),i=r(54),l=r(74),a=r(30),u=o.createClass({displayName:"EditorContainer",mixins:[n],propTypes:{rowData:o.PropTypes.object.isRequired,value:o.PropTypes.oneOfType([o.PropTypes.string,o.PropTypes.number,o.PropTypes.object,o.PropTypes.bool]).isRequired,cellMetaData:o.PropTypes.shape({selected:o.PropTypes.object.isRequired,copied:o.PropTypes.object,dragged:o.PropTypes.object,onCellClick:o.PropTypes.func,onCellDoubleClick:o.PropTypes.func}).isRequired,column:o.PropTypes.object.isRequired,height:o.PropTypes.number.isRequired},changeCommitted:!1,getInitialState:function(){return{isInvalid:!1}},componentDidMount:function(){var e=this.getInputNode();void 0!==e&&(this.setTextInputFocus(),this.getEditor().disableContainerStyles||(e.className+=" editor-main",e.style.height=this.props.height-1+"px"))},createEditor:function(){var e=this,t=function(t){return e.editor=t},r={ref:t,column:this.props.column,value:this.getInitialValue(),onCommit:this.commit,rowMetaData:this.getRowMetaData(),height:this.props.height,onBlur:this.commit,onOverrideKeyDown:this.onKeyDown},s=this.props.column.editor;return s&&o.isValidElement(s)?a(s,r):o.createElement(i,{ref:t,column:this.props.column,value:this.getInitialValue(),onBlur:this.commit,rowMetaData:this.getRowMetaData()})},getRowMetaData:function(){this.props.column.ItemId;return"function"==typeof this.props.column.getRowMetaData?this.props.column.getRowMetaData(this.props.rowData,this.props.column):void 0},onPressEnter:function(e){this.commit({key:"Enter"})},onPressTab:function(e){this.commit({key:"Tab"})},onPressEscape:function(e){this.editorIsSelectOpen()?e.stopPropagation():this.props.cellMetaData.onCommitCancel()},onPressArrowDown:function(e){this.editorHasResults()?e.stopPropagation():this.commit(e)},onPressArrowUp:function(e){this.editorHasResults()?e.stopPropagation():this.commit(e)},onPressArrowLeft:function(e){this.isCaretAtBeginningOfInput()?this.commit(e):e.stopPropagation()},onPressArrowRight:function(e){this.isCaretAtEndOfInput()?this.commit(e):e.stopPropagation()},editorHasResults:function(){return l(this.getEditor().hasResults)?this.getEditor().hasResults():!1},editorIsSelectOpen:function(){return l(this.getEditor().isSelectOpen)?this.getEditor().isSelectOpen():!1},getEditor:function(){return this.editor},commit:function(e){var t=e||{},r=this.getEditor().getValue();if(this.isNewValueValid(r)){var o=this.props.column.key;this.props.cellMetaData.onCommit({cellKey:o,rowIdx:this.props.rowIdx,updated:r,key:t.key})}this.changeCommitted=!0},isNewValueValid:function(e){if(l(this.getEditor().validate)){var t=this.getEditor().validate(e);return this.setState({isInvalid:!t}),t}return!0},getInputNode:function(){return this.getEditor().getInputNode()},getInitialValue:function(){var e=this.props.cellMetaData.selected,t=e.initialKeyCode;if("Delete"===t||"Backspace"===t)return"";if("Enter"===t)return this.props.value;var r=t?String.fromCharCode(t):this.props.value;return r},getContainerClass:function(){return s({"has-error":this.state.isInvalid===!0})},renderStatusIcon:function(){return this.state.isInvalid===!0?o.createElement("span",{className:"glyphicon glyphicon-remove form-control-feedback"}):void 0},render:function(){return o.createElement("div",{className:this.getContainerClass(),onKeyDown:this.onKeyDown},this.createEditor(),this.renderStatusIcon())},setCaretAtEndOfInput:function(){var e=this.getInputNode(),t=e.value.length;if(e.setSelectionRange)e.setSelectionRange(t,t);else if(e.createTextRange){var r=e.createTextRange();r.moveStart("character",t),r.collapse(),r.select()}},isCaretAtBeginningOfInput:function(){var e=this.getInputNode();return e.selectionStart===e.selectionEnd&&0===e.selectionStart},isCaretAtEndOfInput:function(){var e=this.getInputNode();return e.selectionStart===e.value.length},setTextInputFocus:function(){var e=this.props.cellMetaData.selected,t=e.initialKeyCode,r=this.getInputNode();r.focus(),"INPUT"===r.tagName&&(this.isKeyPrintable(t)?r.select():(r.focus(),r.select()))},componentWillUnmount:function(){this.changeCommitted||this.hasEscapeBeenPressed()||this.commit({key:"Enter"})},hasEscapeBeenPressed:function(){var e=!1,t=27;return window.event&&(window.event.keyCode===t?e=!0:window.event.which===t&&(e=!0)),e}});e.exports=u},function(e,t,r){"use strict";var o=(r(18),{onKeyDown:function(e){if(this.isCtrlKeyHeldDown(e))this.checkAndCall("onPressKeyWithCtrl",e);else if(this.isKeyExplicitlyHandled(e.key)){var t="onPress"+e.key;this.checkAndCall(t,e)}else this.isKeyPrintable(e.keyCode)&&this.checkAndCall("onPressChar",e)},isKeyPrintable:function(e){var t=e>47&&58>e||32==e||13==e||e>64&&91>e||e>95&&112>e||e>185&&193>e||e>218&&223>e;return t},isKeyExplicitlyHandled:function(e){return"function"==typeof this["onPress"+e]},isCtrlKeyHeldDown:function(e){return e.ctrlKey===!0&&"Control"!==e.key},checkAndCall:function(e,t){"function"==typeof this[e]&&this[e](t)}});e.exports=o},function(e,t,r){"use strict";var o=r(55)["default"],s=r(61)["default"],n=r(70)["default"],i=r(43)["default"],l=r(18),a=(r(53),r(42),r(73)),u=function(e){function t(){i(this,t),o(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return s(t,e),n(t,[{key:"render",value:function(){return l.createElement("input",{ref:"input",type:"text",onBlur:this.props.onBlur,className:"form-control",defaultValue:this.props.value})}}]),t}(a);e.exports=u},function(e,t,r){"use strict";var o=r(56)["default"];t["default"]=function(e,t,r){for(var s=!0;s;){var n=e,i=t,l=r;s=!1,null===n&&(n=Function.prototype);var a=o(n,i);if(void 0!==a){if("value"in a)return a.value;var u=a.get;if(void 0===u)return;return u.call(l)}var c=Object.getPrototypeOf(n);if(null===c)return;e=c,t=i,r=l,s=!0,a=c=void 0}},t.__esModule=!0},function(e,t,r){e.exports={"default":r(57),__esModule:!0}},function(e,t,r){var o=r(12);r(58),e.exports=function(e,t){return o.getDesc(e,t)}},function(e,t,r){var o=r(59);r(60)("getOwnPropertyDescriptor",function(e){return function(t,r){return e(o(t),r)}})},function(e,t,r){var o=r(15),s=r(14);e.exports=function(e){return o(s(e))}},function(e,t,r){var o=r(6),s=r(8),n=r(17);e.exports=function(e,t){var r=(s.Object||{})[e]||Object[e],i={};i[e]=t(r),o(o.S+o.F*n(function(){r(1)}),"Object",i)}},function(e,t,r){"use strict";var o=r(62)["default"],s=r(64)["default"];t["default"]=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=o(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(s?s(e,t):e.__proto__=t)},t.__esModule=!0},function(e,t,r){e.exports={"default":r(63),__esModule:!0}},function(e,t,r){var o=r(12);e.exports=function(e,t){return o.create(e,t)}},function(e,t,r){e.exports={"default":r(65),__esModule:!0}},function(e,t,r){r(66),e.exports=r(8).Object.setPrototypeOf},function(e,t,r){var o=r(6);o(o.S,"Object",{setPrototypeOf:r(67).set})},function(e,t,r){var o=r(12).getDesc,s=r(68),n=r(69),i=function(e,t){if(n(e),!s(t)&&null!==t)throw TypeError(t+": can't set as prototype!")};e.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,s){try{s=r(9)(Function.call,o(Object.prototype,"__proto__").set,2),s(e,[]),t=!(e instanceof Array)}catch(n){t=!0}return function(e,r){return i(e,r),t?e.__proto__=r:s(e,r),e}}({},!1):void 0),check:i}},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t,r){var o=r(68);e.exports=function(e){if(!o(e))throw TypeError(e+" is not an object!");return e}},function(e,t,r){"use strict";var o=r(71)["default"];t["default"]=function(){function e(e,t){for(var r=0;r<t.length;r++){var s=t[r];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),o(e,s.key,s)}}return function(t,r,o){return r&&e(t.prototype,r),o&&e(t,o),t}}(),t.__esModule=!0},function(e,t,r){e.exports={"default":r(72),__esModule:!0}},function(e,t,r){var o=r(12);e.exports=function(e,t,r){return o.setDesc(e,t,r)}},function(e,t,r){"use strict";var o=r(55)["default"],s=r(61)["default"],n=r(70)["default"],i=r(43)["default"],l=r(18),a=(r(53),r(42)),u=function(e){function t(){i(this,t),o(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return s(t,e),n(t,[{key:"getStyle",value:function(){return{width:"100%"}}},{key:"getValue",value:function(){var e={};return e[this.props.column.key]=this.getInputNode().value,e}},{key:"getInputNode",value:function(){var e=l.findDOMNode(this);return"INPUT"===e.tagName?e:e.querySelector("input:not([type=hidden])")}},{key:"inheritContainerStyles",value:function(){return!0}}]),t}(l.Component);u.propTypes={onKeyDown:l.PropTypes.func.isRequired,value:l.PropTypes.any.isRequired,onBlur:l.PropTypes.func.isRequired,column:l.PropTypes.shape(a).isRequired,commit:l.PropTypes.func.isRequired},e.exports=u},function(e,t){"use strict";var r=function(e){var t={};return e&&"[object Function]"===t.toString.call(e)};e.exports=r},function(e,t,r){"use strict";var o=r(18).PropTypes;e.exports={selected:o.object.isRequired,copied:o.object,dragged:o.object,onCellClick:o.func.isRequired}},function(e,t,r){"use strict";var o=r(18),s=r(77),n=(r(78),o.PropTypes,Math.min),i=Math.max,l=Math.floor,a=Math.ceil;e.exports={mixins:[s.MetricsMixin],DOMMetrics:{viewportHeight:function(){return o.findDOMNode(this).offsetHeight}},propTypes:{rowHeight:o.PropTypes.number,rowsCount:o.PropTypes.number.isRequired},getDefaultProps:function(){return{rowHeight:30}},getInitialState:function(){return this.getGridState(this.props)},getGridState:function(e){var t=a((e.minHeight-e.rowHeight)/e.rowHeight),r=n(2*t,e.rowsCount);return{displayStart:0,displayEnd:r,height:e.minHeight,scrollTop:0,scrollLeft:0}},updateScroll:function(e,t,r,o,s){var u=a(r/o),c=l(e/o),p=n(c+u,s),h=i(0,c-2*u),d=n(c+2*u,s),f={visibleStart:c,visibleEnd:p,displayStart:h,displayEnd:d,height:r,scrollTop:e,scrollLeft:t};this.setState(f)},metricsUpdated:function(){var e=this.DOMMetrics.viewportHeight();e&&this.updateScroll(this.state.scrollTop,this.state.scrollLeft,e,this.props.rowHeight,this.props.rowsCount)},componentWillReceiveProps:function(e){this.props.rowHeight!==e.rowHeight||this.props.minHeight!==e.minHeight?this.setState(this.getGridState(e)):this.props.rowsCount!==e.rowsCount&&this.updateScroll(this.state.scrollTop,this.state.scrollLeft,this.state.height,e.rowHeight,e.rowsCount)}}},function(e,t,r){"use strict";var o=r(18),s=r(37),n=r(22),i={metricsComputator:o.PropTypes.object},l={childContextTypes:i,getChildContext:function(){return{metricsComputator:this}},getMetricImpl:function(e){return this._DOMMetrics.metrics[e].value},registerMetricsImpl:function(e,t){var r={},o=this._DOMMetrics;for(var s in t){if(void 0!==o.metrics[s])throw new Error("DOM metric "+s+" is already defined");o.metrics[s]={component:e,computator:t[s].bind(e)},r[s]=this.getMetricImpl.bind(null,s)}return-1===o.components.indexOf(e)&&o.components.push(e),r},unregisterMetricsFor:function(e){var t=this._DOMMetrics,r=t.components.indexOf(e);if(r>-1){t.components.splice(r,1);var o,s={};for(o in t.metrics)t.metrics[o].component===e&&(s[o]=!0);for(o in s)delete t.metrics[o]}},updateMetrics:function(){var e=this._DOMMetrics,t=!1;for(var r in e.metrics){var o=e.metrics[r].computator();o!==e.metrics[r].value&&(t=!0),e.metrics[r].value=o}if(t)for(var s=0,n=e.components.length;n>s;s++)e.components[s].metricsUpdated&&e.components[s].metricsUpdated()},componentWillMount:function(){this._DOMMetrics={metrics:{},components:[]}},componentDidMount:function(){window.addEventListener?window.addEventListener("resize",this.updateMetrics):window.attachEvent("resize",this.updateMetrics),this.updateMetrics()},componentWillUnmount:function(){window.removeEventListener("resize",this.updateMetrics)}},a={contextTypes:i,componentWillMount:function(){if(this.DOMMetrics){this._DOMMetricsDefs=n(this.DOMMetrics),this.DOMMetrics={};for(var e in this._DOMMetricsDefs)this.DOMMetrics[e]=s}},componentDidMount:function(){this.DOMMetrics&&(this.DOMMetrics=this.registerMetrics(this._DOMMetricsDefs))},componentWillUnmount:function(){return this.registerMetricsImpl?void(this.hasOwnProperty("DOMMetrics")&&delete this.DOMMetrics):this.context.metricsComputator.unregisterMetricsFor(this)},registerMetrics:function(e){return this.registerMetricsImpl?this.registerMetricsImpl(this,e):this.context.metricsComputator.registerMetricsImpl(this,e)},getMetric:function(e){return this.getMetricImpl?this.getMetricImpl(e):this.context.metricsComputator.getMetricImpl(e)}};e.exports={MetricsComputatorMixin:l,MetricsMixin:a}},function(e,t){"use strict";function r(){var e=window.innerWidth,t=window.innerHeight;return e&&t||(e=document.documentElement.clientWidth,t=document.documentElement.clientHeight),e&&t||(e=document.body.clientWidth,t=document.body.clientHeight),{width:e,height:t}}e.exports=r},function(e,t){"use strict";e.exports={componentDidMount:function(){this._scrollLeft=this.refs.viewport.getScroll().scrollLeft,this._onScroll()},componentDidUpdate:function(){this._onScroll()},componentWillMount:function(){this._scrollLeft=void 0},componentWillUnmount:function(){this._scrollLeft=void 0},onScroll:function(e){this._scrollLeft!==e.scrollLeft&&(this._scrollLeft=e.scrollLeft,this._onScroll())},_onScroll:function(){void 0!==this._scrollLeft&&(this.refs.header.setScrollLeft(this._scrollLeft),this.refs.viewport.setScrollLeft(this._scrollLeft))}}},function(e,t,r){"use strict";var o=r(18),s=o.createClass({displayName:"CheckboxEditor",PropTypes:{value:o.PropTypes.bool.isRequired,rowIdx:o.PropTypes.number.isRequired,column:o.PropTypes.shape({key:o.PropTypes.string.isRequired,onCellChange:o.PropTypes.func.isRequired}).isRequired
},render:function(){var e=null!=this.props.value?this.props.value:!1;return o.createElement("input",{className:"react-grid-CheckBox",type:"checkbox",checked:e,onClick:this.handleChange})},handleChange:function(e){this.props.column.onCellChange(this.props.rowIdx,this.props.column.key,e)}});e.exports=s},function(e,t,r){"use strict";var o=r(18),s=r(42),n=o.createClass({displayName:"FilterableHeaderCell",propTypes:{onChange:o.PropTypes.func.isRequired,column:o.PropTypes.shape(s).isRequired},getInitialState:function(){return{filterTerm:""}},handleChange:function(e){var t=e.target.value;this.setState({filterTerm:t}),this.props.onChange({filterTerm:t,columnKey:this.props.column.key})},render:function(){return o.createElement("div",null,o.createElement("div",{className:"form-group"},this.renderInput()))},renderInput:function(){if(this.props.column.filterable===!1)return o.createElement("span",null);var e="header-filter-"+this.props.column.key;return o.createElement("input",{key:e,type:"text",className:"form-control input-sm",placeholder:"Search",value:this.state.filterTerm,onChange:this.handleChange})}});e.exports=n},function(e,t,r){"use strict";var o=r(43)["default"],s=r(23),n=r(77);Object.assign=r(83);var i=r(18).PropTypes,l=r(25),a=r(18),u=function c(){o(this,c)};e.exports={mixins:[n.MetricsMixin],propTypes:{columns:i.arrayOf(u),minColumnWidth:i.number,columnEquality:i.func},DOMMetrics:{gridWidth:function(){return a.findDOMNode(this).parentElement.offsetWidth}},getDefaultProps:function(){return{minColumnWidth:80,columnEquality:s.sameColumn}},componentWillReceiveProps:function(e){if(e.columns&&!s.sameColumns(this.props.columns,e.columns,this.props.columnEquality)){var t=this.createColumnMetrics(e);this.setState({columnMetrics:t})}},getTotalWidth:function(){var e=0;return e=this.isMounted()?this.DOMMetrics.gridWidth():l.getSize(this.props.columns)*this.props.minColumnWidth},getColumnMetricsType:function(e){var t=this.getTotalWidth(),r={columns:e.columns,totalWidth:t,minColumnWidth:e.minColumnWidth},o=s.recalculate(r);return o},getColumn:function(e){var t=this.state.columnMetrics.columns;return Array.isArray(t)?t[e]:"undefined"!=typeof Immutable?t.get(e):void 0},getSize:function(){var e=this.state.columnMetrics.columns;return Array.isArray(e)?e.length:"undefined"!=typeof Immutable?e.size:void 0},metricsUpdated:function(){var e=this.createColumnMetrics();this.setState({columnMetrics:e})},createColumnMetrics:function(){var e=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0],t=this.setupGridColumns(e);return this.getColumnMetricsType({columns:t,minColumnWidth:this.props.minColumnWidth})},onColumnResize:function(e,t){var r=s.resizeColumn(this.state.columnMetrics,e,t);this.setState({columnMetrics:r})}}},function(e,t){"use strict";function r(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}e.exports=Object.assign||function(e,t){for(var o,s,n=r(e),i=1;i<arguments.length;i++){o=arguments[i],s=Object.keys(Object(o));for(var l=0;l<s.length;l++)n[s[l]]=o[s[l]]}return n}},function(e,t){"use strict";var r={get:function(e,t){return"function"==typeof e.get?e.get(t):e[t]}};e.exports=r},function(e,t,r){"use strict";var o={AutoComplete:r(86),DropDownEditor:r(88),SimpleTextEditor:r(54),CheckboxEditor:r(80)};e.exports=o},function(e,t,r){"use strict";var o=r(18),s=r(87),n=(r(53),r(42)),i=o.PropTypes.shape({id:o.PropTypes.required,title:o.PropTypes.string}),l=o.createClass({displayName:"AutoCompleteEditor",propTypes:{onCommit:o.PropTypes.func.isRequired,options:o.PropTypes.arrayOf(i).isRequired,label:o.PropTypes.string,value:o.PropTypes.any.isRequired,valueParams:o.PropTypes.arrayOf(o.PropTypes.string),column:o.PropTypes.shape(n).isRequired,resultIdentifier:o.PropTypes.string,search:o.PropTypes.string},getDefaultProps:function(){return{resultIdentifier:"id"}},getValue:function(){var e,t={};return this.hasResults()&&this.isFocusedOnSuggestion()?(e=this.getLabel(this.refs.autoComplete.state.focusedValue),this.props.valueParams&&(e=this.constuctValueFromParams(this.refs.autoComplete.state.focusedValue,this.props.valueParams))):e=this.refs.autoComplete.state.searchTerm,t[this.props.column.key]=e,t},getInputNode:function(){return this.getDOMNode().getElementsByTagName("input")[0]},render:function(){var e=null!=this.props.label?this.props.label:"title";return o.createElement("div",{height:this.props.height,onKeyDown:this.props.onKeyDown},o.createElement(s,{search:this.props.search,ref:"autoComplete",label:e,onChange:this.handleChange,resultIdentifier:this.props.resultIdentifier,options:this.props.options,value:{title:this.props.value}}))},handleChange:function(){this.props.onCommit()},hasResults:function(){return this.refs.autoComplete.state.results.length>0},isFocusedOnSuggestion:function(){var e=this.refs.autoComplete;return null!=e.state.focusedValue},getLabel:function(e){var t=null!=this.props.label?this.props.label:"title";return"function"==typeof t?t(e):"string"==typeof t?e[t]:void 0},constuctValueFromParams:function(e,t){if(!t)return"";for(var r=[],o=0,s=t.length;s>o;o++)r.push(e[t[o]]);return r.join("|")}});e.exports=l},function(e,t,r){!function(t,o){e.exports=o(r(18))}(this,function(e){return function(e){function t(o){if(r[o])return r[o].exports;var s=r[o]={exports:{},id:o,loaded:!1};return e[o].call(s.exports,s,s.exports,t),s.loaded=!0,s.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){"use strict";function o(e,t,r){if(!e)return r(null,[]);t=new RegExp(t,"i");for(var o=[],s=0,n=e.length;n>s;s++)t.exec(e[s].title)&&o.push(e[s]);r(null,o)}var s=r(1),n=r(2),i=s.createClass({displayName:"Autocomplete",propTypes:{options:s.PropTypes.any,search:s.PropTypes.func,resultRenderer:s.PropTypes.oneOfType([s.PropTypes.component,s.PropTypes.func]),value:s.PropTypes.object,onChange:s.PropTypes.func,onError:s.PropTypes.func},getDefaultProps:function(){return{search:o}},getInitialState:function(){var e=this.props.searchTerm?this.props.searchTerm:this.props.value?this.props.value.title:"";return{results:[],showResults:!1,showResultsInProgress:!1,searchTerm:e,focusedValue:null}},getResultIdentifier:function(e){return void 0===this.props.resultIdentifier?e.id:e[this.props.resultIdentifier]},render:function(){var e=n(this.props.className,"react-autocomplete-Autocomplete",this.state.showResults?"react-autocomplete-Autocomplete--resultsShown":void 0),t={position:"relative",outline:"none"};return s.createElement("div",{tabIndex:"1",className:e,onFocus:this.onFocus,onBlur:this.onBlur,style:t},s.createElement("input",{ref:"search",className:"react-autocomplete-Autocomplete__search",style:{width:"100%"},onClick:this.showAllResults,onChange:this.onQueryChange,onFocus:this.showAllResults,onBlur:this.onQueryBlur,onKeyDown:this.onQueryKeyDown,value:this.state.searchTerm}),s.createElement(l,{className:"react-autocomplete-Autocomplete__results",onSelect:this.onValueChange,onFocus:this.onValueFocus,results:this.state.results,focusedValue:this.state.focusedValue,show:this.state.showResults,renderer:this.props.resultRenderer,label:this.props.label,resultIdentifier:this.props.resultIdentifier}))},componentWillReceiveProps:function(e){var t=e.searchTerm?e.searchTerm:e.value?e.value.title:"";this.setState({searchTerm:t})},componentWillMount:function(){this.blurTimer=null},showResults:function(e){this.setState({showResultsInProgress:!0}),this.props.search(this.props.options,e.trim(),this.onSearchComplete)},showAllResults:function(){this.state.showResultsInProgress||this.state.showResults||this.showResults("")},onValueChange:function(e){var t={value:e,showResults:!1};e&&(t.searchTerm=e.title),this.setState(t),this.props.onChange&&this.props.onChange(e)},onSearchComplete:function(e,t){if(e){if(!this.props.onError)throw e;this.props.onError(e)}this.setState({showResultsInProgress:!1,showResults:!0,results:t})},onValueFocus:function(e){this.setState({focusedValue:e})},onQueryChange:function(e){var t=e.target.value;this.setState({searchTerm:t,focusedValue:null}),this.showResults(t)},onFocus:function(){this.blurTimer&&(clearTimeout(this.blurTimer),this.blurTimer=null),this.refs.search.getDOMNode().focus()},onBlur:function(){this.blurTimer=setTimeout(function(){this.isMounted()&&this.setState({showResults:!1})}.bind(this),100)},onQueryKeyDown:function(e){if("Enter"===e.key)e.preventDefault(),this.state.focusedValue&&this.onValueChange(this.state.focusedValue);else if("ArrowUp"===e.key&&this.state.showResults){e.preventDefault();var t=Math.max(this.focusedValueIndex()-1,0);this.setState({focusedValue:this.state.results[t]})}else if("ArrowDown"===e.key)if(e.preventDefault(),this.state.showResults){var r=Math.min(this.focusedValueIndex()+(this.state.showResults?1:0),this.state.results.length-1);this.setState({showResults:!0,focusedValue:this.state.results[r]})}else this.showAllResults()},focusedValueIndex:function(){if(!this.state.focusedValue)return-1;for(var e=0,t=this.state.results.length;t>e;e++)if(this.getResultIdentifier(this.state.results[e])===this.getResultIdentifier(this.state.focusedValue))return e;return-1}}),l=s.createClass({displayName:"Results",getResultIdentifier:function(e){if(void 0===this.props.resultIdentifier){if(!e.id)throw"id property not found on result. You must specify a resultIdentifier and pass as props to autocomplete component";return e.id}return e[this.props.resultIdentifier]},render:function(){var e={display:this.props.show?"block":"none",position:"absolute",listStyleType:"none"},t=this.props,r=t.className,o=function(e,t){var r={},o=Object.prototype.hasOwnProperty;if(null==e)throw new TypeError;for(var s in e)o.call(e,s)&&!o.call(t,s)&&(r[s]=e[s]);return r}(t,{className:1});return s.createElement("ul",s.__spread({},o,{style:e,className:r+" react-autocomplete-Results"}),this.props.results.map(this.renderResult))},renderResult:function(e){var t=this.props.focusedValue&&this.getResultIdentifier(this.props.focusedValue)===this.getResultIdentifier(e),r=this.props.renderer||a;return s.createElement(r,{ref:t?"focused":void 0,key:this.getResultIdentifier(e),result:e,focused:t,onMouseEnter:this.onMouseEnterResult,onClick:this.props.onSelect,label:this.props.label})},componentDidUpdate:function(){this.scrollToFocused()},componentDidMount:function(){this.scrollToFocused()},componentWillMount:function(){this.ignoreFocus=!1},scrollToFocused:function(){var e=this.refs&&this.refs.focused;if(e){var t=this.getDOMNode(),r=t.scrollTop,o=t.offsetHeight,s=e.getDOMNode(),n=s.offsetTop,i=n+s.offsetHeight;r>n?(this.ignoreFocus=!0,t.scrollTop=n):i-r>o&&(this.ignoreFocus=!0,t.scrollTop=i-o)}},onMouseEnterResult:function(e,t){if(this.ignoreFocus)this.ignoreFocus=!1;else{var r=this.getDOMNode(),o=r.scrollTop,s=r.offsetHeight,n=e.target,i=n.offsetTop,l=i+n.offsetHeight;l>o&&o+s>i&&this.props.onFocus(t)}}}),a=s.createClass({displayName:"Result",getDefaultProps:function(){return{label:function(e){return e.title}}},getLabel:function(e){return"function"==typeof this.props.label?this.props.label(e):"string"==typeof this.props.label?e[this.props.label]:void 0},render:function(){var e=n({"react-autocomplete-Result":!0,"react-autocomplete-Result--active":this.props.focused});return s.createElement("li",{style:{listStyleType:"none"},className:e,onClick:this.onClick,onMouseEnter:this.onMouseEnter},s.createElement("a",null,this.getLabel(this.props.result)))},onClick:function(){this.props.onClick(this.props.result)},onMouseEnter:function(e){this.props.onMouseEnter&&this.props.onMouseEnter(e,this.props.result)},shouldComponentUpdate:function(e){return e.result.id!==this.props.result.id||e.focused!==this.props.focused}});e.exports=i},function(t,r){t.exports=e},function(e,t,r){function o(){for(var e,t="",r=0;r<arguments.length;r++)if(e=arguments[r])if("string"==typeof e||"number"==typeof e)t+=" "+e;else if("[object Array]"===Object.prototype.toString.call(e))t+=" "+o.apply(null,e);else if("object"==typeof e)for(var s in e)e.hasOwnProperty(s)&&e[s]&&(t+=" "+s);return t.substr(1)}var s,n;"undefined"!=typeof e&&e.exports&&(e.exports=o),s=[],n=function(){return o}.apply(t,s),!(void 0!==n&&(e.exports=n))}])})},function(e,t,r){"use strict";var o=r(55)["default"],s=r(61)["default"],n=r(70)["default"],i=r(43)["default"],l=r(18),a=r(73),u=function(e){function t(){i(this,t),o(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return s(t,e),n(t,[{key:"getInputNode",value:function(){return l.findDOMNode(this)}},{key:"onClick",value:function(e){this.getInputNode().focus()}},{key:"onDoubleClick",value:function(e){this.getInputNode().focus()}},{key:"render",value:function(){return l.createElement("select",{style:this.getStyle(),defaultValue:this.props.value,onChange:this.onChange},this.renderOptions())}},{key:"renderOptions",value:function(){var e=[];return this.props.options.forEach(function(t){e.push(l.createElement("option",{key:t,value:t},t))},this),e}}]),t}(a);u.propTypes={options:l.PropTypes.arrayOf(l.PropTypes.string).isRequired},e.exports=u},function(e,t,r){"use strict";var o=r(90),s={ImageFormatter:o};e.exports=s},function(e,t,r){"use strict";var o=r(18),s={},n={},i=o.createClass({displayName:"ImageFormatter",propTypes:{value:o.PropTypes.string.isRequired},getInitialState:function(){return{ready:!1}},componentWillMount:function(){this._load(this.props.value)},componentWillReceiveProps:function(e){e.value!==this.props.value&&(this.setState({value:null}),this._load(e.value))},render:function(){var e=this.state.value?{backgroundImage:"url("+this.state.value+")"}:void 0;return o.createElement("div",{className:"react-grid-image",style:e})},_load:function(e){if(n[e])return void this.setState({value:e});if(s[e])return void s[e].push(this._onLoad);s[e]=[this._onLoad];var t=new Image;t.onload=function(){s[e].forEach(function(t){t(e)}),delete s[e],t.onload=null,e=void 0},t.src=e},_onLoad:function(e){this.isMounted()&&e===this.props.value&&this.setState({value:e})}});e.exports=i},function(e,t,r){"use strict";var o=r(18),s=(r(50),o.createClass({displayName:"Toolbar",propTypes:{onAddRow:o.PropTypes.func,onToggleFilter:o.PropTypes.func.isRequired,enableFilter:o.PropTypes.bool,numberOfRows:o.PropTypes.number.isRequired},onAddRow:function(){null!==this.props.onAddRow&&this.props.onAddRow instanceof Function&&this.props.onAddRow({newRowIndex:this.props.numberOfRows})},getDefaultProps:function(){return{enableAddRow:!0}},renderAddRowButton:function(){return this.props.onAddRow?o.createElement("button",{type:"button",className:"btn",onClick:this.onAddRow},"Add Row"):void 0},renderToggleFilterButton:function(){return this.props.enableFilter?o.createElement("button",{type:"button",className:"btn",onClick:this.props.onToggleFilter},"Filter Rows"):void 0},render:function(){return o.createElement("div",{className:"react-grid-Toolbar"},o.createElement("div",{className:"tools"},this.renderAddRowButton(),this.renderToggleFilterButton()))}}));e.exports=s}])}); |
ajax/libs/flocks.js/0.14.2/flocks.min.js | andersem/cdnjs | if("undefined"==typeof React)var React=require("react");!function(){"use strict";function j(a,b){"string"==typeof a?s(a,["warn","debug","error","log","info","exception","assert"])?console[a]("Flocks2 ["+a+"] "+b.toString()):console.log("Flocks2 [Unknown level] "+b.toString()):void 0===h.flocks_config?console.log("Flocks2 pre-config ["+a.toString()+"] "+b.toString()):h.flocks_config.log_level>=a&&console.log("Flocks2 ["+a.toString()+"] "+b.toString())}function k(a,b){if(b=b||"Argument must be a string","string"!=typeof a)throw b}function l(a){return"[object Array]"===Object.prototype.toString.call(a)}function m(a){return"object"!=typeof a?!1:"[object Array]"===Object.prototype.toString.call(a)?!1:!0}function n(a,b){k(a,"Flocks2 set/2 must take a string for its key"),h[a]=b,j(1,' - Flocks2 setByKey "'+a+'"'),t()}function o(){j(0," - Flocks2 setByPath stub"),t()}function p(){j(0," - Flocks2 setByObject stub"),t()}function q(a,b){if(j(3," - Flocks2 multi-set"),"string"==typeof a)n(a,b);else if(l(a))o(a,b);else{if(!m(a))throw"Flocks2 set/1,2 key must be a string or an array";p(a)}}function r(a,b){if(j(3," + Flocks2 cloning "+(b?b:JSON.stringify(a).substring(0,100))),null===a||"object"!=typeof a)return a;var c=a.constructor();for(var d in a)a.hasOwnProperty(d)&&(c[d]=a[d]);return c}function s(a,b){return!!~b.indexOf(a)}function t(){return j(3," - Flocks2 attempting update"),c=!0,a?b?(j(1," x Flocks2 skipped update: lock count updateBlocks is non-zero"),null):e(h)?(g=h,j(3," - Flocks2 update passed"),React.render(React.createFactory(d)({flocks2context:h}),document.body),c=!1,j(3," - Flocks2 update complete; finalizing"),f(),!0):(j(0," ! Flocks2 rolling back update: handler rejected propset"),h=g,c=!1,null):(j(1," x Flocks2 skipped update: root is not initialized"),null)}function u(b,c){var g=b||{},i=c||{},l=(g.target||document.body,function(){window.alert("whargarbl stub"),t()}),m={get:l,set:q,override:l,clear:l,update:l,lock:l,unlock:l};if(g.log_level=g.log_level||-1,d=g.control,i.flocks_config=g,h=i,j(1,"Flocks2 root creation begins"),!d)throw"Flocks2 fatal error: must provide a control in create/2 FlocksConfig";return g.handler&&(e=g.handler,j(3," - Flocks2 handler assigned")),g.finalizer&&(f=g.finalizer,j(3," - Flocks2 finalizer assigned")),g.preventAutoContext?j(2," - Flocks2 skipping auto-context"):(j(2," - Flocks2 engaging auto-context"),this.fctx=r(h)),j(3,"Flocks2 creation finished; initializing"),a=!0,t(),j(3,"Flocks2 expose updater"),this.fupd=m,this.fset=m.set,j(3,"Flocks2 initialization finished"),m}var a=!1,b=0,c=!1,d=void 0,e=function(){return!0},f=function(){return!0},g={},h={},i={flocks2context:React.PropTypes.object},v={contextTypes:i,childContextTypes:i,componentWillMount:function(){j(1," - Flocks2 component will mount: "+this.constructor.displayName),j(3,"undefined"==typeof this.props.flocks2context?" - No F2 Context Prop":" - F2 Context Prop found"),j(3,"undefined"==typeof this.context.flocks2context?" - No F2 Context":" - F2 Context found"),this.props.flocks2context&&(this.context.flocks2context=this.props.flocks2context),this.fset=function(a,b){q(a,b)},this.fctx=this.context.flocks2context},getChildContext:function(){return this.context}},w={member:v,create:u,clone:r,isArray:l,isNonArrayObject:m,enforceString:k};"undefined"!=typeof module?module.exports=w:window.flocksjs2=w}(); |
app/javascript/mastodon/features/ui/components/follow_requests_nav_link.js | salvadorpla/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { fetchFollowRequests } from 'mastodon/actions/accounts';
import { connect } from 'react-redux';
import { NavLink, withRouter } from 'react-router-dom';
import IconWithBadge from 'mastodon/components/icon_with_badge';
import { me } from 'mastodon/initial_state';
import { List as ImmutableList } from 'immutable';
import { FormattedMessage } from 'react-intl';
const mapStateToProps = state => ({
locked: state.getIn(['accounts', me, 'locked']),
count: state.getIn(['user_lists', 'follow_requests', 'items'], ImmutableList()).size,
});
export default @withRouter
@connect(mapStateToProps)
class FollowRequestsNavLink extends React.Component {
static propTypes = {
dispatch: PropTypes.func.isRequired,
locked: PropTypes.bool,
count: PropTypes.number.isRequired,
};
componentDidMount () {
const { dispatch, locked } = this.props;
if (locked) {
dispatch(fetchFollowRequests());
}
}
render () {
const { locked, count } = this.props;
if (!locked || count === 0) {
return null;
}
return <NavLink className='column-link column-link--transparent' to='/follow_requests'><IconWithBadge className='column-link__icon' id='user-plus' count={count} /><FormattedMessage id='navigation_bar.follow_requests' defaultMessage='Follow requests' /></NavLink>;
}
}
|
src/components/Moment.js | OpenCollective/frontend | import React from 'react';
import moment from 'moment';
const formatDate = value => new Date(value).toISOString();
const Moment = ({ value }) => <span title={moment(value).format('LLLL')}>{moment(formatDate(value)).fromNow()}</span>;
export default Moment;
|
ajax/libs/x-editable/1.5.0/jquery-editable/js/jquery-editable-poshytip.js | samhamilton/cdnjs | /*! X-editable - v1.5.0
* In-place editing with Twitter Bootstrap, jQuery UI or pure jQuery
* http://github.com/vitalets/x-editable
* Copyright (c) 2013 Vitaliy Potapov; Licensed MIT */
/**
Form with single input element, two buttons and two states: normal/loading.
Applied as jQuery method to DIV tag (not to form tag!). This is because form can be in loading state when spinner shown.
Editableform is linked with one of input types, e.g. 'text', 'select' etc.
@class editableform
@uses text
@uses textarea
**/
(function ($) {
"use strict";
var EditableForm = function (div, options) {
this.options = $.extend({}, $.fn.editableform.defaults, options);
this.$div = $(div); //div, containing form. Not form tag. Not editable-element.
if(!this.options.scope) {
this.options.scope = this;
}
//nothing shown after init
};
EditableForm.prototype = {
constructor: EditableForm,
initInput: function() { //called once
//take input from options (as it is created in editable-element)
this.input = this.options.input;
//set initial value
//todo: may be add check: typeof str === 'string' ?
this.value = this.input.str2value(this.options.value);
//prerender: get input.$input
this.input.prerender();
},
initTemplate: function() {
this.$form = $($.fn.editableform.template);
},
initButtons: function() {
var $btn = this.$form.find('.editable-buttons');
$btn.append($.fn.editableform.buttons);
if(this.options.showbuttons === 'bottom') {
$btn.addClass('editable-buttons-bottom');
}
},
/**
Renders editableform
@method render
**/
render: function() {
//init loader
this.$loading = $($.fn.editableform.loading);
this.$div.empty().append(this.$loading);
//init form template and buttons
this.initTemplate();
if(this.options.showbuttons) {
this.initButtons();
} else {
this.$form.find('.editable-buttons').remove();
}
//show loading state
this.showLoading();
//flag showing is form now saving value to server.
//It is needed to wait when closing form.
this.isSaving = false;
/**
Fired when rendering starts
@event rendering
@param {Object} event event object
**/
this.$div.triggerHandler('rendering');
//init input
this.initInput();
//append input to form
this.$form.find('div.editable-input').append(this.input.$tpl);
//append form to container
this.$div.append(this.$form);
//render input
$.when(this.input.render())
.then($.proxy(function () {
//setup input to submit automatically when no buttons shown
if(!this.options.showbuttons) {
this.input.autosubmit();
}
//attach 'cancel' handler
this.$form.find('.editable-cancel').click($.proxy(this.cancel, this));
if(this.input.error) {
this.error(this.input.error);
this.$form.find('.editable-submit').attr('disabled', true);
this.input.$input.attr('disabled', true);
//prevent form from submitting
this.$form.submit(function(e){ e.preventDefault(); });
} else {
this.error(false);
this.input.$input.removeAttr('disabled');
this.$form.find('.editable-submit').removeAttr('disabled');
var value = (this.value === null || this.value === undefined || this.value === '') ? this.options.defaultValue : this.value;
this.input.value2input(value);
//attach submit handler
this.$form.submit($.proxy(this.submit, this));
}
/**
Fired when form is rendered
@event rendered
@param {Object} event event object
**/
this.$div.triggerHandler('rendered');
this.showForm();
//call postrender method to perform actions required visibility of form
if(this.input.postrender) {
this.input.postrender();
}
}, this));
},
cancel: function() {
/**
Fired when form was cancelled by user
@event cancel
@param {Object} event event object
**/
this.$div.triggerHandler('cancel');
},
showLoading: function() {
var w, h;
if(this.$form) {
//set loading size equal to form
w = this.$form.outerWidth();
h = this.$form.outerHeight();
if(w) {
this.$loading.width(w);
}
if(h) {
this.$loading.height(h);
}
this.$form.hide();
} else {
//stretch loading to fill container width
w = this.$loading.parent().width();
if(w) {
this.$loading.width(w);
}
}
this.$loading.show();
},
showForm: function(activate) {
this.$loading.hide();
this.$form.show();
if(activate !== false) {
this.input.activate();
}
/**
Fired when form is shown
@event show
@param {Object} event event object
**/
this.$div.triggerHandler('show');
},
error: function(msg) {
var $group = this.$form.find('.control-group'),
$block = this.$form.find('.editable-error-block'),
lines;
if(msg === false) {
$group.removeClass($.fn.editableform.errorGroupClass);
$block.removeClass($.fn.editableform.errorBlockClass).empty().hide();
} else {
//convert newline to <br> for more pretty error display
if(msg) {
lines = msg.split("\n");
for (var i = 0; i < lines.length; i++) {
lines[i] = $('<div>').text(lines[i]).html();
}
msg = lines.join('<br>');
}
$group.addClass($.fn.editableform.errorGroupClass);
$block.addClass($.fn.editableform.errorBlockClass).html(msg).show();
}
},
submit: function(e) {
e.stopPropagation();
e.preventDefault();
var error,
newValue = this.input.input2value(); //get new value from input
//validation
if (error = this.validate(newValue)) {
this.error(error);
this.showForm();
return;
}
//if value not changed --> trigger 'nochange' event and return
/*jslint eqeq: true*/
if (!this.options.savenochange && this.input.value2str(newValue) == this.input.value2str(this.value)) {
/*jslint eqeq: false*/
/**
Fired when value not changed but form is submitted. Requires savenochange = false.
@event nochange
@param {Object} event event object
**/
this.$div.triggerHandler('nochange');
return;
}
//convert value for submitting to server
var submitValue = this.input.value2submit(newValue);
this.isSaving = true;
//sending data to server
$.when(this.save(submitValue))
.done($.proxy(function(response) {
this.isSaving = false;
//run success callback
var res = typeof this.options.success === 'function' ? this.options.success.call(this.options.scope, response, newValue) : null;
//if success callback returns false --> keep form open and do not activate input
if(res === false) {
this.error(false);
this.showForm(false);
return;
}
//if success callback returns string --> keep form open, show error and activate input
if(typeof res === 'string') {
this.error(res);
this.showForm();
return;
}
//if success callback returns object like {newValue: <something>} --> use that value instead of submitted
//it is usefull if you want to chnage value in url-function
if(res && typeof res === 'object' && res.hasOwnProperty('newValue')) {
newValue = res.newValue;
}
//clear error message
this.error(false);
this.value = newValue;
/**
Fired when form is submitted
@event save
@param {Object} event event object
@param {Object} params additional params
@param {mixed} params.newValue raw new value
@param {mixed} params.submitValue submitted value as string
@param {Object} params.response ajax response
@example
$('#form-div').on('save'), function(e, params){
if(params.newValue === 'username') {...}
});
**/
this.$div.triggerHandler('save', {newValue: newValue, submitValue: submitValue, response: response});
}, this))
.fail($.proxy(function(xhr) {
this.isSaving = false;
var msg;
if(typeof this.options.error === 'function') {
msg = this.options.error.call(this.options.scope, xhr, newValue);
} else {
msg = typeof xhr === 'string' ? xhr : xhr.responseText || xhr.statusText || 'Unknown error!';
}
this.error(msg);
this.showForm();
}, this));
},
save: function(submitValue) {
//try parse composite pk defined as json string in data-pk
this.options.pk = $.fn.editableutils.tryParseJson(this.options.pk, true);
var pk = (typeof this.options.pk === 'function') ? this.options.pk.call(this.options.scope) : this.options.pk,
/*
send on server in following cases:
1. url is function
2. url is string AND (pk defined OR send option = always)
*/
send = !!(typeof this.options.url === 'function' || (this.options.url && ((this.options.send === 'always') || (this.options.send === 'auto' && pk !== null && pk !== undefined)))),
params;
if (send) { //send to server
this.showLoading();
//standard params
params = {
name: this.options.name || '',
value: submitValue,
pk: pk
};
//additional params
if(typeof this.options.params === 'function') {
params = this.options.params.call(this.options.scope, params);
} else {
//try parse json in single quotes (from data-params attribute)
this.options.params = $.fn.editableutils.tryParseJson(this.options.params, true);
$.extend(params, this.options.params);
}
if(typeof this.options.url === 'function') { //user's function
return this.options.url.call(this.options.scope, params);
} else {
//send ajax to server and return deferred object
return $.ajax($.extend({
url : this.options.url,
data : params,
type : 'POST'
}, this.options.ajaxOptions));
}
}
},
validate: function (value) {
if (value === undefined) {
value = this.value;
}
if (typeof this.options.validate === 'function') {
return this.options.validate.call(this.options.scope, value);
}
},
option: function(key, value) {
if(key in this.options) {
this.options[key] = value;
}
if(key === 'value') {
this.setValue(value);
}
//do not pass option to input as it is passed in editable-element
},
setValue: function(value, convertStr) {
if(convertStr) {
this.value = this.input.str2value(value);
} else {
this.value = value;
}
//if form is visible, update input
if(this.$form && this.$form.is(':visible')) {
this.input.value2input(this.value);
}
}
};
/*
Initialize editableform. Applied to jQuery object.
@method $().editableform(options)
@params {Object} options
@example
var $form = $('<div>').editableform({
type: 'text',
name: 'username',
url: '/post',
value: 'vitaliy'
});
//to display form you should call 'render' method
$form.editableform('render');
*/
$.fn.editableform = function (option) {
var args = arguments;
return this.each(function () {
var $this = $(this),
data = $this.data('editableform'),
options = typeof option === 'object' && option;
if (!data) {
$this.data('editableform', (data = new EditableForm(this, options)));
}
if (typeof option === 'string') { //call method
data[option].apply(data, Array.prototype.slice.call(args, 1));
}
});
};
//keep link to constructor to allow inheritance
$.fn.editableform.Constructor = EditableForm;
//defaults
$.fn.editableform.defaults = {
/* see also defaults for input */
/**
Type of input. Can be <code>text|textarea|select|date|checklist</code>
@property type
@type string
@default 'text'
**/
type: 'text',
/**
Url for submit, e.g. <code>'/post'</code>
If function - it will be called instead of ajax. Function should return deferred object to run fail/done callbacks.
@property url
@type string|function
@default null
@example
url: function(params) {
var d = new $.Deferred;
if(params.value === 'abc') {
return d.reject('error message'); //returning error via deferred object
} else {
//async saving data in js model
someModel.asyncSaveMethod({
...,
success: function(){
d.resolve();
}
});
return d.promise();
}
}
**/
url:null,
/**
Additional params for submit. If defined as <code>object</code> - it is **appended** to original ajax data (pk, name and value).
If defined as <code>function</code> - returned object **overwrites** original ajax data.
@example
params: function(params) {
//originally params contain pk, name and value
params.a = 1;
return params;
}
@property params
@type object|function
@default null
**/
params:null,
/**
Name of field. Will be submitted on server. Can be taken from <code>id</code> attribute
@property name
@type string
@default null
**/
name: null,
/**
Primary key of editable object (e.g. record id in database). For composite keys use object, e.g. <code>{id: 1, lang: 'en'}</code>.
Can be calculated dynamically via function.
@property pk
@type string|object|function
@default null
**/
pk: null,
/**
Initial value. If not defined - will be taken from element's content.
For __select__ type should be defined (as it is ID of shown text).
@property value
@type string|object
@default null
**/
value: null,
/**
Value that will be displayed in input if original field value is empty (`null|undefined|''`).
@property defaultValue
@type string|object
@default null
@since 1.4.6
**/
defaultValue: null,
/**
Strategy for sending data on server. Can be `auto|always|never`.
When 'auto' data will be sent on server **only if pk and url defined**, otherwise new value will be stored locally.
@property send
@type string
@default 'auto'
**/
send: 'auto',
/**
Function for client-side validation. If returns string - means validation not passed and string showed as error.
@property validate
@type function
@default null
@example
validate: function(value) {
if($.trim(value) == '') {
return 'This field is required';
}
}
**/
validate: null,
/**
Success callback. Called when value successfully sent on server and **response status = 200**.
Usefull to work with json response. For example, if your backend response can be <code>{success: true}</code>
or <code>{success: false, msg: "server error"}</code> you can check it inside this callback.
If it returns **string** - means error occured and string is shown as error message.
If it returns **object like** <code>{newValue: <something>}</code> - it overwrites value, submitted by user.
Otherwise newValue simply rendered into element.
@property success
@type function
@default null
@example
success: function(response, newValue) {
if(!response.success) return response.msg;
}
**/
success: null,
/**
Error callback. Called when request failed (response status != 200).
Usefull when you want to parse error response and display a custom message.
Must return **string** - the message to be displayed in the error block.
@property error
@type function
@default null
@since 1.4.4
@example
error: function(response, newValue) {
if(response.status === 500) {
return 'Service unavailable. Please try later.';
} else {
return response.responseText;
}
}
**/
error: null,
/**
Additional options for submit ajax request.
List of values: http://api.jquery.com/jQuery.ajax
@property ajaxOptions
@type object
@default null
@since 1.1.1
@example
ajaxOptions: {
type: 'put',
dataType: 'json'
}
**/
ajaxOptions: null,
/**
Where to show buttons: left(true)|bottom|false
Form without buttons is auto-submitted.
@property showbuttons
@type boolean|string
@default true
@since 1.1.1
**/
showbuttons: true,
/**
Scope for callback methods (success, validate).
If <code>null</code> means editableform instance itself.
@property scope
@type DOMElement|object
@default null
@since 1.2.0
@private
**/
scope: null,
/**
Whether to save or cancel value when it was not changed but form was submitted
@property savenochange
@type boolean
@default false
@since 1.2.0
**/
savenochange: false
};
/*
Note: following params could redefined in engine: bootstrap or jqueryui:
Classes 'control-group' and 'editable-error-block' must always present!
*/
$.fn.editableform.template = '<form class="form-inline editableform">'+
'<div class="control-group">' +
'<div><div class="editable-input"></div><div class="editable-buttons"></div></div>'+
'<div class="editable-error-block"></div>' +
'</div>' +
'</form>';
//loading div
$.fn.editableform.loading = '<div class="editableform-loading"></div>';
//buttons
$.fn.editableform.buttons = '<button type="submit" class="editable-submit">ok</button>'+
'<button type="button" class="editable-cancel">cancel</button>';
//error class attached to control-group
$.fn.editableform.errorGroupClass = null;
//error class attached to editable-error-block
$.fn.editableform.errorBlockClass = 'editable-error';
//engine
$.fn.editableform.engine = 'jquery';
}(window.jQuery));
/**
* EditableForm utilites
*/
(function ($) {
"use strict";
//utils
$.fn.editableutils = {
/**
* classic JS inheritance function
*/
inherit: function (Child, Parent) {
var F = function() { };
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.superclass = Parent.prototype;
},
/**
* set caret position in input
* see http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area
*/
setCursorPosition: function(elem, pos) {
if (elem.setSelectionRange) {
elem.setSelectionRange(pos, pos);
} else if (elem.createTextRange) {
var range = elem.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
},
/**
* function to parse JSON in *single* quotes. (jquery automatically parse only double quotes)
* That allows such code as: <a data-source="{'a': 'b', 'c': 'd'}">
* safe = true --> means no exception will be thrown
* for details see http://stackoverflow.com/questions/7410348/how-to-set-json-format-to-html5-data-attributes-in-the-jquery
*/
tryParseJson: function(s, safe) {
if (typeof s === 'string' && s.length && s.match(/^[\{\[].*[\}\]]$/)) {
if (safe) {
try {
/*jslint evil: true*/
s = (new Function('return ' + s))();
/*jslint evil: false*/
} catch (e) {} finally {
return s;
}
} else {
/*jslint evil: true*/
s = (new Function('return ' + s))();
/*jslint evil: false*/
}
}
return s;
},
/**
* slice object by specified keys
*/
sliceObj: function(obj, keys, caseSensitive /* default: false */) {
var key, keyLower, newObj = {};
if (!$.isArray(keys) || !keys.length) {
return newObj;
}
for (var i = 0; i < keys.length; i++) {
key = keys[i];
if (obj.hasOwnProperty(key)) {
newObj[key] = obj[key];
}
if(caseSensitive === true) {
continue;
}
//when getting data-* attributes via $.data() it's converted to lowercase.
//details: http://stackoverflow.com/questions/7602565/using-data-attributes-with-jquery
//workaround is code below.
keyLower = key.toLowerCase();
if (obj.hasOwnProperty(keyLower)) {
newObj[key] = obj[keyLower];
}
}
return newObj;
},
/*
exclude complex objects from $.data() before pass to config
*/
getConfigData: function($element) {
var data = {};
$.each($element.data(), function(k, v) {
if(typeof v !== 'object' || (v && typeof v === 'object' && (v.constructor === Object || v.constructor === Array))) {
data[k] = v;
}
});
return data;
},
/*
returns keys of object
*/
objectKeys: function(o) {
if (Object.keys) {
return Object.keys(o);
} else {
if (o !== Object(o)) {
throw new TypeError('Object.keys called on a non-object');
}
var k=[], p;
for (p in o) {
if (Object.prototype.hasOwnProperty.call(o,p)) {
k.push(p);
}
}
return k;
}
},
/**
method to escape html.
**/
escape: function(str) {
return $('<div>').text(str).html();
},
/*
returns array items from sourceData having value property equal or inArray of 'value'
*/
itemsByValue: function(value, sourceData, valueProp) {
if(!sourceData || value === null) {
return [];
}
if (typeof(valueProp) !== "function") {
var idKey = valueProp || 'value';
valueProp = function (e) { return e[idKey]; };
}
var isValArray = $.isArray(value),
result = [],
that = this;
$.each(sourceData, function(i, o) {
if(o.children) {
result = result.concat(that.itemsByValue(value, o.children, valueProp));
} else {
/*jslint eqeq: true*/
if(isValArray) {
if($.grep(value, function(v){ return v == (o && typeof o === 'object' ? valueProp(o) : o); }).length) {
result.push(o);
}
} else {
var itemValue = (o && (typeof o === 'object')) ? valueProp(o) : o;
if(value == itemValue) {
result.push(o);
}
}
/*jslint eqeq: false*/
}
});
return result;
},
/*
Returns input by options: type, mode.
*/
createInput: function(options) {
var TypeConstructor, typeOptions, input,
type = options.type;
//`date` is some kind of virtual type that is transformed to one of exact types
//depending on mode and core lib
if(type === 'date') {
//inline
if(options.mode === 'inline') {
if($.fn.editabletypes.datefield) {
type = 'datefield';
} else if($.fn.editabletypes.dateuifield) {
type = 'dateuifield';
}
//popup
} else {
if($.fn.editabletypes.date) {
type = 'date';
} else if($.fn.editabletypes.dateui) {
type = 'dateui';
}
}
//if type still `date` and not exist in types, replace with `combodate` that is base input
if(type === 'date' && !$.fn.editabletypes.date) {
type = 'combodate';
}
}
//`datetime` should be datetimefield in 'inline' mode
if(type === 'datetime' && options.mode === 'inline') {
type = 'datetimefield';
}
//change wysihtml5 to textarea for jquery UI and plain versions
if(type === 'wysihtml5' && !$.fn.editabletypes[type]) {
type = 'textarea';
}
//create input of specified type. Input will be used for converting value, not in form
if(typeof $.fn.editabletypes[type] === 'function') {
TypeConstructor = $.fn.editabletypes[type];
typeOptions = this.sliceObj(options, this.objectKeys(TypeConstructor.defaults));
input = new TypeConstructor(typeOptions);
return input;
} else {
$.error('Unknown type: '+ type);
return false;
}
},
//see http://stackoverflow.com/questions/7264899/detect-css-transitions-using-javascript-and-without-modernizr
supportsTransitions: function () {
var b = document.body || document.documentElement,
s = b.style,
p = 'transition',
v = ['Moz', 'Webkit', 'Khtml', 'O', 'ms'];
if(typeof s[p] === 'string') {
return true;
}
// Tests for vendor specific prop
p = p.charAt(0).toUpperCase() + p.substr(1);
for(var i=0; i<v.length; i++) {
if(typeof s[v[i] + p] === 'string') {
return true;
}
}
return false;
}
};
}(window.jQuery));
/**
Attaches stand-alone container with editable-form to HTML element. Element is used only for positioning, value is not stored anywhere.<br>
This method applied internally in <code>$().editable()</code>. You should subscribe on it's events (save / cancel) to get profit of it.<br>
Final realization can be different: bootstrap-popover, jqueryui-tooltip, poshytip, inline-div. It depends on which js file you include.<br>
Applied as jQuery method.
@class editableContainer
@uses editableform
**/
(function ($) {
"use strict";
var Popup = function (element, options) {
this.init(element, options);
};
var Inline = function (element, options) {
this.init(element, options);
};
//methods
Popup.prototype = {
containerName: null, //method to call container on element
containerDataName: null, //object name in element's .data()
innerCss: null, //tbd in child class
containerClass: 'editable-container editable-popup', //css class applied to container element
defaults: {}, //container itself defaults
init: function(element, options) {
this.$element = $(element);
//since 1.4.1 container do not use data-* directly as they already merged into options.
this.options = $.extend({}, $.fn.editableContainer.defaults, options);
this.splitOptions();
//set scope of form callbacks to element
this.formOptions.scope = this.$element[0];
this.initContainer();
//flag to hide container, when saving value will finish
this.delayedHide = false;
//bind 'destroyed' listener to destroy container when element is removed from dom
this.$element.on('destroyed', $.proxy(function(){
this.destroy();
}, this));
//attach document handler to close containers on click / escape
if(!$(document).data('editable-handlers-attached')) {
//close all on escape
$(document).on('keyup.editable', function (e) {
if (e.which === 27) {
$('.editable-open').editableContainer('hide');
//todo: return focus on element
}
});
//close containers when click outside
//(mousedown could be better than click, it closes everything also on drag drop)
$(document).on('click.editable', function(e) {
var $target = $(e.target), i,
exclude_classes = ['.editable-container',
'.ui-datepicker-header',
'.datepicker', //in inline mode datepicker is rendered into body
'.modal-backdrop',
'.bootstrap-wysihtml5-insert-image-modal',
'.bootstrap-wysihtml5-insert-link-modal'
];
//check if element is detached. It occurs when clicking in bootstrap datepicker
if (!$.contains(document.documentElement, e.target)) {
return;
}
//for some reason FF 20 generates extra event (click) in select2 widget with e.target = document
//we need to filter it via construction below. See https://github.com/vitalets/x-editable/issues/199
//Possibly related to http://stackoverflow.com/questions/10119793/why-does-firefox-react-differently-from-webkit-and-ie-to-click-event-on-selec
if($target.is(document)) {
return;
}
//if click inside one of exclude classes --> no nothing
for(i=0; i<exclude_classes.length; i++) {
if($target.is(exclude_classes[i]) || $target.parents(exclude_classes[i]).length) {
return;
}
}
//close all open containers (except one - target)
Popup.prototype.closeOthers(e.target);
});
$(document).data('editable-handlers-attached', true);
}
},
//split options on containerOptions and formOptions
splitOptions: function() {
this.containerOptions = {};
this.formOptions = {};
if(!$.fn[this.containerName]) {
throw new Error(this.containerName + ' not found. Have you included corresponding js file?');
}
//keys defined in container defaults go to container, others go to form
for(var k in this.options) {
if(k in this.defaults) {
this.containerOptions[k] = this.options[k];
} else {
this.formOptions[k] = this.options[k];
}
}
},
/*
Returns jquery object of container
@method tip()
*/
tip: function() {
return this.container() ? this.container().$tip : null;
},
/* returns container object */
container: function() {
var container;
//first, try get it by `containerDataName`
if(this.containerDataName) {
if(container = this.$element.data(this.containerDataName)) {
return container;
}
}
//second, try `containerName`
container = this.$element.data(this.containerName);
return container;
},
/* call native method of underlying container, e.g. this.$element.popover('method') */
call: function() {
this.$element[this.containerName].apply(this.$element, arguments);
},
initContainer: function(){
this.call(this.containerOptions);
},
renderForm: function() {
this.$form
.editableform(this.formOptions)
.on({
save: $.proxy(this.save, this), //click on submit button (value changed)
nochange: $.proxy(function(){ this.hide('nochange'); }, this), //click on submit button (value NOT changed)
cancel: $.proxy(function(){ this.hide('cancel'); }, this), //click on calcel button
show: $.proxy(function() {
if(this.delayedHide) {
this.hide(this.delayedHide.reason);
this.delayedHide = false;
} else {
this.setPosition();
}
}, this), //re-position container every time form is shown (occurs each time after loading state)
rendering: $.proxy(this.setPosition, this), //this allows to place container correctly when loading shown
resize: $.proxy(this.setPosition, this), //this allows to re-position container when form size is changed
rendered: $.proxy(function(){
/**
Fired when container is shown and form is rendered (for select will wait for loading dropdown options).
**Note:** Bootstrap popover has own `shown` event that now cannot be separated from x-editable's one.
The workaround is to check `arguments.length` that is always `2` for x-editable.
@event shown
@param {Object} event event object
@example
$('#username').on('shown', function(e, editable) {
editable.input.$input.val('overwriting value of input..');
});
**/
/*
TODO: added second param mainly to distinguish from bootstrap's shown event. It's a hotfix that will be solved in future versions via namespaced events.
*/
this.$element.triggerHandler('shown', $(this.options.scope).data('editable'));
}, this)
})
.editableform('render');
},
/**
Shows container with form
@method show()
@param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true.
**/
/* Note: poshytip owerwrites this method totally! */
show: function (closeAll) {
this.$element.addClass('editable-open');
if(closeAll !== false) {
//close all open containers (except this)
this.closeOthers(this.$element[0]);
}
//show container itself
this.innerShow();
this.tip().addClass(this.containerClass);
/*
Currently, form is re-rendered on every show.
The main reason is that we dont know, what will container do with content when closed:
remove(), detach() or just hide() - it depends on container.
Detaching form itself before hide and re-insert before show is good solution,
but visually it looks ugly --> container changes size before hide.
*/
//if form already exist - delete previous data
if(this.$form) {
//todo: destroy prev data!
//this.$form.destroy();
}
this.$form = $('<div>');
//insert form into container body
if(this.tip().is(this.innerCss)) {
//for inline container
this.tip().append(this.$form);
} else {
this.tip().find(this.innerCss).append(this.$form);
}
//render form
this.renderForm();
},
/**
Hides container with form
@method hide()
@param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|undefined (=manual)</code>
**/
hide: function(reason) {
if(!this.tip() || !this.tip().is(':visible') || !this.$element.hasClass('editable-open')) {
return;
}
//if form is saving value, schedule hide
if(this.$form.data('editableform').isSaving) {
this.delayedHide = {reason: reason};
return;
} else {
this.delayedHide = false;
}
this.$element.removeClass('editable-open');
this.innerHide();
/**
Fired when container was hidden. It occurs on both save or cancel.
**Note:** Bootstrap popover has own `hidden` event that now cannot be separated from x-editable's one.
The workaround is to check `arguments.length` that is always `2` for x-editable.
@event hidden
@param {object} event event object
@param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|manual</code>
@example
$('#username').on('hidden', function(e, reason) {
if(reason === 'save' || reason === 'cancel') {
//auto-open next editable
$(this).closest('tr').next().find('.editable').editable('show');
}
});
**/
this.$element.triggerHandler('hidden', reason || 'manual');
},
/* internal show method. To be overwritten in child classes */
innerShow: function () {
},
/* internal hide method. To be overwritten in child classes */
innerHide: function () {
},
/**
Toggles container visibility (show / hide)
@method toggle()
@param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true.
**/
toggle: function(closeAll) {
if(this.container() && this.tip() && this.tip().is(':visible')) {
this.hide();
} else {
this.show(closeAll);
}
},
/*
Updates the position of container when content changed.
@method setPosition()
*/
setPosition: function() {
//tbd in child class
},
save: function(e, params) {
/**
Fired when new value was submitted. You can use <code>$(this).data('editableContainer')</code> inside handler to access to editableContainer instance
@event save
@param {Object} event event object
@param {Object} params additional params
@param {mixed} params.newValue submitted value
@param {Object} params.response ajax response
@example
$('#username').on('save', function(e, params) {
//assuming server response: '{success: true}'
var pk = $(this).data('editableContainer').options.pk;
if(params.response && params.response.success) {
alert('value: ' + params.newValue + ' with pk: ' + pk + ' saved!');
} else {
alert('error!');
}
});
**/
this.$element.triggerHandler('save', params);
//hide must be after trigger, as saving value may require methods of plugin, applied to input
this.hide('save');
},
/**
Sets new option
@method option(key, value)
@param {string} key
@param {mixed} value
**/
option: function(key, value) {
this.options[key] = value;
if(key in this.containerOptions) {
this.containerOptions[key] = value;
this.setContainerOption(key, value);
} else {
this.formOptions[key] = value;
if(this.$form) {
this.$form.editableform('option', key, value);
}
}
},
setContainerOption: function(key, value) {
this.call('option', key, value);
},
/**
Destroys the container instance
@method destroy()
**/
destroy: function() {
this.hide();
this.innerDestroy();
this.$element.off('destroyed');
this.$element.removeData('editableContainer');
},
/* to be overwritten in child classes */
innerDestroy: function() {
},
/*
Closes other containers except one related to passed element.
Other containers can be cancelled or submitted (depends on onblur option)
*/
closeOthers: function(element) {
$('.editable-open').each(function(i, el){
//do nothing with passed element and it's children
if(el === element || $(el).find(element).length) {
return;
}
//otherwise cancel or submit all open containers
var $el = $(el),
ec = $el.data('editableContainer');
if(!ec) {
return;
}
if(ec.options.onblur === 'cancel') {
$el.data('editableContainer').hide('onblur');
} else if(ec.options.onblur === 'submit') {
$el.data('editableContainer').tip().find('form').submit();
}
});
},
/**
Activates input of visible container (e.g. set focus)
@method activate()
**/
activate: function() {
if(this.tip && this.tip().is(':visible') && this.$form) {
this.$form.data('editableform').input.activate();
}
}
};
/**
jQuery method to initialize editableContainer.
@method $().editableContainer(options)
@params {Object} options
@example
$('#edit').editableContainer({
type: 'text',
url: '/post',
pk: 1,
value: 'hello'
});
**/
$.fn.editableContainer = function (option) {
var args = arguments;
return this.each(function () {
var $this = $(this),
dataKey = 'editableContainer',
data = $this.data(dataKey),
options = typeof option === 'object' && option,
Constructor = (options.mode === 'inline') ? Inline : Popup;
if (!data) {
$this.data(dataKey, (data = new Constructor(this, options)));
}
if (typeof option === 'string') { //call method
data[option].apply(data, Array.prototype.slice.call(args, 1));
}
});
};
//store constructors
$.fn.editableContainer.Popup = Popup;
$.fn.editableContainer.Inline = Inline;
//defaults
$.fn.editableContainer.defaults = {
/**
Initial value of form input
@property value
@type mixed
@default null
@private
**/
value: null,
/**
Placement of container relative to element. Can be <code>top|right|bottom|left</code>. Not used for inline container.
@property placement
@type string
@default 'top'
**/
placement: 'top',
/**
Whether to hide container on save/cancel.
@property autohide
@type boolean
@default true
@private
**/
autohide: true,
/**
Action when user clicks outside the container. Can be <code>cancel|submit|ignore</code>.
Setting <code>ignore</code> allows to have several containers open.
@property onblur
@type string
@default 'cancel'
@since 1.1.1
**/
onblur: 'cancel',
/**
Animation speed (inline mode only)
@property anim
@type string
@default false
**/
anim: false,
/**
Mode of editable, can be `popup` or `inline`
@property mode
@type string
@default 'popup'
@since 1.4.0
**/
mode: 'popup'
};
/*
* workaround to have 'destroyed' event to destroy popover when element is destroyed
* see http://stackoverflow.com/questions/2200494/jquery-trigger-event-when-an-element-is-removed-from-the-dom
*/
jQuery.event.special.destroyed = {
remove: function(o) {
if (o.handler) {
o.handler();
}
}
};
}(window.jQuery));
/**
* Editable Inline
* ---------------------
*/
(function ($) {
"use strict";
//copy prototype from EditableContainer
//extend methods
$.extend($.fn.editableContainer.Inline.prototype, $.fn.editableContainer.Popup.prototype, {
containerName: 'editableform',
innerCss: '.editable-inline',
containerClass: 'editable-container editable-inline', //css class applied to container element
initContainer: function(){
//container is <span> element
this.$tip = $('<span></span>');
//convert anim to miliseconds (int)
if(!this.options.anim) {
this.options.anim = 0;
}
},
splitOptions: function() {
//all options are passed to form
this.containerOptions = {};
this.formOptions = this.options;
},
tip: function() {
return this.$tip;
},
innerShow: function () {
this.$element.hide();
this.tip().insertAfter(this.$element).show();
},
innerHide: function () {
this.$tip.hide(this.options.anim, $.proxy(function() {
this.$element.show();
this.innerDestroy();
}, this));
},
innerDestroy: function() {
if(this.tip()) {
this.tip().empty().remove();
}
}
});
}(window.jQuery));
/**
Makes editable any HTML element on the page. Applied as jQuery method.
@class editable
@uses editableContainer
**/
(function ($) {
"use strict";
var Editable = function (element, options) {
this.$element = $(element);
//data-* has more priority over js options: because dynamically created elements may change data-*
this.options = $.extend({}, $.fn.editable.defaults, options, $.fn.editableutils.getConfigData(this.$element));
if(this.options.selector) {
this.initLive();
} else {
this.init();
}
//check for transition support
if(this.options.highlight && !$.fn.editableutils.supportsTransitions()) {
this.options.highlight = false;
}
};
Editable.prototype = {
constructor: Editable,
init: function () {
var isValueByText = false,
doAutotext, finalize;
//name
this.options.name = this.options.name || this.$element.attr('id');
//create input of specified type. Input needed already here to convert value for initial display (e.g. show text by id for select)
//also we set scope option to have access to element inside input specific callbacks (e. g. source as function)
this.options.scope = this.$element[0];
this.input = $.fn.editableutils.createInput(this.options);
if(!this.input) {
return;
}
//set value from settings or by element's text
if (this.options.value === undefined || this.options.value === null) {
this.value = this.input.html2value($.trim(this.$element.html()));
isValueByText = true;
} else {
/*
value can be string when received from 'data-value' attribute
for complext objects value can be set as json string in data-value attribute,
e.g. data-value="{city: 'Moscow', street: 'Lenina'}"
*/
this.options.value = $.fn.editableutils.tryParseJson(this.options.value, true);
if(typeof this.options.value === 'string') {
this.value = this.input.str2value(this.options.value);
} else {
this.value = this.options.value;
}
}
//add 'editable' class to every editable element
this.$element.addClass('editable');
//specifically for "textarea" add class .editable-pre-wrapped to keep linebreaks
if(this.input.type === 'textarea') {
this.$element.addClass('editable-pre-wrapped');
}
//attach handler activating editable. In disabled mode it just prevent default action (useful for links)
if(this.options.toggle !== 'manual') {
this.$element.addClass('editable-click');
this.$element.on(this.options.toggle + '.editable', $.proxy(function(e){
//prevent following link if editable enabled
if(!this.options.disabled) {
e.preventDefault();
}
//stop propagation not required because in document click handler it checks event target
//e.stopPropagation();
if(this.options.toggle === 'mouseenter') {
//for hover only show container
this.show();
} else {
//when toggle='click' we should not close all other containers as they will be closed automatically in document click listener
var closeAll = (this.options.toggle !== 'click');
this.toggle(closeAll);
}
}, this));
} else {
this.$element.attr('tabindex', -1); //do not stop focus on element when toggled manually
}
//if display is function it's far more convinient to have autotext = always to render correctly on init
//see https://github.com/vitalets/x-editable-yii/issues/34
if(typeof this.options.display === 'function') {
this.options.autotext = 'always';
}
//check conditions for autotext:
switch(this.options.autotext) {
case 'always':
doAutotext = true;
break;
case 'auto':
//if element text is empty and value is defined and value not generated by text --> run autotext
doAutotext = !$.trim(this.$element.text()).length && this.value !== null && this.value !== undefined && !isValueByText;
break;
default:
doAutotext = false;
}
//depending on autotext run render() or just finilize init
$.when(doAutotext ? this.render() : true).then($.proxy(function() {
if(this.options.disabled) {
this.disable();
} else {
this.enable();
}
/**
Fired when element was initialized by `$().editable()` method.
Please note that you should setup `init` handler **before** applying `editable`.
@event init
@param {Object} event event object
@param {Object} editable editable instance (as here it cannot accessed via data('editable'))
@since 1.2.0
@example
$('#username').on('init', function(e, editable) {
alert('initialized ' + editable.options.name);
});
$('#username').editable();
**/
this.$element.triggerHandler('init', this);
}, this));
},
/*
Initializes parent element for live editables
*/
initLive: function() {
//store selector
var selector = this.options.selector;
//modify options for child elements
this.options.selector = false;
this.options.autotext = 'never';
//listen toggle events
this.$element.on(this.options.toggle + '.editable', selector, $.proxy(function(e){
var $target = $(e.target);
if(!$target.data('editable')) {
//if delegated element initially empty, we need to clear it's text (that was manually set to `empty` by user)
//see https://github.com/vitalets/x-editable/issues/137
if($target.hasClass(this.options.emptyclass)) {
$target.empty();
}
$target.editable(this.options).trigger(e);
}
}, this));
},
/*
Renders value into element's text.
Can call custom display method from options.
Can return deferred object.
@method render()
@param {mixed} response server response (if exist) to pass into display function
*/
render: function(response) {
//do not display anything
if(this.options.display === false) {
return;
}
//if input has `value2htmlFinal` method, we pass callback in third param to be called when source is loaded
if(this.input.value2htmlFinal) {
return this.input.value2html(this.value, this.$element[0], this.options.display, response);
//if display method defined --> use it
} else if(typeof this.options.display === 'function') {
return this.options.display.call(this.$element[0], this.value, response);
//else use input's original value2html() method
} else {
return this.input.value2html(this.value, this.$element[0]);
}
},
/**
Enables editable
@method enable()
**/
enable: function() {
this.options.disabled = false;
this.$element.removeClass('editable-disabled');
this.handleEmpty(this.isEmpty);
if(this.options.toggle !== 'manual') {
if(this.$element.attr('tabindex') === '-1') {
this.$element.removeAttr('tabindex');
}
}
},
/**
Disables editable
@method disable()
**/
disable: function() {
this.options.disabled = true;
this.hide();
this.$element.addClass('editable-disabled');
this.handleEmpty(this.isEmpty);
//do not stop focus on this element
this.$element.attr('tabindex', -1);
},
/**
Toggles enabled / disabled state of editable element
@method toggleDisabled()
**/
toggleDisabled: function() {
if(this.options.disabled) {
this.enable();
} else {
this.disable();
}
},
/**
Sets new option
@method option(key, value)
@param {string|object} key option name or object with several options
@param {mixed} value option new value
@example
$('.editable').editable('option', 'pk', 2);
**/
option: function(key, value) {
//set option(s) by object
if(key && typeof key === 'object') {
$.each(key, $.proxy(function(k, v){
this.option($.trim(k), v);
}, this));
return;
}
//set option by string
this.options[key] = value;
//disabled
if(key === 'disabled') {
return value ? this.disable() : this.enable();
}
//value
if(key === 'value') {
this.setValue(value);
}
//transfer new option to container!
if(this.container) {
this.container.option(key, value);
}
//pass option to input directly (as it points to the same in form)
if(this.input.option) {
this.input.option(key, value);
}
},
/*
* set emptytext if element is empty
*/
handleEmpty: function (isEmpty) {
//do not handle empty if we do not display anything
if(this.options.display === false) {
return;
}
/*
isEmpty may be set directly as param of method.
It is required when we enable/disable field and can't rely on content
as node content is text: "Empty" that is not empty %)
*/
if(isEmpty !== undefined) {
this.isEmpty = isEmpty;
} else {
//detect empty
//for some inputs we need more smart check
//e.g. wysihtml5 may have <br>, <p></p>, <img>
if(typeof(this.input.isEmpty) === 'function') {
this.isEmpty = this.input.isEmpty(this.$element);
} else {
this.isEmpty = $.trim(this.$element.html()) === '';
}
}
//emptytext shown only for enabled
if(!this.options.disabled) {
if (this.isEmpty) {
this.$element.html(this.options.emptytext);
if(this.options.emptyclass) {
this.$element.addClass(this.options.emptyclass);
}
} else if(this.options.emptyclass) {
this.$element.removeClass(this.options.emptyclass);
}
} else {
//below required if element disable property was changed
if(this.isEmpty) {
this.$element.empty();
if(this.options.emptyclass) {
this.$element.removeClass(this.options.emptyclass);
}
}
}
},
/**
Shows container with form
@method show()
@param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true.
**/
show: function (closeAll) {
if(this.options.disabled) {
return;
}
//init editableContainer: popover, tooltip, inline, etc..
if(!this.container) {
var containerOptions = $.extend({}, this.options, {
value: this.value,
input: this.input //pass input to form (as it is already created)
});
this.$element.editableContainer(containerOptions);
//listen `save` event
this.$element.on("save.internal", $.proxy(this.save, this));
this.container = this.$element.data('editableContainer');
} else if(this.container.tip().is(':visible')) {
return;
}
//show container
this.container.show(closeAll);
},
/**
Hides container with form
@method hide()
**/
hide: function () {
if(this.container) {
this.container.hide();
}
},
/**
Toggles container visibility (show / hide)
@method toggle()
@param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true.
**/
toggle: function(closeAll) {
if(this.container && this.container.tip().is(':visible')) {
this.hide();
} else {
this.show(closeAll);
}
},
/*
* called when form was submitted
*/
save: function(e, params) {
//mark element with unsaved class if needed
if(this.options.unsavedclass) {
/*
Add unsaved css to element if:
- url is not user's function
- value was not sent to server
- params.response === undefined, that means data was not sent
- value changed
*/
var sent = false;
sent = sent || typeof this.options.url === 'function';
sent = sent || this.options.display === false;
sent = sent || params.response !== undefined;
sent = sent || (this.options.savenochange && this.input.value2str(this.value) !== this.input.value2str(params.newValue));
if(sent) {
this.$element.removeClass(this.options.unsavedclass);
} else {
this.$element.addClass(this.options.unsavedclass);
}
}
//highlight when saving
if(this.options.highlight) {
var $e = this.$element,
bgColor = $e.css('background-color');
$e.css('background-color', this.options.highlight);
setTimeout(function(){
if(bgColor === 'transparent') {
bgColor = '';
}
$e.css('background-color', bgColor);
$e.addClass('editable-bg-transition');
setTimeout(function(){
$e.removeClass('editable-bg-transition');
}, 1700);
}, 10);
}
//set new value
this.setValue(params.newValue, false, params.response);
/**
Fired when new value was submitted. You can use <code>$(this).data('editable')</code> to access to editable instance
@event save
@param {Object} event event object
@param {Object} params additional params
@param {mixed} params.newValue submitted value
@param {Object} params.response ajax response
@example
$('#username').on('save', function(e, params) {
alert('Saved value: ' + params.newValue);
});
**/
//event itself is triggered by editableContainer. Description here is only for documentation
},
validate: function () {
if (typeof this.options.validate === 'function') {
return this.options.validate.call(this, this.value);
}
},
/**
Sets new value of editable
@method setValue(value, convertStr)
@param {mixed} value new value
@param {boolean} convertStr whether to convert value from string to internal format
**/
setValue: function(value, convertStr, response) {
if(convertStr) {
this.value = this.input.str2value(value);
} else {
this.value = value;
}
if(this.container) {
this.container.option('value', this.value);
}
$.when(this.render(response))
.then($.proxy(function() {
this.handleEmpty();
}, this));
},
/**
Activates input of visible container (e.g. set focus)
@method activate()
**/
activate: function() {
if(this.container) {
this.container.activate();
}
},
/**
Removes editable feature from element
@method destroy()
**/
destroy: function() {
this.disable();
if(this.container) {
this.container.destroy();
}
this.input.destroy();
if(this.options.toggle !== 'manual') {
this.$element.removeClass('editable-click');
this.$element.off(this.options.toggle + '.editable');
}
this.$element.off("save.internal");
this.$element.removeClass('editable editable-open editable-disabled');
this.$element.removeData('editable');
}
};
/* EDITABLE PLUGIN DEFINITION
* ======================= */
/**
jQuery method to initialize editable element.
@method $().editable(options)
@params {Object} options
@example
$('#username').editable({
type: 'text',
url: '/post',
pk: 1
});
**/
$.fn.editable = function (option) {
//special API methods returning non-jquery object
var result = {}, args = arguments, datakey = 'editable';
switch (option) {
/**
Runs client-side validation for all matched editables
@method validate()
@returns {Object} validation errors map
@example
$('#username, #fullname').editable('validate');
// possible result:
{
username: "username is required",
fullname: "fullname should be minimum 3 letters length"
}
**/
case 'validate':
this.each(function () {
var $this = $(this), data = $this.data(datakey), error;
if (data && (error = data.validate())) {
result[data.options.name] = error;
}
});
return result;
/**
Returns current values of editable elements.
Note that it returns an **object** with name-value pairs, not a value itself. It allows to get data from several elements.
If value of some editable is `null` or `undefined` it is excluded from result object.
When param `isSingle` is set to **true** - it is supposed you have single element and will return value of editable instead of object.
@method getValue()
@param {bool} isSingle whether to return just value of single element
@returns {Object} object of element names and values
@example
$('#username, #fullname').editable('getValue');
//result:
{
username: "superuser",
fullname: "John"
}
//isSingle = true
$('#username').editable('getValue', true);
//result "superuser"
**/
case 'getValue':
if(arguments.length === 2 && arguments[1] === true) { //isSingle = true
result = this.eq(0).data(datakey).value;
} else {
this.each(function () {
var $this = $(this), data = $this.data(datakey);
if (data && data.value !== undefined && data.value !== null) {
result[data.options.name] = data.input.value2submit(data.value);
}
});
}
return result;
/**
This method collects values from several editable elements and submit them all to server.
Internally it runs client-side validation for all fields and submits only in case of success.
See <a href="#newrecord">creating new records</a> for details.
@method submit(options)
@param {object} options
@param {object} options.url url to submit data
@param {object} options.data additional data to submit
@param {object} options.ajaxOptions additional ajax options
@param {function} options.error(obj) error handler
@param {function} options.success(obj,config) success handler
@returns {Object} jQuery object
**/
case 'submit': //collects value, validate and submit to server for creating new record
var config = arguments[1] || {},
$elems = this,
errors = this.editable('validate'),
values;
if($.isEmptyObject(errors)) {
values = this.editable('getValue');
if(config.data) {
$.extend(values, config.data);
}
$.ajax($.extend({
url: config.url,
data: values,
type: 'POST'
}, config.ajaxOptions))
.success(function(response) {
//successful response 200 OK
if(typeof config.success === 'function') {
config.success.call($elems, response, config);
}
})
.error(function(){ //ajax error
if(typeof config.error === 'function') {
config.error.apply($elems, arguments);
}
});
} else { //client-side validation error
if(typeof config.error === 'function') {
config.error.call($elems, errors);
}
}
return this;
}
//return jquery object
return this.each(function () {
var $this = $(this),
data = $this.data(datakey),
options = typeof option === 'object' && option;
//for delegated targets do not store `editable` object for element
//it's allows several different selectors.
//see: https://github.com/vitalets/x-editable/issues/312
if(options && options.selector) {
data = new Editable(this, options);
return;
}
if (!data) {
$this.data(datakey, (data = new Editable(this, options)));
}
if (typeof option === 'string') { //call method
data[option].apply(data, Array.prototype.slice.call(args, 1));
}
});
};
$.fn.editable.defaults = {
/**
Type of input. Can be <code>text|textarea|select|date|checklist</code> and more
@property type
@type string
@default 'text'
**/
type: 'text',
/**
Sets disabled state of editable
@property disabled
@type boolean
@default false
**/
disabled: false,
/**
How to toggle editable. Can be <code>click|dblclick|mouseenter|manual</code>.
When set to <code>manual</code> you should manually call <code>show/hide</code> methods of editable.
**Note**: if you call <code>show</code> or <code>toggle</code> inside **click** handler of some DOM element,
you need to apply <code>e.stopPropagation()</code> because containers are being closed on any click on document.
@example
$('#edit-button').click(function(e) {
e.stopPropagation();
$('#username').editable('toggle');
});
@property toggle
@type string
@default 'click'
**/
toggle: 'click',
/**
Text shown when element is empty.
@property emptytext
@type string
@default 'Empty'
**/
emptytext: 'Empty',
/**
Allows to automatically set element's text based on it's value. Can be <code>auto|always|never</code>. Useful for select and date.
For example, if dropdown list is <code>{1: 'a', 2: 'b'}</code> and element's value set to <code>1</code>, it's html will be automatically set to <code>'a'</code>.
<code>auto</code> - text will be automatically set only if element is empty.
<code>always|never</code> - always(never) try to set element's text.
@property autotext
@type string
@default 'auto'
**/
autotext: 'auto',
/**
Initial value of input. If not set, taken from element's text.
Note, that if element's text is empty - text is automatically generated from value and can be customized (see `autotext` option).
For example, to display currency sign:
@example
<a id="price" data-type="text" data-value="100"></a>
<script>
$('#price').editable({
...
display: function(value) {
$(this).text(value + '$');
}
})
</script>
@property value
@type mixed
@default element's text
**/
value: null,
/**
Callback to perform custom displaying of value in element's text.
If `null`, default input's display used.
If `false`, no displaying methods will be called, element's text will never change.
Runs under element's scope.
_**Parameters:**_
* `value` current value to be displayed
* `response` server response (if display called after ajax submit), since 1.4.0
For _inputs with source_ (select, checklist) parameters are different:
* `value` current value to be displayed
* `sourceData` array of items for current input (e.g. dropdown items)
* `response` server response (if display called after ajax submit), since 1.4.0
To get currently selected items use `$.fn.editableutils.itemsByValue(value, sourceData)`.
@property display
@type function|boolean
@default null
@since 1.2.0
@example
display: function(value, sourceData) {
//display checklist as comma-separated values
var html = [],
checked = $.fn.editableutils.itemsByValue(value, sourceData);
if(checked.length) {
$.each(checked, function(i, v) { html.push($.fn.editableutils.escape(v.text)); });
$(this).html(html.join(', '));
} else {
$(this).empty();
}
}
**/
display: null,
/**
Css class applied when editable text is empty.
@property emptyclass
@type string
@since 1.4.1
@default editable-empty
**/
emptyclass: 'editable-empty',
/**
Css class applied when value was stored but not sent to server (`pk` is empty or `send = 'never'`).
You may set it to `null` if you work with editables locally and submit them together.
@property unsavedclass
@type string
@since 1.4.1
@default editable-unsaved
**/
unsavedclass: 'editable-unsaved',
/**
If selector is provided, editable will be delegated to the specified targets.
Usefull for dynamically generated DOM elements.
**Please note**, that delegated targets can't be initialized with `emptytext` and `autotext` options,
as they actually become editable only after first click.
You should manually set class `editable-click` to these elements.
Also, if element originally empty you should add class `editable-empty`, set `data-value=""` and write emptytext into element:
@property selector
@type string
@since 1.4.1
@default null
@example
<div id="user">
<!-- empty -->
<a href="#" data-name="username" data-type="text" class="editable-click editable-empty" data-value="" title="Username">Empty</a>
<!-- non-empty -->
<a href="#" data-name="group" data-type="select" data-source="/groups" data-value="1" class="editable-click" title="Group">Operator</a>
</div>
<script>
$('#user').editable({
selector: 'a',
url: '/post',
pk: 1
});
</script>
**/
selector: null,
/**
Color used to highlight element after update. Implemented via CSS3 transition, works in modern browsers.
@property highlight
@type string|boolean
@since 1.4.5
@default #FFFF80
**/
highlight: '#FFFF80'
};
}(window.jQuery));
/**
AbstractInput - base class for all editable inputs.
It defines interface to be implemented by any input type.
To create your own input you can inherit from this class.
@class abstractinput
**/
(function ($) {
"use strict";
//types
$.fn.editabletypes = {};
var AbstractInput = function () { };
AbstractInput.prototype = {
/**
Initializes input
@method init()
**/
init: function(type, options, defaults) {
this.type = type;
this.options = $.extend({}, defaults, options);
},
/*
this method called before render to init $tpl that is inserted in DOM
*/
prerender: function() {
this.$tpl = $(this.options.tpl); //whole tpl as jquery object
this.$input = this.$tpl; //control itself, can be changed in render method
this.$clear = null; //clear button
this.error = null; //error message, if input cannot be rendered
},
/**
Renders input from tpl. Can return jQuery deferred object.
Can be overwritten in child objects
@method render()
**/
render: function() {
},
/**
Sets element's html by value.
@method value2html(value, element)
@param {mixed} value
@param {DOMElement} element
**/
value2html: function(value, element) {
$(element)[this.options.escape ? 'text' : 'html']($.trim(value));
},
/**
Converts element's html to value
@method html2value(html)
@param {string} html
@returns {mixed}
**/
html2value: function(html) {
return $('<div>').html(html).text();
},
/**
Converts value to string (for internal compare). For submitting to server used value2submit().
@method value2str(value)
@param {mixed} value
@returns {string}
**/
value2str: function(value) {
return value;
},
/**
Converts string received from server into value. Usually from `data-value` attribute.
@method str2value(str)
@param {string} str
@returns {mixed}
**/
str2value: function(str) {
return str;
},
/**
Converts value for submitting to server. Result can be string or object.
@method value2submit(value)
@param {mixed} value
@returns {mixed}
**/
value2submit: function(value) {
return value;
},
/**
Sets value of input.
@method value2input(value)
@param {mixed} value
**/
value2input: function(value) {
this.$input.val(value);
},
/**
Returns value of input. Value can be object (e.g. datepicker)
@method input2value()
**/
input2value: function() {
return this.$input.val();
},
/**
Activates input. For text it sets focus.
@method activate()
**/
activate: function() {
if(this.$input.is(':visible')) {
this.$input.focus();
}
},
/**
Creates input.
@method clear()
**/
clear: function() {
this.$input.val(null);
},
/**
method to escape html.
**/
escape: function(str) {
return $('<div>').text(str).html();
},
/**
attach handler to automatically submit form when value changed (useful when buttons not shown)
**/
autosubmit: function() {
},
/**
Additional actions when destroying element
**/
destroy: function() {
},
// -------- helper functions --------
setClass: function() {
if(this.options.inputclass) {
this.$input.addClass(this.options.inputclass);
}
},
setAttr: function(attr) {
if (this.options[attr] !== undefined && this.options[attr] !== null) {
this.$input.attr(attr, this.options[attr]);
}
},
option: function(key, value) {
this.options[key] = value;
}
};
AbstractInput.defaults = {
/**
HTML template of input. Normally you should not change it.
@property tpl
@type string
@default ''
**/
tpl: '',
/**
CSS class automatically applied to input
@property inputclass
@type string
@default null
**/
inputclass: null,
/**
If `true` - html will be escaped in content of element via $.text() method.
If `false` - html will not be escaped, $.html() used.
When you use own `display` function, this option obviosly has no effect.
@property escape
@type boolean
@since 1.5.0
@default true
**/
escape: true,
//scope for external methods (e.g. source defined as function)
//for internal use only
scope: null,
//need to re-declare showbuttons here to get it's value from common config (passed only options existing in defaults)
showbuttons: true
};
$.extend($.fn.editabletypes, {abstractinput: AbstractInput});
}(window.jQuery));
/**
List - abstract class for inputs that have source option loaded from js array or via ajax
@class list
@extends abstractinput
**/
(function ($) {
"use strict";
var List = function (options) {
};
$.fn.editableutils.inherit(List, $.fn.editabletypes.abstractinput);
$.extend(List.prototype, {
render: function () {
var deferred = $.Deferred();
this.error = null;
this.onSourceReady(function () {
this.renderList();
deferred.resolve();
}, function () {
this.error = this.options.sourceError;
deferred.resolve();
});
return deferred.promise();
},
html2value: function (html) {
return null; //can't set value by text
},
value2html: function (value, element, display, response) {
var deferred = $.Deferred(),
success = function () {
if(typeof display === 'function') {
//custom display method
display.call(element, value, this.sourceData, response);
} else {
this.value2htmlFinal(value, element);
}
deferred.resolve();
};
//for null value just call success without loading source
if(value === null) {
success.call(this);
} else {
this.onSourceReady(success, function () { deferred.resolve(); });
}
return deferred.promise();
},
// ------------- additional functions ------------
onSourceReady: function (success, error) {
//run source if it function
var source;
if ($.isFunction(this.options.source)) {
source = this.options.source.call(this.options.scope);
this.sourceData = null;
//note: if function returns the same source as URL - sourceData will be taken from cahce and no extra request performed
} else {
source = this.options.source;
}
//if allready loaded just call success
if(this.options.sourceCache && $.isArray(this.sourceData)) {
success.call(this);
return;
}
//try parse json in single quotes (for double quotes jquery does automatically)
try {
source = $.fn.editableutils.tryParseJson(source, false);
} catch (e) {
error.call(this);
return;
}
//loading from url
if (typeof source === 'string') {
//try to get sourceData from cache
if(this.options.sourceCache) {
var cacheID = source,
cache;
if (!$(document).data(cacheID)) {
$(document).data(cacheID, {});
}
cache = $(document).data(cacheID);
//check for cached data
if (cache.loading === false && cache.sourceData) { //take source from cache
this.sourceData = cache.sourceData;
this.doPrepend();
success.call(this);
return;
} else if (cache.loading === true) { //cache is loading, put callback in stack to be called later
cache.callbacks.push($.proxy(function () {
this.sourceData = cache.sourceData;
this.doPrepend();
success.call(this);
}, this));
//also collecting error callbacks
cache.err_callbacks.push($.proxy(error, this));
return;
} else { //no cache yet, activate it
cache.loading = true;
cache.callbacks = [];
cache.err_callbacks = [];
}
}
//ajaxOptions for source. Can be overwritten bt options.sourceOptions
var ajaxOptions = $.extend({
url: source,
type: 'get',
cache: false,
dataType: 'json',
success: $.proxy(function (data) {
if(cache) {
cache.loading = false;
}
this.sourceData = this.makeArray(data);
if($.isArray(this.sourceData)) {
if(cache) {
//store result in cache
cache.sourceData = this.sourceData;
//run success callbacks for other fields waiting for this source
$.each(cache.callbacks, function () { this.call(); });
}
this.doPrepend();
success.call(this);
} else {
error.call(this);
if(cache) {
//run error callbacks for other fields waiting for this source
$.each(cache.err_callbacks, function () { this.call(); });
}
}
}, this),
error: $.proxy(function () {
error.call(this);
if(cache) {
cache.loading = false;
//run error callbacks for other fields
$.each(cache.err_callbacks, function () { this.call(); });
}
}, this)
}, this.options.sourceOptions);
//loading sourceData from server
$.ajax(ajaxOptions);
} else { //options as json/array
this.sourceData = this.makeArray(source);
if($.isArray(this.sourceData)) {
this.doPrepend();
success.call(this);
} else {
error.call(this);
}
}
},
doPrepend: function () {
if(this.options.prepend === null || this.options.prepend === undefined) {
return;
}
if(!$.isArray(this.prependData)) {
//run prepend if it is function (once)
if ($.isFunction(this.options.prepend)) {
this.options.prepend = this.options.prepend.call(this.options.scope);
}
//try parse json in single quotes
this.options.prepend = $.fn.editableutils.tryParseJson(this.options.prepend, true);
//convert prepend from string to object
if (typeof this.options.prepend === 'string') {
this.options.prepend = {'': this.options.prepend};
}
this.prependData = this.makeArray(this.options.prepend);
}
if($.isArray(this.prependData) && $.isArray(this.sourceData)) {
this.sourceData = this.prependData.concat(this.sourceData);
}
},
/*
renders input list
*/
renderList: function() {
// this method should be overwritten in child class
},
/*
set element's html by value
*/
value2htmlFinal: function(value, element) {
// this method should be overwritten in child class
},
/**
* convert data to array suitable for sourceData, e.g. [{value: 1, text: 'abc'}, {...}]
*/
makeArray: function(data) {
var count, obj, result = [], item, iterateItem;
if(!data || typeof data === 'string') {
return null;
}
if($.isArray(data)) { //array
/*
function to iterate inside item of array if item is object.
Caclulates count of keys in item and store in obj.
*/
iterateItem = function (k, v) {
obj = {value: k, text: v};
if(count++ >= 2) {
return false;// exit from `each` if item has more than one key.
}
};
for(var i = 0; i < data.length; i++) {
item = data[i];
if(typeof item === 'object') {
count = 0; //count of keys inside item
$.each(item, iterateItem);
//case: [{val1: 'text1'}, {val2: 'text2} ...]
if(count === 1) {
result.push(obj);
//case: [{value: 1, text: 'text1'}, {value: 2, text: 'text2'}, ...]
} else if(count > 1) {
//removed check of existance: item.hasOwnProperty('value') && item.hasOwnProperty('text')
if(item.children) {
item.children = this.makeArray(item.children);
}
result.push(item);
}
} else {
//case: ['text1', 'text2' ...]
result.push({value: item, text: item});
}
}
} else { //case: {val1: 'text1', val2: 'text2, ...}
$.each(data, function (k, v) {
result.push({value: k, text: v});
});
}
return result;
},
option: function(key, value) {
this.options[key] = value;
if(key === 'source') {
this.sourceData = null;
}
if(key === 'prepend') {
this.prependData = null;
}
}
});
List.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
/**
Source data for list.
If **array** - it should be in format: `[{value: 1, text: "text1"}, {value: 2, text: "text2"}, ...]`
For compability, object format is also supported: `{"1": "text1", "2": "text2" ...}` but it does not guarantee elements order.
If **string** - considered ajax url to load items. In that case results will be cached for fields with the same source and name. See also `sourceCache` option.
If **function**, it should return data in format above (since 1.4.0).
Since 1.4.1 key `children` supported to render OPTGROUP (for **select** input only).
`[{text: "group1", children: [{value: 1, text: "text1"}, {value: 2, text: "text2"}]}, ...]`
@property source
@type string | array | object | function
@default null
**/
source: null,
/**
Data automatically prepended to the beginning of dropdown list.
@property prepend
@type string | array | object | function
@default false
**/
prepend: false,
/**
Error message when list cannot be loaded (e.g. ajax error)
@property sourceError
@type string
@default Error when loading list
**/
sourceError: 'Error when loading list',
/**
if <code>true</code> and source is **string url** - results will be cached for fields with the same source.
Usefull for editable column in grid to prevent extra requests.
@property sourceCache
@type boolean
@default true
@since 1.2.0
**/
sourceCache: true,
/**
Additional ajax options to be used in $.ajax() when loading list from server.
Useful to send extra parameters (`data` key) or change request method (`type` key).
@property sourceOptions
@type object|function
@default null
@since 1.5.0
**/
sourceOptions: null
});
$.fn.editabletypes.list = List;
}(window.jQuery));
/**
Text input
@class text
@extends abstractinput
@final
@example
<a href="#" id="username" data-type="text" data-pk="1">awesome</a>
<script>
$(function(){
$('#username').editable({
url: '/post',
title: 'Enter username'
});
});
</script>
**/
(function ($) {
"use strict";
var Text = function (options) {
this.init('text', options, Text.defaults);
};
$.fn.editableutils.inherit(Text, $.fn.editabletypes.abstractinput);
$.extend(Text.prototype, {
render: function() {
this.renderClear();
this.setClass();
this.setAttr('placeholder');
},
activate: function() {
if(this.$input.is(':visible')) {
this.$input.focus();
$.fn.editableutils.setCursorPosition(this.$input.get(0), this.$input.val().length);
if(this.toggleClear) {
this.toggleClear();
}
}
},
//render clear button
renderClear: function() {
if (this.options.clear) {
this.$clear = $('<span class="editable-clear-x"></span>');
this.$input.after(this.$clear)
.css('padding-right', 24)
.keyup($.proxy(function(e) {
//arrows, enter, tab, etc
if(~$.inArray(e.keyCode, [40,38,9,13,27])) {
return;
}
clearTimeout(this.t);
var that = this;
this.t = setTimeout(function() {
that.toggleClear(e);
}, 100);
}, this))
.parent().css('position', 'relative');
this.$clear.click($.proxy(this.clear, this));
}
},
postrender: function() {
/*
//now `clear` is positioned via css
if(this.$clear) {
//can position clear button only here, when form is shown and height can be calculated
// var h = this.$input.outerHeight(true) || 20,
var h = this.$clear.parent().height(),
delta = (h - this.$clear.height()) / 2;
//this.$clear.css({bottom: delta, right: delta});
}
*/
},
//show / hide clear button
toggleClear: function(e) {
if(!this.$clear) {
return;
}
var len = this.$input.val().length,
visible = this.$clear.is(':visible');
if(len && !visible) {
this.$clear.show();
}
if(!len && visible) {
this.$clear.hide();
}
},
clear: function() {
this.$clear.hide();
this.$input.val('').focus();
}
});
Text.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
/**
@property tpl
@default <input type="text">
**/
tpl: '<input type="text">',
/**
Placeholder attribute of input. Shown when input is empty.
@property placeholder
@type string
@default null
**/
placeholder: null,
/**
Whether to show `clear` button
@property clear
@type boolean
@default true
**/
clear: true
});
$.fn.editabletypes.text = Text;
}(window.jQuery));
/**
Textarea input
@class textarea
@extends abstractinput
@final
@example
<a href="#" id="comments" data-type="textarea" data-pk="1">awesome comment!</a>
<script>
$(function(){
$('#comments').editable({
url: '/post',
title: 'Enter comments',
rows: 10
});
});
</script>
**/
(function ($) {
"use strict";
var Textarea = function (options) {
this.init('textarea', options, Textarea.defaults);
};
$.fn.editableutils.inherit(Textarea, $.fn.editabletypes.abstractinput);
$.extend(Textarea.prototype, {
render: function () {
this.setClass();
this.setAttr('placeholder');
this.setAttr('rows');
//ctrl + enter
this.$input.keydown(function (e) {
if (e.ctrlKey && e.which === 13) {
$(this).closest('form').submit();
}
});
},
//using `white-space: pre-wrap` solves \n <--> BR conversion very elegant!
/*
value2html: function(value, element) {
var html = '', lines;
if(value) {
lines = value.split("\n");
for (var i = 0; i < lines.length; i++) {
lines[i] = $('<div>').text(lines[i]).html();
}
html = lines.join('<br>');
}
$(element).html(html);
},
html2value: function(html) {
if(!html) {
return '';
}
var regex = new RegExp(String.fromCharCode(10), 'g');
var lines = html.split(/<br\s*\/?>/i);
for (var i = 0; i < lines.length; i++) {
var text = $('<div>').html(lines[i]).text();
// Remove newline characters (\n) to avoid them being converted by value2html() method
// thus adding extra <br> tags
text = text.replace(regex, '');
lines[i] = text;
}
return lines.join("\n");
},
*/
activate: function() {
$.fn.editabletypes.text.prototype.activate.call(this);
}
});
Textarea.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
/**
@property tpl
@default <textarea></textarea>
**/
tpl:'<textarea></textarea>',
/**
@property inputclass
@default input-large
**/
inputclass: 'input-large',
/**
Placeholder attribute of input. Shown when input is empty.
@property placeholder
@type string
@default null
**/
placeholder: null,
/**
Number of rows in textarea
@property rows
@type integer
@default 7
**/
rows: 7
});
$.fn.editabletypes.textarea = Textarea;
}(window.jQuery));
/**
Select (dropdown)
@class select
@extends list
@final
@example
<a href="#" id="status" data-type="select" data-pk="1" data-url="/post" data-title="Select status"></a>
<script>
$(function(){
$('#status').editable({
value: 2,
source: [
{value: 1, text: 'Active'},
{value: 2, text: 'Blocked'},
{value: 3, text: 'Deleted'}
]
});
});
</script>
**/
(function ($) {
"use strict";
var Select = function (options) {
this.init('select', options, Select.defaults);
};
$.fn.editableutils.inherit(Select, $.fn.editabletypes.list);
$.extend(Select.prototype, {
renderList: function() {
this.$input.empty();
var fillItems = function($el, data) {
var attr;
if($.isArray(data)) {
for(var i=0; i<data.length; i++) {
attr = {};
if(data[i].children) {
attr.label = data[i].text;
$el.append(fillItems($('<optgroup>', attr), data[i].children));
} else {
attr.value = data[i].value;
if(data[i].disabled) {
attr.disabled = true;
}
$el.append($('<option>', attr).text(data[i].text));
}
}
}
return $el;
};
fillItems(this.$input, this.sourceData);
this.setClass();
//enter submit
this.$input.on('keydown.editable', function (e) {
if (e.which === 13) {
$(this).closest('form').submit();
}
});
},
value2htmlFinal: function(value, element) {
var text = '',
items = $.fn.editableutils.itemsByValue(value, this.sourceData);
if(items.length) {
text = items[0].text;
}
//$(element).text(text);
$.fn.editabletypes.abstractinput.prototype.value2html.call(this, text, element);
},
autosubmit: function() {
this.$input.off('keydown.editable').on('change.editable', function(){
$(this).closest('form').submit();
});
}
});
Select.defaults = $.extend({}, $.fn.editabletypes.list.defaults, {
/**
@property tpl
@default <select></select>
**/
tpl:'<select></select>'
});
$.fn.editabletypes.select = Select;
}(window.jQuery));
/**
List of checkboxes.
Internally value stored as javascript array of values.
@class checklist
@extends list
@final
@example
<a href="#" id="options" data-type="checklist" data-pk="1" data-url="/post" data-title="Select options"></a>
<script>
$(function(){
$('#options').editable({
value: [2, 3],
source: [
{value: 1, text: 'option1'},
{value: 2, text: 'option2'},
{value: 3, text: 'option3'}
]
});
});
</script>
**/
(function ($) {
"use strict";
var Checklist = function (options) {
this.init('checklist', options, Checklist.defaults);
};
$.fn.editableutils.inherit(Checklist, $.fn.editabletypes.list);
$.extend(Checklist.prototype, {
renderList: function() {
var $label, $div;
this.$tpl.empty();
if(!$.isArray(this.sourceData)) {
return;
}
for(var i=0; i<this.sourceData.length; i++) {
$label = $('<label>').append($('<input>', {
type: 'checkbox',
value: this.sourceData[i].value
}))
.append($('<span>').text(' '+this.sourceData[i].text));
$('<div>').append($label).appendTo(this.$tpl);
}
this.$input = this.$tpl.find('input[type="checkbox"]');
this.setClass();
},
value2str: function(value) {
return $.isArray(value) ? value.sort().join($.trim(this.options.separator)) : '';
},
//parse separated string
str2value: function(str) {
var reg, value = null;
if(typeof str === 'string' && str.length) {
reg = new RegExp('\\s*'+$.trim(this.options.separator)+'\\s*');
value = str.split(reg);
} else if($.isArray(str)) {
value = str;
} else {
value = [str];
}
return value;
},
//set checked on required checkboxes
value2input: function(value) {
this.$input.prop('checked', false);
if($.isArray(value) && value.length) {
this.$input.each(function(i, el) {
var $el = $(el);
// cannot use $.inArray as it performs strict comparison
$.each(value, function(j, val){
/*jslint eqeq: true*/
if($el.val() == val) {
/*jslint eqeq: false*/
$el.prop('checked', true);
}
});
});
}
},
input2value: function() {
var checked = [];
this.$input.filter(':checked').each(function(i, el) {
checked.push($(el).val());
});
return checked;
},
//collect text of checked boxes
value2htmlFinal: function(value, element) {
var html = [],
checked = $.fn.editableutils.itemsByValue(value, this.sourceData),
escape = this.options.escape;
if(checked.length) {
$.each(checked, function(i, v) {
var text = escape ? $.fn.editableutils.escape(v.text) : v.text;
html.push(text);
});
$(element).html(html.join('<br>'));
} else {
$(element).empty();
}
},
activate: function() {
this.$input.first().focus();
},
autosubmit: function() {
this.$input.on('keydown', function(e){
if (e.which === 13) {
$(this).closest('form').submit();
}
});
}
});
Checklist.defaults = $.extend({}, $.fn.editabletypes.list.defaults, {
/**
@property tpl
@default <div></div>
**/
tpl:'<div class="editable-checklist"></div>',
/**
@property inputclass
@type string
@default null
**/
inputclass: null,
/**
Separator of values when reading from `data-value` attribute
@property separator
@type string
@default ','
**/
separator: ','
});
$.fn.editabletypes.checklist = Checklist;
}(window.jQuery));
/**
HTML5 input types.
Following types are supported:
* password
* email
* url
* tel
* number
* range
* time
Learn more about html5 inputs:
http://www.w3.org/wiki/HTML5_form_additions
To check browser compatibility please see:
https://developer.mozilla.org/en-US/docs/HTML/Element/Input
@class html5types
@extends text
@final
@since 1.3.0
@example
<a href="#" id="email" data-type="email" data-pk="1">[email protected]</a>
<script>
$(function(){
$('#email').editable({
url: '/post',
title: 'Enter email'
});
});
</script>
**/
/**
@property tpl
@default depends on type
**/
/*
Password
*/
(function ($) {
"use strict";
var Password = function (options) {
this.init('password', options, Password.defaults);
};
$.fn.editableutils.inherit(Password, $.fn.editabletypes.text);
$.extend(Password.prototype, {
//do not display password, show '[hidden]' instead
value2html: function(value, element) {
if(value) {
$(element).text('[hidden]');
} else {
$(element).empty();
}
},
//as password not displayed, should not set value by html
html2value: function(html) {
return null;
}
});
Password.defaults = $.extend({}, $.fn.editabletypes.text.defaults, {
tpl: '<input type="password">'
});
$.fn.editabletypes.password = Password;
}(window.jQuery));
/*
Email
*/
(function ($) {
"use strict";
var Email = function (options) {
this.init('email', options, Email.defaults);
};
$.fn.editableutils.inherit(Email, $.fn.editabletypes.text);
Email.defaults = $.extend({}, $.fn.editabletypes.text.defaults, {
tpl: '<input type="email">'
});
$.fn.editabletypes.email = Email;
}(window.jQuery));
/*
Url
*/
(function ($) {
"use strict";
var Url = function (options) {
this.init('url', options, Url.defaults);
};
$.fn.editableutils.inherit(Url, $.fn.editabletypes.text);
Url.defaults = $.extend({}, $.fn.editabletypes.text.defaults, {
tpl: '<input type="url">'
});
$.fn.editabletypes.url = Url;
}(window.jQuery));
/*
Tel
*/
(function ($) {
"use strict";
var Tel = function (options) {
this.init('tel', options, Tel.defaults);
};
$.fn.editableutils.inherit(Tel, $.fn.editabletypes.text);
Tel.defaults = $.extend({}, $.fn.editabletypes.text.defaults, {
tpl: '<input type="tel">'
});
$.fn.editabletypes.tel = Tel;
}(window.jQuery));
/*
Number
*/
(function ($) {
"use strict";
var NumberInput = function (options) {
this.init('number', options, NumberInput.defaults);
};
$.fn.editableutils.inherit(NumberInput, $.fn.editabletypes.text);
$.extend(NumberInput.prototype, {
render: function () {
NumberInput.superclass.render.call(this);
this.setAttr('min');
this.setAttr('max');
this.setAttr('step');
},
postrender: function() {
if(this.$clear) {
//increase right ffset for up/down arrows
this.$clear.css({right: 24});
/*
//can position clear button only here, when form is shown and height can be calculated
var h = this.$input.outerHeight(true) || 20,
delta = (h - this.$clear.height()) / 2;
//add 12px to offset right for up/down arrows
this.$clear.css({top: delta, right: delta + 16});
*/
}
}
});
NumberInput.defaults = $.extend({}, $.fn.editabletypes.text.defaults, {
tpl: '<input type="number">',
inputclass: 'input-mini',
min: null,
max: null,
step: null
});
$.fn.editabletypes.number = NumberInput;
}(window.jQuery));
/*
Range (inherit from number)
*/
(function ($) {
"use strict";
var Range = function (options) {
this.init('range', options, Range.defaults);
};
$.fn.editableutils.inherit(Range, $.fn.editabletypes.number);
$.extend(Range.prototype, {
render: function () {
this.$input = this.$tpl.filter('input');
this.setClass();
this.setAttr('min');
this.setAttr('max');
this.setAttr('step');
this.$input.on('input', function(){
$(this).siblings('output').text($(this).val());
});
},
activate: function() {
this.$input.focus();
}
});
Range.defaults = $.extend({}, $.fn.editabletypes.number.defaults, {
tpl: '<input type="range"><output style="width: 30px; display: inline-block"></output>',
inputclass: 'input-medium'
});
$.fn.editabletypes.range = Range;
}(window.jQuery));
/*
Time
*/
(function ($) {
"use strict";
var Time = function (options) {
this.init('time', options, Time.defaults);
};
//inherit from abstract, as inheritance from text gives selection error.
$.fn.editableutils.inherit(Time, $.fn.editabletypes.abstractinput);
$.extend(Time.prototype, {
render: function() {
this.setClass();
}
});
Time.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
tpl: '<input type="time">'
});
$.fn.editabletypes.time = Time;
}(window.jQuery));
/**
Select2 input. Based on amazing work of Igor Vaynberg https://github.com/ivaynberg/select2.
Please see [original select2 docs](http://ivaynberg.github.com/select2) for detailed description and options.
You should manually download and include select2 distributive:
<link href="select2/select2.css" rel="stylesheet" type="text/css"></link>
<script src="select2/select2.js"></script>
To make it **bootstrap-styled** you can use css from [here](https://github.com/t0m/select2-bootstrap-css):
<link href="select2-bootstrap.css" rel="stylesheet" type="text/css"></link>
**Note:** currently `autotext` feature does not work for select2 with `ajax` remote source.
You need initially put both `data-value` and element's text youself:
<a href="#" data-type="select2" data-value="1">Text1</a>
@class select2
@extends abstractinput
@since 1.4.1
@final
@example
<a href="#" id="country" data-type="select2" data-pk="1" data-value="ru" data-url="/post" data-title="Select country"></a>
<script>
$(function(){
//local source
$('#country').editable({
source: [
{id: 'gb', text: 'Great Britain'},
{id: 'us', text: 'United States'},
{id: 'ru', text: 'Russia'}
],
select2: {
multiple: true
}
});
//remote source (simple)
$('#country').editable({
source: '/getCountries'
});
//remote source (advanced)
$('#country').editable({
select2: {
placeholder: 'Select Country',
allowClear: true,
minimumInputLength: 3,
id: function (item) {
return item.CountryId;
},
ajax: {
url: '/getCountries',
dataType: 'json',
data: function (term, page) {
return { query: term };
},
results: function (data, page) {
return { results: data };
}
},
formatResult: function (item) {
return item.CountryName;
},
formatSelection: function (item) {
return item.CountryName;
},
initSelection: function (element, callback) {
return $.get('/getCountryById', { query: element.val() }, function (data) {
callback(data);
});
}
}
});
});
</script>
**/
(function ($) {
"use strict";
var Constructor = function (options) {
this.init('select2', options, Constructor.defaults);
options.select2 = options.select2 || {};
this.sourceData = null;
//placeholder
if(options.placeholder) {
options.select2.placeholder = options.placeholder;
}
//if not `tags` mode, use source
if(!options.select2.tags && options.source) {
var source = options.source;
//if source is function, call it (once!)
if ($.isFunction(options.source)) {
source = options.source.call(options.scope);
}
if (typeof source === 'string') {
options.select2.ajax = options.select2.ajax || {};
//some default ajax params
if(!options.select2.ajax.data) {
options.select2.ajax.data = function(term) {return { query:term };};
}
if(!options.select2.ajax.results) {
options.select2.ajax.results = function(data) { return {results:data };};
}
options.select2.ajax.url = source;
} else {
//check format and convert x-editable format to select2 format (if needed)
this.sourceData = this.convertSource(source);
options.select2.data = this.sourceData;
}
}
//overriding objects in config (as by default jQuery extend() is not recursive)
this.options.select2 = $.extend({}, Constructor.defaults.select2, options.select2);
//detect whether it is multi-valued
this.isMultiple = this.options.select2.tags || this.options.select2.multiple;
this.isRemote = ('ajax' in this.options.select2);
//store function returning ID of item
//should be here as used inautotext for local source
this.idFunc = this.options.select2.id;
if (typeof(this.idFunc) !== "function") {
var idKey = this.idFunc || 'id';
this.idFunc = function (e) { return e[idKey]; };
}
//store function that renders text in select2
this.formatSelection = this.options.select2.formatSelection;
if (typeof(this.formatSelection) !== "function") {
this.formatSelection = function (e) { return e.text; };
}
};
$.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput);
$.extend(Constructor.prototype, {
render: function() {
this.setClass();
//can not apply select2 here as it calls initSelection
//over input that does not have correct value yet.
//apply select2 only in value2input
//this.$input.select2(this.options.select2);
//when data is loaded via ajax, we need to know when it's done to populate listData
if(this.isRemote) {
//listen to loaded event to populate data
this.$input.on('select2-loaded', $.proxy(function(e) {
this.sourceData = e.items.results;
}, this));
}
//trigger resize of editableform to re-position container in multi-valued mode
if(this.isMultiple) {
this.$input.on('change', function() {
$(this).closest('form').parent().triggerHandler('resize');
});
}
},
value2html: function(value, element) {
var text = '', data,
that = this;
if(this.options.select2.tags) { //in tags mode just assign value
data = value;
//data = $.fn.editableutils.itemsByValue(value, this.options.select2.tags, this.idFunc);
} else if(this.sourceData) {
data = $.fn.editableutils.itemsByValue(value, this.sourceData, this.idFunc);
} else {
//can not get list of possible values
//(e.g. autotext for select2 with ajax source)
}
//data may be array (when multiple values allowed)
if($.isArray(data)) {
//collect selected data and show with separator
text = [];
$.each(data, function(k, v){
text.push(v && typeof v === 'object' ? that.formatSelection(v) : v);
});
} else if(data) {
text = that.formatSelection(data);
}
text = $.isArray(text) ? text.join(this.options.viewseparator) : text;
//$(element).text(text);
Constructor.superclass.value2html.call(this, text, element);
},
html2value: function(html) {
return this.options.select2.tags ? this.str2value(html, this.options.viewseparator) : null;
},
value2input: function(value) {
//for local source use data directly from source (to allow autotext)
/*
if(!this.isRemote && !this.isMultiple) {
var items = $.fn.editableutils.itemsByValue(value, this.sourceData, this.idFunc);
if(items.length) {
this.$input.select2('data', items[0]);
return;
}
}
*/
//for remote source just set value, text is updated by initSelection
if(!this.$input.data('select2')) {
this.$input.val(value);
this.$input.select2(this.options.select2);
} else {
//second argument needed to separate initial change from user's click (for autosubmit)
this.$input.val(value).trigger('change', true);
}
//if remote source AND no user's initSelection provided --> try to use element's text
if(this.isRemote && !this.isMultiple && !this.options.select2.initSelection) {
var customId = this.options.select2.id,
customText = this.options.select2.formatSelection;
if(!customId && !customText) {
var data = {id: value, text: $(this.options.scope).text()};
this.$input.select2('data', data);
}
}
},
input2value: function() {
return this.$input.select2('val');
},
str2value: function(str, separator) {
if(typeof str !== 'string' || !this.isMultiple) {
return str;
}
separator = separator || this.options.select2.separator || $.fn.select2.defaults.separator;
var val, i, l;
if (str === null || str.length < 1) {
return null;
}
val = str.split(separator);
for (i = 0, l = val.length; i < l; i = i + 1) {
val[i] = $.trim(val[i]);
}
return val;
},
autosubmit: function() {
this.$input.on('change', function(e, isInitial){
if(!isInitial) {
$(this).closest('form').submit();
}
});
},
/*
Converts source from x-editable format: {value: 1, text: "1"} to
select2 format: {id: 1, text: "1"}
*/
convertSource: function(source) {
if($.isArray(source) && source.length && source[0].value !== undefined) {
for(var i = 0; i<source.length; i++) {
if(source[i].value !== undefined) {
source[i].id = source[i].value;
delete source[i].value;
}
}
}
return source;
},
destroy: function() {
if(this.$input.data('select2')) {
this.$input.select2('destroy');
}
}
});
Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
/**
@property tpl
@default <input type="hidden">
**/
tpl:'<input type="hidden">',
/**
Configuration of select2. [Full list of options](http://ivaynberg.github.com/select2).
@property select2
@type object
@default null
**/
select2: null,
/**
Placeholder attribute of select
@property placeholder
@type string
@default null
**/
placeholder: null,
/**
Source data for select. It will be assigned to select2 `data` property and kept here just for convenience.
Please note, that format is different from simple `select` input: use 'id' instead of 'value'.
E.g. `[{id: 1, text: "text1"}, {id: 2, text: "text2"}, ...]`.
@property source
@type array|string|function
@default null
**/
source: null,
/**
Separator used to display tags.
@property viewseparator
@type string
@default ', '
**/
viewseparator: ', '
});
$.fn.editabletypes.select2 = Constructor;
}(window.jQuery));
/**
* Combodate - 1.0.4
* Dropdown date and time picker.
* Converts text input into dropdowns to pick day, month, year, hour, minute and second.
* Uses momentjs as datetime library http://momentjs.com.
* For internalization include corresponding file from https://github.com/timrwood/moment/tree/master/lang
*
* Confusion at noon and midnight - see http://en.wikipedia.org/wiki/12-hour_clock#Confusion_at_noon_and_midnight
* In combodate:
* 12:00 pm --> 12:00 (24-h format, midday)
* 12:00 am --> 00:00 (24-h format, midnight, start of day)
*
* Differs from momentjs parse rules:
* 00:00 pm, 12:00 pm --> 12:00 (24-h format, day not change)
* 00:00 am, 12:00 am --> 00:00 (24-h format, day not change)
*
*
* Author: Vitaliy Potapov
* Project page: http://github.com/vitalets/combodate
* Copyright (c) 2012 Vitaliy Potapov. Released under MIT License.
**/
(function ($) {
var Combodate = function (element, options) {
this.$element = $(element);
if(!this.$element.is('input')) {
$.error('Combodate should be applied to INPUT element');
return;
}
this.options = $.extend({}, $.fn.combodate.defaults, options, this.$element.data());
this.init();
};
Combodate.prototype = {
constructor: Combodate,
init: function () {
this.map = {
//key regexp moment.method
day: ['D', 'date'],
month: ['M', 'month'],
year: ['Y', 'year'],
hour: ['[Hh]', 'hours'],
minute: ['m', 'minutes'],
second: ['s', 'seconds'],
ampm: ['[Aa]', '']
};
this.$widget = $('<span class="combodate"></span>').html(this.getTemplate());
this.initCombos();
//update original input on change
this.$widget.on('change', 'select', $.proxy(function(){
this.$element.val(this.getValue());
}, this));
this.$widget.find('select').css('width', 'auto');
//hide original input and insert widget
this.$element.hide().after(this.$widget);
//set initial value
this.setValue(this.$element.val() || this.options.value);
},
/*
Replace tokens in template with <select> elements
*/
getTemplate: function() {
var tpl = this.options.template;
//first pass
$.each(this.map, function(k, v) {
v = v[0];
var r = new RegExp(v+'+'),
token = v.length > 1 ? v.substring(1, 2) : v;
tpl = tpl.replace(r, '{'+token+'}');
});
//replace spaces with
tpl = tpl.replace(/ /g, ' ');
//second pass
$.each(this.map, function(k, v) {
v = v[0];
var token = v.length > 1 ? v.substring(1, 2) : v;
tpl = tpl.replace('{'+token+'}', '<select class="'+k+'"></select>');
});
return tpl;
},
/*
Initialize combos that presents in template
*/
initCombos: function() {
var that = this;
$.each(this.map, function(k, v) {
var $c = that.$widget.find('.'+k), f, items;
if($c.length) {
that['$'+k] = $c; //set properties like this.$day, this.$month etc.
f = 'fill' + k.charAt(0).toUpperCase() + k.slice(1); //define method name to fill items, e.g `fillDays`
items = that[f]();
that['$'+k].html(that.renderItems(items));
}
});
},
/*
Initialize items of combos. Handles `firstItem` option
*/
initItems: function(key) {
var values = [],
relTime;
if(this.options.firstItem === 'name') {
//need both to support moment ver < 2 and >= 2
relTime = moment.relativeTime || moment.langData()._relativeTime;
var header = typeof relTime[key] === 'function' ? relTime[key](1, true, key, false) : relTime[key];
//take last entry (see momentjs lang files structure)
header = header.split(' ').reverse()[0];
values.push(['', header]);
} else if(this.options.firstItem === 'empty') {
values.push(['', '']);
}
return values;
},
/*
render items to string of <option> tags
*/
renderItems: function(items) {
var str = [];
for(var i=0; i<items.length; i++) {
str.push('<option value="'+items[i][0]+'">'+items[i][1]+'</option>');
}
return str.join("\n");
},
/*
fill day
*/
fillDay: function() {
var items = this.initItems('d'), name, i,
twoDigit = this.options.template.indexOf('DD') !== -1;
for(i=1; i<=31; i++) {
name = twoDigit ? this.leadZero(i) : i;
items.push([i, name]);
}
return items;
},
/*
fill month
*/
fillMonth: function() {
var items = this.initItems('M'), name, i,
longNames = this.options.template.indexOf('MMMM') !== -1,
shortNames = this.options.template.indexOf('MMM') !== -1,
twoDigit = this.options.template.indexOf('MM') !== -1;
for(i=0; i<=11; i++) {
if(longNames) {
//see https://github.com/timrwood/momentjs.com/pull/36
name = moment().date(1).month(i).format('MMMM');
} else if(shortNames) {
name = moment().date(1).month(i).format('MMM');
} else if(twoDigit) {
name = this.leadZero(i+1);
} else {
name = i+1;
}
items.push([i, name]);
}
return items;
},
/*
fill year
*/
fillYear: function() {
var items = [], name, i,
longNames = this.options.template.indexOf('YYYY') !== -1;
for(i=this.options.maxYear; i>=this.options.minYear; i--) {
name = longNames ? i : (i+'').substring(2);
items[this.options.yearDescending ? 'push' : 'unshift']([i, name]);
}
items = this.initItems('y').concat(items);
return items;
},
/*
fill hour
*/
fillHour: function() {
var items = this.initItems('h'), name, i,
h12 = this.options.template.indexOf('h') !== -1,
h24 = this.options.template.indexOf('H') !== -1,
twoDigit = this.options.template.toLowerCase().indexOf('hh') !== -1,
min = h12 ? 1 : 0,
max = h12 ? 12 : 23;
for(i=min; i<=max; i++) {
name = twoDigit ? this.leadZero(i) : i;
items.push([i, name]);
}
return items;
},
/*
fill minute
*/
fillMinute: function() {
var items = this.initItems('m'), name, i,
twoDigit = this.options.template.indexOf('mm') !== -1;
for(i=0; i<=59; i+= this.options.minuteStep) {
name = twoDigit ? this.leadZero(i) : i;
items.push([i, name]);
}
return items;
},
/*
fill second
*/
fillSecond: function() {
var items = this.initItems('s'), name, i,
twoDigit = this.options.template.indexOf('ss') !== -1;
for(i=0; i<=59; i+= this.options.secondStep) {
name = twoDigit ? this.leadZero(i) : i;
items.push([i, name]);
}
return items;
},
/*
fill ampm
*/
fillAmpm: function() {
var ampmL = this.options.template.indexOf('a') !== -1,
ampmU = this.options.template.indexOf('A') !== -1,
items = [
['am', ampmL ? 'am' : 'AM'],
['pm', ampmL ? 'pm' : 'PM']
];
return items;
},
/*
Returns current date value from combos.
If format not specified - `options.format` used.
If format = `null` - Moment object returned.
*/
getValue: function(format) {
var dt, values = {},
that = this,
notSelected = false;
//getting selected values
$.each(this.map, function(k, v) {
if(k === 'ampm') {
return;
}
var def = k === 'day' ? 1 : 0;
values[k] = that['$'+k] ? parseInt(that['$'+k].val(), 10) : def;
if(isNaN(values[k])) {
notSelected = true;
return false;
}
});
//if at least one visible combo not selected - return empty string
if(notSelected) {
return '';
}
//convert hours 12h --> 24h
if(this.$ampm) {
//12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day)
if(values.hour === 12) {
values.hour = this.$ampm.val() === 'am' ? 0 : 12;
} else {
values.hour = this.$ampm.val() === 'am' ? values.hour : values.hour+12;
}
}
dt = moment([values.year, values.month, values.day, values.hour, values.minute, values.second]);
//highlight invalid date
this.highlight(dt);
format = format === undefined ? this.options.format : format;
if(format === null) {
return dt.isValid() ? dt : null;
} else {
return dt.isValid() ? dt.format(format) : '';
}
},
setValue: function(value) {
if(!value) {
return;
}
var dt = typeof value === 'string' ? moment(value, this.options.format) : moment(value),
that = this,
values = {};
//function to find nearest value in select options
function getNearest($select, value) {
var delta = {};
$select.children('option').each(function(i, opt){
var optValue = $(opt).attr('value'),
distance;
if(optValue === '') return;
distance = Math.abs(optValue - value);
if(typeof delta.distance === 'undefined' || distance < delta.distance) {
delta = {value: optValue, distance: distance};
}
});
return delta.value;
}
if(dt.isValid()) {
//read values from date object
$.each(this.map, function(k, v) {
if(k === 'ampm') {
return;
}
values[k] = dt[v[1]]();
});
if(this.$ampm) {
//12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day)
if(values.hour >= 12) {
values.ampm = 'pm';
if(values.hour > 12) {
values.hour -= 12;
}
} else {
values.ampm = 'am';
if(values.hour === 0) {
values.hour = 12;
}
}
}
$.each(values, function(k, v) {
//call val() for each existing combo, e.g. this.$hour.val()
if(that['$'+k]) {
if(k === 'minute' && that.options.minuteStep > 1 && that.options.roundTime) {
v = getNearest(that['$'+k], v);
}
if(k === 'second' && that.options.secondStep > 1 && that.options.roundTime) {
v = getNearest(that['$'+k], v);
}
that['$'+k].val(v);
}
});
this.$element.val(dt.format(this.options.format));
}
},
/*
highlight combos if date is invalid
*/
highlight: function(dt) {
if(!dt.isValid()) {
if(this.options.errorClass) {
this.$widget.addClass(this.options.errorClass);
} else {
//store original border color
if(!this.borderColor) {
this.borderColor = this.$widget.find('select').css('border-color');
}
this.$widget.find('select').css('border-color', 'red');
}
} else {
if(this.options.errorClass) {
this.$widget.removeClass(this.options.errorClass);
} else {
this.$widget.find('select').css('border-color', this.borderColor);
}
}
},
leadZero: function(v) {
return v <= 9 ? '0' + v : v;
},
destroy: function() {
this.$widget.remove();
this.$element.removeData('combodate').show();
}
//todo: clear method
};
$.fn.combodate = function ( option ) {
var d, args = Array.apply(null, arguments);
args.shift();
//getValue returns date as string / object (not jQuery object)
if(option === 'getValue' && this.length && (d = this.eq(0).data('combodate'))) {
return d.getValue.apply(d, args);
}
return this.each(function () {
var $this = $(this),
data = $this.data('combodate'),
options = typeof option == 'object' && option;
if (!data) {
$this.data('combodate', (data = new Combodate(this, options)));
}
if (typeof option == 'string' && typeof data[option] == 'function') {
data[option].apply(data, args);
}
});
};
$.fn.combodate.defaults = {
//in this format value stored in original input
format: 'DD-MM-YYYY HH:mm',
//in this format items in dropdowns are displayed
template: 'D / MMM / YYYY H : mm',
//initial value, can be `new Date()`
value: null,
minYear: 1970,
maxYear: 2015,
yearDescending: true,
minuteStep: 5,
secondStep: 1,
firstItem: 'empty', //'name', 'empty', 'none'
errorClass: null,
roundTime: true //whether to round minutes and seconds if step > 1
};
}(window.jQuery));
/**
Combodate input - dropdown date and time picker.
Based on [combodate](http://vitalets.github.com/combodate) plugin (included). To use it you should manually include [momentjs](http://momentjs.com).
<script src="js/moment.min.js"></script>
Allows to input:
* only date
* only time
* both date and time
Please note, that format is taken from momentjs and **not compatible** with bootstrap-datepicker / jquery UI datepicker.
Internally value stored as `momentjs` object.
@class combodate
@extends abstractinput
@final
@since 1.4.0
@example
<a href="#" id="dob" data-type="combodate" data-pk="1" data-url="/post" data-value="1984-05-15" data-title="Select date"></a>
<script>
$(function(){
$('#dob').editable({
format: 'YYYY-MM-DD',
viewformat: 'DD.MM.YYYY',
template: 'D / MMMM / YYYY',
combodate: {
minYear: 2000,
maxYear: 2015,
minuteStep: 1
}
}
});
});
</script>
**/
/*global moment*/
(function ($) {
"use strict";
var Constructor = function (options) {
this.init('combodate', options, Constructor.defaults);
//by default viewformat equals to format
if(!this.options.viewformat) {
this.options.viewformat = this.options.format;
}
//try parse combodate config defined as json string in data-combodate
options.combodate = $.fn.editableutils.tryParseJson(options.combodate, true);
//overriding combodate config (as by default jQuery extend() is not recursive)
this.options.combodate = $.extend({}, Constructor.defaults.combodate, options.combodate, {
format: this.options.format,
template: this.options.template
});
};
$.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput);
$.extend(Constructor.prototype, {
render: function () {
this.$input.combodate(this.options.combodate);
if($.fn.editableform.engine === 'bs3') {
this.$input.siblings().find('select').addClass('form-control');
}
if(this.options.inputclass) {
this.$input.siblings().find('select').addClass(this.options.inputclass);
}
//"clear" link
/*
if(this.options.clear) {
this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){
e.preventDefault();
e.stopPropagation();
this.clear();
}, this));
this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear));
}
*/
},
value2html: function(value, element) {
var text = value ? value.format(this.options.viewformat) : '';
//$(element).text(text);
Constructor.superclass.value2html.call(this, text, element);
},
html2value: function(html) {
return html ? moment(html, this.options.viewformat) : null;
},
value2str: function(value) {
return value ? value.format(this.options.format) : '';
},
str2value: function(str) {
return str ? moment(str, this.options.format) : null;
},
value2submit: function(value) {
return this.value2str(value);
},
value2input: function(value) {
this.$input.combodate('setValue', value);
},
input2value: function() {
return this.$input.combodate('getValue', null);
},
activate: function() {
this.$input.siblings('.combodate').find('select').eq(0).focus();
},
/*
clear: function() {
this.$input.data('datepicker').date = null;
this.$input.find('.active').removeClass('active');
},
*/
autosubmit: function() {
}
});
Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
/**
@property tpl
@default <input type="text">
**/
tpl:'<input type="text">',
/**
@property inputclass
@default null
**/
inputclass: null,
/**
Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br>
See list of tokens in [momentjs docs](http://momentjs.com/docs/#/parsing/string-format)
@property format
@type string
@default YYYY-MM-DD
**/
format:'YYYY-MM-DD',
/**
Format used for displaying date. Also applied when converting date from element's text on init.
If not specified equals to `format`.
@property viewformat
@type string
@default null
**/
viewformat: null,
/**
Template used for displaying dropdowns.
@property template
@type string
@default D / MMM / YYYY
**/
template: 'D / MMM / YYYY',
/**
Configuration of combodate.
Full list of options: http://vitalets.github.com/combodate/#docs
@property combodate
@type object
@default null
**/
combodate: null
/*
(not implemented yet)
Text shown as clear date button.
If <code>false</code> clear button will not be rendered.
@property clear
@type boolean|string
@default 'x clear'
*/
//clear: '× clear'
});
$.fn.editabletypes.combodate = Constructor;
}(window.jQuery));
/**
* Editable Poshytip
* ---------------------
* requires jquery.poshytip.js
*/
(function ($) {
"use strict";
//extend methods
$.extend($.fn.editableContainer.Popup.prototype, {
containerName: 'poshytip',
innerCss: 'div.tip-inner',
defaults: $.fn.poshytip.defaults,
initContainer: function(){
this.handlePlacement();
$.extend(this.containerOptions, {
showOn: 'none',
content: '',
alignTo: 'target'
});
this.call(this.containerOptions);
},
/*
Overwrite totally show() method as poshytip requires content is set before show
*/
show: function (closeAll) {
this.$element.addClass('editable-open');
if(closeAll !== false) {
//close all open containers (except this)
this.closeOthers(this.$element[0]);
}
//render form
this.$form = $('<div>');
this.renderForm();
var $label = $('<label>').text(this.options.title || this.$element.data( "title") || this.$element.data( "originalTitle")),
$content = $('<div>').append($label).append(this.$form);
this.call('update', $content);
this.call('show');
this.tip().addClass(this.containerClass);
this.$form.data('editableform').input.activate();
},
/* hide */
innerHide: function () {
this.call('hide');
},
/* destroy */
innerDestroy: function() {
this.call('destroy');
},
setPosition: function() {
this.container().refresh(false);
},
handlePlacement: function() {
var x, y, ox = 0, oy = 0;
switch(this.options.placement) {
case 'top':
x = 'center';
y = 'top';
oy = 5;
break;
case 'right':
x = 'right';
y = 'center';
ox = 10;
break;
case 'bottom':
x = 'center';
y = 'bottom';
oy = 5;
break;
case 'left':
x = 'left';
y = 'center';
ox = 10;
break;
}
$.extend(this.containerOptions, {
alignX: x,
offsetX: ox,
alignY: y,
offsetY:oy
});
}
});
//defaults
$.fn.editableContainer.defaults = $.extend({}, $.fn.editableContainer.defaults, {
className: 'tip-yellowsimple'
});
/**
* Poshytip fix: disable incorrect table display
* see https://github.com/vadikom/poshytip/issues/7
*/
/*jshint eqeqeq:false, curly: false*/
if($.Poshytip) { //need this check, because in inline mode poshytip may not be loaded!
var tips = [],
reBgImage = /^url\(["']?([^"'\)]*)["']?\);?$/i,
rePNG = /\.png$/i,
ie6 = !!window.createPopup && document.documentElement.currentStyle.minWidth == 'undefined';
$.Poshytip.prototype.refresh = function(async) {
if (this.disabled)
return;
var currPos;
if (async) {
if (!this.$tip.data('active'))
return;
// save current position as we will need to animate
currPos = {left: this.$tip.css('left'), top: this.$tip.css('top')};
}
// reset position to avoid text wrapping, etc.
this.$tip.css({left: 0, top: 0}).appendTo(document.body);
// save default opacity
if (this.opacity === undefined)
this.opacity = this.$tip.css('opacity');
// check for images - this code is here (i.e. executed each time we show the tip and not on init) due to some browser inconsistencies
var bgImage = this.$tip.css('background-image').match(reBgImage),
arrow = this.$arrow.css('background-image').match(reBgImage);
if (bgImage) {
var bgImagePNG = rePNG.test(bgImage[1]);
// fallback to background-color/padding/border in IE6 if a PNG is used
if (ie6 && bgImagePNG) {
this.$tip.css('background-image', 'none');
this.$inner.css({margin: 0, border: 0, padding: 0});
bgImage = bgImagePNG = false;
} else {
this.$tip.prepend('<table class="fallback" border="0" cellpadding="0" cellspacing="0"><tr><td class="tip-top tip-bg-image" colspan="2"><span></span></td><td class="tip-right tip-bg-image" rowspan="2"><span></span></td></tr><tr><td class="tip-left tip-bg-image" rowspan="2"><span></span></td><td></td></tr><tr><td class="tip-bottom tip-bg-image" colspan="2"><span></span></td></tr></table>')
.css({border: 0, padding: 0, 'background-image': 'none', 'background-color': 'transparent'})
.find('.tip-bg-image').css('background-image', 'url("' + bgImage[1] +'")').end()
.find('td').eq(3).append(this.$inner);
}
// disable fade effect in IE due to Alpha filter + translucent PNG issue
if (bgImagePNG && !$.support.opacity)
this.opts.fade = false;
}
// IE arrow fixes
if (arrow && !$.support.opacity) {
// disable arrow in IE6 if using a PNG
if (ie6 && rePNG.test(arrow[1])) {
arrow = false;
this.$arrow.css('background-image', 'none');
}
// disable fade effect in IE due to Alpha filter + translucent PNG issue
this.opts.fade = false;
}
var $table = this.$tip.find('table.fallback');
if (ie6) {
// fix min/max-width in IE6
this.$tip[0].style.width = '';
$table.width('auto').find('td').eq(3).width('auto');
var tipW = this.$tip.width(),
minW = parseInt(this.$tip.css('min-width'), 10),
maxW = parseInt(this.$tip.css('max-width'), 10);
if (!isNaN(minW) && tipW < minW)
tipW = minW;
else if (!isNaN(maxW) && tipW > maxW)
tipW = maxW;
this.$tip.add($table).width(tipW).eq(0).find('td').eq(3).width('100%');
} else if ($table[0]) {
// fix the table width if we are using a background image
// IE9, FF4 use float numbers for width/height so use getComputedStyle for them to avoid text wrapping
// for details look at: http://vadikom.com/dailies/offsetwidth-offsetheight-useless-in-ie9-firefox4/
$table.width('auto').find('td').eq(3).width('auto').end().end().width(document.defaultView && document.defaultView.getComputedStyle && parseFloat(document.defaultView.getComputedStyle(this.$tip[0], null).width) || this.$tip.width()).find('td').eq(3).width('100%');
}
this.tipOuterW = this.$tip.outerWidth();
this.tipOuterH = this.$tip.outerHeight();
this.calcPos();
// position and show the arrow image
if (arrow && this.pos.arrow) {
this.$arrow[0].className = 'tip-arrow tip-arrow-' + this.pos.arrow;
this.$arrow.css('visibility', 'inherit');
}
if (async) {
this.asyncAnimating = true;
var self = this;
this.$tip.css(currPos).animate({left: this.pos.l, top: this.pos.t}, 200, function() { self.asyncAnimating = false; });
} else {
this.$tip.css({left: this.pos.l, top: this.pos.t});
}
};
}
/*jshinteqeqeq: true, curly: true*/
}(window.jQuery));
/**
jQuery UI Datepicker.
Description and examples: http://jqueryui.com/datepicker.
This input is also accessible as **date** type. Do not use it together with __bootstrap-datepicker__ as both apply <code>$().datepicker()</code> method.
For **i18n** you should include js file from here: https://github.com/jquery/jquery-ui/tree/master/ui/i18n.
@class dateui
@extends abstractinput
@final
@example
<a href="#" id="dob" data-type="date" data-pk="1" data-url="/post" data-title="Select date">15/05/1984</a>
<script>
$(function(){
$('#dob').editable({
format: 'yyyy-mm-dd',
viewformat: 'dd/mm/yyyy',
datepicker: {
firstDay: 1
}
}
});
});
</script>
**/
(function ($) {
"use strict";
var DateUI = function (options) {
this.init('dateui', options, DateUI.defaults);
this.initPicker(options, DateUI.defaults);
};
$.fn.editableutils.inherit(DateUI, $.fn.editabletypes.abstractinput);
$.extend(DateUI.prototype, {
initPicker: function(options, defaults) {
//by default viewformat equals to format
if(!this.options.viewformat) {
this.options.viewformat = this.options.format;
}
//correct formats: replace yyyy with yy (for compatibility with bootstrap datepicker)
this.options.viewformat = this.options.viewformat.replace('yyyy', 'yy');
this.options.format = this.options.format.replace('yyyy', 'yy');
//overriding datepicker config (as by default jQuery extend() is not recursive)
//since 1.4 datepicker internally uses viewformat instead of format. Format is for submit only
this.options.datepicker = $.extend({}, defaults.datepicker, options.datepicker, {
dateFormat: this.options.viewformat
});
},
render: function () {
this.$input.datepicker(this.options.datepicker);
//"clear" link
if(this.options.clear) {
this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){
e.preventDefault();
e.stopPropagation();
this.clear();
}, this));
this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear));
}
},
value2html: function(value, element) {
var text = $.datepicker.formatDate(this.options.viewformat, value);
DateUI.superclass.value2html.call(this, text, element);
},
html2value: function(html) {
if(typeof html !== 'string') {
return html;
}
//if string does not match format, UI datepicker throws exception
var d;
try {
d = $.datepicker.parseDate(this.options.viewformat, html);
} catch(e) {}
return d;
},
value2str: function(value) {
return $.datepicker.formatDate(this.options.format, value);
},
str2value: function(str) {
if(typeof str !== 'string') {
return str;
}
//if string does not match format, UI datepicker throws exception
var d;
try {
d = $.datepicker.parseDate(this.options.format, str);
} catch(e) {}
return d;
},
value2submit: function(value) {
return this.value2str(value);
},
value2input: function(value) {
this.$input.datepicker('setDate', value);
},
input2value: function() {
return this.$input.datepicker('getDate');
},
activate: function() {
},
clear: function() {
this.$input.datepicker('setDate', null);
},
autosubmit: function() {
this.$input.on('mouseup', 'table.ui-datepicker-calendar a.ui-state-default', function(e){
var $form = $(this).closest('form');
setTimeout(function() {
$form.submit();
}, 200);
});
}
});
DateUI.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
/**
@property tpl
@default <div></div>
**/
tpl:'<div class="editable-date"></div>',
/**
@property inputclass
@default null
**/
inputclass: null,
/**
Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br>
Full list of tokens: http://docs.jquery.com/UI/Datepicker/formatDate
@property format
@type string
@default yyyy-mm-dd
**/
format:'yyyy-mm-dd',
/**
Format used for displaying date. Also applied when converting date from element's text on init.
If not specified equals to <code>format</code>
@property viewformat
@type string
@default null
**/
viewformat: null,
/**
Configuration of datepicker.
Full list of options: http://api.jqueryui.com/datepicker
@property datepicker
@type object
@default {
firstDay: 0,
changeYear: true,
changeMonth: true
}
**/
datepicker: {
firstDay: 0,
changeYear: true,
changeMonth: true,
showOtherMonths: true
},
/**
Text shown as clear date button.
If <code>false</code> clear button will not be rendered.
@property clear
@type boolean|string
@default 'x clear'
**/
clear: '× clear'
});
$.fn.editabletypes.dateui = DateUI;
}(window.jQuery));
/**
jQuery UI datefield input - modification for inline mode.
Shows normal <input type="text"> and binds popup datepicker.
Automatically shown in inline mode.
@class dateuifield
@extends dateui
@since 1.4.0
**/
(function ($) {
"use strict";
var DateUIField = function (options) {
this.init('dateuifield', options, DateUIField.defaults);
this.initPicker(options, DateUIField.defaults);
};
$.fn.editableutils.inherit(DateUIField, $.fn.editabletypes.dateui);
$.extend(DateUIField.prototype, {
render: function () {
// this.$input = this.$tpl.find('input');
this.$input.datepicker(this.options.datepicker);
$.fn.editabletypes.text.prototype.renderClear.call(this);
},
value2input: function(value) {
this.$input.val($.datepicker.formatDate(this.options.viewformat, value));
},
input2value: function() {
return this.html2value(this.$input.val());
},
activate: function() {
$.fn.editabletypes.text.prototype.activate.call(this);
},
toggleClear: function() {
$.fn.editabletypes.text.prototype.toggleClear.call(this);
},
autosubmit: function() {
//reset autosubmit to empty
}
});
DateUIField.defaults = $.extend({}, $.fn.editabletypes.dateui.defaults, {
/**
@property tpl
@default <input type="text">
**/
tpl: '<input type="text"/>',
/**
@property inputclass
@default null
**/
inputclass: null,
/* datepicker config */
datepicker: {
showOn: "button",
buttonImage: "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif",
buttonImageOnly: true,
firstDay: 0,
changeYear: true,
changeMonth: true,
showOtherMonths: true
},
/* disable clear link */
clear: false
});
$.fn.editabletypes.dateuifield = DateUIField;
}(window.jQuery)); |
Docker/KlusterKiteMonitoring/klusterkite-web/src/containers/PackagePage/PackagePage.js | KlusterKite/KlusterKite | import React from 'react'
import Relay from 'react-relay'
import { browserHistory } from 'react-router'
import UpdateFeedMutation from '../FeedPage/mutations/UpdateFeedMutation'
import SinglePackageForm from '../../components/PackageForm/SinglePackageForm'
class PackagePage extends React.Component {
static propTypes = {
api: React.PropTypes.object,
params: React.PropTypes.object,
};
static contextTypes = {
router: React.PropTypes.object,
};
constructor (props) {
super(props);
this.state = {
}
}
onSubmit = (model) => {
this.editNode(model);
};
editNode = (model) => {
this.setState({
saving: true
});
Relay.Store.commitUpdate(
new UpdateFeedMutation(
{
nodeId: this.props.params.configurationId,
configurationId: this.props.api.configuration.__id,
settings: this.props.api.configuration.settings,
packages: this.props.api.configuration.settings.packages,
}),
{
onSuccess: (response) => {
if (response.klusterKiteNodeApi_klusterKiteNodesApi_configurations_update.errors &&
response.klusterKiteNodeApi_klusterKiteNodesApi_configurations_update.errors.edges) {
const messages = this.getErrorMessagesFromEdge(response.klusterKiteNodeApi_klusterKiteNodesApi_configurations_update.errors.edges);
this.setState({
saving: false,
saveErrors: messages
});
} else {
browserHistory.push(`/klusterkite/Configuration/${this.props.params.configurationId}`);
}
},
onFailure: (transaction) => {
this.setState({
saving: false
});
console.log(transaction)},
},
)
};
getErrorMessagesFromEdge = (edges) => {
return edges.map(x => x.node).map(x => x.message);
}
onCancel = () => {
browserHistory.push(`/klusterkite/Configuration/${this.props.params.configurationId}`)
};
render () {
const packages = this.props.api.klusterKiteNodesApi.nugetPackages;
const model = {
package: {
id: this.props.api.package.__id,
specificVersion: this.props.api.package.version
},
};
return (
<div>
<SinglePackageForm
onSubmit={this.onSubmit}
onCancel={this.onCancel}
initialValues={model}
packagesList={packages}
saving={this.state.saving}
deleting={this.state.deleting}
saveErrors={this.state.saveErrors}
/>
</div>
)
}
}
export default Relay.createContainer(
PackagePage,
{
initialVariables: {
id: null,
configurationId: null,
nodeExists: false,
},
prepareVariables: (prevVariables) => Object.assign({}, prevVariables, {
nodeExists: prevVariables.id !== null,
}),
fragments: {
api: () => Relay.QL`
fragment on IKlusterKiteNodeApi {
__typename
id
klusterKiteNodesApi {
nugetPackages {
edges {
node {
name
version
availableVersions
}
}
}
}
configuration:__node(id: $configurationId) {
...on IKlusterKiteNodeApi_Configuration {
__id
settings {
${UpdateFeedMutation.getFragment('settings')},
nugetFeed,
}
}
}
package:__node(id: $id) @include( if: $nodeExists ) {
...on IKlusterKiteNodeApi_PackageDescription {
id
version
__id
}
}
}
`,
},
},
)
|
public/bower_components/rxjs/dist/rx.all.compat.js | v1shva/MplayN | // Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'function': true,
'object': true
};
function checkGlobal(value) {
return (value && value.Object === Object) ? value : null;
}
var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ? exports : null;
var freeModule = (objectTypes[typeof module] && module && !module.nodeType) ? module : null;
var freeGlobal = checkGlobal(freeExports && freeModule && typeof global === 'object' && global);
var freeSelf = checkGlobal(objectTypes[typeof self] && self);
var freeWindow = checkGlobal(objectTypes[typeof window] && window);
var moduleExports = (freeModule && freeModule.exports === freeExports) ? freeExports : null;
var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
var root = freeGlobal || ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || freeSelf || thisGlobal || Function('return this')();
var Rx = {
internals: {},
config: {
Promise: root.Promise
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
identity = Rx.helpers.identity = function (x) { return x; },
defaultNow = Rx.helpers.defaultNow = (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.subscribe !== 'function' && typeof p.then === 'function'; },
isFunction = Rx.helpers.isFunction = (function () {
var isFn = function (value) {
return typeof value == 'function' || false;
};
// fallback for older versions of Chrome and Safari
if (isFn(/x/)) {
isFn = function(value) {
return typeof value == 'function' && toString.call(value) == '[object Function]';
};
}
return isFn;
}());
function cloneArray(arr) {
var len = arr.length, a = new Array(len);
for(var i = 0; i < len; i++) { a[i] = arr[i]; }
return a;
}
var errorObj = {e: {}};
function tryCatcherGen(tryCatchTarget) {
return function tryCatcher() {
try {
return tryCatchTarget.apply(this, arguments);
} catch (e) {
errorObj.e = e;
return errorObj;
}
};
}
var tryCatch = Rx.internals.tryCatch = function tryCatch(fn) {
if (!isFunction(fn)) { throw new TypeError('fn must be a function'); }
return tryCatcherGen(fn);
};
function thrower(e) {
throw e;
}
Rx.config.longStackSupport = false;
var hasStacks = false, stacks = tryCatch(function () { throw new Error(); })();
hasStacks = !!stacks.e && !!stacks.e.stack;
// All code after this point will be filtered from stack traces reported by RxJS
var rStartingLine = captureLine(), rFileName;
var STACK_JUMP_SEPARATOR = 'From previous event:';
function makeStackTraceLong(error, observable) {
// If possible, transform the error stack trace by removing Node and RxJS
// cruft, then concatenating with the stack trace of `observable`.
if (hasStacks &&
observable.stack &&
typeof error === 'object' &&
error !== null &&
error.stack &&
error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
) {
var stacks = [];
for (var o = observable; !!o; o = o.source) {
if (o.stack) {
stacks.unshift(o.stack);
}
}
stacks.unshift(error.stack);
var concatedStacks = stacks.join('\n' + STACK_JUMP_SEPARATOR + '\n');
error.stack = filterStackString(concatedStacks);
}
}
function filterStackString(stackString) {
var lines = stackString.split('\n'), desiredLines = [];
for (var i = 0, len = lines.length; i < len; i++) {
var line = lines[i];
if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
desiredLines.push(line);
}
}
return desiredLines.join('\n');
}
function isInternalFrame(stackLine) {
var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
if (!fileNameAndLineNumber) {
return false;
}
var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1];
return fileName === rFileName &&
lineNumber >= rStartingLine &&
lineNumber <= rEndingLine;
}
function isNodeFrame(stackLine) {
return stackLine.indexOf('(module.js:') !== -1 ||
stackLine.indexOf('(node.js:') !== -1;
}
function captureLine() {
if (!hasStacks) { return; }
try {
throw new Error();
} catch (e) {
var lines = e.stack.split('\n');
var firstLine = lines[0].indexOf('@') > 0 ? lines[1] : lines[2];
var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
if (!fileNameAndLineNumber) { return; }
rFileName = fileNameAndLineNumber[0];
return fileNameAndLineNumber[1];
}
}
function getFileNameAndLineNumber(stackLine) {
// Named functions: 'at functionName (filename:lineNumber:columnNumber)'
var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
if (attempt1) { return [attempt1[1], Number(attempt1[2])]; }
// Anonymous functions: 'at filename:lineNumber:columnNumber'
var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
if (attempt2) { return [attempt2[1], Number(attempt2[2])]; }
// Firefox style: 'function@filename:lineNumber or @filename:lineNumber'
var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
if (attempt3) { return [attempt3[1], Number(attempt3[2])]; }
}
// Utilities
var toString = Object.prototype.toString;
var arrayClass = '[object Array]',
funcClass = '[object Function]',
stringClass = '[object String]';
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 = new Array(length),
thisp = arguments[1];
if (toString.call(fun) !== funcClass) {
throw new TypeError(fun + ' is not a function');
}
for (var i = 0; i < length; i++) {
if (i in self) {
result[i] = fun.call(thisp, self[i], i, object);
}
}
return result;
};
}
if (!Array.prototype.filter) {
Array.prototype.filter = function (predicate) {
var results = [], item, t = new Object(this);
for (var i = 0, len = t.length >>> 0; i < len; i++) {
item = t[i];
if (i in t && predicate.call(arguments[1], item, i, t)) {
results.push(item);
}
}
return results;
};
}
if (!Array.isArray) {
Array.isArray = function (arg) {
return toString.call(arg) === arrayClass;
};
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function indexOf(searchElement) {
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n !== n) {
n = 0;
} else if (n !== 0 && n !== Infinity && n !== -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
// Fix for Tessel
if (!Object.prototype.propertyIsEnumerable) {
Object.prototype.propertyIsEnumerable = function (key) {
for (var k in this) { if (k === key) { return true; } }
return false;
};
}
if (!Object.keys) {
Object.keys = (function() {
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString');
return function(obj) {
if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
throw new TypeError('Object.keys called on non-object');
}
var result = [], prop, i;
for (prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
result.push(prop);
}
}
if (hasDontEnumBug) {
for (i = 0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) {
result.push(dontEnums[i]);
}
}
}
return result;
};
}());
}
if (typeof Object.create !== 'function') {
// Production steps of ECMA-262, Edition 5, 15.2.3.5
// Reference: http://es5.github.io/#x15.2.3.5
Object.create = (function() {
function Temp() {}
var hasOwn = Object.prototype.hasOwnProperty;
return function (O) {
if (typeof O !== 'object') {
throw new TypeError('Object prototype may only be an Object or null');
}
Temp.prototype = O;
var obj = new Temp();
Temp.prototype = null;
if (arguments.length > 1) {
// Object.defineProperties does ToObject on its first argument.
var Properties = Object(arguments[1]);
for (var prop in Properties) {
if (hasOwn.call(Properties, prop)) {
obj[prop] = Properties[prop];
}
}
}
// 5. Return obj
return obj;
};
})();
}
root.Element && root.Element.prototype.attachEvent && !root.Element.prototype.addEventListener && (function () {
function addMethod(name, fn) {
Window.prototype[name] = HTMLDocument.prototype[name] = Element.prototype[name] = fn;
}
addMethod('addEventListener', function (type, listener) {
var target = this;
var listeners = target._c1_listeners = target._c1_listeners || {};
var typeListeners = listeners[type] = listeners[type] || [];
target.attachEvent('on' + type, typeListeners.event = function (e) {
e || (e = root.event);
var documentElement = target.document &&
target.document.documentElement ||
target.documentElement ||
{ scrollLeft: 0, scrollTop: 0 };
e.currentTarget = target;
e.pageX = e.clientX + documentElement.scrollLeft;
e.pageY = e.clientY + documentElement.scrollTop;
e.preventDefault = function () {
e.bubbledKeyCode = e.keyCode;
if (e.ctrlKey) {
try {
e.keyCode = 0;
} catch (e) { }
}
e.defaultPrevented = true;
e.returnValue = false;
e.modified = true;
e.returnValue = false;
};
e.stopImmediatePropagation = function () {
immediatePropagation = false;
e.cancelBubble = true;
};
e.stopPropagation = function () {
e.cancelBubble = true;
};
e.relatedTarget = e.fromElement || null;
e.target = e.srcElement || target;
e.timeStamp = +new Date();
// Normalize key events
switch(e.type) {
case 'keypress':
var c = ('charCode' in e ? e.charCode : e.keyCode);
if (c === 10) {
c = 0;
e.keyCode = 13;
} else if (c === 13 || c === 27) {
c = 0;
} else if (c === 3) {
c = 99;
}
e.charCode = c;
e.keyChar = e.charCode ? String.fromCharCode(e.charCode) : '';
break;
}
var copiedEvent = {};
for (var prop in e) {
copiedEvent[prop] = e[prop];
}
for (var i = 0, typeListenersCache = [].concat(typeListeners), typeListenerCache, immediatePropagation = true; immediatePropagation && (typeListenerCache = typeListenersCache[i]); ++i) {
for (var ii = 0, typeListener; typeListener = typeListeners[ii]; ++ii) {
if (typeListener === typeListenerCache) { typeListener.call(target, copiedEvent); break; }
}
}
});
typeListeners.push(listener);
});
addMethod('removeEventListener', function (type, listener) {
var target = this;
var listeners = target._c1_listeners = target._c1_listeners || {};
var typeListeners = listeners[type] = listeners[type] || [];
for (var i = typeListeners.length - 1, typeListener; typeListener = typeListeners[i]; --i) {
if (typeListener === listener) { typeListeners.splice(i, 1); break; }
}
!typeListeners.length &&
typeListeners.event &&
target.detachEvent('on' + type, typeListeners.event);
});
addMethod('dispatchEvent', function (e) {
var target = this;
var type = e.type;
var listeners = target._c1_listeners = target._c1_listeners || {};
var typeListeners = listeners[type] = listeners[type] || [];
try {
return target.fireEvent('on' + type, e);
} catch (err) {
return typeListeners.event && typeListeners.event(e);
}
});
function ready() {
if (ready.interval && document.body) {
ready.interval = clearInterval(ready.interval);
document.dispatchEvent(new CustomEvent('DOMContentLoaded'));
}
}
ready.interval = setInterval(ready, 1);
root.addEventListener('load', ready);
}());
(!root.CustomEvent || typeof root.CustomEvent === 'object') && (function() {
function CustomEvent (type, params) {
var event;
params = params || { bubbles: false, cancelable: false, detail: undefined };
try {
if (document.createEvent) {
event = document.createEvent('CustomEvent');
event.initCustomEvent(type, params.bubbles, params.cancelable, params.detail);
} else if (document.createEventObject) {
event = document.createEventObject();
}
} catch (error) {
event = document.createEvent('Event');
event.initEvent(type, params.bubbles, params.cancelable);
event.detail = params.detail;
}
return event;
}
root.CustomEvent && (CustomEvent.prototype = root.CustomEvent.prototype);
root.CustomEvent = CustomEvent;
}());
var EmptyError = Rx.EmptyError = function() {
this.message = 'Sequence contains no elements.';
Error.call(this);
};
EmptyError.prototype = Object.create(Error.prototype);
EmptyError.prototype.name = 'EmptyError';
var ObjectDisposedError = Rx.ObjectDisposedError = function() {
this.message = 'Object has been disposed';
Error.call(this);
};
ObjectDisposedError.prototype = Object.create(Error.prototype);
ObjectDisposedError.prototype.name = 'ObjectDisposedError';
var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () {
this.message = 'Argument out of range';
Error.call(this);
};
ArgumentOutOfRangeError.prototype = Object.create(Error.prototype);
ArgumentOutOfRangeError.prototype.name = 'ArgumentOutOfRangeError';
var NotSupportedError = Rx.NotSupportedError = function (message) {
this.message = message || 'This operation is not supported';
Error.call(this);
};
NotSupportedError.prototype = Object.create(Error.prototype);
NotSupportedError.prototype.name = 'NotSupportedError';
var NotImplementedError = Rx.NotImplementedError = function (message) {
this.message = message || 'This operation is not implemented';
Error.call(this);
};
NotImplementedError.prototype = Object.create(Error.prototype);
NotImplementedError.prototype.name = 'NotImplementedError';
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 && 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;
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dateTag] = typedArrayTags[errorTag] =
typedArrayTags[funcTag] = typedArrayTags[mapTag] =
typedArrayTags[numberTag] = typedArrayTags[objectTag] =
typedArrayTags[regexpTag] = typedArrayTags[setTag] =
typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
var objectProto = Object.prototype,
hasOwnProperty = objectProto.hasOwnProperty,
objToString = objectProto.toString,
MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
var keys = Object.keys || (function() {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
return function(obj) {
if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
throw new TypeError('Object.keys called on non-object');
}
var result = [], prop, i;
for (prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
result.push(prop);
}
}
if (hasDontEnumBug) {
for (i = 0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) {
result.push(dontEnums[i]);
}
}
}
return result;
};
}());
function equalObjects(object, other, equalFunc, isLoose, stackA, stackB) {
var objProps = keys(object),
objLength = objProps.length,
othProps = keys(other),
othLength = othProps.length;
if (objLength !== othLength && !isLoose) {
return false;
}
var index = objLength, key;
while (index--) {
key = objProps[index];
if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) {
return false;
}
}
var skipCtor = isLoose;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key],
result;
if (!(result === undefined ? equalFunc(objValue, othValue, isLoose, stackA, stackB) : result)) {
return false;
}
skipCtor || (skipCtor = key === 'constructor');
}
if (!skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
if (objCtor !== othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor === 'function' && objCtor instanceof objCtor &&
typeof othCtor === 'function' && othCtor instanceof othCtor)) {
return false;
}
}
return true;
}
function equalByTag(object, other, tag) {
switch (tag) {
case boolTag:
case dateTag:
return +object === +other;
case errorTag:
return object.name === other.name && object.message === other.message;
case numberTag:
return (object !== +object) ?
other !== +other :
object === +other;
case regexpTag:
case stringTag:
return object === (other + '');
}
return false;
}
var isObject = Rx.internals.isObject = function(value) {
var type = typeof value;
return !!value && (type === 'object' || type === 'function');
};
function isObjectLike(value) {
return !!value && typeof value === 'object';
}
function isLength(value) {
return typeof value === 'number' && value > -1 && value % 1 === 0 && value <= MAX_SAFE_INTEGER;
}
var isHostObject = (function() {
try {
Object({ 'toString': 0 } + '');
} catch(e) {
return function() { return false; };
}
return function(value) {
return typeof value.toString !== 'function' && typeof (value + '') === 'string';
};
}());
function isTypedArray(value) {
return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
}
var isArray = Array.isArray || function(value) {
return isObjectLike(value) && isLength(value.length) && objToString.call(value) === arrayTag;
};
function arraySome (array, predicate) {
var index = -1,
length = array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
function equalArrays(array, other, equalFunc, isLoose, stackA, stackB) {
var index = -1,
arrLength = array.length,
othLength = other.length;
if (arrLength !== othLength && !(isLoose && othLength > arrLength)) {
return false;
}
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index],
result;
if (result !== undefined) {
if (result) {
continue;
}
return false;
}
// Recursively compare arrays (susceptible to call stack limits).
if (isLoose) {
if (!arraySome(other, function(othValue) {
return arrValue === othValue || equalFunc(arrValue, othValue, isLoose, stackA, stackB);
})) {
return false;
}
} else if (!(arrValue === othValue || equalFunc(arrValue, othValue, isLoose, stackA, stackB))) {
return false;
}
}
return true;
}
function baseIsEqualDeep(object, other, equalFunc, isLoose, stackA, stackB) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = arrayTag,
othTag = arrayTag;
if (!objIsArr) {
objTag = objToString.call(object);
if (objTag === argsTag) {
objTag = objectTag;
} else if (objTag !== objectTag) {
objIsArr = isTypedArray(object);
}
}
if (!othIsArr) {
othTag = objToString.call(other);
if (othTag === argsTag) {
othTag = objectTag;
}
}
var objIsObj = objTag === objectTag && !isHostObject(object),
othIsObj = othTag === objectTag && !isHostObject(other),
isSameTag = objTag === othTag;
if (isSameTag && !(objIsArr || objIsObj)) {
return equalByTag(object, other, objTag);
}
if (!isLoose) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, isLoose, stackA, stackB);
}
}
if (!isSameTag) {
return false;
}
// Assume cyclic values are equal.
// For more information on detecting circular references see https://es5.github.io/#JO.
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] === object) {
return stackB[length] === other;
}
}
// Add `object` and `other` to the stack of traversed objects.
stackA.push(object);
stackB.push(other);
var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, isLoose, stackA, stackB);
stackA.pop();
stackB.pop();
return result;
}
function baseIsEqual(value, other, isLoose, stackA, stackB) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, baseIsEqual, isLoose, stackA, stackB);
}
var isEqual = Rx.internals.isEqual = function (value, other) {
return baseIsEqual(value, other);
};
var hasProp = {}.hasOwnProperty,
slice = Array.prototype.slice;
var inherits = Rx.internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
var addProperties = Rx.internals.addProperties = function (obj) {
for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
for (var idx = 0, ln = sources.length; idx < ln; idx++) {
var source = sources[idx];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new BinaryDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
function IndexedItem(id, value) {
this.id = id;
this.value = value;
}
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
c === 0 && (c = this.id - other.id);
return c;
};
var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) { return; }
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) { return; }
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
+index || (index = 0);
if (index >= this.length || index < 0) { return; }
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
this.items[this.length] = undefined;
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
var args = [], i, len;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
len = arguments.length;
args = new Array(len);
for(i = 0; i < len; i++) { args[i] = arguments[i]; }
}
this.disposables = args;
this.isDisposed = false;
this.length = args.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var len = this.disposables.length, currentDisposables = new Array(len);
for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; }
this.disposables = [];
this.length = 0;
for (i = 0; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Provides a set of static methods for creating Disposables.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
/**
* Validates whether the given object is a disposable
* @param {Object} Object to test whether it has a dispose method
* @returns {Boolean} true if a disposable object, else false.
*/
var isDisposable = Disposable.isDisposable = function (d) {
return d && isFunction(d.dispose);
};
var checkDisposed = Disposable.checkDisposed = function (disposable) {
if (disposable.isDisposed) { throw new ObjectDisposedError(); }
};
var disposableFixup = Disposable._fixup = function (result) {
return isDisposable(result) ? result : disposableEmpty;
};
// Single assignment
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () {
this.isDisposed = false;
this.current = null;
};
SingleAssignmentDisposable.prototype.getDisposable = function () {
return this.current;
};
SingleAssignmentDisposable.prototype.setDisposable = function (value) {
if (this.current) { throw new Error('Disposable has already been assigned'); }
var shouldDispose = this.isDisposed;
!shouldDispose && (this.current = value);
shouldDispose && value && value.dispose();
};
SingleAssignmentDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var old = this.current;
this.current = null;
old && old.dispose();
}
};
// Multiple assignment disposable
var SerialDisposable = Rx.SerialDisposable = function () {
this.isDisposed = false;
this.current = null;
};
SerialDisposable.prototype.getDisposable = function () {
return this.current;
};
SerialDisposable.prototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed;
if (!shouldDispose) {
var old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
SerialDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var old = this.current;
this.current = null;
}
old && old.dispose();
};
var BinaryDisposable = Rx.BinaryDisposable = function (first, second) {
this._first = first;
this._second = second;
this.isDisposed = false;
};
BinaryDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var old1 = this._first;
this._first = null;
old1 && old1.dispose();
var old2 = this._second;
this._second = null;
old2 && old2.dispose();
}
};
var NAryDisposable = Rx.NAryDisposable = function (disposables) {
this._disposables = disposables;
this.isDisposed = false;
};
NAryDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
for (var i = 0, len = this._disposables.length; i < len; i++) {
this._disposables[i].dispose();
}
this._disposables.length = 0;
}
};
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed && !this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed && !this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler;
this.disposable = disposable;
this.isDisposed = false;
}
function scheduleItem(s, self) {
if (!self.isDisposed) {
self.isDisposed = true;
self.disposable.dispose();
}
}
ScheduledDisposable.prototype.dispose = function () {
this.scheduler.schedule(this, scheduleItem);
};
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
};
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return disposableFixup(this.action(this.scheduler, this.state));
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler() { }
/** Determines whether the given object is a scheduler */
Scheduler.isScheduler = function (s) {
return s instanceof Scheduler;
};
var schedulerProto = Scheduler.prototype;
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (state, action) {
throw new NotImplementedError();
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleFuture = function (state, dueTime, action) {
var dt = dueTime;
dt instanceof Date && (dt = dt - this.now());
dt = Scheduler.normalize(dt);
if (dt === 0) { return this.schedule(state, action); }
return this._scheduleFuture(state, dt, action);
};
schedulerProto._scheduleFuture = function (state, dueTime, action) {
throw new NotImplementedError();
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/** Gets the current time according to the local machine's system clock. */
Scheduler.prototype.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
timeSpan < 0 && (timeSpan = 0);
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize, isScheduler = Scheduler.isScheduler;
(function (schedulerProto) {
function invokeRecImmediate(scheduler, pair) {
var state = pair[0], action = pair[1], group = new CompositeDisposable();
action(state, innerAction);
return group;
function innerAction(state2) {
var isAdded = false, isDone = false;
var d = scheduler.schedule(state2, scheduleWork);
if (!isDone) {
group.add(d);
isAdded = true;
}
function scheduleWork(_, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
action(state3, innerAction);
return disposableEmpty;
}
}
}
function invokeRecDate(scheduler, pair) {
var state = pair[0], action = pair[1], group = new CompositeDisposable();
action(state, innerAction);
return group;
function innerAction(state2, dueTime1) {
var isAdded = false, isDone = false;
var d = scheduler.scheduleFuture(state2, dueTime1, scheduleWork);
if (!isDone) {
group.add(d);
isAdded = true;
}
function scheduleWork(_, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
action(state3, innerAction);
return disposableEmpty;
}
}
}
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (state, action) {
return this.schedule([state, action], invokeRecImmediate);
};
/**
* Schedules an action to be executed recursively after a specified relative or absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number | Date} dueTime Relative or absolute time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveFuture = function (state, dueTime, action) {
return this.scheduleFuture([state, action], dueTime, invokeRecDate);
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
schedulerProto.schedulePeriodic = function(state, period, action) {
if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); }
period = normalizeTime(period);
var s = state, id = root.setInterval(function () { s = action(s); }, period);
return disposableCreate(function () { root.clearInterval(id); });
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
* @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
* @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
*/
schedulerProto.catchError = schedulerProto['catch'] = function (handler) {
return new CatchScheduler(this, handler);
};
}(Scheduler.prototype));
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function createTick(self) {
return function tick(command, recurse) {
recurse(0, self._period);
var state = tryCatch(self._action)(self._state);
if (state === errorObj) {
self._cancel.dispose();
thrower(state.e);
}
self._state = state;
};
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveFuture(0, this._period, createTick(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
/** Gets a scheduler that schedules work immediately on the current thread. */
var ImmediateScheduler = (function (__super__) {
inherits(ImmediateScheduler, __super__);
function ImmediateScheduler() {
__super__.call(this);
}
ImmediateScheduler.prototype.schedule = function (state, action) {
return disposableFixup(action(this, state));
};
return ImmediateScheduler;
}(Scheduler));
var immediateScheduler = Scheduler.immediate = new ImmediateScheduler();
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var CurrentThreadScheduler = (function (__super__) {
var queue;
function runTrampoline () {
while (queue.length > 0) {
var item = queue.dequeue();
!item.isCancelled() && item.invoke();
}
}
inherits(CurrentThreadScheduler, __super__);
function CurrentThreadScheduler() {
__super__.call(this);
}
CurrentThreadScheduler.prototype.schedule = function (state, action) {
var si = new ScheduledItem(this, state, action, this.now());
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
var result = tryCatch(runTrampoline)();
queue = null;
if (result === errorObj) { thrower(result.e); }
} else {
queue.enqueue(si);
}
return si.disposable;
};
CurrentThreadScheduler.prototype.scheduleRequired = function () { return !queue; };
return CurrentThreadScheduler;
}(Scheduler));
var currentThreadScheduler = Scheduler.currentThread = new CurrentThreadScheduler();
var scheduleMethod, clearMethod;
var localTimer = (function () {
var localSetTimeout, localClearTimeout = noop;
if (!!root.setTimeout) {
localSetTimeout = root.setTimeout;
localClearTimeout = root.clearTimeout;
} else if (!!root.WScript) {
localSetTimeout = function (fn, time) {
root.WScript.Sleep(time);
fn();
};
} else {
throw new NotSupportedError();
}
return {
setTimeout: localSetTimeout,
clearTimeout: localClearTimeout
};
}());
var localSetTimeout = localTimer.setTimeout,
localClearTimeout = localTimer.clearTimeout;
(function () {
var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false;
clearMethod = function (handle) {
delete tasksByHandle[handle];
};
function runTask(handle) {
if (currentlyRunning) {
localSetTimeout(function () { runTask(handle); }, 0);
} else {
var task = tasksByHandle[handle];
if (task) {
currentlyRunning = true;
var result = tryCatch(task)();
clearMethod(handle);
currentlyRunning = false;
if (result === errorObj) { thrower(result.e); }
}
}
}
var reNative = new RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false, oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('', '*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout
if (isFunction(setImmediate)) {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
setImmediate(function () { runTask(id); });
return id;
};
} else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
process.nextTick(function () { runTask(id); });
return id;
};
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random();
var onGlobalPostMessage = function (event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
runTask(event.data.substring(MSG_PREFIX.length));
}
};
root.addEventListener('message', onGlobalPostMessage, false);
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
root.postMessage(MSG_PREFIX + id, '*');
return id;
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel();
channel.port1.onmessage = function (e) { runTask(e.data); };
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
channel.port2.postMessage(id);
return id;
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
var id = nextHandle++;
tasksByHandle[id] = action;
scriptElement.onreadystatechange = function () {
runTask(id);
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
return id;
};
} else {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
localSetTimeout(function () {
runTask(id);
}, 0);
return id;
};
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var DefaultScheduler = (function (__super__) {
inherits(DefaultScheduler, __super__);
function DefaultScheduler() {
__super__.call(this);
}
function scheduleAction(disposable, action, scheduler, state) {
return function schedule() {
disposable.setDisposable(Disposable._fixup(action(scheduler, state)));
};
}
function ClearDisposable(id) {
this._id = id;
this.isDisposed = false;
}
ClearDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
clearMethod(this._id);
}
};
function LocalClearDisposable(id) {
this._id = id;
this.isDisposed = false;
}
LocalClearDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
localClearTimeout(this._id);
}
};
DefaultScheduler.prototype.schedule = function (state, action) {
var disposable = new SingleAssignmentDisposable(),
id = scheduleMethod(scheduleAction(disposable, action, this, state));
return new BinaryDisposable(disposable, new ClearDisposable(id));
};
DefaultScheduler.prototype._scheduleFuture = function (state, dueTime, action) {
if (dueTime === 0) { return this.schedule(state, action); }
var disposable = new SingleAssignmentDisposable(),
id = localSetTimeout(scheduleAction(disposable, action, this, state), dueTime);
return new BinaryDisposable(disposable, new LocalClearDisposable(id));
};
function scheduleLongRunning(state, action, disposable) {
return function () { action(state, disposable); };
}
DefaultScheduler.prototype.scheduleLongRunning = function (state, action) {
var disposable = disposableCreate(noop);
scheduleMethod(scheduleLongRunning(state, action, disposable));
return disposable;
};
return DefaultScheduler;
}(Scheduler));
var defaultScheduler = Scheduler['default'] = Scheduler.async = new DefaultScheduler();
var CatchScheduler = (function (__super__) {
inherits(CatchScheduler, __super__);
function CatchScheduler(scheduler, handler) {
this._scheduler = scheduler;
this._handler = handler;
this._recursiveOriginal = null;
this._recursiveWrapper = null;
__super__.call(this);
}
CatchScheduler.prototype.schedule = function (state, action) {
return this._scheduler.schedule(state, this._wrap(action));
};
CatchScheduler.prototype._scheduleFuture = function (state, dueTime, action) {
return this._scheduler.schedule(state, dueTime, this._wrap(action));
};
CatchScheduler.prototype.now = function () { return this._scheduler.now(); };
CatchScheduler.prototype._clone = function (scheduler) {
return new CatchScheduler(scheduler, this._handler);
};
CatchScheduler.prototype._wrap = function (action) {
var parent = this;
return function (self, state) {
var res = tryCatch(action)(parent._getRecursiveWrapper(self), state);
if (res === errorObj) {
if (!parent._handler(res.e)) { thrower(res.e); }
return disposableEmpty;
}
return disposableFixup(res);
};
};
CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
if (this._recursiveOriginal !== scheduler) {
this._recursiveOriginal = scheduler;
var wrapper = this._clone(scheduler);
wrapper._recursiveOriginal = scheduler;
wrapper._recursiveWrapper = wrapper;
this._recursiveWrapper = wrapper;
}
return this._recursiveWrapper;
};
CatchScheduler.prototype.schedulePeriodic = function (state, period, action) {
var self = this, failed = false, d = new SingleAssignmentDisposable();
d.setDisposable(this._scheduler.schedulePeriodic(state, period, function (state1) {
if (failed) { return null; }
var res = tryCatch(action)(state1);
if (res === errorObj) {
failed = true;
if (!self._handler(res.e)) { thrower(res.e); }
d.dispose();
return null;
}
return res;
}));
return d;
};
return CatchScheduler;
}(Scheduler));
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification() {
}
Notification.prototype._accept = function (onNext, onError, onCompleted) {
throw new NotImplementedError();
};
Notification.prototype._acceptObserver = function (onNext, onError, onCompleted) {
throw new NotImplementedError();
};
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
* @param {Function | Observer} observerOrOnNext Function to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Function to invoke for an OnError notification.
* @param {Function} onCompleted Function 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._acceptObserver(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
Notification.prototype.toObservable = function (scheduler) {
var self = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (o) {
return scheduler.schedule(self, function (_, notification) {
notification._acceptObserver(o);
notification.kind === 'N' && o.onCompleted();
});
});
};
return Notification;
})();
var OnNextNotification = (function (__super__) {
inherits(OnNextNotification, __super__);
function OnNextNotification(value) {
this.value = value;
this.kind = 'N';
}
OnNextNotification.prototype._accept = function (onNext) {
return onNext(this.value);
};
OnNextNotification.prototype._acceptObserver = function (o) {
return o.onNext(this.value);
};
OnNextNotification.prototype.toString = function () {
return 'OnNext(' + this.value + ')';
};
return OnNextNotification;
}(Notification));
var OnErrorNotification = (function (__super__) {
inherits(OnErrorNotification, __super__);
function OnErrorNotification(error) {
this.error = error;
this.kind = 'E';
}
OnErrorNotification.prototype._accept = function (onNext, onError) {
return onError(this.error);
};
OnErrorNotification.prototype._acceptObserver = function (o) {
return o.onError(this.error);
};
OnErrorNotification.prototype.toString = function () {
return 'OnError(' + this.error + ')';
};
return OnErrorNotification;
}(Notification));
var OnCompletedNotification = (function (__super__) {
inherits(OnCompletedNotification, __super__);
function OnCompletedNotification() {
this.kind = 'C';
}
OnCompletedNotification.prototype._accept = function (onNext, onError, onCompleted) {
return onCompleted();
};
OnCompletedNotification.prototype._acceptObserver = function (o) {
return o.onCompleted();
};
OnCompletedNotification.prototype.toString = function () {
return 'OnCompleted()';
};
return OnCompletedNotification;
}(Notification));
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = function (value) {
return new OnNextNotification(value);
};
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = function (error) {
return new OnErrorNotification(error);
};
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = function () {
return new OnCompletedNotification();
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) { return n.accept(observer); };
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
var self = this;
return new AnonymousObserver(
function (x) { self.onNext(x); },
function (err) { self.onError(err); },
function () { self.onCompleted(); });
};
/**
* Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
* If a violation is detected, an Error is thrown from the offending observer method call.
* @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
*/
Observer.prototype.checked = function () { return new CheckedObserver(this); };
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler, thisArg) {
var cb = bindCallback(handler, thisArg, 1);
return new AnonymousObserver(function (x) {
return cb(notificationCreateOnNext(x));
}, function (e) {
return cb(notificationCreateOnError(e));
}, function () {
return cb(notificationCreateOnCompleted());
});
};
/**
* Schedules the invocation of observer methods on the given scheduler.
* @param {Scheduler} scheduler Scheduler to schedule observer messages on.
* @returns {Observer} Observer whose messages are scheduled on the given scheduler.
*/
Observer.prototype.notifyOn = function (scheduler) {
return new ObserveOnObserver(scheduler, this);
};
Observer.prototype.makeSafe = function(disposable) {
return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable);
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) {
inherits(AbstractObserver, __super__);
/**
* Creates a new observer in a non-stopped state.
*/
function AbstractObserver() {
this.isStopped = false;
}
// Must be implemented by other observers
AbstractObserver.prototype.next = notImplemented;
AbstractObserver.prototype.error = notImplemented;
AbstractObserver.prototype.completed = notImplemented;
/**
* Notifies the observer of a new element in the sequence.
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
!this.isStopped && this.next(value);
};
/**
* Notifies the observer that an exception has occurred.
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () { this.isStopped = true; };
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) {
inherits(AnonymousObserver, __super__);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
__super__.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (error) {
this._onError(error);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var CheckedObserver = (function (__super__) {
inherits(CheckedObserver, __super__);
function CheckedObserver(observer) {
__super__.call(this);
this._observer = observer;
this._state = 0; // 0 - idle, 1 - busy, 2 - done
}
var CheckedObserverPrototype = CheckedObserver.prototype;
CheckedObserverPrototype.onNext = function (value) {
this.checkAccess();
var res = tryCatch(this._observer.onNext).call(this._observer, value);
this._state = 0;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.onError = function (err) {
this.checkAccess();
var res = tryCatch(this._observer.onError).call(this._observer, err);
this._state = 2;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.onCompleted = function () {
this.checkAccess();
var res = tryCatch(this._observer.onCompleted).call(this._observer);
this._state = 2;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.checkAccess = function () {
if (this._state === 1) { throw new Error('Re-entrancy detected'); }
if (this._state === 2) { throw new Error('Observer completed'); }
if (this._state === 0) { this._state = 1; }
};
return CheckedObserver;
}(Observer));
var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) {
inherits(ScheduledObserver, __super__);
function ScheduledObserver(scheduler, observer) {
__super__.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
function enqueueNext(observer, x) { return function () { observer.onNext(x); }; }
function enqueueError(observer, e) { return function () { observer.onError(e); }; }
function enqueueCompleted(observer) { return function () { observer.onCompleted(); }; }
ScheduledObserver.prototype.next = function (x) {
this.queue.push(enqueueNext(this.observer, x));
};
ScheduledObserver.prototype.error = function (e) {
this.queue.push(enqueueError(this.observer, e));
};
ScheduledObserver.prototype.completed = function () {
this.queue.push(enqueueCompleted(this.observer));
};
function scheduleMethod(state, recurse) {
var work;
if (state.queue.length > 0) {
work = state.queue.shift();
} else {
state.isAcquired = false;
return;
}
var res = tryCatch(work)();
if (res === errorObj) {
state.queue = [];
state.hasFaulted = true;
return thrower(res.e);
}
recurse(state);
}
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
isOwner &&
this.disposable.setDisposable(this.scheduler.scheduleRecursive(this, scheduleMethod));
};
ScheduledObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
var ObserveOnObserver = (function (__super__) {
inherits(ObserveOnObserver, __super__);
function ObserveOnObserver(scheduler, observer, cancel) {
__super__.call(this, scheduler, observer);
this._cancel = cancel;
}
ObserveOnObserver.prototype.next = function (value) {
__super__.prototype.next.call(this, value);
this.ensureActive();
};
ObserveOnObserver.prototype.error = function (e) {
__super__.prototype.error.call(this, e);
this.ensureActive();
};
ObserveOnObserver.prototype.completed = function () {
__super__.prototype.completed.call(this);
this.ensureActive();
};
ObserveOnObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this._cancel && this._cancel.dispose();
this._cancel = null;
};
return ObserveOnObserver;
})(ScheduledObserver);
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function makeSubscribe(self, subscribe) {
return function (o) {
var oldOnError = o.onError;
o.onError = function (e) {
makeStackTraceLong(e, self);
oldOnError.call(o, e);
};
return subscribe.call(self, o);
};
}
function Observable() {
if (Rx.config.longStackSupport && hasStacks) {
var oldSubscribe = this._subscribe;
var e = tryCatch(thrower)(new Error()).e;
this.stack = e.stack.substring(e.stack.indexOf('\n') + 1);
this._subscribe = makeSubscribe(this, oldSubscribe);
}
}
observableProto = Observable.prototype;
/**
* Determines whether the given object is an Observable
* @param {Any} An object to determine whether it is an Observable
* @returns {Boolean} true if an Observable, else false.
*/
Observable.isObservable = function (o) {
return o && isFunction(o.subscribe);
};
/**
* Subscribes an o to the observable sequence.
* @param {Mixed} [oOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribe = observableProto.forEach = function (oOrOnNext, onError, onCompleted) {
return this._subscribe(typeof oOrOnNext === 'object' ?
oOrOnNext :
observerCreate(oOrOnNext, onError, onCompleted));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onNext The function to invoke on each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnNext = function (onNext, thisArg) {
return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext));
};
/**
* Subscribes to an exceptional condition in the sequence with an optional "this" argument.
* @param {Function} onError The function to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnError = function (onError, thisArg) {
return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnCompleted = function (onCompleted, thisArg) {
return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted));
};
return Observable;
})();
var ObservableBase = Rx.ObservableBase = (function (__super__) {
inherits(ObservableBase, __super__);
function fixSubscriber(subscriber) {
return subscriber && isFunction(subscriber.dispose) ? subscriber :
isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
}
function setDisposable(s, state) {
var ado = state[0], self = state[1];
var sub = tryCatch(self.subscribeCore).call(self, ado);
if (sub === errorObj && !ado.fail(errorObj.e)) { thrower(errorObj.e); }
ado.setDisposable(fixSubscriber(sub));
}
function ObservableBase() {
__super__.call(this);
}
ObservableBase.prototype._subscribe = function (o) {
var ado = new AutoDetachObserver(o), state = [ado, this];
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.schedule(state, setDisposable);
} else {
setDisposable(null, state);
}
return ado;
};
ObservableBase.prototype.subscribeCore = notImplemented;
return ObservableBase;
}(Observable));
var FlatMapObservable = Rx.FlatMapObservable = (function(__super__) {
inherits(FlatMapObservable, __super__);
function FlatMapObservable(source, selector, resultSelector, thisArg) {
this.resultSelector = isFunction(resultSelector) ? resultSelector : null;
this.selector = bindCallback(isFunction(selector) ? selector : function() { return selector; }, thisArg, 3);
this.source = source;
__super__.call(this);
}
FlatMapObservable.prototype.subscribeCore = function(o) {
return this.source.subscribe(new InnerObserver(o, this.selector, this.resultSelector, this));
};
inherits(InnerObserver, AbstractObserver);
function InnerObserver(observer, selector, resultSelector, source) {
this.i = 0;
this.selector = selector;
this.resultSelector = resultSelector;
this.source = source;
this.o = observer;
AbstractObserver.call(this);
}
InnerObserver.prototype._wrapResult = function(result, x, i) {
return this.resultSelector ?
result.map(function(y, i2) { return this.resultSelector(x, y, i, i2); }, this) :
result;
};
InnerObserver.prototype.next = function(x) {
var i = this.i++;
var result = tryCatch(this.selector)(x, i, this.source);
if (result === errorObj) { return this.o.onError(result.e); }
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = Observable.from(result));
this.o.onNext(this._wrapResult(result, x, i));
};
InnerObserver.prototype.error = function(e) { this.o.onError(e); };
InnerObserver.prototype.completed = function() { this.o.onCompleted(); };
return FlatMapObservable;
}(ObservableBase));
var Enumerable = Rx.internals.Enumerable = function () { };
function IsDisposedDisposable(state) {
this._s = state;
this.isDisposed = false;
}
IsDisposedDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
this._s.isDisposed = true;
}
};
var ConcatEnumerableObservable = (function(__super__) {
inherits(ConcatEnumerableObservable, __super__);
function ConcatEnumerableObservable(sources) {
this.sources = sources;
__super__.call(this);
}
function scheduleMethod(state, recurse) {
if (state.isDisposed) { return; }
var currentItem = tryCatch(state.e.next).call(state.e);
if (currentItem === errorObj) { return state.o.onError(currentItem.e); }
if (currentItem.done) { return state.o.onCompleted(); }
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
state.subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(new InnerObserver(state, recurse)));
}
ConcatEnumerableObservable.prototype.subscribeCore = function (o) {
var subscription = new SerialDisposable();
var state = {
isDisposed: false,
o: o,
subscription: subscription,
e: this.sources[$iterator$]()
};
var cancelable = currentThreadScheduler.scheduleRecursive(state, scheduleMethod);
return new NAryDisposable([subscription, cancelable, new IsDisposedDisposable(state)]);
};
function InnerObserver(state, recurse) {
this._state = state;
this._recurse = recurse;
AbstractObserver.call(this);
}
inherits(InnerObserver, AbstractObserver);
InnerObserver.prototype.next = function (x) { this._state.o.onNext(x); };
InnerObserver.prototype.error = function (e) { this._state.o.onError(e); };
InnerObserver.prototype.completed = function () { this._recurse(this._state); };
return ConcatEnumerableObservable;
}(ObservableBase));
Enumerable.prototype.concat = function () {
return new ConcatEnumerableObservable(this);
};
var CatchErrorObservable = (function(__super__) {
function CatchErrorObservable(sources) {
this.sources = sources;
__super__.call(this);
}
inherits(CatchErrorObservable, __super__);
function scheduleMethod(state, recurse) {
if (state.isDisposed) { return; }
var currentItem = tryCatch(state.e.next).call(state.e);
if (currentItem === errorObj) { return state.o.onError(currentItem.e); }
if (currentItem.done) { return state.lastError !== null ? state.o.onError(state.lastError) : state.o.onCompleted(); }
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
state.subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(new InnerObserver(state, recurse)));
}
CatchErrorObservable.prototype.subscribeCore = function (o) {
var subscription = new SerialDisposable();
var state = {
isDisposed: false,
e: this.sources[$iterator$](),
subscription: subscription,
lastError: null,
o: o
};
var cancelable = currentThreadScheduler.scheduleRecursive(state, scheduleMethod);
return new NAryDisposable([subscription, cancelable, new IsDisposedDisposable(state)]);
};
function InnerObserver(state, recurse) {
this._state = state;
this._recurse = recurse;
AbstractObserver.call(this);
}
inherits(InnerObserver, AbstractObserver);
InnerObserver.prototype.next = function (x) { this._state.o.onNext(x); };
InnerObserver.prototype.error = function (e) { this._state.lastError = e; this._recurse(this._state); };
InnerObserver.prototype.completed = function () { this._state.o.onCompleted(); };
return CatchErrorObservable;
}(ObservableBase));
Enumerable.prototype.catchError = function () {
return new CatchErrorObservable(this);
};
var RepeatEnumerable = (function (__super__) {
inherits(RepeatEnumerable, __super__);
function RepeatEnumerable(v, c) {
this.v = v;
this.c = c == null ? -1 : c;
}
RepeatEnumerable.prototype[$iterator$] = function () {
return new RepeatEnumerator(this);
};
function RepeatEnumerator(p) {
this.v = p.v;
this.l = p.c;
}
RepeatEnumerator.prototype.next = function () {
if (this.l === 0) { return doneEnumerator; }
if (this.l > 0) { this.l--; }
return { done: false, value: this.v };
};
return RepeatEnumerable;
}(Enumerable));
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
return new RepeatEnumerable(value, repeatCount);
};
var OfEnumerable = (function(__super__) {
inherits(OfEnumerable, __super__);
function OfEnumerable(s, fn, thisArg) {
this.s = s;
this.fn = fn ? bindCallback(fn, thisArg, 3) : null;
}
OfEnumerable.prototype[$iterator$] = function () {
return new OfEnumerator(this);
};
function OfEnumerator(p) {
this.i = -1;
this.s = p.s;
this.l = this.s.length;
this.fn = p.fn;
}
OfEnumerator.prototype.next = function () {
return ++this.i < this.l ?
{ done: false, value: !this.fn ? this.s[this.i] : this.fn(this.s[this.i], this.i, this.s) } :
doneEnumerator;
};
return OfEnumerable;
}(Enumerable));
var enumerableOf = Enumerable.of = function (source, selector, thisArg) {
return new OfEnumerable(source, selector, thisArg);
};
var ObserveOnObservable = (function (__super__) {
inherits(ObserveOnObservable, __super__);
function ObserveOnObservable(source, s) {
this.source = source;
this._s = s;
__super__.call(this);
}
ObserveOnObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new ObserveOnObserver(this._s, o));
};
return ObserveOnObservable;
}(ObservableBase));
/**
* Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
*
* This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
* that require to be run on a scheduler, use subscribeOn.
*
* @param {Scheduler} scheduler Scheduler to notify observers on.
* @returns {Observable} The source sequence whose observations happen on the specified scheduler.
*/
observableProto.observeOn = function (scheduler) {
return new ObserveOnObservable(this, scheduler);
};
var SubscribeOnObservable = (function (__super__) {
inherits(SubscribeOnObservable, __super__);
function SubscribeOnObservable(source, s) {
this.source = source;
this._s = s;
__super__.call(this);
}
function scheduleMethod(scheduler, state) {
var source = state[0], d = state[1], o = state[2];
d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(o)));
}
SubscribeOnObservable.prototype.subscribeCore = function (o) {
var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
d.setDisposable(m);
m.setDisposable(this._s.schedule([this.source, d, o], scheduleMethod));
return d;
};
return SubscribeOnObservable;
}(ObservableBase));
/**
* Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
* see the remarks section for more information on the distinction between subscribeOn and observeOn.
* This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
* callbacks on a scheduler, use observeOn.
* @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
* @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribeOn = function (scheduler) {
return new SubscribeOnObservable(this, scheduler);
};
var FromPromiseObservable = (function(__super__) {
inherits(FromPromiseObservable, __super__);
function FromPromiseObservable(p, s) {
this._p = p;
this._s = s;
__super__.call(this);
}
function scheduleNext(s, state) {
var o = state[0], data = state[1];
o.onNext(data);
o.onCompleted();
}
function scheduleError(s, state) {
var o = state[0], err = state[1];
o.onError(err);
}
FromPromiseObservable.prototype.subscribeCore = function(o) {
var sad = new SingleAssignmentDisposable(), self = this, p = this._p;
if (isFunction(p)) {
p = tryCatch(p)();
if (p === errorObj) {
o.onError(p.e);
return sad;
}
}
p
.then(function (data) {
sad.setDisposable(self._s.schedule([o, data], scheduleNext));
}, function (err) {
sad.setDisposable(self._s.schedule([o, err], scheduleError));
});
return sad;
};
return FromPromiseObservable;
}(ObservableBase));
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise, scheduler) {
scheduler || (scheduler = defaultScheduler);
return new FromPromiseObservable(promise, scheduler);
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); }
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value;
source.subscribe(function (v) {
value = v;
}, reject, function () {
resolve(value);
});
});
};
var ToArrayObservable = (function(__super__) {
inherits(ToArrayObservable, __super__);
function ToArrayObservable(source) {
this.source = source;
__super__.call(this);
}
ToArrayObservable.prototype.subscribeCore = function(o) {
return this.source.subscribe(new InnerObserver(o));
};
inherits(InnerObserver, AbstractObserver);
function InnerObserver(o) {
this.o = o;
this.a = [];
AbstractObserver.call(this);
}
InnerObserver.prototype.next = function (x) { this.a.push(x); };
InnerObserver.prototype.error = function (e) { this.o.onError(e); };
InnerObserver.prototype.completed = function () { this.o.onNext(this.a); this.o.onCompleted(); };
return ToArrayObservable;
}(ObservableBase));
/**
* Creates an array from an observable sequence.
* @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
return new ToArrayObservable(this);
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = function (subscribe, parent) {
return new AnonymousObservable(subscribe, parent);
};
var Defer = (function(__super__) {
inherits(Defer, __super__);
function Defer(factory) {
this._f = factory;
__super__.call(this);
}
Defer.prototype.subscribeCore = function (o) {
var result = tryCatch(this._f)();
if (result === errorObj) { return observableThrow(result.e).subscribe(o);}
isPromise(result) && (result = observableFromPromise(result));
return result.subscribe(o);
};
return Defer;
}(ObservableBase));
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new Defer(observableFactory);
};
var EmptyObservable = (function(__super__) {
inherits(EmptyObservable, __super__);
function EmptyObservable(scheduler) {
this.scheduler = scheduler;
__super__.call(this);
}
EmptyObservable.prototype.subscribeCore = function (observer) {
var sink = new EmptySink(observer, this.scheduler);
return sink.run();
};
function EmptySink(observer, scheduler) {
this.observer = observer;
this.scheduler = scheduler;
}
function scheduleItem(s, state) {
state.onCompleted();
return disposableEmpty;
}
EmptySink.prototype.run = function () {
var state = this.observer;
return this.scheduler === immediateScheduler ?
scheduleItem(null, state) :
this.scheduler.schedule(state, scheduleItem);
};
return EmptyObservable;
}(ObservableBase));
var EMPTY_OBSERVABLE = new EmptyObservable(immediateScheduler);
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return scheduler === immediateScheduler ? EMPTY_OBSERVABLE : new EmptyObservable(scheduler);
};
var FromObservable = (function(__super__) {
inherits(FromObservable, __super__);
function FromObservable(iterable, fn, scheduler) {
this._iterable = iterable;
this._fn = fn;
this._scheduler = scheduler;
__super__.call(this);
}
function createScheduleMethod(o, it, fn) {
return function loopRecursive(i, recurse) {
var next = tryCatch(it.next).call(it);
if (next === errorObj) { return o.onError(next.e); }
if (next.done) { return o.onCompleted(); }
var result = next.value;
if (isFunction(fn)) {
result = tryCatch(fn)(result, i);
if (result === errorObj) { return o.onError(result.e); }
}
o.onNext(result);
recurse(i + 1);
};
}
FromObservable.prototype.subscribeCore = function (o) {
var list = Object(this._iterable),
it = getIterable(list);
return this._scheduler.scheduleRecursive(0, createScheduleMethod(o, it, this._fn));
};
return FromObservable;
}(ObservableBase));
var maxSafeInteger = Math.pow(2, 53) - 1;
function StringIterable(s) {
this._s = s;
}
StringIterable.prototype[$iterator$] = function () {
return new StringIterator(this._s);
};
function StringIterator(s) {
this._s = s;
this._l = s.length;
this._i = 0;
}
StringIterator.prototype[$iterator$] = function () {
return this;
};
StringIterator.prototype.next = function () {
return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator;
};
function ArrayIterable(a) {
this._a = a;
}
ArrayIterable.prototype[$iterator$] = function () {
return new ArrayIterator(this._a);
};
function ArrayIterator(a) {
this._a = a;
this._l = toLength(a);
this._i = 0;
}
ArrayIterator.prototype[$iterator$] = function () {
return this;
};
ArrayIterator.prototype.next = function () {
return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator;
};
function numberIsFinite(value) {
return typeof value === 'number' && root.isFinite(value);
}
function isNan(n) {
return n !== n;
}
function getIterable(o) {
var i = o[$iterator$], it;
if (!i && typeof o === 'string') {
it = new StringIterable(o);
return it[$iterator$]();
}
if (!i && o.length !== undefined) {
it = new ArrayIterable(o);
return it[$iterator$]();
}
if (!i) { throw new TypeError('Object is not iterable'); }
return o[$iterator$]();
}
function sign(value) {
var number = +value;
if (number === 0) { return number; }
if (isNaN(number)) { return number; }
return number < 0 ? -1 : 1;
}
function toLength(o) {
var len = +o.length;
if (isNaN(len)) { return 0; }
if (len === 0 || !numberIsFinite(len)) { return len; }
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) { return 0; }
if (len > maxSafeInteger) { return maxSafeInteger; }
return len;
}
/**
* This method creates a new Observable sequence from an array-like or iterable object.
* @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
* @param {Function} [mapFn] Map function to call on every element of the array.
* @param {Any} [thisArg] The context to use calling the mapFn if provided.
* @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
*/
var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) {
if (iterable == null) {
throw new Error('iterable cannot be null.')
}
if (mapFn && !isFunction(mapFn)) {
throw new Error('mapFn when provided must be a function');
}
if (mapFn) {
var mapper = bindCallback(mapFn, thisArg, 2);
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromObservable(iterable, mapper, scheduler);
}
var FromArrayObservable = (function(__super__) {
inherits(FromArrayObservable, __super__);
function FromArrayObservable(args, scheduler) {
this._args = args;
this._scheduler = scheduler;
__super__.call(this);
}
function scheduleMethod(o, args) {
var len = args.length;
return function loopRecursive (i, recurse) {
if (i < len) {
o.onNext(args[i]);
recurse(i + 1);
} else {
o.onCompleted();
}
};
}
FromArrayObservable.prototype.subscribeCore = function (o) {
return this._scheduler.scheduleRecursive(0, scheduleMethod(o, this._args));
};
return FromArrayObservable;
}(ObservableBase));
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
* @deprecated use Observable.from or Observable.of
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromArrayObservable(array, scheduler)
};
var GenerateObservable = (function (__super__) {
inherits(GenerateObservable, __super__);
function GenerateObservable(state, cndFn, itrFn, resFn, s) {
this._initialState = state;
this._cndFn = cndFn;
this._itrFn = itrFn;
this._resFn = resFn;
this._s = s;
__super__.call(this);
}
function scheduleRecursive(state, recurse) {
if (state.first) {
state.first = false;
} else {
state.newState = tryCatch(state.self._itrFn)(state.newState);
if (state.newState === errorObj) { return state.o.onError(state.newState.e); }
}
var hasResult = tryCatch(state.self._cndFn)(state.newState);
if (hasResult === errorObj) { return state.o.onError(hasResult.e); }
if (hasResult) {
var result = tryCatch(state.self._resFn)(state.newState);
if (result === errorObj) { return state.o.onError(result.e); }
state.o.onNext(result);
recurse(state);
} else {
state.o.onCompleted();
}
}
GenerateObservable.prototype.subscribeCore = function (o) {
var state = {
o: o,
self: this,
first: true,
newState: this._initialState
};
return this._s.scheduleRecursive(state, scheduleRecursive);
};
return GenerateObservable;
}(ObservableBase));
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new GenerateObservable(initialState, condition, iterate, resultSelector, scheduler);
};
function observableOf (scheduler, array) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromArrayObservable(array, scheduler);
}
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return new FromArrayObservable(args, currentThreadScheduler);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.ofWithScheduler = function (scheduler) {
var len = arguments.length, args = new Array(len - 1);
for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; }
return new FromArrayObservable(args, scheduler);
};
var NeverObservable = (function(__super__) {
inherits(NeverObservable, __super__);
function NeverObservable() {
__super__.call(this);
}
NeverObservable.prototype.subscribeCore = function (observer) {
return disposableEmpty;
};
return NeverObservable;
}(ObservableBase));
var NEVER_OBSERVABLE = new NeverObservable();
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return NEVER_OBSERVABLE;
};
var PairsObservable = (function(__super__) {
inherits(PairsObservable, __super__);
function PairsObservable(o, scheduler) {
this._o = o;
this._keys = Object.keys(o);
this._scheduler = scheduler;
__super__.call(this);
}
function scheduleMethod(o, obj, keys) {
return function loopRecursive(i, recurse) {
if (i < keys.length) {
var key = keys[i];
o.onNext([key, obj[key]]);
recurse(i + 1);
} else {
o.onCompleted();
}
};
}
PairsObservable.prototype.subscribeCore = function (o) {
return this._scheduler.scheduleRecursive(0, scheduleMethod(o, this._o, this._keys));
};
return PairsObservable;
}(ObservableBase));
/**
* Convert an object into an observable sequence of [key, value] pairs.
* @param {Object} obj The object to inspect.
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} An observable sequence of [key, value] pairs from the object.
*/
Observable.pairs = function (obj, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new PairsObservable(obj, scheduler);
};
var RangeObservable = (function(__super__) {
inherits(RangeObservable, __super__);
function RangeObservable(start, count, scheduler) {
this.start = start;
this.rangeCount = count;
this.scheduler = scheduler;
__super__.call(this);
}
function loopRecursive(start, count, o) {
return function loop (i, recurse) {
if (i < count) {
o.onNext(start + i);
recurse(i + 1);
} else {
o.onCompleted();
}
};
}
RangeObservable.prototype.subscribeCore = function (o) {
return this.scheduler.scheduleRecursive(
0,
loopRecursive(this.start, this.rangeCount, o)
);
};
return RangeObservable;
}(ObservableBase));
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new RangeObservable(start, count, scheduler);
};
var RepeatObservable = (function(__super__) {
inherits(RepeatObservable, __super__);
function RepeatObservable(value, repeatCount, scheduler) {
this.value = value;
this.repeatCount = repeatCount == null ? -1 : repeatCount;
this.scheduler = scheduler;
__super__.call(this);
}
RepeatObservable.prototype.subscribeCore = function (observer) {
var sink = new RepeatSink(observer, this);
return sink.run();
};
return RepeatObservable;
}(ObservableBase));
function RepeatSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
RepeatSink.prototype.run = function () {
var observer = this.observer, value = this.parent.value;
function loopRecursive(i, recurse) {
if (i === -1 || i > 0) {
observer.onNext(value);
i > 0 && i--;
}
if (i === 0) { return observer.onCompleted(); }
recurse(i);
}
return this.parent.scheduler.scheduleRecursive(this.parent.repeatCount, loopRecursive);
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new RepeatObservable(value, repeatCount, scheduler);
};
var JustObservable = (function(__super__) {
inherits(JustObservable, __super__);
function JustObservable(value, scheduler) {
this._value = value;
this._scheduler = scheduler;
__super__.call(this);
}
JustObservable.prototype.subscribeCore = function (o) {
var state = [this._value, o];
return this._scheduler === immediateScheduler ?
scheduleItem(null, state) :
this._scheduler.schedule(state, scheduleItem);
};
function scheduleItem(s, state) {
var value = state[0], observer = state[1];
observer.onNext(value);
observer.onCompleted();
return disposableEmpty;
}
return JustObservable;
}(ObservableBase));
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'just' or browsers <IE9.
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.just = function (value, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new JustObservable(value, scheduler);
};
var ThrowObservable = (function(__super__) {
inherits(ThrowObservable, __super__);
function ThrowObservable(error, scheduler) {
this._error = error;
this._scheduler = scheduler;
__super__.call(this);
}
ThrowObservable.prototype.subscribeCore = function (o) {
var state = [this._error, o];
return this._scheduler === immediateScheduler ?
scheduleItem(null, state) :
this._scheduler.schedule(state, scheduleItem);
};
function scheduleItem(s, state) {
var e = state[0], o = state[1];
o.onError(e);
return disposableEmpty;
}
return ThrowObservable;
}(ObservableBase));
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwError' for browsers <IE9.
* @param {Mixed} error An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = function (error, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new ThrowObservable(error, scheduler);
};
var UsingObservable = (function (__super__) {
inherits(UsingObservable, __super__);
function UsingObservable(resFn, obsFn) {
this._resFn = resFn;
this._obsFn = obsFn;
__super__.call(this);
}
UsingObservable.prototype.subscribeCore = function (o) {
var disposable = disposableEmpty;
var resource = tryCatch(this._resFn)();
if (resource === errorObj) {
return new BinaryDisposable(observableThrow(resource.e).subscribe(o), disposable);
}
resource && (disposable = resource);
var source = tryCatch(this._obsFn)(resource);
if (source === errorObj) {
return new BinaryDisposable(observableThrow(source.e).subscribe(o), disposable);
}
return new BinaryDisposable(source.subscribe(o), disposable);
};
return UsingObservable;
}(ObservableBase));
/**
* Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
* @param {Function} resourceFactory Factory function to obtain a resource object.
* @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
* @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
Observable.using = function (resourceFactory, observableFactory) {
return new UsingObservable(resourceFactory, observableFactory);
};
/**
* Propagates the observable sequence or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
observableProto.amb = function (rightSource) {
var leftSource = this;
return new AnonymousObservable(function (observer) {
var choice,
leftChoice = 'L', rightChoice = 'R',
leftSubscription = new SingleAssignmentDisposable(),
rightSubscription = new SingleAssignmentDisposable();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
function choiceL() {
if (!choice) {
choice = leftChoice;
rightSubscription.dispose();
}
}
function choiceR() {
if (!choice) {
choice = rightChoice;
leftSubscription.dispose();
}
}
var leftSubscribe = observerCreate(
function (left) {
choiceL();
choice === leftChoice && observer.onNext(left);
},
function (e) {
choiceL();
choice === leftChoice && observer.onError(e);
},
function () {
choiceL();
choice === leftChoice && observer.onCompleted();
}
);
var rightSubscribe = observerCreate(
function (right) {
choiceR();
choice === rightChoice && observer.onNext(right);
},
function (e) {
choiceR();
choice === rightChoice && observer.onError(e);
},
function () {
choiceR();
choice === rightChoice && observer.onCompleted();
}
);
leftSubscription.setDisposable(leftSource.subscribe(leftSubscribe));
rightSubscription.setDisposable(rightSource.subscribe(rightSubscribe));
return new BinaryDisposable(leftSubscription, rightSubscription);
});
};
function amb(p, c) { return p.amb(c); }
/**
* Propagates the observable sequence or Promise that reacts first.
* @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
Observable.amb = function () {
var acc = observableNever(), items;
if (Array.isArray(arguments[0])) {
items = arguments[0];
} else {
var len = arguments.length;
items = new Array(items);
for(var i = 0; i < len; i++) { items[i] = arguments[i]; }
}
for (var i = 0, len = items.length; i < len; i++) {
acc = amb(acc, items[i]);
}
return acc;
};
var CatchObservable = (function (__super__) {
inherits(CatchObservable, __super__);
function CatchObservable(source, fn) {
this.source = source;
this._fn = fn;
__super__.call(this);
}
CatchObservable.prototype.subscribeCore = function (o) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(this.source.subscribe(new CatchObserver(o, subscription, this._fn)));
return subscription;
};
return CatchObservable;
}(ObservableBase));
var CatchObserver = (function(__super__) {
inherits(CatchObserver, __super__);
function CatchObserver(o, s, fn) {
this._o = o;
this._s = s;
this._fn = fn;
__super__.call(this);
}
CatchObserver.prototype.next = function (x) { this._o.onNext(x); };
CatchObserver.prototype.completed = function () { return this._o.onCompleted(); };
CatchObserver.prototype.error = function (e) {
var result = tryCatch(this._fn)(e);
if (result === errorObj) { return this._o.onError(result.e); }
isPromise(result) && (result = observableFromPromise(result));
var d = new SingleAssignmentDisposable();
this._s.setDisposable(d);
d.setDisposable(result.subscribe(this._o));
};
return CatchObserver;
}(AbstractObserver));
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = function (handlerOrSecond) {
return isFunction(handlerOrSecond) ? new CatchObservable(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs.
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable['catch'] = function () {
var items;
if (Array.isArray(arguments[0])) {
items = arguments[0];
} else {
var len = arguments.length;
items = new Array(len);
for(var i = 0; i < len; i++) { items[i] = arguments[i]; }
}
return enumerableOf(items).catchError();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
function falseFactory() { return false; }
function argumentsToArray() {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return args;
}
var CombineLatestObservable = (function(__super__) {
inherits(CombineLatestObservable, __super__);
function CombineLatestObservable(params, cb) {
this._params = params;
this._cb = cb;
__super__.call(this);
}
CombineLatestObservable.prototype.subscribeCore = function(observer) {
var len = this._params.length,
subscriptions = new Array(len);
var state = {
hasValue: arrayInitialize(len, falseFactory),
hasValueAll: false,
isDone: arrayInitialize(len, falseFactory),
values: new Array(len)
};
for (var i = 0; i < len; i++) {
var source = this._params[i], sad = new SingleAssignmentDisposable();
subscriptions[i] = sad;
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(new CombineLatestObserver(observer, i, this._cb, state)));
}
return new NAryDisposable(subscriptions);
};
return CombineLatestObservable;
}(ObservableBase));
var CombineLatestObserver = (function (__super__) {
inherits(CombineLatestObserver, __super__);
function CombineLatestObserver(o, i, cb, state) {
this._o = o;
this._i = i;
this._cb = cb;
this._state = state;
__super__.call(this);
}
function notTheSame(i) {
return function (x, j) {
return j !== i;
};
}
CombineLatestObserver.prototype.next = function (x) {
this._state.values[this._i] = x;
this._state.hasValue[this._i] = true;
if (this._state.hasValueAll || (this._state.hasValueAll = this._state.hasValue.every(identity))) {
var res = tryCatch(this._cb).apply(null, this._state.values);
if (res === errorObj) { return this._o.onError(res.e); }
this._o.onNext(res);
} else if (this._state.isDone.filter(notTheSame(this._i)).every(identity)) {
this._o.onCompleted();
}
};
CombineLatestObserver.prototype.error = function (e) {
this._o.onError(e);
};
CombineLatestObserver.prototype.completed = function () {
this._state.isDone[this._i] = true;
this._state.isDone.every(identity) && this._o.onCompleted();
};
return CombineLatestObserver;
}(AbstractObserver));
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
Array.isArray(args[0]) && (args = args[0]);
return new CombineLatestObservable(args, resultSelector);
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
args.unshift(this);
return observableConcat.apply(null, args);
};
var ConcatObserver = (function(__super__) {
inherits(ConcatObserver, __super__);
function ConcatObserver(s, fn) {
this._s = s;
this._fn = fn;
__super__.call(this);
}
ConcatObserver.prototype.next = function (x) { this._s.o.onNext(x); };
ConcatObserver.prototype.error = function (e) { this._s.o.onError(e); };
ConcatObserver.prototype.completed = function () { this._s.i++; this._fn(this._s); };
return ConcatObserver;
}(AbstractObserver));
var ConcatObservable = (function(__super__) {
inherits(ConcatObservable, __super__);
function ConcatObservable(sources) {
this._sources = sources;
__super__.call(this);
}
function scheduleRecursive (state, recurse) {
if (state.disposable.isDisposed) { return; }
if (state.i === state.sources.length) { return state.o.onCompleted(); }
// Check if promise
var currentValue = state.sources[state.i];
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
state.subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(new ConcatObserver(state, recurse)));
}
ConcatObservable.prototype.subscribeCore = function(o) {
var subscription = new SerialDisposable();
var disposable = disposableCreate(noop);
var state = {
o: o,
i: 0,
subscription: subscription,
disposable: disposable,
sources: this._sources
};
var cancelable = immediateScheduler.scheduleRecursive(state, scheduleRecursive);
return new NAryDisposable([subscription, disposable, cancelable]);
};
return ConcatObservable;
}(ObservableBase));
/**
* Concatenates all the observable sequences.
* @param {Array | Arguments} args Arguments or an array to concat to the observable sequence.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
args = new Array(arguments.length);
for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; }
}
return new ConcatObservable(args);
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatAll = function () {
return this.merge(1);
};
var MergeObservable = (function (__super__) {
inherits(MergeObservable, __super__);
function MergeObservable(source, maxConcurrent) {
this.source = source;
this.maxConcurrent = maxConcurrent;
__super__.call(this);
}
MergeObservable.prototype.subscribeCore = function(observer) {
var g = new CompositeDisposable();
g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g)));
return g;
};
return MergeObservable;
}(ObservableBase));
var MergeObserver = (function (__super__) {
function MergeObserver(o, max, g) {
this.o = o;
this.max = max;
this.g = g;
this.done = false;
this.q = [];
this.activeCount = 0;
__super__.call(this);
}
inherits(MergeObserver, __super__);
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.next = function (innerSource) {
if(this.activeCount < this.max) {
this.activeCount++;
this.handleSubscribe(innerSource);
} else {
this.q.push(innerSource);
}
};
MergeObserver.prototype.error = function (e) { this.o.onError(e); };
MergeObserver.prototype.completed = function () { this.done = true; this.activeCount === 0 && this.o.onCompleted(); };
function InnerObserver(parent, sad) {
this.parent = parent;
this.sad = sad;
__super__.call(this);
}
inherits(InnerObserver, __super__);
InnerObserver.prototype.next = function (x) { this.parent.o.onNext(x); };
InnerObserver.prototype.error = function (e) { this.parent.o.onError(e); };
InnerObserver.prototype.completed = function () {
this.parent.g.remove(this.sad);
if (this.parent.q.length > 0) {
this.parent.handleSubscribe(this.parent.q.shift());
} else {
this.parent.activeCount--;
this.parent.done && this.parent.activeCount === 0 && this.parent.o.onCompleted();
}
};
return MergeObserver;
}(AbstractObserver));
/**
* 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.
* @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 (o) {
var g = new CompositeDisposable(), m = new SingleAssignmentDisposable();
g.add(m);
m.setDisposable(this.source.subscribe(new MergeAllObserver(o, g)));
return g;
};
return MergeAllObservable;
}(ObservableBase));
var MergeAllObserver = (function (__super__) {
function MergeAllObserver(o, g) {
this.o = o;
this.g = g;
this.done = false;
__super__.call(this);
}
inherits(MergeAllObserver, __super__);
MergeAllObserver.prototype.next = function(innerSource) {
var sad = new SingleAssignmentDisposable();
this.g.add(sad);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
sad.setDisposable(innerSource.subscribe(new InnerObserver(this, sad)));
};
MergeAllObserver.prototype.error = function (e) {
this.o.onError(e);
};
MergeAllObserver.prototype.completed = function () {
this.done = true;
this.g.length === 1 && this.o.onCompleted();
};
function InnerObserver(parent, sad) {
this.parent = parent;
this.sad = sad;
__super__.call(this);
}
inherits(InnerObserver, __super__);
InnerObserver.prototype.next = function (x) {
this.parent.o.onNext(x);
};
InnerObserver.prototype.error = function (e) {
this.parent.o.onError(e);
};
InnerObserver.prototype.completed = function () {
this.parent.g.remove(this.sad);
this.parent.done && this.parent.g.length === 1 && this.parent.o.onCompleted();
};
return MergeAllObserver;
}(AbstractObserver));
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeAll = function () {
return new MergeAllObservable(this);
};
var CompositeError = Rx.CompositeError = function(errors) {
this.innerErrors = errors;
this.message = 'This contains multiple errors. Check the innerErrors';
Error.call(this);
};
CompositeError.prototype = Object.create(Error.prototype);
CompositeError.prototype.name = 'CompositeError';
var MergeDelayErrorObservable = (function(__super__) {
inherits(MergeDelayErrorObservable, __super__);
function MergeDelayErrorObservable(source) {
this.source = source;
__super__.call(this);
}
MergeDelayErrorObservable.prototype.subscribeCore = function (o) {
var group = new CompositeDisposable(),
m = new SingleAssignmentDisposable(),
state = { isStopped: false, errors: [], o: o };
group.add(m);
m.setDisposable(this.source.subscribe(new MergeDelayErrorObserver(group, state)));
return group;
};
return MergeDelayErrorObservable;
}(ObservableBase));
var MergeDelayErrorObserver = (function(__super__) {
inherits(MergeDelayErrorObserver, __super__);
function MergeDelayErrorObserver(group, state) {
this._group = group;
this._state = state;
__super__.call(this);
}
function setCompletion(o, errors) {
if (errors.length === 0) {
o.onCompleted();
} else if (errors.length === 1) {
o.onError(errors[0]);
} else {
o.onError(new CompositeError(errors));
}
}
MergeDelayErrorObserver.prototype.next = function (x) {
var inner = new SingleAssignmentDisposable();
this._group.add(inner);
// Check for promises support
isPromise(x) && (x = observableFromPromise(x));
inner.setDisposable(x.subscribe(new InnerObserver(inner, this._group, this._state)));
};
MergeDelayErrorObserver.prototype.error = function (e) {
this._state.errors.push(e);
this._state.isStopped = true;
this._group.length === 1 && setCompletion(this._state.o, this._state.errors);
};
MergeDelayErrorObserver.prototype.completed = function () {
this._state.isStopped = true;
this._group.length === 1 && setCompletion(this._state.o, this._state.errors);
};
inherits(InnerObserver, __super__);
function InnerObserver(inner, group, state) {
this._inner = inner;
this._group = group;
this._state = state;
__super__.call(this);
}
InnerObserver.prototype.next = function (x) { this._state.o.onNext(x); };
InnerObserver.prototype.error = function (e) {
this._state.errors.push(e);
this._group.remove(this._inner);
this._state.isStopped && this._group.length === 1 && setCompletion(this._state.o, this._state.errors);
};
InnerObserver.prototype.completed = function () {
this._group.remove(this._inner);
this._state.isStopped && this._group.length === 1 && setCompletion(this._state.o, this._state.errors);
};
return MergeDelayErrorObserver;
}(AbstractObserver));
/**
* 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 MergeDelayErrorObservable(source);
};
/**
* 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]);
};
var OnErrorResumeNextObservable = (function(__super__) {
inherits(OnErrorResumeNextObservable, __super__);
function OnErrorResumeNextObservable(sources) {
this.sources = sources;
__super__.call(this);
}
function scheduleMethod(state, recurse) {
if (state.pos < state.sources.length) {
var current = state.sources[state.pos++];
isPromise(current) && (current = observableFromPromise(current));
var d = new SingleAssignmentDisposable();
state.subscription.setDisposable(d);
d.setDisposable(current.subscribe(new OnErrorResumeNextObserver(state, recurse)));
} else {
state.o.onCompleted();
}
}
OnErrorResumeNextObservable.prototype.subscribeCore = function (o) {
var subscription = new SerialDisposable(),
state = {pos: 0, subscription: subscription, o: o, sources: this.sources },
cancellable = immediateScheduler.scheduleRecursive(state, scheduleMethod);
return new BinaryDisposable(subscription, cancellable);
};
return OnErrorResumeNextObservable;
}(ObservableBase));
var OnErrorResumeNextObserver = (function(__super__) {
inherits(OnErrorResumeNextObserver, __super__);
function OnErrorResumeNextObserver(state, recurse) {
this._state = state;
this._recurse = recurse;
__super__.call(this);
}
OnErrorResumeNextObserver.prototype.next = function (x) { this._state.o.onNext(x); };
OnErrorResumeNextObserver.prototype.error = function () { this._recurse(this._state); };
OnErrorResumeNextObserver.prototype.completed = function () { this._recurse(this._state); };
return OnErrorResumeNextObserver;
}(AbstractObserver));
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
* @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 {
var len = arguments.length;
sources = new Array(len);
for(var i = 0; i < len; i++) { sources[i] = arguments[i]; }
}
return new OnErrorResumeNextObservable(sources);
};
var SkipUntilObservable = (function(__super__) {
inherits(SkipUntilObservable, __super__);
function SkipUntilObservable(source, other) {
this._s = source;
this._o = isPromise(other) ? observableFromPromise(other) : other;
this._open = false;
__super__.call(this);
}
SkipUntilObservable.prototype.subscribeCore = function(o) {
var leftSubscription = new SingleAssignmentDisposable();
leftSubscription.setDisposable(this._s.subscribe(new SkipUntilSourceObserver(o, this)));
isPromise(this._o) && (this._o = observableFromPromise(this._o));
var rightSubscription = new SingleAssignmentDisposable();
rightSubscription.setDisposable(this._o.subscribe(new SkipUntilOtherObserver(o, this, rightSubscription)));
return new BinaryDisposable(leftSubscription, rightSubscription);
};
return SkipUntilObservable;
}(ObservableBase));
var SkipUntilSourceObserver = (function(__super__) {
inherits(SkipUntilSourceObserver, __super__);
function SkipUntilSourceObserver(o, p) {
this._o = o;
this._p = p;
__super__.call(this);
}
SkipUntilSourceObserver.prototype.next = function (x) {
this._p._open && this._o.onNext(x);
};
SkipUntilSourceObserver.prototype.error = function (err) {
this._o.onError(err);
};
SkipUntilSourceObserver.prototype.onCompleted = function () {
this._p._open && this._o.onCompleted();
};
return SkipUntilSourceObserver;
}(AbstractObserver));
var SkipUntilOtherObserver = (function(__super__) {
inherits(SkipUntilOtherObserver, __super__);
function SkipUntilOtherObserver(o, p, r) {
this._o = o;
this._p = p;
this._r = r;
__super__.call(this);
}
SkipUntilOtherObserver.prototype.next = function () {
this._p._open = true;
this._r.dispose();
};
SkipUntilOtherObserver.prototype.error = function (err) {
this._o.onError(err);
};
SkipUntilOtherObserver.prototype.onCompleted = function () {
this._r.dispose();
};
return SkipUntilOtherObserver;
}(AbstractObserver));
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
return new SkipUntilObservable(this, other);
};
var SwitchObservable = (function(__super__) {
inherits(SwitchObservable, __super__);
function SwitchObservable(source) {
this.source = source;
__super__.call(this);
}
SwitchObservable.prototype.subscribeCore = function (o) {
var inner = new SerialDisposable(), s = this.source.subscribe(new SwitchObserver(o, inner));
return new BinaryDisposable(s, inner);
};
inherits(SwitchObserver, AbstractObserver);
function SwitchObserver(o, inner) {
this.o = o;
this.inner = inner;
this.stopped = false;
this.latest = 0;
this.hasLatest = false;
AbstractObserver.call(this);
}
SwitchObserver.prototype.next = function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++this.latest;
this.hasLatest = true;
this.inner.setDisposable(d);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
d.setDisposable(innerSource.subscribe(new InnerObserver(this, id)));
};
SwitchObserver.prototype.error = function (e) {
this.o.onError(e);
};
SwitchObserver.prototype.completed = function () {
this.stopped = true;
!this.hasLatest && this.o.onCompleted();
};
inherits(InnerObserver, AbstractObserver);
function InnerObserver(parent, id) {
this.parent = parent;
this.id = id;
AbstractObserver.call(this);
}
InnerObserver.prototype.next = function (x) {
this.parent.latest === this.id && this.parent.o.onNext(x);
};
InnerObserver.prototype.error = function (e) {
this.parent.latest === this.id && this.parent.o.onError(e);
};
InnerObserver.prototype.completed = function () {
if (this.parent.latest === this.id) {
this.parent.hasLatest = false;
this.parent.stopped && this.parent.o.onCompleted();
}
};
return SwitchObservable;
}(ObservableBase));
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
return new SwitchObservable(this);
};
var TakeUntilObservable = (function(__super__) {
inherits(TakeUntilObservable, __super__);
function TakeUntilObservable(source, other) {
this.source = source;
this.other = isPromise(other) ? observableFromPromise(other) : other;
__super__.call(this);
}
TakeUntilObservable.prototype.subscribeCore = function(o) {
return new BinaryDisposable(
this.source.subscribe(o),
this.other.subscribe(new TakeUntilObserver(o))
);
};
return TakeUntilObservable;
}(ObservableBase));
var TakeUntilObserver = (function(__super__) {
inherits(TakeUntilObserver, __super__);
function TakeUntilObserver(o) {
this._o = o;
__super__.call(this);
}
TakeUntilObserver.prototype.next = function () {
this._o.onCompleted();
};
TakeUntilObserver.prototype.error = function (err) {
this._o.onError(err);
};
TakeUntilObserver.prototype.onCompleted = noop;
return TakeUntilObserver;
}(AbstractObserver));
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
return new TakeUntilObservable(this, other);
};
function falseFactory() { return false; }
function argumentsToArray() {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return args;
}
var WithLatestFromObservable = (function(__super__) {
inherits(WithLatestFromObservable, __super__);
function WithLatestFromObservable(source, sources, resultSelector) {
this._s = source;
this._ss = sources;
this._cb = resultSelector;
__super__.call(this);
}
WithLatestFromObservable.prototype.subscribeCore = function (o) {
var len = this._ss.length;
var state = {
hasValue: arrayInitialize(len, falseFactory),
hasValueAll: false,
values: new Array(len)
};
var n = this._ss.length, subscriptions = new Array(n + 1);
for (var i = 0; i < n; i++) {
var other = this._ss[i], sad = new SingleAssignmentDisposable();
isPromise(other) && (other = observableFromPromise(other));
sad.setDisposable(other.subscribe(new WithLatestFromOtherObserver(o, i, state)));
subscriptions[i] = sad;
}
var outerSad = new SingleAssignmentDisposable();
outerSad.setDisposable(this._s.subscribe(new WithLatestFromSourceObserver(o, this._cb, state)));
subscriptions[n] = outerSad;
return new NAryDisposable(subscriptions);
};
return WithLatestFromObservable;
}(ObservableBase));
var WithLatestFromOtherObserver = (function (__super__) {
inherits(WithLatestFromOtherObserver, __super__);
function WithLatestFromOtherObserver(o, i, state) {
this._o = o;
this._i = i;
this._state = state;
__super__.call(this);
}
WithLatestFromOtherObserver.prototype.next = function (x) {
this._state.values[this._i] = x;
this._state.hasValue[this._i] = true;
this._state.hasValueAll = this._state.hasValue.every(identity);
};
WithLatestFromOtherObserver.prototype.error = function (e) {
this._o.onError(e);
};
WithLatestFromOtherObserver.prototype.completed = noop;
return WithLatestFromOtherObserver;
}(AbstractObserver));
var WithLatestFromSourceObserver = (function (__super__) {
inherits(WithLatestFromSourceObserver, __super__);
function WithLatestFromSourceObserver(o, cb, state) {
this._o = o;
this._cb = cb;
this._state = state;
__super__.call(this);
}
WithLatestFromSourceObserver.prototype.next = function (x) {
var allValues = [x].concat(this._state.values);
if (!this._state.hasValueAll) { return; }
var res = tryCatch(this._cb).apply(null, allValues);
if (res === errorObj) { return this._o.onError(res.e); }
this._o.onNext(res);
};
WithLatestFromSourceObserver.prototype.error = function (e) {
this._o.onError(e);
};
WithLatestFromSourceObserver.prototype.completed = function () {
this._o.onCompleted();
};
return WithLatestFromSourceObserver;
}(AbstractObserver));
/**
* Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.withLatestFrom = function () {
if (arguments.length === 0) { throw new Error('invalid arguments'); }
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
Array.isArray(args[0]) && (args = args[0]);
return new WithLatestFromObservable(this, args, resultSelector);
};
function falseFactory() { return false; }
function emptyArrayFactory() { return []; }
var ZipObservable = (function(__super__) {
inherits(ZipObservable, __super__);
function ZipObservable(sources, resultSelector) {
this._s = sources;
this._cb = resultSelector;
__super__.call(this);
}
ZipObservable.prototype.subscribeCore = function(observer) {
var n = this._s.length,
subscriptions = new Array(n),
done = arrayInitialize(n, falseFactory),
q = arrayInitialize(n, emptyArrayFactory);
for (var i = 0; i < n; i++) {
var source = this._s[i], sad = new SingleAssignmentDisposable();
subscriptions[i] = sad;
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(new ZipObserver(observer, i, this, q, done)));
}
return new NAryDisposable(subscriptions);
};
return ZipObservable;
}(ObservableBase));
var ZipObserver = (function (__super__) {
inherits(ZipObserver, __super__);
function ZipObserver(o, i, p, q, d) {
this._o = o;
this._i = i;
this._p = p;
this._q = q;
this._d = d;
__super__.call(this);
}
function notEmpty(x) { return x.length > 0; }
function shiftEach(x) { return x.shift(); }
function notTheSame(i) {
return function (x, j) {
return j !== i;
};
}
ZipObserver.prototype.next = function (x) {
this._q[this._i].push(x);
if (this._q.every(notEmpty)) {
var queuedValues = this._q.map(shiftEach);
var res = tryCatch(this._p._cb).apply(null, queuedValues);
if (res === errorObj) { return this._o.onError(res.e); }
this._o.onNext(res);
} else if (this._d.filter(notTheSame(this._i)).every(identity)) {
this._o.onCompleted();
}
};
ZipObserver.prototype.error = function (e) {
this._o.onError(e);
};
ZipObserver.prototype.completed = function () {
this._d[this._i] = true;
this._d.every(identity) && this._o.onCompleted();
};
return ZipObserver;
}(AbstractObserver));
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.
* @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.
*/
observableProto.zip = function () {
if (arguments.length === 0) { throw new Error('invalid arguments'); }
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
Array.isArray(args[0]) && (args = args[0]);
var parent = this;
args.unshift(parent);
return new ZipObservable(args, resultSelector);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
if (Array.isArray(args[0])) {
args = isFunction(args[1]) ? args[0].concat(args[1]) : args[0];
}
var first = args.shift();
return first.zip.apply(first, args);
};
function falseFactory() { return false; }
function emptyArrayFactory() { return []; }
function argumentsToArray() {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return args;
}
var ZipIterableObservable = (function(__super__) {
inherits(ZipIterableObservable, __super__);
function ZipIterableObservable(sources, cb) {
this.sources = sources;
this._cb = cb;
__super__.call(this);
}
ZipIterableObservable.prototype.subscribeCore = function (o) {
var sources = this.sources, len = sources.length, subscriptions = new Array(len);
var state = {
q: arrayInitialize(len, emptyArrayFactory),
done: arrayInitialize(len, falseFactory),
cb: this._cb,
o: o
};
for (var i = 0; i < len; i++) {
(function (i) {
var source = sources[i], sad = new SingleAssignmentDisposable();
(isArrayLike(source) || isIterable(source)) && (source = observableFrom(source));
subscriptions[i] = sad;
sad.setDisposable(source.subscribe(new ZipIterableObserver(state, i)));
}(i));
}
return new NAryDisposable(subscriptions);
};
return ZipIterableObservable;
}(ObservableBase));
var ZipIterableObserver = (function (__super__) {
inherits(ZipIterableObserver, __super__);
function ZipIterableObserver(s, i) {
this._s = s;
this._i = i;
__super__.call(this);
}
function notEmpty(x) { return x.length > 0; }
function shiftEach(x) { return x.shift(); }
function notTheSame(i) {
return function (x, j) {
return j !== i;
};
}
ZipIterableObserver.prototype.next = function (x) {
this._s.q[this._i].push(x);
if (this._s.q.every(notEmpty)) {
var queuedValues = this._s.q.map(shiftEach),
res = tryCatch(this._s.cb).apply(null, queuedValues);
if (res === errorObj) { return this._s.o.onError(res.e); }
this._s.o.onNext(res);
} else if (this._s.done.filter(notTheSame(this._i)).every(identity)) {
this._s.o.onCompleted();
}
};
ZipIterableObserver.prototype.error = function (e) { this._s.o.onError(e); };
ZipIterableObserver.prototype.completed = function () {
this._s.done[this._i] = true;
this._s.done.every(identity) && this._s.o.onCompleted();
};
return ZipIterableObserver;
}(AbstractObserver));
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.
* @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.
*/
observableProto.zipIterable = function () {
if (arguments.length === 0) { throw new Error('invalid arguments'); }
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
var parent = this;
args.unshift(parent);
return new ZipIterableObservable(args, resultSelector);
};
function asObservable(source) {
return function subscribe(o) { return source.subscribe(o); };
}
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
return new AnonymousObservable(asObservable(this), this);
};
function toArray(x) { return x.toArray(); }
function notEmpty(x) { return x.length > 0; }
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
* @param {Number} count Length of each buffer.
* @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithCount = observableProto.bufferCount = function (count, skip) {
typeof skip !== 'number' && (skip = count);
return this.windowWithCount(count, skip)
.flatMap(toArray)
.filter(notEmpty);
};
var DematerializeObservable = (function (__super__) {
inherits(DematerializeObservable, __super__);
function DematerializeObservable(source) {
this.source = source;
__super__.call(this);
}
DematerializeObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new DematerializeObserver(o));
};
return DematerializeObservable;
}(ObservableBase));
var DematerializeObserver = (function (__super__) {
inherits(DematerializeObserver, __super__);
function DematerializeObserver(o) {
this._o = o;
__super__.call(this);
}
DematerializeObserver.prototype.next = function (x) { x.accept(this._o); };
DematerializeObserver.prototype.error = function (e) { this._o.onError(e); };
DematerializeObserver.prototype.completed = function () { this._o.onCompleted(); };
return DematerializeObserver;
}(AbstractObserver));
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
return new DematerializeObservable(this);
};
var DistinctUntilChangedObservable = (function(__super__) {
inherits(DistinctUntilChangedObservable, __super__);
function DistinctUntilChangedObservable(source, keyFn, comparer) {
this.source = source;
this.keyFn = keyFn;
this.comparer = comparer;
__super__.call(this);
}
DistinctUntilChangedObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new DistinctUntilChangedObserver(o, this.keyFn, this.comparer));
};
return DistinctUntilChangedObservable;
}(ObservableBase));
var DistinctUntilChangedObserver = (function(__super__) {
inherits(DistinctUntilChangedObserver, __super__);
function DistinctUntilChangedObserver(o, keyFn, comparer) {
this.o = o;
this.keyFn = keyFn;
this.comparer = comparer;
this.hasCurrentKey = false;
this.currentKey = null;
__super__.call(this);
}
DistinctUntilChangedObserver.prototype.next = function (x) {
var key = x, comparerEquals;
if (isFunction(this.keyFn)) {
key = tryCatch(this.keyFn)(x);
if (key === errorObj) { return this.o.onError(key.e); }
}
if (this.hasCurrentKey) {
comparerEquals = tryCatch(this.comparer)(this.currentKey, key);
if (comparerEquals === errorObj) { return this.o.onError(comparerEquals.e); }
}
if (!this.hasCurrentKey || !comparerEquals) {
this.hasCurrentKey = true;
this.currentKey = key;
this.o.onNext(x);
}
};
DistinctUntilChangedObserver.prototype.error = function(e) {
this.o.onError(e);
};
DistinctUntilChangedObserver.prototype.completed = function () {
this.o.onCompleted();
};
return DistinctUntilChangedObserver;
}(AbstractObserver));
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keyFn and the comparer.
* @param {Function} [keyFn] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keyFn, comparer) {
comparer || (comparer = defaultComparer);
return new DistinctUntilChangedObservable(this, keyFn, comparer);
};
var TapObservable = (function(__super__) {
inherits(TapObservable,__super__);
function TapObservable(source, observerOrOnNext, onError, onCompleted) {
this.source = source;
this._oN = observerOrOnNext;
this._oE = onError;
this._oC = onCompleted;
__super__.call(this);
}
TapObservable.prototype.subscribeCore = function(o) {
return this.source.subscribe(new InnerObserver(o, this));
};
inherits(InnerObserver, AbstractObserver);
function InnerObserver(o, p) {
this.o = o;
this.t = !p._oN || isFunction(p._oN) ?
observerCreate(p._oN || noop, p._oE || noop, p._oC || noop) :
p._oN;
this.isStopped = false;
AbstractObserver.call(this);
}
InnerObserver.prototype.next = function(x) {
var res = tryCatch(this.t.onNext).call(this.t, x);
if (res === errorObj) { this.o.onError(res.e); }
this.o.onNext(x);
};
InnerObserver.prototype.error = function(err) {
var res = tryCatch(this.t.onError).call(this.t, err);
if (res === errorObj) { return this.o.onError(res.e); }
this.o.onError(err);
};
InnerObserver.prototype.completed = function() {
var res = tryCatch(this.t.onCompleted).call(this.t);
if (res === errorObj) { return this.o.onError(res.e); }
this.o.onCompleted();
};
return TapObservable;
}(ObservableBase));
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an o.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
return new TapObservable(this, observerOrOnNext, onError, onCompleted);
};
/**
* Invokes an action for each element in the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onNext Action to invoke for each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) {
return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext);
};
/**
* Invokes an action upon exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onError Action to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) {
return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError);
};
/**
* Invokes an action upon graceful termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) {
return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted);
};
var FinallyObservable = (function (__super__) {
inherits(FinallyObservable, __super__);
function FinallyObservable(source, fn, thisArg) {
this.source = source;
this._fn = bindCallback(fn, thisArg, 0);
__super__.call(this);
}
FinallyObservable.prototype.subscribeCore = function (o) {
var d = tryCatch(this.source.subscribe).call(this.source, o);
if (d === errorObj) {
this._fn();
thrower(d.e);
}
return new FinallyDisposable(d, this._fn);
};
function FinallyDisposable(s, fn) {
this.isDisposed = false;
this._s = s;
this._fn = fn;
}
FinallyDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
var res = tryCatch(this._s.dispose).call(this._s);
this._fn();
res === errorObj && thrower(res.e);
}
};
return FinallyObservable;
}(ObservableBase));
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = function (action, thisArg) {
return new FinallyObservable(this, action, thisArg);
};
var IgnoreElementsObservable = (function(__super__) {
inherits(IgnoreElementsObservable, __super__);
function IgnoreElementsObservable(source) {
this.source = source;
__super__.call(this);
}
IgnoreElementsObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new InnerObserver(o));
};
function InnerObserver(o) {
this.o = o;
this.isStopped = false;
}
InnerObserver.prototype.onNext = noop;
InnerObserver.prototype.onError = function (err) {
if(!this.isStopped) {
this.isStopped = true;
this.o.onError(err);
}
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
this.isStopped = true;
this.o.onCompleted();
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
return IgnoreElementsObservable;
}(ObservableBase));
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
return new IgnoreElementsObservable(this);
};
var MaterializeObservable = (function (__super__) {
inherits(MaterializeObservable, __super__);
function MaterializeObservable(source, fn) {
this.source = source;
__super__.call(this);
}
MaterializeObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new MaterializeObserver(o));
};
return MaterializeObservable;
}(ObservableBase));
var MaterializeObserver = (function (__super__) {
inherits(MaterializeObserver, __super__);
function MaterializeObserver(o) {
this._o = o;
__super__.call(this);
}
MaterializeObserver.prototype.next = function (x) { this._o.onNext(notificationCreateOnNext(x)) };
MaterializeObserver.prototype.error = function (e) { this._o.onNext(notificationCreateOnError(e)); this._o.onCompleted(); };
MaterializeObserver.prototype.completed = function () { this._o.onNext(notificationCreateOnCompleted()); this._o.onCompleted(); };
return MaterializeObserver;
}(AbstractObserver));
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
return new MaterializeObservable(this);
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
* Note if you encounter an error and want it to retry once, then you must use .retry(2);
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(2);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchError();
};
function repeat(value) {
return {
'@@iterator': function () {
return {
next: function () {
return { done: false, value: value };
}
};
}
};
}
var RetryWhenObservable = (function(__super__) {
function createDisposable(state) {
return {
isDisposed: false,
dispose: function () {
if (!this.isDisposed) {
this.isDisposed = true;
state.isDisposed = true;
}
}
};
}
function RetryWhenObservable(source, notifier) {
this.source = source;
this._notifier = notifier;
__super__.call(this);
}
inherits(RetryWhenObservable, __super__);
RetryWhenObservable.prototype.subscribeCore = function (o) {
var exceptions = new Subject(),
notifier = new Subject(),
handled = this._notifier(exceptions),
notificationDisposable = handled.subscribe(notifier);
var e = this.source['@@iterator']();
var state = { isDisposed: false },
lastError,
subscription = new SerialDisposable();
var cancelable = currentThreadScheduler.scheduleRecursive(null, function (_, recurse) {
if (state.isDisposed) { return; }
var currentItem = e.next();
if (currentItem.done) {
if (lastError) {
o.onError(lastError);
} else {
o.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var outer = new SingleAssignmentDisposable();
var inner = new SingleAssignmentDisposable();
subscription.setDisposable(new BinaryDisposable(inner, outer));
outer.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
function (exn) {
inner.setDisposable(notifier.subscribe(recurse, function(ex) {
o.onError(ex);
}, function() {
o.onCompleted();
}));
exceptions.onNext(exn);
outer.dispose();
},
function() { o.onCompleted(); }));
});
return new NAryDisposable([notificationDisposable, subscription, cancelable, createDisposable(state)]);
};
return RetryWhenObservable;
}(ObservableBase));
observableProto.retryWhen = function (notifier) {
return new RetryWhenObservable(repeat(this), notifier);
};
function repeat(value) {
return {
'@@iterator': function () {
return {
next: function () {
return { done: false, value: value };
}
};
}
};
}
var RepeatWhenObservable = (function(__super__) {
function createDisposable(state) {
return {
isDisposed: false,
dispose: function () {
if (!this.isDisposed) {
this.isDisposed = true;
state.isDisposed = true;
}
}
};
}
function RepeatWhenObservable(source, notifier) {
this.source = source;
this._notifier = notifier;
__super__.call(this);
}
inherits(RepeatWhenObservable, __super__);
RepeatWhenObservable.prototype.subscribeCore = function (o) {
var completions = new Subject(),
notifier = new Subject(),
handled = this._notifier(completions),
notificationDisposable = handled.subscribe(notifier);
var e = this.source['@@iterator']();
var state = { isDisposed: false },
lastError,
subscription = new SerialDisposable();
var cancelable = currentThreadScheduler.scheduleRecursive(null, function (_, recurse) {
if (state.isDisposed) { return; }
var currentItem = e.next();
if (currentItem.done) {
if (lastError) {
o.onError(lastError);
} else {
o.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var outer = new SingleAssignmentDisposable();
var inner = new SingleAssignmentDisposable();
subscription.setDisposable(new BinaryDisposable(inner, outer));
outer.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
function (exn) { o.onError(exn); },
function() {
inner.setDisposable(notifier.subscribe(recurse, function(ex) {
o.onError(ex);
}, function() {
o.onCompleted();
}));
completions.onNext(null);
outer.dispose();
}));
});
return new NAryDisposable([notificationDisposable, subscription, cancelable, createDisposable(state)]);
};
return RepeatWhenObservable;
}(ObservableBase));
observableProto.repeatWhen = function (notifier) {
return new RepeatWhenObservable(repeat(this), notifier);
};
var ScanObservable = (function(__super__) {
inherits(ScanObservable, __super__);
function ScanObservable(source, accumulator, hasSeed, seed) {
this.source = source;
this.accumulator = accumulator;
this.hasSeed = hasSeed;
this.seed = seed;
__super__.call(this);
}
ScanObservable.prototype.subscribeCore = function(o) {
return this.source.subscribe(new ScanObserver(o,this));
};
return ScanObservable;
}(ObservableBase));
var ScanObserver = (function (__super__) {
inherits(ScanObserver, __super__);
function ScanObserver(o, parent) {
this._o = o;
this._p = parent;
this._fn = parent.accumulator;
this._hs = parent.hasSeed;
this._s = parent.seed;
this._ha = false;
this._a = null;
this._hv = false;
this._i = 0;
__super__.call(this);
}
ScanObserver.prototype.next = function (x) {
!this._hv && (this._hv = true);
if (this._ha) {
this._a = tryCatch(this._fn)(this._a, x, this._i, this._p);
} else {
this._a = this._hs ? tryCatch(this._fn)(this._s, x, this._i, this._p) : x;
this._ha = true;
}
if (this._a === errorObj) { return this._o.onError(this._a.e); }
this._o.onNext(this._a);
this._i++;
};
ScanObserver.prototype.error = function (e) {
this._o.onError(e);
};
ScanObserver.prototype.completed = function () {
!this._hv && this._hs && this._o.onNext(this._s);
this._o.onCompleted();
};
return ScanObserver;
}(AbstractObserver));
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator = arguments[0];
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[1];
}
return new ScanObservable(this, accumulator, hasSeed, seed);
};
var SkipLastObservable = (function (__super__) {
inherits(SkipLastObservable, __super__);
function SkipLastObservable(source, c) {
this.source = source;
this._c = c;
__super__.call(this);
}
SkipLastObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new SkipLastObserver(o, this._c));
};
return SkipLastObservable;
}(ObservableBase));
var SkipLastObserver = (function (__super__) {
inherits(SkipLastObserver, __super__);
function SkipLastObserver(o, c) {
this._o = o;
this._c = c;
this._q = [];
__super__.call(this);
}
SkipLastObserver.prototype.next = function (x) {
this._q.push(x);
this._q.length > this._c && this._o.onNext(this._q.shift());
};
SkipLastObserver.prototype.error = function (e) {
this._o.onError(e);
};
SkipLastObserver.prototype.completed = function () {
this._o.onCompleted();
};
return SkipLastObserver;
}(AbstractObserver));
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
return new SkipLastObservable(this, count);
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
* @example
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
* @param {Arguments} args The specified values to prepend to the observable sequence
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && isScheduler(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
return observableConcat.apply(null, [observableFromArray(args, scheduler), this]);
};
var TakeLastObserver = (function (__super__) {
inherits(TakeLastObserver, __super__);
function TakeLastObserver(o, c) {
this._o = o;
this._c = c;
this._q = [];
__super__.call(this);
}
TakeLastObserver.prototype.next = function (x) {
this._q.push(x);
this._q.length > this._c && this._q.shift();
};
TakeLastObserver.prototype.error = function (e) {
this._o.onError(e);
};
TakeLastObserver.prototype.completed = function () {
while (this._q.length > 0) { this._o.onNext(this._q.shift()); }
this._o.onCompleted();
};
return TakeLastObserver;
}(AbstractObserver));
/**
* Returns a specified number of contiguous elements from the end of an observable sequence.
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
return source.subscribe(new TakeLastObserver(o, count));
}, source);
};
var TakeLastBufferObserver = (function (__super__) {
inherits(TakeLastBufferObserver, __super__);
function TakeLastBufferObserver(o, c) {
this._o = o;
this._c = c;
this._q = [];
__super__.call(this);
}
TakeLastBufferObserver.prototype.next = function (x) {
this._q.push(x);
this._q.length > this._c && this._q.shift();
};
TakeLastBufferObserver.prototype.error = function (e) {
this._o.onError(e);
};
TakeLastBufferObserver.prototype.completed = function () {
this._o.onNext(this._q);
this._o.onCompleted();
};
return TakeLastBufferObserver;
}(AbstractObserver));
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
return source.subscribe(new TakeLastBufferObserver(o, count));
}, source);
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
* @param {Number} count Length of each window.
* @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithCount = observableProto.windowCount = 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);
};
observableProto.flatMapConcat = observableProto.concatMap = function(selector, resultSelector, thisArg) {
return new FlatMapObservable(this, selector, resultSelector, thisArg).merge(1);
};
/**
* Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) {
var source = this,
onNextFunc = bindCallback(onNext, thisArg, 2),
onErrorFunc = bindCallback(onError, thisArg, 1),
onCompletedFunc = bindCallback(onCompleted, thisArg, 0);
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNextFunc(x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onErrorFunc(err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompletedFunc();
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}, this).concatAll();
};
var DefaultIfEmptyObserver = (function (__super__) {
inherits(DefaultIfEmptyObserver, __super__);
function DefaultIfEmptyObserver(o, d) {
this._o = o;
this._d = d;
this._f = false;
__super__.call(this);
}
DefaultIfEmptyObserver.prototype.next = function (x) {
this._f = true;
this._o.onNext(x);
};
DefaultIfEmptyObserver.prototype.error = function (e) {
this._o.onError(e);
};
DefaultIfEmptyObserver.prototype.completed = function () {
!this._f && this._o.onNext(this._d);
this._o.onCompleted();
};
return DefaultIfEmptyObserver;
}(AbstractObserver));
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* var res = obs = xs.defaultIfEmpty();
* 2 - obs = xs.defaultIfEmpty(false);
*
* @memberOf Observable#
* @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
* @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
*/
observableProto.defaultIfEmpty = function (defaultValue) {
var source = this;
defaultValue === undefined && (defaultValue = null);
return new AnonymousObservable(function (o) {
return source.subscribe(new DefaultIfEmptyObserver(o, defaultValue));
}, source);
};
// Swap out for Array.findIndex
function arrayIndexOfComparer(array, item, comparer) {
for (var i = 0, len = array.length; i < len; i++) {
if (comparer(array[i], item)) { return i; }
}
return -1;
}
function HashSet(comparer) {
this.comparer = comparer;
this.set = [];
}
HashSet.prototype.push = function(value) {
var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
retValue && this.set.push(value);
return retValue;
};
var DistinctObservable = (function (__super__) {
inherits(DistinctObservable, __super__);
function DistinctObservable(source, keyFn, cmpFn) {
this.source = source;
this._keyFn = keyFn;
this._cmpFn = cmpFn;
__super__.call(this);
}
DistinctObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new DistinctObserver(o, this._keyFn, this._cmpFn));
};
return DistinctObservable;
}(ObservableBase));
var DistinctObserver = (function (__super__) {
inherits(DistinctObserver, __super__);
function DistinctObserver(o, keyFn, cmpFn) {
this._o = o;
this._keyFn = keyFn;
this._h = new HashSet(cmpFn);
__super__.call(this);
}
DistinctObserver.prototype.next = function (x) {
var key = x;
if (isFunction(this._keyFn)) {
key = tryCatch(this._keyFn)(x);
if (key === errorObj) { return this._o.onError(key.e); }
}
this._h.push(key) && this._o.onNext(x);
};
DistinctObserver.prototype.error = function (e) { this._o.onError(e); };
DistinctObserver.prototype.completed = function () { this._o.onCompleted(); };
return DistinctObserver;
}(AbstractObserver));
/**
* Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
* Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
*
* @example
* var res = obs = xs.distinct();
* 2 - obs = xs.distinct(function (x) { return x.id; });
* 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [comparer] Used to compare items in the collection.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, comparer) {
comparer || (comparer = defaultComparer);
return new DistinctObservable(this, keySelector, comparer);
};
/**
* Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function.
*
* @example
* var res = observable.groupBy(function (x) { return x.id; });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); });
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} [elementSelector] A function to map each source element to an element in an observable group.
* @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
*/
observableProto.groupBy = function (keySelector, elementSelector) {
return this.groupByUntil(keySelector, elementSelector, observableNever);
};
/**
* Groups the elements of an observable sequence according to a specified key selector function.
* A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same
* key value as a reclaimed group occurs, the group will be reborn with a new lifetime request.
*
* @example
* var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); });
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} durationSelector A function to signal the expiration of a group.
* @returns {Observable}
* A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
* If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered.
*
*/
observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector) {
var source = this;
return new AnonymousObservable(function (o) {
var map = new Map(),
groupDisposable = new CompositeDisposable(),
refCountDisposable = new RefCountDisposable(groupDisposable),
handleError = function (e) { return function (item) { item.onError(e); }; };
groupDisposable.add(
source.subscribe(function (x) {
var key = tryCatch(keySelector)(x);
if (key === errorObj) {
map.forEach(handleError(key.e));
return o.onError(key.e);
}
var fireNewMapEntry = false, writer = map.get(key);
if (writer === undefined) {
writer = new Subject();
map.set(key, writer);
fireNewMapEntry = true;
}
if (fireNewMapEntry) {
var group = new GroupedObservable(key, writer, refCountDisposable),
durationGroup = new GroupedObservable(key, writer);
var duration = tryCatch(durationSelector)(durationGroup);
if (duration === errorObj) {
map.forEach(handleError(duration.e));
return o.onError(duration.e);
}
o.onNext(group);
var md = new SingleAssignmentDisposable();
groupDisposable.add(md);
md.setDisposable(duration.take(1).subscribe(
noop,
function (e) {
map.forEach(handleError(e));
o.onError(e);
},
function () {
if (map['delete'](key)) { writer.onCompleted(); }
groupDisposable.remove(md);
}));
}
var element = x;
if (isFunction(elementSelector)) {
element = tryCatch(elementSelector)(x);
if (element === errorObj) {
map.forEach(handleError(element.e));
return o.onError(element.e);
}
}
writer.onNext(element);
}, function (e) {
map.forEach(handleError(e));
o.onError(e);
}, function () {
map.forEach(function (item) { item.onCompleted(); });
o.onCompleted();
}));
return refCountDisposable;
}, source);
};
var MapObservable = (function (__super__) {
inherits(MapObservable, __super__);
function MapObservable(source, selector, thisArg) {
this.source = source;
this.selector = bindCallback(selector, thisArg, 3);
__super__.call(this);
}
function innerMap(selector, self) {
return function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); };
}
MapObservable.prototype.internalMap = function (selector, thisArg) {
return new MapObservable(this.source, innerMap(selector, this), thisArg);
};
MapObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new InnerObserver(o, this.selector, this));
};
inherits(InnerObserver, AbstractObserver);
function InnerObserver(o, selector, source) {
this.o = o;
this.selector = selector;
this.source = source;
this.i = 0;
AbstractObserver.call(this);
}
InnerObserver.prototype.next = function(x) {
var result = tryCatch(this.selector)(x, this.i++, this.source);
if (result === errorObj) { return this.o.onError(result.e); }
this.o.onNext(result);
};
InnerObserver.prototype.error = function (e) {
this.o.onError(e);
};
InnerObserver.prototype.completed = function () {
this.o.onCompleted();
};
return MapObservable;
}(ObservableBase));
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.map = observableProto.select = function (selector, thisArg) {
var selectorFn = typeof selector === 'function' ? selector : function () { return selector; };
return this instanceof MapObservable ?
this.internalMap(selectorFn, thisArg) :
new MapObservable(this, selectorFn, thisArg);
};
function plucker(args, len) {
return function mapper(x) {
var currentProp = x;
for (var i = 0; i < len; i++) {
var p = currentProp[args[i]];
if (typeof p !== 'undefined') {
currentProp = p;
} else {
return undefined;
}
}
return currentProp;
};
}
/**
* Retrieves the value of a specified nested property from all elements in
* the Observable sequence.
* @param {Arguments} arguments The nested properties to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function () {
var len = arguments.length, args = new Array(len);
if (len === 0) { throw new Error('List of properties cannot be empty.'); }
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return this.map(plucker(args, len));
};
observableProto.flatMap = observableProto.selectMany = observableProto.mergeMap = function(selector, resultSelector, thisArg) {
return new FlatMapObservable(this, selector, resultSelector, thisArg).mergeAll();
};
/**
* 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();
};
observableProto.flatMapLatest = observableProto.switchMap = function(selector, resultSelector, thisArg) {
return new FlatMapObservable(this, selector, resultSelector, thisArg).switchLatest();
};
var SkipObservable = (function(__super__) {
inherits(SkipObservable, __super__);
function SkipObservable(source, count) {
this.source = source;
this._count = count;
__super__.call(this);
}
SkipObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new SkipObserver(o, this._count));
};
function SkipObserver(o, c) {
this._o = o;
this._r = c;
AbstractObserver.call(this);
}
inherits(SkipObserver, AbstractObserver);
SkipObserver.prototype.next = function (x) {
if (this._r <= 0) {
this._o.onNext(x);
} else {
this._r--;
}
};
SkipObserver.prototype.error = function(e) { this._o.onError(e); };
SkipObserver.prototype.completed = function() { this._o.onCompleted(); };
return SkipObservable;
}(ObservableBase));
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
return new SkipObservable(this, count);
};
var SkipWhileObservable = (function (__super__) {
inherits(SkipWhileObservable, __super__);
function SkipWhileObservable(source, fn) {
this.source = source;
this._fn = fn;
__super__.call(this);
}
SkipWhileObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new SkipWhileObserver(o, this));
};
return SkipWhileObservable;
}(ObservableBase));
var SkipWhileObserver = (function (__super__) {
inherits(SkipWhileObserver, __super__);
function SkipWhileObserver(o, p) {
this._o = o;
this._p = p;
this._i = 0;
this._r = false;
__super__.call(this);
}
SkipWhileObserver.prototype.next = function (x) {
if (!this._r) {
var res = tryCatch(this._p._fn)(x, this._i++, this._p);
if (res === errorObj) { return this._o.onError(res.e); }
this._r = !res;
}
this._r && this._o.onNext(x);
};
SkipWhileObserver.prototype.error = function (e) { this._o.onError(e); };
SkipWhileObserver.prototype.completed = function () { this._o.onCompleted(); };
return SkipWhileObserver;
}(AbstractObserver));
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var fn = bindCallback(predicate, thisArg, 3);
return new SkipWhileObservable(this, fn);
};
var TakeObservable = (function(__super__) {
inherits(TakeObservable, __super__);
function TakeObservable(source, count) {
this.source = source;
this._count = count;
__super__.call(this);
}
TakeObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new TakeObserver(o, this._count));
};
function TakeObserver(o, c) {
this._o = o;
this._c = c;
this._r = c;
AbstractObserver.call(this);
}
inherits(TakeObserver, AbstractObserver);
TakeObserver.prototype.next = function (x) {
if (this._r-- > 0) {
this._o.onNext(x);
this._r <= 0 && this._o.onCompleted();
}
};
TakeObserver.prototype.error = function (e) { this._o.onError(e); };
TakeObserver.prototype.completed = function () { this._o.onCompleted(); };
return TakeObservable;
}(ObservableBase));
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
if (count === 0) { return observableEmpty(scheduler); }
return new TakeObservable(this, count);
};
var TakeWhileObservable = (function (__super__) {
inherits(TakeWhileObservable, __super__);
function TakeWhileObservable(source, fn) {
this.source = source;
this._fn = fn;
__super__.call(this);
}
TakeWhileObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new TakeWhileObserver(o, this));
};
return TakeWhileObservable;
}(ObservableBase));
var TakeWhileObserver = (function (__super__) {
inherits(TakeWhileObserver, __super__);
function TakeWhileObserver(o, p) {
this._o = o;
this._p = p;
this._i = 0;
this._r = true;
__super__.call(this);
}
TakeWhileObserver.prototype.next = function (x) {
if (this._r) {
this._r = tryCatch(this._p._fn)(x, this._i++, this._p);
if (this._r === errorObj) { return this._o.onError(this._r.e); }
}
if (this._r) {
this._o.onNext(x);
} else {
this._o.onCompleted();
}
};
TakeWhileObserver.prototype.error = function (e) { this._o.onError(e); };
TakeWhileObserver.prototype.completed = function () { this._o.onCompleted(); };
return TakeWhileObserver;
}(AbstractObserver));
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var fn = bindCallback(predicate, thisArg, 3);
return new TakeWhileObservable(this, fn);
};
var FilterObservable = (function (__super__) {
inherits(FilterObservable, __super__);
function FilterObservable(source, predicate, thisArg) {
this.source = source;
this.predicate = bindCallback(predicate, thisArg, 3);
__super__.call(this);
}
FilterObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new InnerObserver(o, this.predicate, this));
};
function innerPredicate(predicate, self) {
return function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); }
}
FilterObservable.prototype.internalFilter = function(predicate, thisArg) {
return new FilterObservable(this.source, innerPredicate(predicate, this), thisArg);
};
inherits(InnerObserver, AbstractObserver);
function InnerObserver(o, predicate, source) {
this.o = o;
this.predicate = predicate;
this.source = source;
this.i = 0;
AbstractObserver.call(this);
}
InnerObserver.prototype.next = function(x) {
var shouldYield = tryCatch(this.predicate)(x, this.i++, this.source);
if (shouldYield === errorObj) {
return this.o.onError(shouldYield.e);
}
shouldYield && this.o.onNext(x);
};
InnerObserver.prototype.error = function (e) {
this.o.onError(e);
};
InnerObserver.prototype.completed = function () {
this.o.onCompleted();
};
return FilterObservable;
}(ObservableBase));
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.filter = observableProto.where = function (predicate, thisArg) {
return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) :
new FilterObservable(this, predicate, thisArg);
};
var ExtremaByObservable = (function (__super__) {
inherits(ExtremaByObservable, __super__);
function ExtremaByObservable(source, k, c) {
this.source = source;
this._k = k;
this._c = c;
__super__.call(this);
}
ExtremaByObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new ExtremaByObserver(o, this._k, this._c));
};
return ExtremaByObservable;
}(ObservableBase));
var ExtremaByObserver = (function (__super__) {
inherits(ExtremaByObserver, __super__);
function ExtremaByObserver(o, k, c) {
this._o = o;
this._k = k;
this._c = c;
this._v = null;
this._hv = false;
this._l = [];
__super__.call(this);
}
ExtremaByObserver.prototype.next = function (x) {
var key = tryCatch(this._k)(x);
if (key === errorObj) { return this._o.onError(key.e); }
var comparison = 0;
if (!this._hv) {
this._hv = true;
this._v = key;
} else {
comparison = tryCatch(this._c)(key, this._v);
if (comparison === errorObj) { return this._o.onError(comparison.e); }
}
if (comparison > 0) {
this._v = key;
this._l = [];
}
if (comparison >= 0) { this._l.push(x); }
};
ExtremaByObserver.prototype.error = function (e) {
this._o.onError(e);
};
ExtremaByObserver.prototype.completed = function () {
this._o.onNext(this._l);
this._o.onCompleted();
};
return ExtremaByObserver;
}(AbstractObserver));
function firstOnly(x) {
if (x.length === 0) { throw new EmptyError(); }
return x[0];
}
var ReduceObservable = (function(__super__) {
inherits(ReduceObservable, __super__);
function ReduceObservable(source, accumulator, hasSeed, seed) {
this.source = source;
this.accumulator = accumulator;
this.hasSeed = hasSeed;
this.seed = seed;
__super__.call(this);
}
ReduceObservable.prototype.subscribeCore = function(observer) {
return this.source.subscribe(new ReduceObserver(observer,this));
};
return ReduceObservable;
}(ObservableBase));
var ReduceObserver = (function (__super__) {
inherits(ReduceObserver, __super__);
function ReduceObserver(o, parent) {
this._o = o;
this._p = parent;
this._fn = parent.accumulator;
this._hs = parent.hasSeed;
this._s = parent.seed;
this._ha = false;
this._a = null;
this._hv = false;
this._i = 0;
__super__.call(this);
}
ReduceObserver.prototype.next = function (x) {
!this._hv && (this._hv = true);
if (this._ha) {
this._a = tryCatch(this._fn)(this._a, x, this._i, this._p);
} else {
this._a = this._hs ? tryCatch(this._fn)(this._s, x, this._i, this._p) : x;
this._ha = true;
}
if (this._a === errorObj) { return this._o.onError(this._a.e); }
this._i++;
};
ReduceObserver.prototype.error = function (e) {
this._o.onError(e);
};
ReduceObserver.prototype.completed = function () {
this._hv && this._o.onNext(this._a);
!this._hv && this._hs && this._o.onNext(this._s);
!this._hv && !this._hs && this._o.onError(new EmptyError());
this._o.onCompleted();
};
return ReduceObserver;
}(AbstractObserver));
/**
* Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
* For aggregation behavior with incremental intermediate results, see Observable.scan.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @param {Any} [seed] The initial accumulator value.
* @returns {Observable} An observable sequence containing a single element with the final accumulator value.
*/
observableProto.reduce = function () {
var hasSeed = false, seed, accumulator = arguments[0];
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[1];
}
return new ReduceObservable(this, accumulator, hasSeed, seed);
};
var SomeObservable = (function (__super__) {
inherits(SomeObservable, __super__);
function SomeObservable(source, fn) {
this.source = source;
this._fn = fn;
__super__.call(this);
}
SomeObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new SomeObserver(o, this._fn, this.source));
};
return SomeObservable;
}(ObservableBase));
var SomeObserver = (function (__super__) {
inherits(SomeObserver, __super__);
function SomeObserver(o, fn, s) {
this._o = o;
this._fn = fn;
this._s = s;
this._i = 0;
__super__.call(this);
}
SomeObserver.prototype.next = function (x) {
var result = tryCatch(this._fn)(x, this._i++, this._s);
if (result === errorObj) { return this._o.onError(result.e); }
if (Boolean(result)) {
this._o.onNext(true);
this._o.onCompleted();
}
};
SomeObserver.prototype.error = function (e) { this._o.onError(e); };
SomeObserver.prototype.completed = function () {
this._o.onNext(false);
this._o.onCompleted();
};
return SomeObserver;
}(AbstractObserver));
/**
* Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence.
* @param {Function} [predicate] A function to test each element for a condition.
* @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence.
*/
observableProto.some = function (predicate, thisArg) {
var fn = bindCallback(predicate, thisArg, 3);
return new SomeObservable(this, fn);
};
var IsEmptyObservable = (function (__super__) {
inherits(IsEmptyObservable, __super__);
function IsEmptyObservable(source) {
this.source = source;
__super__.call(this);
}
IsEmptyObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new IsEmptyObserver(o));
};
return IsEmptyObservable;
}(ObservableBase));
var IsEmptyObserver = (function(__super__) {
inherits(IsEmptyObserver, __super__);
function IsEmptyObserver(o) {
this._o = o;
__super__.call(this);
}
IsEmptyObserver.prototype.next = function () {
this._o.onNext(false);
this._o.onCompleted();
};
IsEmptyObserver.prototype.error = function (e) { this._o.onError(e); };
IsEmptyObserver.prototype.completed = function () {
this._o.onNext(true);
this._o.onCompleted();
};
return IsEmptyObserver;
}(AbstractObserver));
/**
* Determines whether an observable sequence is empty.
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty.
*/
observableProto.isEmpty = function () {
return new IsEmptyObservable(this);
};
var EveryObservable = (function (__super__) {
inherits(EveryObservable, __super__);
function EveryObservable(source, fn) {
this.source = source;
this._fn = fn;
__super__.call(this);
}
EveryObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new EveryObserver(o, this._fn, this.source));
};
return EveryObservable;
}(ObservableBase));
var EveryObserver = (function (__super__) {
inherits(EveryObserver, __super__);
function EveryObserver(o, fn, s) {
this._o = o;
this._fn = fn;
this._s = s;
this._i = 0;
__super__.call(this);
}
EveryObserver.prototype.next = function (x) {
var result = tryCatch(this._fn)(x, this._i++, this._s);
if (result === errorObj) { return this._o.onError(result.e); }
if (!Boolean(result)) {
this._o.onNext(false);
this._o.onCompleted();
}
};
EveryObserver.prototype.error = function (e) { this._o.onError(e); };
EveryObserver.prototype.completed = function () {
this._o.onNext(true);
this._o.onCompleted();
};
return EveryObserver;
}(AbstractObserver));
/**
* Determines whether all elements of an observable sequence satisfy a condition.
* @param {Function} [predicate] A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate.
*/
observableProto.every = function (predicate, thisArg) {
var fn = bindCallback(predicate, thisArg, 3);
return new EveryObservable(this, fn);
};
var IncludesObservable = (function (__super__) {
inherits(IncludesObservable, __super__);
function IncludesObservable(source, elem, idx) {
var n = +idx || 0;
Math.abs(n) === Infinity && (n = 0);
this.source = source;
this._elem = elem;
this._n = n;
__super__.call(this);
}
IncludesObservable.prototype.subscribeCore = function (o) {
if (this._n < 0) {
o.onNext(false);
o.onCompleted();
return disposableEmpty;
}
return this.source.subscribe(new IncludesObserver(o, this._elem, this._n));
};
return IncludesObservable;
}(ObservableBase));
var IncludesObserver = (function (__super__) {
inherits(IncludesObserver, __super__);
function IncludesObserver(o, elem, n) {
this._o = o;
this._elem = elem;
this._n = n;
this._i = 0;
__super__.call(this);
}
function comparer(a, b) {
return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b)));
}
IncludesObserver.prototype.next = function (x) {
if (this._i++ >= this._n && comparer(x, this._elem)) {
this._o.onNext(true);
this._o.onCompleted();
}
};
IncludesObserver.prototype.error = function (e) { this._o.onError(e); };
IncludesObserver.prototype.completed = function () { this._o.onNext(false); this._o.onCompleted(); };
return IncludesObserver;
}(AbstractObserver));
/**
* Determines whether an observable sequence includes a specified element with an optional equality comparer.
* @param searchElement The value to locate in the source sequence.
* @param {Number} [fromIndex] An equality comparer to compare elements.
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence includes an element that has the specified value from the given index.
*/
observableProto.includes = function (searchElement, fromIndex) {
return new IncludesObservable(this, searchElement, fromIndex);
};
var CountObservable = (function (__super__) {
inherits(CountObservable, __super__);
function CountObservable(source, fn) {
this.source = source;
this._fn = fn;
__super__.call(this);
}
CountObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new CountObserver(o, this._fn, this.source));
};
return CountObservable;
}(ObservableBase));
var CountObserver = (function (__super__) {
inherits(CountObserver, __super__);
function CountObserver(o, fn, s) {
this._o = o;
this._fn = fn;
this._s = s;
this._i = 0;
this._c = 0;
__super__.call(this);
}
CountObserver.prototype.next = function (x) {
if (this._fn) {
var result = tryCatch(this._fn)(x, this._i++, this._s);
if (result === errorObj) { return this._o.onError(result.e); }
Boolean(result) && (this._c++);
} else {
this._c++;
}
};
CountObserver.prototype.error = function (e) { this._o.onError(e); };
CountObserver.prototype.completed = function () {
this._o.onNext(this._c);
this._o.onCompleted();
};
return CountObserver;
}(AbstractObserver));
/**
* Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items.
* @example
* res = source.count();
* res = source.count(function (x) { return x > 3; });
* @param {Function} [predicate]A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence.
*/
observableProto.count = function (predicate, thisArg) {
var fn = bindCallback(predicate, thisArg, 3);
return new CountObservable(this, fn);
};
var IndexOfObservable = (function (__super__) {
inherits(IndexOfObservable, __super__);
function IndexOfObservable(source, e, n) {
this.source = source;
this._e = e;
this._n = n;
__super__.call(this);
}
IndexOfObservable.prototype.subscribeCore = function (o) {
if (this._n < 0) {
o.onNext(-1);
o.onCompleted();
return disposableEmpty;
}
return this.source.subscribe(new IndexOfObserver(o, this._e, this._n));
};
return IndexOfObservable;
}(ObservableBase));
var IndexOfObserver = (function (__super__) {
inherits(IndexOfObserver, __super__);
function IndexOfObserver(o, e, n) {
this._o = o;
this._e = e;
this._n = n;
this._i = 0;
__super__.call(this);
}
IndexOfObserver.prototype.next = function (x) {
if (this._i >= this._n && x === this._e) {
this._o.onNext(this._i);
this._o.onCompleted();
}
this._i++;
};
IndexOfObserver.prototype.error = function (e) { this._o.onError(e); };
IndexOfObserver.prototype.completed = function () { this._o.onNext(-1); this._o.onCompleted(); };
return IndexOfObserver;
}(AbstractObserver));
/**
* Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present.
* @param {Any} searchElement Element to locate in the array.
* @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0.
* @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present.
*/
observableProto.indexOf = function(searchElement, fromIndex) {
var n = +fromIndex || 0;
Math.abs(n) === Infinity && (n = 0);
return new IndexOfObservable(this, searchElement, n);
};
var SumObservable = (function (__super__) {
inherits(SumObservable, __super__);
function SumObservable(source, fn) {
this.source = source;
this._fn = fn;
__super__.call(this);
}
SumObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new SumObserver(o, this._fn, this.source));
};
return SumObservable;
}(ObservableBase));
var SumObserver = (function (__super__) {
inherits(SumObserver, __super__);
function SumObserver(o, fn, s) {
this._o = o;
this._fn = fn;
this._s = s;
this._i = 0;
this._c = 0;
__super__.call(this);
}
SumObserver.prototype.next = function (x) {
if (this._fn) {
var result = tryCatch(this._fn)(x, this._i++, this._s);
if (result === errorObj) { return this._o.onError(result.e); }
this._c += result;
} else {
this._c += x;
}
};
SumObserver.prototype.error = function (e) { this._o.onError(e); };
SumObserver.prototype.completed = function () {
this._o.onNext(this._c);
this._o.onCompleted();
};
return SumObserver;
}(AbstractObserver));
/**
* Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence.
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence.
*/
observableProto.sum = function (keySelector, thisArg) {
var fn = bindCallback(keySelector, thisArg, 3);
return new SumObservable(this, fn);
};
/**
* Returns the elements in an observable sequence with the minimum key value according to the specified comparer.
* @example
* var res = source.minBy(function (x) { return x.value; });
* var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value.
*/
observableProto.minBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return new ExtremaByObservable(this, keySelector, function (x, y) { return comparer(x, y) * -1; });
};
/**
* Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check.
* @example
* var res = source.min();
* var res = source.min(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence.
*/
observableProto.min = function (comparer) {
return this.minBy(identity, comparer).map(firstOnly);
};
/**
* Returns the elements in an observable sequence with the maximum key value according to the specified comparer.
* @example
* var res = source.maxBy(function (x) { return x.value; });
* var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value.
*/
observableProto.maxBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return new ExtremaByObservable(this, keySelector, comparer);
};
/**
* Returns the maximum value in an observable sequence according to the specified comparer.
* @example
* var res = source.max();
* var res = source.max(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence.
*/
observableProto.max = function (comparer) {
return this.maxBy(identity, comparer).map(firstOnly);
};
var AverageObservable = (function (__super__) {
inherits(AverageObservable, __super__);
function AverageObservable(source, fn) {
this.source = source;
this._fn = fn;
__super__.call(this);
}
AverageObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new AverageObserver(o, this._fn, this.source));
};
return AverageObservable;
}(ObservableBase));
var AverageObserver = (function(__super__) {
inherits(AverageObserver, __super__);
function AverageObserver(o, fn, s) {
this._o = o;
this._fn = fn;
this._s = s;
this._c = 0;
this._t = 0;
__super__.call(this);
}
AverageObserver.prototype.next = function (x) {
if(this._fn) {
var r = tryCatch(this._fn)(x, this._c++, this._s);
if (r === errorObj) { return this._o.onError(r.e); }
this._t += r;
} else {
this._c++;
this._t += x;
}
};
AverageObserver.prototype.error = function (e) { this._o.onError(e); };
AverageObserver.prototype.completed = function () {
if (this._c === 0) { return this._o.onError(new EmptyError()); }
this._o.onNext(this._t / this._c);
this._o.onCompleted();
};
return AverageObserver;
}(AbstractObserver));
/**
* Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present.
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the average of the sequence of values.
*/
observableProto.average = function (keySelector, thisArg) {
var source = this, fn;
if (isFunction(keySelector)) {
fn = bindCallback(keySelector, thisArg, 3);
}
return new AverageObservable(source, fn);
};
/**
* Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer.
*
* @example
* var res = res = source.sequenceEqual([1,2,3]);
* var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; });
* 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42));
* 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; });
* @param {Observable} second Second observable sequence or array to compare.
* @param {Function} [comparer] Comparer used to compare elements of both sequences.
* @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer.
*/
observableProto.sequenceEqual = function (second, comparer) {
var first = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var donel = false, doner = false, ql = [], qr = [];
var subscription1 = first.subscribe(function (x) {
if (qr.length > 0) {
var v = qr.shift();
var equal = tryCatch(comparer)(v, x);
if (equal === errorObj) { return o.onError(equal.e); }
if (!equal) {
o.onNext(false);
o.onCompleted();
}
} else if (doner) {
o.onNext(false);
o.onCompleted();
} else {
ql.push(x);
}
}, function(e) { o.onError(e); }, function () {
donel = true;
if (ql.length === 0) {
if (qr.length > 0) {
o.onNext(false);
o.onCompleted();
} else if (doner) {
o.onNext(true);
o.onCompleted();
}
}
});
(isArrayLike(second) || isIterable(second)) && (second = observableFrom(second));
isPromise(second) && (second = observableFromPromise(second));
var subscription2 = second.subscribe(function (x) {
if (ql.length > 0) {
var v = ql.shift();
var equal = tryCatch(comparer)(v, x);
if (equal === errorObj) { return o.onError(equal.e); }
if (!equal) {
o.onNext(false);
o.onCompleted();
}
} else if (donel) {
o.onNext(false);
o.onCompleted();
} else {
qr.push(x);
}
}, function(e) { o.onError(e); }, function () {
doner = true;
if (qr.length === 0) {
if (ql.length > 0) {
o.onNext(false);
o.onCompleted();
} else if (donel) {
o.onNext(true);
o.onCompleted();
}
}
});
return new BinaryDisposable(subscription1, subscription2);
}, first);
};
var ElementAtObservable = (function (__super__) {
inherits(ElementAtObservable, __super__);
function ElementAtObservable(source, i, d) {
this.source = source;
this._i = i;
this._d = d;
__super__.call(this);
}
ElementAtObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new ElementAtObserver(o, this._i, this._d));
};
return ElementAtObservable;
}(ObservableBase));
var ElementAtObserver = (function (__super__) {
inherits(ElementAtObserver, __super__);
function ElementAtObserver(o, i, d) {
this._o = o;
this._i = i;
this._d = d;
__super__.call(this);
}
ElementAtObserver.prototype.next = function (x) {
if (this._i-- === 0) {
this._o.onNext(x);
this._o.onCompleted();
}
};
ElementAtObserver.prototype.error = function (e) { this._o.onError(e); };
ElementAtObserver.prototype.completed = function () {
if (this._d === undefined) {
this._o.onError(new ArgumentOutOfRangeError());
} else {
this._o.onNext(this._d);
this._o.onCompleted();
}
};
return ElementAtObserver;
}(AbstractObserver));
/**
* Returns the element at a specified index in a sequence or default value if not found.
* @param {Number} index The zero-based index of the element to retrieve.
* @param {Any} [defaultValue] The default value to use if elementAt does not find a value.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence.
*/
observableProto.elementAt = function (index, defaultValue) {
if (index < 0) { throw new ArgumentOutOfRangeError(); }
return new ElementAtObservable(this, index, defaultValue);
};
var SingleObserver = (function(__super__) {
inherits(SingleObserver, __super__);
function SingleObserver(o, obj, s) {
this._o = o;
this._obj = obj;
this._s = s;
this._i = 0;
this._hv = false;
this._v = null;
__super__.call(this);
}
SingleObserver.prototype.next = function (x) {
var shouldYield = false;
if (this._obj.predicate) {
var res = tryCatch(this._obj.predicate)(x, this._i++, this._s);
if (res === errorObj) { return this._o.onError(res.e); }
Boolean(res) && (shouldYield = true);
} else if (!this._obj.predicate) {
shouldYield = true;
}
if (shouldYield) {
if (this._hv) {
return this._o.onError(new Error('Sequence contains more than one matching element'));
}
this._hv = true;
this._v = x;
}
};
SingleObserver.prototype.error = function (e) { this._o.onError(e); };
SingleObserver.prototype.completed = function () {
if (this._hv) {
this._o.onNext(this._v);
this._o.onCompleted();
}
else if (this._obj.defaultValue === undefined) {
this._o.onError(new EmptyError());
} else {
this._o.onNext(this._obj.defaultValue);
this._o.onCompleted();
}
};
return SingleObserver;
}(AbstractObserver));
/**
* Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.single = function (predicate, thisArg) {
var obj = {}, source = this;
if (typeof arguments[0] === 'object') {
obj = arguments[0];
} else {
obj = {
predicate: arguments[0],
thisArg: arguments[1],
defaultValue: arguments[2]
};
}
if (isFunction (obj.predicate)) {
var fn = obj.predicate;
obj.predicate = bindCallback(fn, obj.thisArg, 3);
}
return new AnonymousObservable(function (o) {
return source.subscribe(new SingleObserver(o, obj, source));
}, source);
};
var FirstObservable = (function (__super__) {
inherits(FirstObservable, __super__);
function FirstObservable(source, obj) {
this.source = source;
this._obj = obj;
__super__.call(this);
}
FirstObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new FirstObserver(o, this._obj, this.source));
};
return FirstObservable;
}(ObservableBase));
var FirstObserver = (function(__super__) {
inherits(FirstObserver, __super__);
function FirstObserver(o, obj, s) {
this._o = o;
this._obj = obj;
this._s = s;
this._i = 0;
__super__.call(this);
}
FirstObserver.prototype.next = function (x) {
if (this._obj.predicate) {
var res = tryCatch(this._obj.predicate)(x, this._i++, this._s);
if (res === errorObj) { return this._o.onError(res.e); }
if (Boolean(res)) {
this._o.onNext(x);
this._o.onCompleted();
}
} else if (!this._obj.predicate) {
this._o.onNext(x);
this._o.onCompleted();
}
};
FirstObserver.prototype.error = function (e) { this._o.onError(e); };
FirstObserver.prototype.completed = function () {
if (this._obj.defaultValue === undefined) {
this._o.onError(new EmptyError());
} else {
this._o.onNext(this._obj.defaultValue);
this._o.onCompleted();
}
};
return FirstObserver;
}(AbstractObserver));
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence.
*/
observableProto.first = function () {
var obj = {}, source = this;
if (typeof arguments[0] === 'object') {
obj = arguments[0];
} else {
obj = {
predicate: arguments[0],
thisArg: arguments[1],
defaultValue: arguments[2]
};
}
if (isFunction (obj.predicate)) {
var fn = obj.predicate;
obj.predicate = bindCallback(fn, obj.thisArg, 3);
}
return new FirstObservable(this, obj);
};
var LastObservable = (function (__super__) {
inherits(LastObservable, __super__);
function LastObservable(source, obj) {
this.source = source;
this._obj = obj;
__super__.call(this);
}
LastObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new LastObserver(o, this._obj, this.source));
};
return LastObservable;
}(ObservableBase));
var LastObserver = (function(__super__) {
inherits(LastObserver, __super__);
function LastObserver(o, obj, s) {
this._o = o;
this._obj = obj;
this._s = s;
this._i = 0;
this._hv = false;
this._v = null;
__super__.call(this);
}
LastObserver.prototype.next = function (x) {
var shouldYield = false;
if (this._obj.predicate) {
var res = tryCatch(this._obj.predicate)(x, this._i++, this._s);
if (res === errorObj) { return this._o.onError(res.e); }
Boolean(res) && (shouldYield = true);
} else if (!this._obj.predicate) {
shouldYield = true;
}
if (shouldYield) {
this._hv = true;
this._v = x;
}
};
LastObserver.prototype.error = function (e) { this._o.onError(e); };
LastObserver.prototype.completed = function () {
if (this._hv) {
this._o.onNext(this._v);
this._o.onCompleted();
}
else if (this._obj.defaultValue === undefined) {
this._o.onError(new EmptyError());
} else {
this._o.onNext(this._obj.defaultValue);
this._o.onCompleted();
}
};
return LastObserver;
}(AbstractObserver));
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.last = function () {
var obj = {}, source = this;
if (typeof arguments[0] === 'object') {
obj = arguments[0];
} else {
obj = {
predicate: arguments[0],
thisArg: arguments[1],
defaultValue: arguments[2]
};
}
if (isFunction (obj.predicate)) {
var fn = obj.predicate;
obj.predicate = bindCallback(fn, obj.thisArg, 3);
}
return new LastObservable(this, obj);
};
var FindValueObserver = (function(__super__) {
inherits(FindValueObserver, __super__);
function FindValueObserver(observer, source, callback, yieldIndex) {
this._o = observer;
this._s = source;
this._cb = callback;
this._y = yieldIndex;
this._i = 0;
__super__.call(this);
}
FindValueObserver.prototype.next = function (x) {
var shouldRun = tryCatch(this._cb)(x, this._i, this._s);
if (shouldRun === errorObj) { return this._o.onError(shouldRun.e); }
if (shouldRun) {
this._o.onNext(this._y ? this._i : x);
this._o.onCompleted();
} else {
this._i++;
}
};
FindValueObserver.prototype.error = function (e) {
this._o.onError(e);
};
FindValueObserver.prototype.completed = function () {
this._y && this._o.onNext(-1);
this._o.onCompleted();
};
return FindValueObserver;
}(AbstractObserver));
function findValue (source, predicate, thisArg, yieldIndex) {
var callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
return source.subscribe(new FindValueObserver(o, source, callback, yieldIndex));
}, source);
}
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined.
*/
observableProto.find = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, false);
};
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns
* an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1.
*/
observableProto.findIndex = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, true);
};
var ToSetObservable = (function (__super__) {
inherits(ToSetObservable, __super__);
function ToSetObservable(source) {
this.source = source;
__super__.call(this);
}
ToSetObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new ToSetObserver(o));
};
return ToSetObservable;
}(ObservableBase));
var ToSetObserver = (function (__super__) {
inherits(ToSetObserver, __super__);
function ToSetObserver(o) {
this._o = o;
this._s = new root.Set();
__super__.call(this);
}
ToSetObserver.prototype.next = function (x) {
this._s.add(x);
};
ToSetObserver.prototype.error = function (e) {
this._o.onError(e);
};
ToSetObserver.prototype.completed = function () {
this._o.onNext(this._s);
this._o.onCompleted();
};
return ToSetObserver;
}(AbstractObserver));
/**
* Converts the observable sequence to a Set if it exists.
* @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence.
*/
observableProto.toSet = function () {
if (typeof root.Set === 'undefined') { throw new TypeError(); }
return new ToSetObservable(this);
};
var ToMapObservable = (function (__super__) {
inherits(ToMapObservable, __super__);
function ToMapObservable(source, k, e) {
this.source = source;
this._k = k;
this._e = e;
__super__.call(this);
}
ToMapObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new ToMapObserver(o, this._k, this._e));
};
return ToMapObservable;
}(ObservableBase));
var ToMapObserver = (function (__super__) {
inherits(ToMapObserver, __super__);
function ToMapObserver(o, k, e) {
this._o = o;
this._k = k;
this._e = e;
this._m = new root.Map();
__super__.call(this);
}
ToMapObserver.prototype.next = function (x) {
var key = tryCatch(this._k)(x);
if (key === errorObj) { return this._o.onError(key.e); }
var elem = x;
if (this._e) {
elem = tryCatch(this._e)(x);
if (elem === errorObj) { return this._o.onError(elem.e); }
}
this._m.set(key, elem);
};
ToMapObserver.prototype.error = function (e) {
this._o.onError(e);
};
ToMapObserver.prototype.completed = function () {
this._o.onNext(this._m);
this._o.onCompleted();
};
return ToMapObserver;
}(AbstractObserver));
/**
* Converts the observable sequence to a Map if it exists.
* @param {Function} keySelector A function which produces the key for the Map.
* @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence.
* @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence.
*/
observableProto.toMap = function (keySelector, elementSelector) {
if (typeof root.Map === 'undefined') { throw new TypeError(); }
return new ToMapObservable(this, keySelector, elementSelector);
};
var SliceObservable = (function (__super__) {
inherits(SliceObservable, __super__);
function SliceObservable(source, b, e) {
this.source = source;
this._b = b;
this._e = e;
__super__.call(this);
}
SliceObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new SliceObserver(o, this._b, this._e));
};
return SliceObservable;
}(ObservableBase));
var SliceObserver = (function (__super__) {
inherits(SliceObserver, __super__);
function SliceObserver(o, b, e) {
this._o = o;
this._b = b;
this._e = e;
this._i = 0;
__super__.call(this);
}
SliceObserver.prototype.next = function (x) {
if (this._i >= this._b) {
if (this._e === this._i) {
this._o.onCompleted();
} else {
this._o.onNext(x);
}
}
this._i++;
};
SliceObserver.prototype.error = function (e) { this._o.onError(e); };
SliceObserver.prototype.completed = function () { this._o.onCompleted(); };
return SliceObserver;
}(AbstractObserver));
/*
* The slice() method returns a shallow copy of a portion of an Observable into a new Observable object.
* Unlike the array version, this does not support negative numbers for being or end.
* @param {Number} [begin] Zero-based index at which to begin extraction. If omitted, this will default to zero.
* @param {Number} [end] Zero-based index at which to end extraction. slice extracts up to but not including end.
* If omitted, this will emit the rest of the Observable object.
* @returns {Observable} A shallow copy of a portion of an Observable into a new Observable object.
*/
observableProto.slice = function (begin, end) {
var start = begin || 0;
if (start < 0) { throw new Rx.ArgumentOutOfRangeError(); }
if (typeof end === 'number' && end < start) {
throw new Rx.ArgumentOutOfRangeError();
}
return new SliceObservable(this, start, end);
};
var LastIndexOfObservable = (function (__super__) {
inherits(LastIndexOfObservable, __super__);
function LastIndexOfObservable(source, e, n) {
this.source = source;
this._e = e;
this._n = n;
__super__.call(this);
}
LastIndexOfObservable.prototype.subscribeCore = function (o) {
if (this._n < 0) {
o.onNext(-1);
o.onCompleted();
return disposableEmpty;
}
return this.source.subscribe(new LastIndexOfObserver(o, this._e, this._n));
};
return LastIndexOfObservable;
}(ObservableBase));
var LastIndexOfObserver = (function (__super__) {
inherits(LastIndexOfObserver, __super__);
function LastIndexOfObserver(o, e, n) {
this._o = o;
this._e = e;
this._n = n;
this._v = 0;
this._hv = false;
this._i = 0;
__super__.call(this);
}
LastIndexOfObserver.prototype.next = function (x) {
if (this._i >= this._n && x === this._e) {
this._hv = true;
this._v = this._i;
}
this._i++;
};
LastIndexOfObserver.prototype.error = function (e) { this._o.onError(e); };
LastIndexOfObserver.prototype.completed = function () {
if (this._hv) {
this._o.onNext(this._v);
} else {
this._o.onNext(-1);
}
this._o.onCompleted();
};
return LastIndexOfObserver;
}(AbstractObserver));
/**
* Returns the last index at which a given element can be found in the observable sequence, or -1 if it is not present.
* @param {Any} searchElement Element to locate in the array.
* @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0.
* @returns {Observable} And observable sequence containing the last index at which a given element can be found in the observable sequence, or -1 if it is not present.
*/
observableProto.lastIndexOf = function(searchElement, fromIndex) {
var n = +fromIndex || 0;
Math.abs(n) === Infinity && (n = 0);
return new LastIndexOfObservable(this, searchElement, n);
};
Observable.wrap = function (fn) {
function createObservable() {
return Observable.spawn.call(this, fn.apply(this, arguments));
}
createObservable.__generatorFunction__ = fn;
return createObservable;
};
var spawn = Observable.spawn = function () {
var gen = arguments[0], self = this, args = [];
for (var i = 1, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
return new AnonymousObservable(function (o) {
var g = new CompositeDisposable();
if (isFunction(gen)) { gen = gen.apply(self, args); }
if (!gen || !isFunction(gen.next)) {
o.onNext(gen);
return o.onCompleted();
}
function processGenerator(res) {
var ret = tryCatch(gen.next).call(gen, res);
if (ret === errorObj) { return o.onError(ret.e); }
next(ret);
}
processGenerator();
function onError(err) {
var ret = tryCatch(gen.next).call(gen, err);
if (ret === errorObj) { return o.onError(ret.e); }
next(ret);
}
function next(ret) {
if (ret.done) {
o.onNext(ret.value);
o.onCompleted();
return;
}
var obs = toObservable.call(self, ret.value);
var value = null;
var hasValue = false;
if (Observable.isObservable(obs)) {
g.add(obs.subscribe(function(val) {
hasValue = true;
value = val;
}, onError, function() {
hasValue && processGenerator(value);
}));
} else {
onError(new TypeError('type not supported'));
}
}
return g;
});
};
function toObservable(obj) {
if (!obj) { return obj; }
if (Observable.isObservable(obj)) { return obj; }
if (isPromise(obj)) { return Observable.fromPromise(obj); }
if (isGeneratorFunction(obj) || isGenerator(obj)) { return spawn.call(this, obj); }
if (isFunction(obj)) { return thunkToObservable.call(this, obj); }
if (isArrayLike(obj) || isIterable(obj)) { return arrayToObservable.call(this, obj); }
if (isObject(obj)) {return objectToObservable.call(this, obj);}
return obj;
}
function arrayToObservable (obj) {
return Observable.from(obj).concatMap(function(o) {
if(Observable.isObservable(o) || isObject(o)) {
return toObservable.call(null, o);
} else {
return Rx.Observable.just(o);
}
}).toArray();
}
function objectToObservable (obj) {
var results = new obj.constructor(), keys = Object.keys(obj), observables = [];
for (var i = 0, len = keys.length; i < len; i++) {
var key = keys[i];
var observable = toObservable.call(this, obj[key]);
if(observable && Observable.isObservable(observable)) {
defer(observable, key);
} else {
results[key] = obj[key];
}
}
return Observable.forkJoin.apply(Observable, observables).map(function() {
return results;
});
function defer (observable, key) {
results[key] = undefined;
observables.push(observable.map(function (next) {
results[key] = next;
}));
}
}
function thunkToObservable(fn) {
var self = this;
return new AnonymousObservable(function (o) {
fn.call(self, function () {
var err = arguments[0], res = arguments[1];
if (err) { return o.onError(err); }
if (arguments.length > 2) {
var args = [];
for (var i = 1, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
res = args;
}
o.onNext(res);
o.onCompleted();
});
});
}
function isGenerator(obj) {
return isFunction (obj.next) && isFunction (obj['throw']);
}
function isGeneratorFunction(obj) {
var ctor = obj.constructor;
if (!ctor) { return false; }
if (ctor.name === 'GeneratorFunction' || ctor.displayName === 'GeneratorFunction') { return true; }
return isGenerator(ctor.prototype);
}
function isObject(val) {
return Object == val.constructor;
}
/**
* Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence.
*
* @example
* var res = Rx.Observable.start(function () { console.log('hello'); });
* var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout);
* var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console);
*
* @param {Function} func Function to run asynchronously.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*
* Remarks
* * The function is called immediately, not during the subscription of the resulting sequence.
* * Multiple subscriptions to the resulting sequence can observe the function's result.
*/
Observable.start = function (func, context, scheduler) {
return observableToAsync(func, context, scheduler)();
};
/**
* Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler.
* @param {Function} function Function to convert to an asynchronous function.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @returns {Function} Asynchronous function.
*/
var observableToAsync = Observable.toAsync = function (func, context, scheduler) {
isScheduler(scheduler) || (scheduler = defaultScheduler);
return function () {
var args = arguments,
subject = new AsyncSubject();
scheduler.schedule(null, function () {
var result;
try {
result = func.apply(context, args);
} catch (e) {
subject.onError(e);
return;
}
subject.onNext(result);
subject.onCompleted();
});
return subject.asObservable();
};
};
function createCbObservable(fn, ctx, selector, args) {
var o = new AsyncSubject();
args.push(createCbHandler(o, ctx, selector));
fn.apply(ctx, args);
return o.asObservable();
}
function createCbHandler(o, ctx, selector) {
return function handler () {
var len = arguments.length, results = new Array(len);
for(var i = 0; i < len; i++) { results[i] = arguments[i]; }
if (isFunction(selector)) {
results = tryCatch(selector).apply(ctx, results);
if (results === errorObj) { return o.onError(results.e); }
o.onNext(results);
} else {
if (results.length <= 1) {
o.onNext(results[0]);
} else {
o.onNext(results);
}
}
o.onCompleted();
};
}
/**
* Converts a callback function to an observable sequence.
*
* @param {Function} fn Function with a callback as the last parameter to convert to an Observable sequence.
* @param {Mixed} [ctx] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next.
* @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array.
*/
Observable.fromCallback = function (fn, ctx, selector) {
return function () {
typeof ctx === 'undefined' && (ctx = this);
var len = arguments.length, args = new Array(len)
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return createCbObservable(fn, ctx, selector, args);
};
};
function createNodeObservable(fn, ctx, selector, args) {
var o = new AsyncSubject();
args.push(createNodeHandler(o, ctx, selector));
fn.apply(ctx, args);
return o.asObservable();
}
function createNodeHandler(o, ctx, selector) {
return function handler () {
var err = arguments[0];
if (err) { return o.onError(err); }
var len = arguments.length, results = [];
for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; }
if (isFunction(selector)) {
var results = tryCatch(selector).apply(ctx, results);
if (results === errorObj) { return o.onError(results.e); }
o.onNext(results);
} else {
if (results.length <= 1) {
o.onNext(results[0]);
} else {
o.onNext(results);
}
}
o.onCompleted();
};
}
/**
* Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.
* @param {Function} fn The function to call
* @param {Mixed} [ctx] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.
* @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.
*/
Observable.fromNodeCallback = function (fn, ctx, selector) {
return function () {
typeof ctx === 'undefined' && (ctx = this);
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return createNodeObservable(fn, ctx, selector, args);
};
};
function isNodeList(el) {
if (root.StaticNodeList) {
// IE8 Specific
// instanceof is slower than Object#toString, but Object#toString will not work as intended in IE8
return el instanceof root.StaticNodeList || el instanceof root.NodeList;
} else {
return Object.prototype.toString.call(el) === '[object NodeList]';
}
}
function ListenDisposable(e, n, fn) {
this._e = e;
this._n = n;
this._fn = fn;
this._e.addEventListener(this._n, this._fn, false);
this.isDisposed = false;
}
ListenDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
this._e.removeEventListener(this._n, this._fn, false);
this.isDisposed = true;
}
};
function createEventListener (el, eventName, handler) {
var disposables = new CompositeDisposable();
// Asume NodeList or HTMLCollection
var elemToString = Object.prototype.toString.call(el);
if (isNodeList(el) || elemToString === '[object HTMLCollection]') {
for (var i = 0, len = el.length; i < len; i++) {
disposables.add(createEventListener(el.item(i), eventName, handler));
}
} else if (el) {
disposables.add(new ListenDisposable(el, eventName, handler));
}
return disposables;
}
/**
* Configuration option to determine whether to use native events only
*/
Rx.config.useNativeEvents = false;
var EventObservable = (function(__super__) {
inherits(EventObservable, __super__);
function EventObservable(el, name, fn) {
this._el = el;
this._n = name;
this._fn = fn;
__super__.call(this);
}
function createHandler(o, fn) {
return function handler () {
var results = arguments[0];
if (isFunction(fn)) {
results = tryCatch(fn).apply(null, arguments);
if (results === errorObj) { return o.onError(results.e); }
}
o.onNext(results);
};
}
EventObservable.prototype.subscribeCore = function (o) {
return createEventListener(
this._el,
this._n,
createHandler(o, this._fn));
};
return EventObservable;
}(ObservableBase));
/**
* Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.
* @param {Object} element The DOMElement or NodeList to attach a listener.
* @param {String} eventName The event name to attach the observable sequence.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence of events from the specified element and the specified event.
*/
Observable.fromEvent = function (element, eventName, selector) {
// Node.js specific
if (element.addListener) {
return fromEventPattern(
function (h) { element.addListener(eventName, h); },
function (h) { element.removeListener(eventName, h); },
selector);
}
// Use only if non-native events are allowed
if (!Rx.config.useNativeEvents) {
// Handles jq, Angular.js, Zepto, Marionette, Ember.js
if (typeof element.on === 'function' && typeof element.off === 'function') {
return fromEventPattern(
function (h) { element.on(eventName, h); },
function (h) { element.off(eventName, h); },
selector);
}
}
return new EventObservable(element, eventName, selector).publish().refCount();
};
var EventPatternObservable = (function(__super__) {
inherits(EventPatternObservable, __super__);
function EventPatternObservable(add, del, fn) {
this._add = add;
this._del = del;
this._fn = fn;
__super__.call(this);
}
function createHandler(o, fn) {
return function handler () {
var results = arguments[0];
if (isFunction(fn)) {
results = tryCatch(fn).apply(null, arguments);
if (results === errorObj) { return o.onError(results.e); }
}
o.onNext(results);
};
}
EventPatternObservable.prototype.subscribeCore = function (o) {
var fn = createHandler(o, this._fn);
var returnValue = this._add(fn);
return new EventPatternDisposable(this._del, fn, returnValue);
};
function EventPatternDisposable(del, fn, ret) {
this._del = del;
this._fn = fn;
this._ret = ret;
this.isDisposed = false;
}
EventPatternDisposable.prototype.dispose = function () {
if(!this.isDisposed) {
isFunction(this._del) && this._del(this._fn, this._ret);
this.isDisposed = true;
}
};
return EventPatternObservable;
}(ObservableBase));
/**
* 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 EventPatternObservable(addHandler, removeHandler, selector).publish().refCount();
};
/**
* Invokes the asynchronous function, surfacing the result through an observable sequence.
* @param {Function} functionAsync Asynchronous function which returns a Promise to run.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*/
Observable.startAsync = function (functionAsync) {
var promise = tryCatch(functionAsync)();
if (promise === errorObj) { return observableThrow(promise.e); }
return observableFromPromise(promise);
};
var PausableObservable = (function (__super__) {
inherits(PausableObservable, __super__);
function PausableObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
this.paused = true;
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
__super__.call(this);
}
PausableObservable.prototype._subscribe = function (o) {
var conn = this.source.publish(),
subscription = conn.subscribe(o),
connection = disposableEmpty;
var pausable = this.pauser.startWith(!this.paused).distinctUntilChanged().subscribe(function (b) {
if (b) {
connection = conn.connect();
} else {
connection.dispose();
connection = disposableEmpty;
}
});
return new NAryDisposable([subscription, connection, pausable]);
};
PausableObservable.prototype.pause = function () {
this.paused = true;
this.controller.onNext(false);
};
PausableObservable.prototype.resume = function () {
this.paused = false;
this.controller.onNext(true);
};
return PausableObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausable(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausable = function (pauser) {
return new PausableObservable(this, pauser);
};
function combineLatestSource(source, subject, resultSelector) {
return new AnonymousObservable(function (o) {
var hasValue = [false, false],
hasValueAll = false,
isDone = false,
values = new Array(2),
err;
function next(x, i) {
values[i] = x;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
if (err) { return o.onError(err); }
var res = tryCatch(resultSelector).apply(null, values);
if (res === errorObj) { return o.onError(res.e); }
o.onNext(res);
}
isDone && values[1] && o.onCompleted();
}
return new BinaryDisposable(
source.subscribe(
function (x) {
next(x, 0);
},
function (e) {
if (values[1]) {
o.onError(e);
} else {
err = e;
}
},
function () {
isDone = true;
values[1] && o.onCompleted();
}),
subject.subscribe(
function (x) {
next(x, 1);
},
function (e) { o.onError(e); },
function () {
isDone = true;
next(true, 1);
})
);
}, source);
}
var PausableBufferedObservable = (function (__super__) {
inherits(PausableBufferedObservable, __super__);
function PausableBufferedObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
this.paused = true;
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
__super__.call(this);
}
PausableBufferedObservable.prototype._subscribe = function (o) {
var q = [], previousShouldFire;
function drainQueue() { while (q.length > 0) { o.onNext(q.shift()); } }
var subscription =
combineLatestSource(
this.source,
this.pauser.startWith(!this.paused).distinctUntilChanged(),
function (data, shouldFire) {
return { data: data, shouldFire: shouldFire };
})
.subscribe(
function (results) {
if (previousShouldFire !== undefined && results.shouldFire !== previousShouldFire) {
previousShouldFire = results.shouldFire;
// change in shouldFire
if (results.shouldFire) { drainQueue(); }
} else {
previousShouldFire = results.shouldFire;
// new data
if (results.shouldFire) {
o.onNext(results.data);
} else {
q.push(results.data);
}
}
},
function (err) {
drainQueue();
o.onError(err);
},
function () {
drainQueue();
o.onCompleted();
}
);
return subscription;
};
PausableBufferedObservable.prototype.pause = function () {
this.paused = true;
this.controller.onNext(false);
};
PausableBufferedObservable.prototype.resume = function () {
this.paused = false;
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 (pauser) {
return new PausableBufferedObservable(this, pauser);
};
var ControlledObservable = (function (__super__) {
inherits(ControlledObservable, __super__);
function ControlledObservable (source, enableQueue, scheduler) {
__super__.call(this);
this.subject = new ControlledSubject(enableQueue, scheduler);
this.source = source.multicast(this.subject).refCount();
}
ControlledObservable.prototype._subscribe = function (o) {
return this.source.subscribe(o);
};
ControlledObservable.prototype.request = function (numberOfItems) {
return this.subject.request(numberOfItems == null ? -1 : numberOfItems);
};
return ControlledObservable;
}(Observable));
var ControlledSubject = (function (__super__) {
inherits(ControlledSubject, __super__);
function ControlledSubject(enableQueue, scheduler) {
enableQueue == null && (enableQueue = true);
__super__.call(this);
this.subject = new Subject();
this.enableQueue = enableQueue;
this.queue = enableQueue ? [] : null;
this.requestedCount = 0;
this.requestedDisposable = null;
this.error = null;
this.hasFailed = false;
this.hasCompleted = false;
this.scheduler = scheduler || currentThreadScheduler;
}
addProperties(ControlledSubject.prototype, Observer, {
_subscribe: function (o) {
return this.subject.subscribe(o);
},
onCompleted: function () {
this.hasCompleted = true;
if (!this.enableQueue || this.queue.length === 0) {
this.subject.onCompleted();
this.disposeCurrentRequest();
} else {
this.queue.push(Notification.createOnCompleted());
}
},
onError: function (error) {
this.hasFailed = true;
this.error = error;
if (!this.enableQueue || this.queue.length === 0) {
this.subject.onError(error);
this.disposeCurrentRequest();
} else {
this.queue.push(Notification.createOnError(error));
}
},
onNext: function (value) {
if (this.requestedCount <= 0) {
this.enableQueue && this.queue.push(Notification.createOnNext(value));
} else {
(this.requestedCount-- === 0) && this.disposeCurrentRequest();
this.subject.onNext(value);
}
},
_processRequest: function (numberOfItems) {
if (this.enableQueue) {
while (this.queue.length > 0 && (numberOfItems > 0 || this.queue[0].kind !== 'N')) {
var first = this.queue.shift();
first.accept(this.subject);
if (first.kind === 'N') {
numberOfItems--;
} else {
this.disposeCurrentRequest();
this.queue = [];
}
}
}
return numberOfItems;
},
request: function (number) {
this.disposeCurrentRequest();
var self = this;
this.requestedDisposable = this.scheduler.schedule(number,
function(s, i) {
var remaining = self._processRequest(i);
var stopped = self.hasCompleted || self.hasFailed;
if (!stopped && remaining > 0) {
self.requestedCount = remaining;
return disposableCreate(function () {
self.requestedCount = 0;
});
// Scheduled item is still in progress. Return a new
// disposable to allow the request to be interrupted
// via dispose.
}
});
return this.requestedDisposable;
},
disposeCurrentRequest: function () {
if (this.requestedDisposable) {
this.requestedDisposable.dispose();
this.requestedDisposable = null;
}
}
});
return ControlledSubject;
}(Observable));
/**
* Attaches a controller to the observable sequence with the ability to queue.
* @example
* var source = Rx.Observable.interval(100).controlled();
* source.request(3); // Reads 3 values
* @param {bool} enableQueue truthy value to determine if values should be queued pending the next request
* @param {Scheduler} scheduler determines how the requests will be scheduled
* @returns {Observable} The observable sequence which only propagates values on request.
*/
observableProto.controlled = function (enableQueue, scheduler) {
if (enableQueue && isScheduler(enableQueue)) {
scheduler = enableQueue;
enableQueue = true;
}
if (enableQueue == null) { enableQueue = true; }
return new ControlledObservable(this, enableQueue, scheduler);
};
var StopAndWaitObservable = (function (__super__) {
inherits(StopAndWaitObservable, __super__);
function StopAndWaitObservable (source) {
__super__.call(this);
this.source = source;
}
function scheduleMethod(s, self) {
return self.source.request(1);
}
StopAndWaitObservable.prototype._subscribe = function (o) {
this.subscription = this.source.subscribe(new StopAndWaitObserver(o, this, this.subscription));
return new BinaryDisposable(
this.subscription,
defaultScheduler.schedule(this, scheduleMethod)
);
};
var StopAndWaitObserver = (function (__sub__) {
inherits(StopAndWaitObserver, __sub__);
function StopAndWaitObserver (observer, observable, cancel) {
__sub__.call(this);
this.observer = observer;
this.observable = observable;
this.cancel = cancel;
this.scheduleDisposable = null;
}
StopAndWaitObserver.prototype.completed = function () {
this.observer.onCompleted();
this.dispose();
};
StopAndWaitObserver.prototype.error = function (error) {
this.observer.onError(error);
this.dispose();
};
function innerScheduleMethod(s, self) {
return self.observable.source.request(1);
}
StopAndWaitObserver.prototype.next = function (value) {
this.observer.onNext(value);
this.scheduleDisposable = defaultScheduler.schedule(this, innerScheduleMethod);
};
StopAndWaitObserver.dispose = function () {
this.observer = null;
if (this.cancel) {
this.cancel.dispose();
this.cancel = null;
}
if (this.scheduleDisposable) {
this.scheduleDisposable.dispose();
this.scheduleDisposable = null;
}
__sub__.prototype.dispose.call(this);
};
return StopAndWaitObserver;
}(AbstractObserver));
return StopAndWaitObservable;
}(Observable));
/**
* Attaches a stop and wait observable to the current observable.
* @returns {Observable} A stop and wait observable.
*/
ControlledObservable.prototype.stopAndWait = function () {
return new StopAndWaitObservable(this);
};
var WindowedObservable = (function (__super__) {
inherits(WindowedObservable, __super__);
function WindowedObservable(source, windowSize) {
__super__.call(this);
this.source = source;
this.windowSize = windowSize;
}
function scheduleMethod(s, self) {
return self.source.request(self.windowSize);
}
WindowedObservable.prototype._subscribe = function (o) {
this.subscription = this.source.subscribe(new WindowedObserver(o, this, this.subscription));
return new BinaryDisposable(
this.subscription,
defaultScheduler.schedule(this, scheduleMethod)
);
};
var WindowedObserver = (function (__sub__) {
inherits(WindowedObserver, __sub__);
function WindowedObserver(observer, observable, cancel) {
this.observer = observer;
this.observable = observable;
this.cancel = cancel;
this.received = 0;
this.scheduleDisposable = null;
__sub__.call(this);
}
WindowedObserver.prototype.completed = function () {
this.observer.onCompleted();
this.dispose();
};
WindowedObserver.prototype.error = function (error) {
this.observer.onError(error);
this.dispose();
};
function innerScheduleMethod(s, self) {
return self.observable.source.request(self.observable.windowSize);
}
WindowedObserver.prototype.next = function (value) {
this.observer.onNext(value);
this.received = ++this.received % this.observable.windowSize;
this.received === 0 && (this.scheduleDisposable = defaultScheduler.schedule(this, innerScheduleMethod));
};
WindowedObserver.prototype.dispose = function () {
this.observer = null;
if (this.cancel) {
this.cancel.dispose();
this.cancel = null;
}
if (this.scheduleDisposable) {
this.scheduleDisposable.dispose();
this.scheduleDisposable = null;
}
__sub__.prototype.dispose.call(this);
};
return WindowedObserver;
}(AbstractObserver));
return WindowedObservable;
}(Observable));
/**
* Creates a sliding windowed observable based upon the window size.
* @param {Number} windowSize The number of items in the window
* @returns {Observable} A windowed observable based upon the window size.
*/
ControlledObservable.prototype.windowed = function (windowSize) {
return new WindowedObservable(this, windowSize);
};
/**
* Pipes the existing Observable sequence into a Node.js Stream.
* @param {Stream} dest The destination Node.js stream.
* @returns {Stream} The destination stream.
*/
observableProto.pipe = function (dest) {
var source = this.pausableBuffered();
function onDrain() {
source.resume();
}
dest.addListener('drain', onDrain);
source.subscribe(
function (x) {
!dest.write(x) && source.pause();
},
function (err) {
dest.emit('error', err);
},
function () {
// Hack check because STDIO is not closable
!dest._isStdio && dest.end();
dest.removeListener('drain', onDrain);
});
source.resume();
return dest;
};
var MulticastObservable = (function (__super__) {
inherits(MulticastObservable, __super__);
function MulticastObservable(source, fn1, fn2) {
this.source = source;
this._fn1 = fn1;
this._fn2 = fn2;
__super__.call(this);
}
MulticastObservable.prototype.subscribeCore = function (o) {
var connectable = this.source.multicast(this._fn1());
return new BinaryDisposable(this._fn2(connectable).subscribe(o), connectable.connect());
};
return MulticastObservable;
}(ObservableBase));
/**
* Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
* subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
* invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
*
* @example
* 1 - res = source.multicast(observable);
* 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
*
* @param {Function|Subject} subjectOrSubjectSelector
* Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
* Or:
* Subject to push source elements into.
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.multicast = function (subjectOrSubjectSelector, selector) {
return isFunction(subjectOrSubjectSelector) ?
new MulticastObservable(this, subjectOrSubjectSelector, selector) :
new ConnectableObservable(this, subjectOrSubjectSelector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of Multicast using a regular Subject.
*
* @example
* var resres = source.publish();
* var res = source.publish(function (x) { return x; });
*
* @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publish = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new Subject(); }, selector) :
this.multicast(new Subject());
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.share = function () {
return this.publish().refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification.
* This operator is a specialization of Multicast using a AsyncSubject.
*
* @example
* var res = source.publishLast();
* var res = source.publishLast(function (x) { return x; });
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishLast = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new AsyncSubject(); }, selector) :
this.multicast(new AsyncSubject());
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue.
* This operator is a specialization of Multicast using a BehaviorSubject.
*
* @example
* var res = source.publishValue(42);
* var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishValue = function (initialValueOrSelector, initialValue) {
return arguments.length === 2 ?
this.multicast(function () {
return new BehaviorSubject(initialValue);
}, initialValueOrSelector) :
this.multicast(new BehaviorSubject(initialValueOrSelector));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
* This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareValue = function (initialValue) {
return this.publishValue(initialValue).refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of Multicast using a ReplaySubject.
*
* @example
* var res = source.replay(null, 3);
* var res = source.replay(null, 3, 500);
* var res = source.replay(null, 3, 500, scheduler);
* var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy.
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param windowSize [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.replay = function (selector, bufferSize, windowSize, scheduler) {
return selector && isFunction(selector) ?
this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) :
this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareReplay(3);
* var res = source.shareReplay(3, 500);
* var res = source.shareReplay(3, 500, scheduler);
*
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareReplay = function (bufferSize, windowSize, scheduler) {
return this.replay(null, bufferSize, windowSize, scheduler).refCount();
};
var InnerSubscription = function (s, o) {
this._s = s;
this._o = o;
};
InnerSubscription.prototype.dispose = function () {
if (!this._s.isDisposed && this._o !== null) {
var idx = this._s.observers.indexOf(this._o);
this._s.observers.splice(idx, 1);
this._o = null;
}
};
var RefCountObservable = (function (__super__) {
inherits(RefCountObservable, __super__);
function RefCountObservable(source) {
this.source = source;
this._count = 0;
this._connectableSubscription = null;
__super__.call(this);
}
RefCountObservable.prototype.subscribeCore = function (o) {
var subscription = this.source.subscribe(o);
++this._count === 1 && (this._connectableSubscription = this.source.connect());
return new RefCountDisposable(this, subscription);
};
function RefCountDisposable(p, s) {
this._p = p;
this._s = s;
this.isDisposed = false;
}
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
this._s.dispose();
--this._p._count === 0 && this._p._connectableSubscription.dispose();
}
};
return RefCountObservable;
}(ObservableBase));
var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) {
inherits(ConnectableObservable, __super__);
function ConnectableObservable(source, subject) {
this.source = source;
this._connection = null;
this._source = source.asObservable();
this._subject = subject;
__super__.call(this);
}
function ConnectDisposable(parent, subscription) {
this._p = parent;
this._s = subscription;
}
ConnectDisposable.prototype.dispose = function () {
if (this._s) {
this._s.dispose();
this._s = null;
this._p._connection = null;
}
};
ConnectableObservable.prototype.connect = function () {
if (!this._connection) {
if (this._subject.isStopped) {
return disposableEmpty;
}
var subscription = this._source.subscribe(this._subject);
this._connection = new ConnectDisposable(this, subscription);
}
return this._connection;
};
ConnectableObservable.prototype._subscribe = function (o) {
return this._subject.subscribe(o);
};
ConnectableObservable.prototype.refCount = function () {
return new RefCountObservable(this);
};
return ConnectableObservable;
}(Observable));
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence. This observable sequence
* can be resubscribed to, even if all prior subscriptions have ended. (unlike `.publish().refCount()`)
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source.
*/
observableProto.singleInstance = function() {
var source = this, hasObservable = false, observable;
function getObservable() {
if (!hasObservable) {
hasObservable = true;
observable = source['finally'](function() { hasObservable = false; }).publish().refCount();
}
return observable;
}
return new AnonymousObservable(function(o) {
return getObservable().subscribe(o);
});
};
/**
* Correlates the elements of two sequences based on overlapping durations.
*
* @param {Observable} right The right observable sequence to join elements for.
* @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
* @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
* @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs.
* @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
*/
observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
var left = this;
return new AnonymousObservable(function (o) {
var group = new CompositeDisposable();
var leftDone = false, rightDone = false;
var leftId = 0, rightId = 0;
var leftMap = new Map(), rightMap = new Map();
var handleError = function (e) { o.onError(e); };
group.add(left.subscribe(
function (value) {
var id = leftId++, md = new SingleAssignmentDisposable();
leftMap.set(id, value);
group.add(md);
var duration = tryCatch(leftDurationSelector)(value);
if (duration === errorObj) { return o.onError(duration.e); }
md.setDisposable(duration.take(1).subscribe(
noop,
handleError,
function () {
leftMap['delete'](id) && leftMap.size === 0 && leftDone && o.onCompleted();
group.remove(md);
}));
rightMap.forEach(function (v) {
var result = tryCatch(resultSelector)(value, v);
if (result === errorObj) { return o.onError(result.e); }
o.onNext(result);
});
},
handleError,
function () {
leftDone = true;
(rightDone || leftMap.size === 0) && o.onCompleted();
})
);
group.add(right.subscribe(
function (value) {
var id = rightId++, md = new SingleAssignmentDisposable();
rightMap.set(id, value);
group.add(md);
var duration = tryCatch(rightDurationSelector)(value);
if (duration === errorObj) { return o.onError(duration.e); }
md.setDisposable(duration.take(1).subscribe(
noop,
handleError,
function () {
rightMap['delete'](id) && rightMap.size === 0 && rightDone && o.onCompleted();
group.remove(md);
}));
leftMap.forEach(function (v) {
var result = tryCatch(resultSelector)(v, value);
if (result === errorObj) { return o.onError(result.e); }
o.onNext(result);
});
},
handleError,
function () {
rightDone = true;
(leftDone || rightMap.size === 0) && o.onCompleted();
})
);
return group;
}, left);
};
/**
* Correlates the elements of two sequences based on overlapping durations, and groups the results.
*
* @param {Observable} right The right observable sequence to join elements for.
* @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
* @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
* @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element.
* @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
*/
observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
var left = this;
return new AnonymousObservable(function (o) {
var group = new CompositeDisposable();
var r = new RefCountDisposable(group);
var leftMap = new Map(), rightMap = new Map();
var leftId = 0, rightId = 0;
var handleError = function (e) { return function (v) { v.onError(e); }; };
function handleError(e) { };
group.add(left.subscribe(
function (value) {
var s = new Subject();
var id = leftId++;
leftMap.set(id, s);
var result = tryCatch(resultSelector)(value, addRef(s, r));
if (result === errorObj) {
leftMap.forEach(handleError(result.e));
return o.onError(result.e);
}
o.onNext(result);
rightMap.forEach(function (v) { s.onNext(v); });
var md = new SingleAssignmentDisposable();
group.add(md);
var duration = tryCatch(leftDurationSelector)(value);
if (duration === errorObj) {
leftMap.forEach(handleError(duration.e));
return o.onError(duration.e);
}
md.setDisposable(duration.take(1).subscribe(
noop,
function (e) {
leftMap.forEach(handleError(e));
o.onError(e);
},
function () {
leftMap['delete'](id) && s.onCompleted();
group.remove(md);
}));
},
function (e) {
leftMap.forEach(handleError(e));
o.onError(e);
},
function () { o.onCompleted(); })
);
group.add(right.subscribe(
function (value) {
var id = rightId++;
rightMap.set(id, value);
var md = new SingleAssignmentDisposable();
group.add(md);
var duration = tryCatch(rightDurationSelector)(value);
if (duration === errorObj) {
leftMap.forEach(handleError(duration.e));
return o.onError(duration.e);
}
md.setDisposable(duration.take(1).subscribe(
noop,
function (e) {
leftMap.forEach(handleError(e));
o.onError(e);
},
function () {
rightMap['delete'](id);
group.remove(md);
}));
leftMap.forEach(function (v) { v.onNext(value); });
},
function (e) {
leftMap.forEach(handleError(e));
o.onError(e);
})
);
return r;
}, left);
};
function toArray(x) { return x.toArray(); }
/**
* Projects each element of an observable sequence into zero or more buffers.
* @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
* @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.buffer = function () {
return this.window.apply(this, arguments)
.flatMap(toArray);
};
/**
* Projects each element of an observable sequence into zero or more windows.
*
* @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
* @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) {
if (arguments.length === 1 && typeof arguments[0] !== 'function') {
return observableWindowWithBoundaries.call(this, windowOpeningsOrClosingSelector);
}
return typeof windowOpeningsOrClosingSelector === 'function' ?
observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) :
observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector);
};
function observableWindowWithOpenings(windowOpenings, windowClosingSelector) {
return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) {
return win;
});
}
function observableWindowWithBoundaries(windowBoundaries) {
var source = this;
return new AnonymousObservable(function (observer) {
var win = new Subject(),
d = new CompositeDisposable(),
r = new RefCountDisposable(d);
observer.onNext(addRef(win, r));
d.add(source.subscribe(function (x) {
win.onNext(x);
}, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
observer.onCompleted();
}));
isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries));
d.add(windowBoundaries.subscribe(function (w) {
win.onCompleted();
win = new Subject();
observer.onNext(addRef(win, r));
}, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
observer.onCompleted();
}));
return r;
}, source);
}
function observableWindowWithClosingSelector(windowClosingSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SerialDisposable(),
d = new CompositeDisposable(m),
r = new RefCountDisposable(d),
win = new Subject();
observer.onNext(addRef(win, r));
d.add(source.subscribe(function (x) {
win.onNext(x);
}, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
observer.onCompleted();
}));
function createWindowClose () {
var windowClose;
try {
windowClose = windowClosingSelector();
} catch (e) {
observer.onError(e);
return;
}
isPromise(windowClose) && (windowClose = observableFromPromise(windowClose));
var m1 = new SingleAssignmentDisposable();
m.setDisposable(m1);
m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
win = new Subject();
observer.onNext(addRef(win, r));
createWindowClose();
}));
}
createWindowClose();
return r;
}, source);
}
var PairwiseObservable = (function (__super__) {
inherits(PairwiseObservable, __super__);
function PairwiseObservable(source) {
this.source = source;
__super__.call(this);
}
PairwiseObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new PairwiseObserver(o));
};
return PairwiseObservable;
}(ObservableBase));
var PairwiseObserver = (function(__super__) {
inherits(PairwiseObserver, __super__);
function PairwiseObserver(o) {
this._o = o;
this._p = null;
this._hp = false;
__super__.call(this);
}
PairwiseObserver.prototype.next = function (x) {
if (this._hp) {
this._o.onNext([this._p, x]);
} else {
this._hp = true;
}
this._p = x;
};
PairwiseObserver.prototype.error = function (err) { this._o.onError(err); };
PairwiseObserver.prototype.completed = function () { this._o.onCompleted(); };
return PairwiseObserver;
}(AbstractObserver));
/**
* 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 () {
return new PairwiseObservable(this);
};
/**
* Returns two observables which partition the observations of the source by the given function.
* The first will trigger observations for those values for which the predicate returns true.
* The second will trigger observations for those values where the predicate returns false.
* The predicate is executed once for each subscribed observer.
* Both also propagate all error observations arising from the source and each completes
* when the source completes.
* @param {Function} predicate
* The function to determine which output Observable will trigger a particular observation.
* @returns {Array}
* An array of observables. The first triggers when the predicate returns true,
* and the second triggers when the predicate returns false.
*/
observableProto.partition = function(predicate, thisArg) {
var fn = bindCallback(predicate, thisArg, 3);
return [
this.filter(predicate, thisArg),
this.filter(function (x, i, o) { return !fn(x, i, o); })
];
};
var WhileEnumerable = (function(__super__) {
inherits(WhileEnumerable, __super__);
function WhileEnumerable(c, s) {
this.c = c;
this.s = s;
}
WhileEnumerable.prototype[$iterator$] = function () {
var self = this;
return {
next: function () {
return self.c() ?
{ done: false, value: self.s } :
{ done: true, value: void 0 };
}
};
};
return WhileEnumerable;
}(Enumerable));
function enumerableWhile(condition, source) {
return new WhileEnumerable(condition, source);
}
/**
* Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions.
* This operator allows for a fluent style of writing queries that use the same sequence multiple times.
*
* @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.letBind = observableProto['let'] = function (func) {
return func(this);
};
/**
* Determines whether an observable collection contains values.
*
* @example
* 1 - res = Rx.Observable.if(condition, obs1);
* 2 - res = Rx.Observable.if(condition, obs1, obs2);
* 3 - res = Rx.Observable.if(condition, obs1, scheduler);
* @param {Function} condition The condition which determines if the thenSource or elseSource will be run.
* @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true.
* @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler.
* @returns {Observable} An observable sequence which is either the thenSource or elseSource.
*/
Observable['if'] = function (condition, thenSource, elseSourceOrScheduler) {
return observableDefer(function () {
elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty());
isPromise(thenSource) && (thenSource = observableFromPromise(thenSource));
isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler));
// Assume a scheduler for empty only
typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler));
return condition() ? thenSource : elseSourceOrScheduler;
});
};
/**
* Concatenates the observable sequences obtained by running the specified result selector for each element in source.
* There is an alias for this method called 'forIn' for browsers <IE9
* @param {Array} sources An array of values to turn into an observable sequence.
* @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence.
* @returns {Observable} An observable sequence from the concatenated observable sequences.
*/
Observable['for'] = Observable.forIn = function (sources, resultSelector, thisArg) {
return enumerableOf(sources, resultSelector, thisArg).concat();
};
/**
* Repeats source as long as condition holds emulating a while loop.
* There is an alias for this method called 'whileDo' for browsers <IE9
*
* @param {Function} condition The condition which determines if the source will be repeated.
* @param {Observable} source The observable sequence that will be run if the condition function returns true.
* @returns {Observable} An observable sequence which is repeated as long as the condition holds.
*/
var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) {
isPromise(source) && (source = observableFromPromise(source));
return enumerableWhile(condition, source).concat();
};
/**
* Repeats source as long as condition holds emulating a do while loop.
*
* @param {Function} condition The condition which determines if the source will be repeated.
* @param {Observable} source The observable sequence that will be run if the condition function returns true.
* @returns {Observable} An observable sequence which is repeated as long as the condition holds.
*/
observableProto.doWhile = function (condition) {
return observableConcat([this, observableWhileDo(condition, this)]);
};
/**
* Uses selector to determine which source in sources to use.
* @param {Function} selector The function which extracts the value for to test in a case statement.
* @param {Array} sources A object which has keys which correspond to the case statement labels.
* @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler.
*
* @returns {Observable} An observable sequence which is determined by a case statement.
*/
Observable['case'] = function (selector, sources, defaultSourceOrScheduler) {
return observableDefer(function () {
isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler));
defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty());
isScheduler(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler));
var result = sources[selector()];
isPromise(result) && (result = observableFromPromise(result));
return result || defaultSourceOrScheduler;
});
};
var ExpandObservable = (function(__super__) {
inherits(ExpandObservable, __super__);
function ExpandObservable(source, fn, scheduler) {
this.source = source;
this._fn = fn;
this._scheduler = scheduler;
__super__.call(this);
}
function scheduleRecursive(args, recurse) {
var state = args[0], self = args[1];
var work;
if (state.q.length > 0) {
work = state.q.shift();
} else {
state.isAcquired = false;
return;
}
var m1 = new SingleAssignmentDisposable();
state.d.add(m1);
m1.setDisposable(work.subscribe(new ExpandObserver(state, self, m1)));
recurse([state, self]);
}
ExpandObservable.prototype._ensureActive = function (state) {
var isOwner = false;
if (state.q.length > 0) {
isOwner = !state.isAcquired;
state.isAcquired = true;
}
isOwner && state.m.setDisposable(this._scheduler.scheduleRecursive([state, this], scheduleRecursive));
};
ExpandObservable.prototype.subscribeCore = function (o) {
var m = new SerialDisposable(),
d = new CompositeDisposable(m),
state = {
q: [],
m: m,
d: d,
activeCount: 0,
isAcquired: false,
o: o
};
state.q.push(this.source);
state.activeCount++;
this._ensureActive(state);
return d;
};
return ExpandObservable;
}(ObservableBase));
var ExpandObserver = (function(__super__) {
inherits(ExpandObserver, __super__);
function ExpandObserver(state, parent, m1) {
this._s = state;
this._p = parent;
this._m1 = m1;
__super__.call(this);
}
ExpandObserver.prototype.next = function (x) {
this._s.o.onNext(x);
var result = tryCatch(this._p._fn)(x);
if (result === errorObj) { return this._s.o.onError(result.e); }
this._s.q.push(result);
this._s.activeCount++;
this._p._ensureActive(this._s);
};
ExpandObserver.prototype.error = function (e) {
this._s.o.onError(e);
};
ExpandObserver.prototype.completed = function () {
this._s.d.remove(this._m1);
this._s.activeCount--;
this._s.activeCount === 0 && this._s.o.onCompleted();
};
return ExpandObserver;
}(AbstractObserver));
/**
* 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 = currentThreadScheduler);
return new ExpandObservable(this, selector, scheduler);
};
function argumentsToArray() {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return args;
}
var ForkJoinObservable = (function (__super__) {
inherits(ForkJoinObservable, __super__);
function ForkJoinObservable(sources, cb) {
this._sources = sources;
this._cb = cb;
__super__.call(this);
}
ForkJoinObservable.prototype.subscribeCore = function (o) {
if (this._sources.length === 0) {
o.onCompleted();
return disposableEmpty;
}
var count = this._sources.length;
var state = {
finished: false,
hasResults: new Array(count),
hasCompleted: new Array(count),
results: new Array(count)
};
var subscriptions = new CompositeDisposable();
for (var i = 0, len = this._sources.length; i < len; i++) {
var source = this._sources[i];
isPromise(source) && (source = observableFromPromise(source));
subscriptions.add(source.subscribe(new ForkJoinObserver(o, state, i, this._cb, subscriptions)));
}
return subscriptions;
};
return ForkJoinObservable;
}(ObservableBase));
var ForkJoinObserver = (function(__super__) {
inherits(ForkJoinObserver, __super__);
function ForkJoinObserver(o, s, i, cb, subs) {
this._o = o;
this._s = s;
this._i = i;
this._cb = cb;
this._subs = subs;
__super__.call(this);
}
ForkJoinObserver.prototype.next = function (x) {
if (!this._s.finished) {
this._s.hasResults[this._i] = true;
this._s.results[this._i] = x;
}
};
ForkJoinObserver.prototype.error = function (e) {
this._s.finished = true;
this._o.onError(e);
this._subs.dispose();
};
ForkJoinObserver.prototype.completed = function () {
if (!this._s.finished) {
if (!this._s.hasResults[this._i]) {
return this._o.onCompleted();
}
this._s.hasCompleted[this._i] = true;
for (var i = 0; i < this._s.results.length; i++) {
if (!this._s.hasCompleted[i]) { return; }
}
this._s.finished = true;
var res = tryCatch(this._cb).apply(null, this._s.results);
if (res === errorObj) { return this._o.onError(res.e); }
this._o.onNext(res);
this._o.onCompleted();
}
};
return ForkJoinObserver;
}(AbstractObserver));
/**
* 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 len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
Array.isArray(args[0]) && (args = args[0]);
return new ForkJoinObservable(args, resultSelector);
};
/**
* 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 () {
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 Observable.forkJoin.apply(null, args);
};
/**
* Comonadic bind operator.
* @param {Function} selector A transform function to apply to each element.
* @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler.
* @returns {Observable} An observable sequence which results from the comonadic bind operation.
*/
observableProto.manySelect = observableProto.extend = function (selector, scheduler) {
isScheduler(scheduler) || (scheduler = Rx.Scheduler.immediate);
var source = this;
return observableDefer(function () {
var chain;
return source
.map(function (x) {
var curr = new ChainObservable(x);
chain && chain.onNext(x);
chain = curr;
return curr;
})
.tap(
noop,
function (e) { chain && chain.onError(e); },
function () { chain && chain.onCompleted(); }
)
.observeOn(scheduler)
.map(selector);
}, source);
};
var ChainObservable = (function (__super__) {
inherits(ChainObservable, __super__);
function ChainObservable(head) {
__super__.call(this);
this.head = head;
this.tail = new AsyncSubject();
}
addProperties(ChainObservable.prototype, Observer, {
_subscribe: function (o) {
var g = new CompositeDisposable();
g.add(currentThreadScheduler.schedule(this, function (_, self) {
o.onNext(self.head);
g.add(self.tail.mergeAll().subscribe(o));
}));
return g;
},
onCompleted: function () {
this.onNext(Observable.empty());
},
onError: function (e) {
this.onNext(Observable['throw'](e));
},
onNext: function (v) {
this.tail.onNext(v);
this.tail.onCompleted();
}
});
return ChainObservable;
}(Observable));
var Map = root.Map || (function () {
function Map() {
this.size = 0;
this._values = [];
this._keys = [];
}
Map.prototype['delete'] = function (key) {
var i = this._keys.indexOf(key);
if (i === -1) { return false; }
this._values.splice(i, 1);
this._keys.splice(i, 1);
this.size--;
return true;
};
Map.prototype.get = function (key) {
var i = this._keys.indexOf(key);
return i === -1 ? undefined : this._values[i];
};
Map.prototype.set = function (key, value) {
var i = this._keys.indexOf(key);
if (i === -1) {
this._keys.push(key);
this._values.push(value);
this.size++;
} else {
this._values[i] = value;
}
return this;
};
Map.prototype.forEach = function (cb, thisArg) {
for (var i = 0; i < this.size; i++) {
cb.call(thisArg, this._values[i], this._keys[i]);
}
};
return Map;
}());
/**
* @constructor
* Represents a join pattern over observable sequences.
*/
function Pattern(patterns) {
this.patterns = patterns;
}
/**
* Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value.
* @param other Observable sequence to match in addition to the current pattern.
* @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value.
*/
Pattern.prototype.and = function (other) {
return new Pattern(this.patterns.concat(other));
};
/**
* Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values.
* @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern.
* @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator.
*/
Pattern.prototype.thenDo = function (selector) {
return new Plan(this, selector);
};
function Plan(expression, selector) {
this.expression = expression;
this.selector = selector;
}
function handleOnError(o) { return function (e) { o.onError(e); }; }
function handleOnNext(self, observer) {
return function onNext () {
var result = tryCatch(self.selector).apply(self, arguments);
if (result === errorObj) { return observer.onError(result.e); }
observer.onNext(result);
};
}
Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) {
var joinObservers = [], errHandler = handleOnError(observer);
for (var i = 0, len = this.expression.patterns.length; i < len; i++) {
joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], errHandler));
}
var activePlan = new ActivePlan(joinObservers, handleOnNext(this, observer), function () {
for (var j = 0, jlen = joinObservers.length; j < jlen; j++) {
joinObservers[j].removeActivePlan(activePlan);
}
deactivate(activePlan);
});
for (i = 0, len = joinObservers.length; i < len; i++) {
joinObservers[i].addActivePlan(activePlan);
}
return activePlan;
};
function planCreateObserver(externalSubscriptions, observable, onError) {
var entry = externalSubscriptions.get(observable);
if (!entry) {
var observer = new JoinObserver(observable, onError);
externalSubscriptions.set(observable, observer);
return observer;
}
return entry;
}
function ActivePlan(joinObserverArray, onNext, onCompleted) {
this.joinObserverArray = joinObserverArray;
this.onNext = onNext;
this.onCompleted = onCompleted;
this.joinObservers = new Map();
for (var i = 0, len = this.joinObserverArray.length; i < len; i++) {
var joinObserver = this.joinObserverArray[i];
this.joinObservers.set(joinObserver, joinObserver);
}
}
ActivePlan.prototype.dequeue = function () {
this.joinObservers.forEach(function (v) { v.queue.shift(); });
};
ActivePlan.prototype.match = function () {
var i, len, hasValues = true;
for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
if (this.joinObserverArray[i].queue.length === 0) {
hasValues = false;
break;
}
}
if (hasValues) {
var firstValues = [],
isCompleted = false;
for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
firstValues.push(this.joinObserverArray[i].queue[0]);
this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true);
}
if (isCompleted) {
this.onCompleted();
} else {
this.dequeue();
var values = [];
for (i = 0, len = firstValues.length; i < firstValues.length; i++) {
values.push(firstValues[i].value);
}
this.onNext.apply(this, values);
}
}
};
var JoinObserver = (function (__super__) {
inherits(JoinObserver, __super__);
function JoinObserver(source, onError) {
__super__.call(this);
this.source = source;
this.onError = onError;
this.queue = [];
this.activePlans = [];
this.subscription = new SingleAssignmentDisposable();
this.isDisposed = false;
}
var JoinObserverPrototype = JoinObserver.prototype;
JoinObserverPrototype.next = function (notification) {
if (!this.isDisposed) {
if (notification.kind === 'E') {
return this.onError(notification.error);
}
this.queue.push(notification);
var activePlans = this.activePlans.slice(0);
for (var i = 0, len = activePlans.length; i < len; i++) {
activePlans[i].match();
}
}
};
JoinObserverPrototype.error = noop;
JoinObserverPrototype.completed = noop;
JoinObserverPrototype.addActivePlan = function (activePlan) {
this.activePlans.push(activePlan);
};
JoinObserverPrototype.subscribe = function () {
this.subscription.setDisposable(this.source.materialize().subscribe(this));
};
JoinObserverPrototype.removeActivePlan = function (activePlan) {
this.activePlans.splice(this.activePlans.indexOf(activePlan), 1);
this.activePlans.length === 0 && this.dispose();
};
JoinObserverPrototype.dispose = function () {
__super__.prototype.dispose.call(this);
if (!this.isDisposed) {
this.isDisposed = true;
this.subscription.dispose();
}
};
return JoinObserver;
} (AbstractObserver));
/**
* Creates a pattern that matches when both observable sequences have an available value.
*
* @param right Observable sequence to match with the current sequence.
* @return {Pattern} Pattern object that matches when both observable sequences have an available value.
*/
observableProto.and = function (right) {
return new Pattern([this, right]);
};
/**
* Matches when the observable sequence has an available value and projects the value.
*
* @param {Function} selector Selector that will be invoked for values in the source sequence.
* @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator.
*/
observableProto.thenDo = function (selector) {
return new Pattern([this]).thenDo(selector);
};
/**
* Joins together the results from several patterns.
*
* @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns.
* @returns {Observable} Observable sequence with the results form matching several patterns.
*/
Observable.when = function () {
var len = arguments.length, plans;
if (Array.isArray(arguments[0])) {
plans = arguments[0];
} else {
plans = new Array(len);
for(var i = 0; i < len; i++) { plans[i] = arguments[i]; }
}
return new AnonymousObservable(function (o) {
var activePlans = [],
externalSubscriptions = new Map();
var outObserver = observerCreate(
function (x) { o.onNext(x); },
function (err) {
externalSubscriptions.forEach(function (v) { v.onError(err); });
o.onError(err);
},
function (x) { o.onCompleted(); }
);
try {
for (var i = 0, len = plans.length; i < len; i++) {
activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) {
var idx = activePlans.indexOf(activePlan);
activePlans.splice(idx, 1);
activePlans.length === 0 && o.onCompleted();
}));
}
} catch (e) {
return observableThrow(e).subscribe(o);
}
var group = new CompositeDisposable();
externalSubscriptions.forEach(function (joinObserver) {
joinObserver.subscribe();
group.add(joinObserver);
});
return group;
});
};
var TimerObservable = (function(__super__) {
inherits(TimerObservable, __super__);
function TimerObservable(dt, s) {
this._dt = dt;
this._s = s;
__super__.call(this);
}
TimerObservable.prototype.subscribeCore = function (o) {
return this._s.scheduleFuture(o, this._dt, scheduleMethod);
};
function scheduleMethod(s, o) {
o.onNext(0);
o.onCompleted();
}
return TimerObservable;
}(ObservableBase));
function _observableTimer(dueTime, scheduler) {
return new TimerObservable(dueTime, scheduler);
}
function observableTimerDateAndPeriod(dueTime, period, scheduler) {
return new AnonymousObservable(function (observer) {
var d = dueTime, p = normalizeTime(period);
return scheduler.scheduleRecursiveFuture(0, d, function (count, self) {
if (p > 0) {
var now = scheduler.now();
d = new Date(d.getTime() + p);
d.getTime() <= now && (d = new Date(now + p));
}
observer.onNext(count);
self(count + 1, new Date(d));
});
});
}
function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) {
return dueTime === period ?
new AnonymousObservable(function (observer) {
return scheduler.schedulePeriodic(0, period, function (count) {
observer.onNext(count);
return count + 1;
});
}) :
observableDefer(function () {
return observableTimerDateAndPeriod(new Date(scheduler.now() + dueTime), period, scheduler);
});
}
/**
* Returns an observable sequence that produces a value after each period.
*
* @example
* 1 - res = Rx.Observable.interval(1000);
* 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout);
*
* @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used.
* @returns {Observable} An observable sequence that produces a value after each period.
*/
var observableinterval = Observable.interval = function (period, scheduler) {
return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : defaultScheduler);
};
/**
* Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value.
* @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period.
*/
var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) {
var period;
isScheduler(scheduler) || (scheduler = defaultScheduler);
if (periodOrScheduler != null && typeof periodOrScheduler === 'number') {
period = periodOrScheduler;
} else if (isScheduler(periodOrScheduler)) {
scheduler = periodOrScheduler;
}
if ((dueTime instanceof Date || typeof dueTime === 'number') && period === undefined) {
return _observableTimer(dueTime, scheduler);
}
if (dueTime instanceof Date && period !== undefined) {
return observableTimerDateAndPeriod(dueTime, periodOrScheduler, scheduler);
}
return observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
};
function observableDelayRelative(source, dueTime, scheduler) {
return new AnonymousObservable(function (o) {
var active = false,
cancelable = new SerialDisposable(),
exception = null,
q = [],
running = false,
subscription;
subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) {
var d, shouldRun;
if (notification.value.kind === 'E') {
q = [];
q.push(notification);
exception = notification.value.error;
shouldRun = !running;
} else {
q.push({ value: notification.value, timestamp: notification.timestamp + dueTime });
shouldRun = !active;
active = true;
}
if (shouldRun) {
if (exception !== null) {
o.onError(exception);
} else {
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleRecursiveFuture(null, dueTime, function (_, self) {
var e, recurseDueTime, result, shouldRecurse;
if (exception !== null) {
return;
}
running = true;
do {
result = null;
if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) {
result = q.shift().value;
}
if (result !== null) {
result.accept(o);
}
} while (result !== null);
shouldRecurse = false;
recurseDueTime = 0;
if (q.length > 0) {
shouldRecurse = true;
recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now());
} else {
active = false;
}
e = exception;
running = false;
if (e !== null) {
o.onError(e);
} else if (shouldRecurse) {
self(null, recurseDueTime);
}
}));
}
}
});
return new BinaryDisposable(subscription, cancelable);
}, source);
}
function observableDelayAbsolute(source, dueTime, scheduler) {
return observableDefer(function () {
return observableDelayRelative(source, dueTime - scheduler.now(), scheduler);
});
}
function delayWithSelector(source, subscriptionDelay, delayDurationSelector) {
var subDelay, selector;
if (isFunction(subscriptionDelay)) {
selector = subscriptionDelay;
} else {
subDelay = subscriptionDelay;
selector = delayDurationSelector;
}
return new AnonymousObservable(function (o) {
var delays = new CompositeDisposable(), atEnd = false, subscription = new SerialDisposable();
function start() {
subscription.setDisposable(source.subscribe(
function (x) {
var delay = tryCatch(selector)(x);
if (delay === errorObj) { return o.onError(delay.e); }
var d = new SingleAssignmentDisposable();
delays.add(d);
d.setDisposable(delay.subscribe(
function () {
o.onNext(x);
delays.remove(d);
done();
},
function (e) { o.onError(e); },
function () {
o.onNext(x);
delays.remove(d);
done();
}
));
},
function (e) { o.onError(e); },
function () {
atEnd = true;
subscription.dispose();
done();
}
));
}
function done () {
atEnd && delays.length === 0 && o.onCompleted();
}
if (!subDelay) {
start();
} else {
subscription.setDisposable(subDelay.subscribe(start, function (e) { o.onError(e); }, start));
}
return new BinaryDisposable(subscription, delays);
}, source);
}
/**
* Time shifts the observable sequence by dueTime.
* The relative time intervals between the values are preserved.
*
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence.
* @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delay = function () {
var firstArg = arguments[0];
if (typeof firstArg === 'number' || firstArg instanceof Date) {
var dueTime = firstArg, scheduler = arguments[1];
isScheduler(scheduler) || (scheduler = defaultScheduler);
return dueTime instanceof Date ?
observableDelayAbsolute(this, dueTime, scheduler) :
observableDelayRelative(this, dueTime, scheduler);
} else if (Observable.isObservable(firstArg) || isFunction(firstArg)) {
return delayWithSelector(this, firstArg, arguments[1]);
} else {
throw new Error('Invalid arguments');
}
};
var DebounceObservable = (function (__super__) {
inherits(DebounceObservable, __super__);
function DebounceObservable(source, dt, s) {
isScheduler(s) || (s = defaultScheduler);
this.source = source;
this._dt = dt;
this._s = s;
__super__.call(this);
}
DebounceObservable.prototype.subscribeCore = function (o) {
var cancelable = new SerialDisposable();
return new BinaryDisposable(
this.source.subscribe(new DebounceObserver(o, this._dt, this._s, cancelable)),
cancelable);
};
return DebounceObservable;
}(ObservableBase));
var DebounceObserver = (function (__super__) {
inherits(DebounceObserver, __super__);
function DebounceObserver(observer, dueTime, scheduler, cancelable) {
this._o = observer;
this._d = dueTime;
this._scheduler = scheduler;
this._c = cancelable;
this._v = null;
this._hv = false;
this._id = 0;
__super__.call(this);
}
function scheduleFuture(s, state) {
state.self._hv && state.self._id === state.currentId && state.self._o.onNext(state.x);
state.self._hv = false;
}
DebounceObserver.prototype.next = function (x) {
this._hv = true;
this._v = x;
var currentId = ++this._id, d = new SingleAssignmentDisposable();
this._c.setDisposable(d);
d.setDisposable(this._scheduler.scheduleFuture(this, this._d, function (_, self) {
self._hv && self._id === currentId && self._o.onNext(x);
self._hv = false;
}));
};
DebounceObserver.prototype.error = function (e) {
this._c.dispose();
this._o.onError(e);
this._hv = false;
this._id++;
};
DebounceObserver.prototype.completed = function () {
this._c.dispose();
this._hv && this._o.onNext(this._v);
this._o.onCompleted();
this._hv = false;
this._id++;
};
return DebounceObserver;
}(AbstractObserver));
function debounceWithSelector(source, durationSelector) {
return new AnonymousObservable(function (o) {
var value, hasValue = false, cancelable = new SerialDisposable(), id = 0;
var subscription = source.subscribe(
function (x) {
var throttle = tryCatch(durationSelector)(x);
if (throttle === errorObj) { return o.onError(throttle.e); }
isPromise(throttle) && (throttle = observableFromPromise(throttle));
hasValue = true;
value = x;
id++;
var currentid = id, d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(throttle.subscribe(
function () {
hasValue && id === currentid && o.onNext(value);
hasValue = false;
d.dispose();
},
function (e) { o.onError(e); },
function () {
hasValue && id === currentid && o.onNext(value);
hasValue = false;
d.dispose();
}
));
},
function (e) {
cancelable.dispose();
o.onError(e);
hasValue = false;
id++;
},
function () {
cancelable.dispose();
hasValue && o.onNext(value);
o.onCompleted();
hasValue = false;
id++;
}
);
return new BinaryDisposable(subscription, cancelable);
}, source);
}
observableProto.debounce = function () {
if (isFunction (arguments[0])) {
return debounceWithSelector(this, arguments[0]);
} else if (typeof arguments[0] === 'number') {
return new DebounceObservable(this, arguments[0], arguments[1]);
} else {
throw new Error('Invalid arguments');
}
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on timing information.
* @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTime = observableProto.windowTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
var source = this, timeShift;
timeShiftOrScheduler == null && (timeShift = timeSpan);
isScheduler(scheduler) || (scheduler = defaultScheduler);
if (typeof timeShiftOrScheduler === 'number') {
timeShift = timeShiftOrScheduler;
} else if (isScheduler(timeShiftOrScheduler)) {
timeShift = timeSpan;
scheduler = timeShiftOrScheduler;
}
return new AnonymousObservable(function (observer) {
var groupDisposable,
nextShift = timeShift,
nextSpan = timeSpan,
q = [],
refCountDisposable,
timerD = new SerialDisposable(),
totalTime = 0;
groupDisposable = new CompositeDisposable(timerD),
refCountDisposable = new RefCountDisposable(groupDisposable);
function createTimer () {
var m = new SingleAssignmentDisposable(),
isSpan = false,
isShift = false;
timerD.setDisposable(m);
if (nextSpan === nextShift) {
isSpan = true;
isShift = true;
} else if (nextSpan < nextShift) {
isSpan = true;
} else {
isShift = true;
}
var newTotalTime = isSpan ? nextSpan : nextShift,
ts = newTotalTime - totalTime;
totalTime = newTotalTime;
if (isSpan) {
nextSpan += timeShift;
}
if (isShift) {
nextShift += timeShift;
}
m.setDisposable(scheduler.scheduleFuture(null, ts, function () {
if (isShift) {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
isSpan && q.shift().onCompleted();
createTimer();
}));
};
q.push(new Subject());
observer.onNext(addRef(q[0], refCountDisposable));
createTimer();
groupDisposable.add(source.subscribe(
function (x) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
},
function (e) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); }
observer.onError(e);
},
function () {
for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); }
observer.onCompleted();
}
));
return refCountDisposable;
}, source);
};
/**
* Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed.
* @param {Number} timeSpan Maximum time length of a window.
* @param {Number} count Maximum element count of a window.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTimeOrCount = observableProto.windowTimeOrCount = function (timeSpan, count, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = defaultScheduler);
return new AnonymousObservable(function (observer) {
var timerD = new SerialDisposable(),
groupDisposable = new CompositeDisposable(timerD),
refCountDisposable = new RefCountDisposable(groupDisposable),
n = 0,
windowId = 0,
s = new Subject();
function createTimer(id) {
var m = new SingleAssignmentDisposable();
timerD.setDisposable(m);
m.setDisposable(scheduler.scheduleFuture(null, timeSpan, function () {
if (id !== windowId) { return; }
n = 0;
var newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
createTimer(newId);
}));
}
observer.onNext(addRef(s, refCountDisposable));
createTimer(0);
groupDisposable.add(source.subscribe(
function (x) {
var newId = 0, newWindow = false;
s.onNext(x);
if (++n === count) {
newWindow = true;
n = 0;
newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
}
newWindow && createTimer(newId);
},
function (e) {
s.onError(e);
observer.onError(e);
}, function () {
s.onCompleted();
observer.onCompleted();
}
));
return refCountDisposable;
}, source);
};
function toArray(x) { return x.toArray(); }
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on timing information.
* @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers.
* @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTime = observableProto.bufferTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
return this.windowWithTime(timeSpan, timeShiftOrScheduler, scheduler).flatMap(toArray);
};
function toArray(x) { return x.toArray(); }
/**
* Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed.
* @param {Number} timeSpan Maximum time length of a buffer.
* @param {Number} count Maximum element count of a buffer.
* @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTimeOrCount = observableProto.bufferTimeOrCount = function (timeSpan, count, scheduler) {
return this.windowWithTimeOrCount(timeSpan, count, scheduler).flatMap(toArray);
};
var TimeIntervalObservable = (function (__super__) {
inherits(TimeIntervalObservable, __super__);
function TimeIntervalObservable(source, s) {
this.source = source;
this._s = s;
__super__.call(this);
}
TimeIntervalObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new TimeIntervalObserver(o, this._s));
};
return TimeIntervalObservable;
}(ObservableBase));
var TimeIntervalObserver = (function (__super__) {
inherits(TimeIntervalObserver, __super__);
function TimeIntervalObserver(o, s) {
this._o = o;
this._s = s;
this._l = s.now();
__super__.call(this);
}
TimeIntervalObserver.prototype.next = function (x) {
var now = this._s.now(), span = now - this._l;
this._l = now;
this._o.onNext({ value: x, interval: span });
};
TimeIntervalObserver.prototype.error = function (e) { this._o.onError(e); };
TimeIntervalObserver.prototype.completed = function () { this._o.onCompleted(); };
return TimeIntervalObserver;
}(AbstractObserver));
/**
* Records the time interval between consecutive values in an observable sequence.
*
* @example
* 1 - res = source.timeInterval();
* 2 - res = source.timeInterval(Rx.Scheduler.timeout);
*
* @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with time interval information on values.
*/
observableProto.timeInterval = function (scheduler) {
isScheduler(scheduler) || (scheduler = defaultScheduler);
return new TimeIntervalObservable(this, scheduler);
};
var TimestampObservable = (function (__super__) {
inherits(TimestampObservable, __super__);
function TimestampObservable(source, s) {
this.source = source;
this._s = s;
__super__.call(this);
}
TimestampObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new TimestampObserver(o, this._s));
};
return TimestampObservable;
}(ObservableBase));
var TimestampObserver = (function (__super__) {
inherits(TimestampObserver, __super__);
function TimestampObserver(o, s) {
this._o = o;
this._s = s;
__super__.call(this);
}
TimestampObserver.prototype.next = function (x) {
this._o.onNext({ value: x, timestamp: this._s.now() });
};
TimestampObserver.prototype.error = function (e) {
this._o.onError(e);
};
TimestampObserver.prototype.completed = function () {
this._o.onCompleted();
};
return TimestampObserver;
}(AbstractObserver));
/**
* Records the timestamp for each value in an observable sequence.
*
* @example
* 1 - res = source.timestamp(); // produces { value: x, timestamp: ts }
* 2 - res = source.timestamp(Rx.Scheduler.default);
*
* @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the default scheduler is used.
* @returns {Observable} An observable sequence with timestamp information on values.
*/
observableProto.timestamp = function (scheduler) {
isScheduler(scheduler) || (scheduler = defaultScheduler);
return new TimestampObservable(this, scheduler);
};
var SampleObservable = (function(__super__) {
inherits(SampleObservable, __super__);
function SampleObservable(source, sampler) {
this.source = source;
this._sampler = sampler;
__super__.call(this);
}
SampleObservable.prototype.subscribeCore = function (o) {
var state = {
o: o,
atEnd: false,
value: null,
hasValue: false,
sourceSubscription: new SingleAssignmentDisposable()
};
state.sourceSubscription.setDisposable(this.source.subscribe(new SampleSourceObserver(state)));
return new BinaryDisposable(
state.sourceSubscription,
this._sampler.subscribe(new SamplerObserver(state))
);
};
return SampleObservable;
}(ObservableBase));
var SamplerObserver = (function(__super__) {
inherits(SamplerObserver, __super__);
function SamplerObserver(s) {
this._s = s;
__super__.call(this);
}
SamplerObserver.prototype._handleMessage = function () {
if (this._s.hasValue) {
this._s.hasValue = false;
this._s.o.onNext(this._s.value);
}
this._s.atEnd && this._s.o.onCompleted();
};
SamplerObserver.prototype.next = function () { this._handleMessage(); };
SamplerObserver.prototype.error = function (e) { this._s.onError(e); };
SamplerObserver.prototype.completed = function () { this._handleMessage(); };
return SamplerObserver;
}(AbstractObserver));
var SampleSourceObserver = (function(__super__) {
inherits(SampleSourceObserver, __super__);
function SampleSourceObserver(s) {
this._s = s;
__super__.call(this);
}
SampleSourceObserver.prototype.next = function (x) {
this._s.hasValue = true;
this._s.value = x;
};
SampleSourceObserver.prototype.error = function (e) { this._s.o.onError(e); };
SampleSourceObserver.prototype.completed = function () {
this._s.atEnd = true;
this._s.sourceSubscription.dispose();
};
return SampleSourceObserver;
}(AbstractObserver));
/**
* 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 = defaultScheduler);
return typeof intervalOrSampler === 'number' ?
new SampleObservable(this, observableinterval(intervalOrSampler, scheduler)) :
new SampleObservable(this, intervalOrSampler);
};
var TimeoutError = Rx.TimeoutError = function(message) {
this.message = message || 'Timeout has occurred';
this.name = 'TimeoutError';
Error.call(this);
};
TimeoutError.prototype = Object.create(Error.prototype);
function timeoutWithSelector(source, firstTimeout, timeoutDurationSelector, other) {
if (isFunction(firstTimeout)) {
other = timeoutDurationSelector;
timeoutDurationSelector = firstTimeout;
firstTimeout = observableNever();
}
Observable.isObservable(other) || (other = observableThrow(new TimeoutError()));
return new AnonymousObservable(function (o) {
var subscription = new SerialDisposable(),
timer = new SerialDisposable(),
original = new SingleAssignmentDisposable();
subscription.setDisposable(original);
var id = 0, switched = false;
function setTimer(timeout) {
var myId = id, d = new SingleAssignmentDisposable();
function timerWins() {
switched = (myId === id);
return switched;
}
timer.setDisposable(d);
d.setDisposable(timeout.subscribe(function () {
timerWins() && subscription.setDisposable(other.subscribe(o));
d.dispose();
}, function (e) {
timerWins() && o.onError(e);
}, function () {
timerWins() && subscription.setDisposable(other.subscribe(o));
}));
};
setTimer(firstTimeout);
function oWins() {
var res = !switched;
if (res) { id++; }
return res;
}
original.setDisposable(source.subscribe(function (x) {
if (oWins()) {
o.onNext(x);
var timeout = tryCatch(timeoutDurationSelector)(x);
if (timeout === errorObj) { return o.onError(timeout.e); }
setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout);
}
}, function (e) {
oWins() && o.onError(e);
}, function () {
oWins() && o.onCompleted();
}));
return new BinaryDisposable(subscription, timer);
}, source);
}
function timeout(source, dueTime, other, scheduler) {
if (isScheduler(other)) {
scheduler = other;
other = observableThrow(new TimeoutError());
}
if (other instanceof Error) { other = observableThrow(other); }
isScheduler(scheduler) || (scheduler = defaultScheduler);
Observable.isObservable(other) || (other = observableThrow(new TimeoutError()));
return new AnonymousObservable(function (o) {
var id = 0,
original = new SingleAssignmentDisposable(),
subscription = new SerialDisposable(),
switched = false,
timer = new SerialDisposable();
subscription.setDisposable(original);
function createTimer() {
var myId = id;
timer.setDisposable(scheduler.scheduleFuture(null, dueTime, function () {
switched = id === myId;
if (switched) {
isPromise(other) && (other = observableFromPromise(other));
subscription.setDisposable(other.subscribe(o));
}
}));
}
createTimer();
original.setDisposable(source.subscribe(function (x) {
if (!switched) {
id++;
o.onNext(x);
createTimer();
}
}, function (e) {
if (!switched) {
id++;
o.onError(e);
}
}, function () {
if (!switched) {
id++;
o.onCompleted();
}
}));
return new BinaryDisposable(subscription, timer);
}, source);
}
observableProto.timeout = function () {
var firstArg = arguments[0];
if (firstArg instanceof Date || typeof firstArg === 'number') {
return timeout(this, firstArg, arguments[1], arguments[2]);
} else if (Observable.isObservable(firstArg) || isFunction(firstArg)) {
return timeoutWithSelector(this, firstArg, arguments[1], arguments[2]);
} else {
throw new Error('Invalid arguments');
}
};
var GenerateAbsoluteObservable = (function (__super__) {
inherits(GenerateAbsoluteObservable, __super__);
function GenerateAbsoluteObservable(state, cndFn, itrFn, resFn, timeFn, s) {
this._state = state;
this._cndFn = cndFn;
this._itrFn = itrFn;
this._resFn = resFn;
this._timeFn = timeFn;
this._s = s;
__super__.call(this);
}
function scheduleRecursive(state, recurse) {
state.hasResult && state.o.onNext(state.result);
if (state.first) {
state.first = false;
} else {
state.newState = tryCatch(state.self._itrFn)(state.newState);
if (state.newState === errorObj) { return state.o.onError(state.newState.e); }
}
state.hasResult = tryCatch(state.self._cndFn)(state.newState);
if (state.hasResult === errorObj) { return state.o.onError(state.hasResult.e); }
if (state.hasResult) {
state.result = tryCatch(state.self._resFn)(state.newState);
if (state.result === errorObj) { return state.o.onError(state.result.e); }
var time = tryCatch(state.self._timeFn)(state.newState);
if (time === errorObj) { return state.o.onError(time.e); }
recurse(state, time);
} else {
state.o.onCompleted();
}
}
GenerateAbsoluteObservable.prototype.subscribeCore = function (o) {
var state = {
o: o,
self: this,
newState: this._state,
first: true,
hasResult: false
};
return this._s.scheduleRecursiveFuture(state, new Date(this._s.now()), scheduleRecursive);
};
return GenerateAbsoluteObservable;
}(ObservableBase));
/**
* GenerateAbsolutes an observable sequence by iterating a state from an initial state until the condition fails.
*
* @example
* res = source.generateWithAbsoluteTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return new Date(); }
* });
*
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
* @returns {Observable} The generated sequence.
*/
Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
isScheduler(scheduler) || (scheduler = defaultScheduler);
return new GenerateAbsoluteObservable(initialState, condition, iterate, resultSelector, timeSelector, scheduler);
};
var GenerateRelativeObservable = (function (__super__) {
inherits(GenerateRelativeObservable, __super__);
function GenerateRelativeObservable(state, cndFn, itrFn, resFn, timeFn, s) {
this._state = state;
this._cndFn = cndFn;
this._itrFn = itrFn;
this._resFn = resFn;
this._timeFn = timeFn;
this._s = s;
__super__.call(this);
}
function scheduleRecursive(state, recurse) {
state.hasResult && state.o.onNext(state.result);
if (state.first) {
state.first = false;
} else {
state.newState = tryCatch(state.self._itrFn)(state.newState);
if (state.newState === errorObj) { return state.o.onError(state.newState.e); }
}
state.hasResult = tryCatch(state.self._cndFn)(state.newState);
if (state.hasResult === errorObj) { return state.o.onError(state.hasResult.e); }
if (state.hasResult) {
state.result = tryCatch(state.self._resFn)(state.newState);
if (state.result === errorObj) { return state.o.onError(state.result.e); }
var time = tryCatch(state.self._timeFn)(state.newState);
if (time === errorObj) { return state.o.onError(time.e); }
recurse(state, time);
} else {
state.o.onCompleted();
}
}
GenerateRelativeObservable.prototype.subscribeCore = function (o) {
var state = {
o: o,
self: this,
newState: this._state,
first: true,
hasResult: false
};
return this._s.scheduleRecursiveFuture(state, 0, scheduleRecursive);
};
return GenerateRelativeObservable;
}(ObservableBase));
/**
* Generates an observable sequence by iterating a state from an initial state until the condition fails.
*
* @example
* res = source.generateWithRelativeTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return 500; }
* );
*
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
* @returns {Observable} The generated sequence.
*/
Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
isScheduler(scheduler) || (scheduler = defaultScheduler);
return new GenerateRelativeObservable(initialState, condition, iterate, resultSelector, timeSelector, scheduler);
};
var DelaySubscription = (function(__super__) {
inherits(DelaySubscription, __super__);
function DelaySubscription(source, dt, s) {
this.source = source;
this._dt = dt;
this._s = s;
__super__.call(this);
}
DelaySubscription.prototype.subscribeCore = function (o) {
var d = new SerialDisposable();
d.setDisposable(this._s.scheduleFuture([this.source, o, d], this._dt, scheduleMethod));
return d;
};
function scheduleMethod(s, state) {
var source = state[0], o = state[1], d = state[2];
d.setDisposable(source.subscribe(o));
}
return DelaySubscription;
}(ObservableBase));
/**
* Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.delaySubscription(5000); // 5s
* 2 - res = source.delaySubscription(5000, Rx.Scheduler.default); // 5 seconds
*
* @param {Number} dueTime Relative or absolute time shift of the subscription.
* @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delaySubscription = function (dueTime, scheduler) {
isScheduler(scheduler) || (scheduler = defaultScheduler);
return new DelaySubscription(this, dueTime, scheduler);
};
var SkipLastWithTimeObservable = (function (__super__) {
inherits(SkipLastWithTimeObservable, __super__);
function SkipLastWithTimeObservable(source, d, s) {
this.source = source;
this._d = d;
this._s = s;
__super__.call(this);
}
SkipLastWithTimeObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new SkipLastWithTimeObserver(o, this));
};
return SkipLastWithTimeObservable;
}(ObservableBase));
var SkipLastWithTimeObserver = (function (__super__) {
inherits(SkipLastWithTimeObserver, __super__);
function SkipLastWithTimeObserver(o, p) {
this._o = o;
this._s = p._s;
this._d = p._d;
this._q = [];
__super__.call(this);
}
SkipLastWithTimeObserver.prototype.next = function (x) {
var now = this._s.now();
this._q.push({ interval: now, value: x });
while (this._q.length > 0 && now - this._q[0].interval >= this._d) {
this._o.onNext(this._q.shift().value);
}
};
SkipLastWithTimeObserver.prototype.error = function (e) { this._o.onError(e); };
SkipLastWithTimeObserver.prototype.completed = function () {
var now = this._s.now();
while (this._q.length > 0 && now - this._q[0].interval >= this._d) {
this._o.onNext(this._q.shift().value);
}
this._o.onCompleted();
};
return SkipLastWithTimeObserver;
}(AbstractObserver));
/**
* Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for skipping elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence.
*/
observableProto.skipLastWithTime = function (duration, scheduler) {
isScheduler(scheduler) || (scheduler = defaultScheduler);
return new SkipLastWithTimeObservable(this, duration, scheduler);
};
var TakeLastWithTimeObservable = (function (__super__) {
inherits(TakeLastWithTimeObservable, __super__);
function TakeLastWithTimeObservable(source, d, s) {
this.source = source;
this._d = d;
this._s = s;
__super__.call(this);
}
TakeLastWithTimeObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new TakeLastWithTimeObserver(o, this._d, this._s));
};
return TakeLastWithTimeObservable;
}(ObservableBase));
var TakeLastWithTimeObserver = (function (__super__) {
inherits(TakeLastWithTimeObserver, __super__);
function TakeLastWithTimeObserver(o, d, s) {
this._o = o;
this._d = d;
this._s = s;
this._q = [];
__super__.call(this);
}
TakeLastWithTimeObserver.prototype.next = function (x) {
var now = this._s.now();
this._q.push({ interval: now, value: x });
while (this._q.length > 0 && now - this._q[0].interval >= this._d) {
this._q.shift();
}
};
TakeLastWithTimeObserver.prototype.error = function (e) { this._o.onError(e); };
TakeLastWithTimeObserver.prototype.completed = function () {
var now = this._s.now();
while (this._q.length > 0) {
var next = this._q.shift();
if (now - next.interval <= this._d) { this._o.onNext(next.value); }
}
this._o.onCompleted();
};
return TakeLastWithTimeObserver;
}(AbstractObserver));
/**
* Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements.
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastWithTime = function (duration, scheduler) {
isScheduler(scheduler) || (scheduler = defaultScheduler);
return new TakeLastWithTimeObservable(this, duration, scheduler);
};
/**
* Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastBufferWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = defaultScheduler);
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
q.shift();
}
}, function (e) { o.onError(e); }, function () {
var now = scheduler.now(), res = [];
while (q.length > 0) {
var next = q.shift();
now - next.interval <= duration && res.push(next.value);
}
o.onNext(res);
o.onCompleted();
});
}, source);
};
var TakeWithTimeObservable = (function (__super__) {
inherits(TakeWithTimeObservable, __super__);
function TakeWithTimeObservable(source, d, s) {
this.source = source;
this._d = d;
this._s = s;
__super__.call(this);
}
function scheduleMethod(s, o) {
o.onCompleted();
}
TakeWithTimeObservable.prototype.subscribeCore = function (o) {
return new BinaryDisposable(
this._s.scheduleFuture(o, this._d, scheduleMethod),
this.source.subscribe(o)
);
};
return TakeWithTimeObservable;
}(ObservableBase));
/**
* Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeWithTime(5000, [optional scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence.
*/
observableProto.takeWithTime = function (duration, scheduler) {
isScheduler(scheduler) || (scheduler = defaultScheduler);
return new TakeWithTimeObservable(this, duration, scheduler);
};
var SkipWithTimeObservable = (function (__super__) {
inherits(SkipWithTimeObservable, __super__);
function SkipWithTimeObservable(source, d, s) {
this.source = source;
this._d = d;
this._s = s;
this._open = false;
__super__.call(this);
}
function scheduleMethod(s, self) {
self._open = true;
}
SkipWithTimeObservable.prototype.subscribeCore = function (o) {
return new BinaryDisposable(
this._s.scheduleFuture(this, this._d, scheduleMethod),
this.source.subscribe(new SkipWithTimeObserver(o, this))
);
};
return SkipWithTimeObservable;
}(ObservableBase));
var SkipWithTimeObserver = (function (__super__) {
inherits(SkipWithTimeObserver, __super__);
function SkipWithTimeObserver(o, p) {
this._o = o;
this._p = p;
__super__.call(this);
}
SkipWithTimeObserver.prototype.next = function (x) { this._p._open && this._o.onNext(x); };
SkipWithTimeObserver.prototype.error = function (e) { this._o.onError(e); };
SkipWithTimeObserver.prototype.completed = function () { this._o.onCompleted(); };
return SkipWithTimeObserver;
}(AbstractObserver));
/**
* Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
* @description
* Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence.
* This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded
* may not execute immediately, despite the zero due time.
*
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration.
* @param {Number} duration Duration for skipping elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
*/
observableProto.skipWithTime = function (duration, scheduler) {
isScheduler(scheduler) || (scheduler = defaultScheduler);
return new SkipWithTimeObservable(this, duration, scheduler);
};
var SkipUntilWithTimeObservable = (function (__super__) {
inherits(SkipUntilWithTimeObservable, __super__);
function SkipUntilWithTimeObservable(source, startTime, scheduler) {
this.source = source;
this._st = startTime;
this._s = scheduler;
__super__.call(this);
}
function scheduleMethod(s, state) {
state._open = true;
}
SkipUntilWithTimeObservable.prototype.subscribeCore = function (o) {
this._open = false;
return new BinaryDisposable(
this._s.scheduleFuture(this, this._st, scheduleMethod),
this.source.subscribe(new SkipUntilWithTimeObserver(o, this))
);
};
return SkipUntilWithTimeObservable;
}(ObservableBase));
var SkipUntilWithTimeObserver = (function (__super__) {
inherits(SkipUntilWithTimeObserver, __super__);
function SkipUntilWithTimeObserver(o, p) {
this._o = o;
this._p = p;
__super__.call(this);
}
SkipUntilWithTimeObserver.prototype.next = function (x) { this._p._open && this._o.onNext(x); };
SkipUntilWithTimeObserver.prototype.error = function (e) { this._o.onError(e); };
SkipUntilWithTimeObserver.prototype.completed = function () { this._o.onCompleted(); };
return SkipUntilWithTimeObserver;
}(AbstractObserver));
/**
* Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers.
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time.
*
* @examples
* 1 - res = source.skipUntilWithTime(new Date(), [scheduler]);
* 2 - res = source.skipUntilWithTime(5000, [scheduler]);
* @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped until the specified start time.
*/
observableProto.skipUntilWithTime = function (startTime, scheduler) {
isScheduler(scheduler) || (scheduler = defaultScheduler);
return new SkipUntilWithTimeObservable(this, startTime, scheduler);
};
/**
* Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers.
* @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately.
* @param {Scheduler} [scheduler] Scheduler to run the timer on.
* @returns {Observable} An observable sequence with the elements taken until the specified end time.
*/
observableProto.takeUntilWithTime = function (endTime, scheduler) {
isScheduler(scheduler) || (scheduler = defaultScheduler);
var source = this;
return new AnonymousObservable(function (o) {
return new BinaryDisposable(
scheduler.scheduleFuture(o, endTime, function (_, o) { o.onCompleted(); }),
source.subscribe(o));
}, source);
};
/**
* Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration.
* @param {Number} windowDuration time to wait before emitting another item after emitting the last item
* @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout.
* @returns {Observable} An Observable that performs the throttle operation.
*/
observableProto.throttle = function (windowDuration, scheduler) {
isScheduler(scheduler) || (scheduler = defaultScheduler);
var duration = +windowDuration || 0;
if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); }
var source = this;
return new AnonymousObservable(function (o) {
var lastOnNext = 0;
return source.subscribe(
function (x) {
var now = scheduler.now();
if (lastOnNext === 0 || now - lastOnNext >= duration) {
lastOnNext = now;
o.onNext(x);
}
},function (e) { o.onError(e); }, function () { o.onCompleted(); }
);
}, source);
};
var SwitchFirstObservable = (function (__super__) {
inherits(SwitchFirstObservable, __super__);
function SwitchFirstObservable(source) {
this.source = source;
__super__.call(this);
}
SwitchFirstObservable.prototype.subscribeCore = function (o) {
var m = new SingleAssignmentDisposable(),
g = new CompositeDisposable(),
state = {
hasCurrent: false,
isStopped: false,
o: o,
g: g
};
g.add(m);
m.setDisposable(this.source.subscribe(new SwitchFirstObserver(state)));
return g;
};
return SwitchFirstObservable;
}(ObservableBase));
var SwitchFirstObserver = (function(__super__) {
inherits(SwitchFirstObserver, __super__);
function SwitchFirstObserver(state) {
this._s = state;
__super__.call(this);
}
SwitchFirstObserver.prototype.next = function (x) {
if (!this._s.hasCurrent) {
this._s.hasCurrent = true;
isPromise(x) && (x = observableFromPromise(x));
var inner = new SingleAssignmentDisposable();
this._s.g.add(inner);
inner.setDisposable(x.subscribe(new InnerObserver(this._s, inner)));
}
};
SwitchFirstObserver.prototype.error = function (e) {
this._s.o.onError(e);
};
SwitchFirstObserver.prototype.completed = function () {
this._s.isStopped = true;
!this._s.hasCurrent && this._s.g.length === 1 && this._s.o.onCompleted();
};
inherits(InnerObserver, __super__);
function InnerObserver(state, inner) {
this._s = state;
this._i = inner;
__super__.call(this);
}
InnerObserver.prototype.next = function (x) { this._s.o.onNext(x); };
InnerObserver.prototype.error = function (e) { this._s.o.onError(e); };
InnerObserver.prototype.completed = function () {
this._s.g.remove(this._i);
this._s.hasCurrent = false;
this._s.isStopped && this._s.g.length === 1 && this._s.o.onCompleted();
};
return SwitchFirstObserver;
}(AbstractObserver));
/**
* Performs a exclusive waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @returns {Observable} A exclusive observable with only the results that happen when subscribed.
*/
observableProto.switchFirst = function () {
return new SwitchFirstObservable(this);
};
observableProto.flatMapFirst = observableProto.exhaustMap = function(selector, resultSelector, thisArg) {
return new FlatMapObservable(this, selector, resultSelector, thisArg).switchFirst();
};
observableProto.flatMapWithMaxConcurrent = observableProto.flatMapMaxConcurrent = function(limit, selector, resultSelector, thisArg) {
return new FlatMapObservable(this, selector, resultSelector, thisArg).merge(limit);
};
var TransduceObserver = (function (__super__) {
inherits(TransduceObserver, __super__);
function TransduceObserver(o, xform) {
this._o = o;
this._xform = xform;
__super__.call(this);
}
TransduceObserver.prototype.next = function (x) {
var res = tryCatch(this._xform['@@transducer/step']).call(this._xform, this._o, x);
if (res === errorObj) { this._o.onError(res.e); }
};
TransduceObserver.prototype.error = function (e) { this._o.onError(e); };
TransduceObserver.prototype.completed = function () {
this._xform['@@transducer/result'](this._o);
};
return TransduceObserver;
}(AbstractObserver));
function transformForObserver(o) {
return {
'@@transducer/init': function() {
return o;
},
'@@transducer/step': function(obs, input) {
return obs.onNext(input);
},
'@@transducer/result': function(obs) {
return obs.onCompleted();
}
};
}
/**
* Executes a transducer to transform the observable sequence
* @param {Transducer} transducer A transducer to execute
* @returns {Observable} An Observable sequence containing the results from the transducer.
*/
observableProto.transduce = function(transducer) {
var source = this;
return new AnonymousObservable(function(o) {
var xform = transducer(transformForObserver(o));
return source.subscribe(new TransduceObserver(o, xform));
}, source);
};
/** Provides a set of extension methods for virtual time scheduling. */
var VirtualTimeScheduler = Rx.VirtualTimeScheduler = (function (__super__) {
inherits(VirtualTimeScheduler, __super__);
/**
* Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer.
*
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function VirtualTimeScheduler(initialClock, comparer) {
this.clock = initialClock;
this.comparer = comparer;
this.isEnabled = false;
this.queue = new PriorityQueue(1024);
__super__.call(this);
}
var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype;
VirtualTimeSchedulerPrototype.now = function () {
return this.toAbsoluteTime(this.clock);
};
VirtualTimeSchedulerPrototype.schedule = function (state, action) {
return this.scheduleAbsolute(state, this.clock, action);
};
VirtualTimeSchedulerPrototype.scheduleFuture = function (state, dueTime, action) {
var dt = dueTime instanceof Date ?
this.toRelativeTime(dueTime - this.now()) :
this.toRelativeTime(dueTime);
return this.scheduleRelative(state, dt, action);
};
/**
* Adds a relative time value to an absolute time value.
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
VirtualTimeSchedulerPrototype.add = notImplemented;
/**
* Converts an absolute time to a number
* @param {Any} The absolute time.
* @returns {Number} The absolute time in ms
*/
VirtualTimeSchedulerPrototype.toAbsoluteTime = notImplemented;
/**
* Converts the TimeSpan value to a relative virtual time value.
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
VirtualTimeSchedulerPrototype.toRelativeTime = notImplemented;
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
VirtualTimeSchedulerPrototype.schedulePeriodic = function (state, period, action) {
var s = new SchedulePeriodicRecursive(this, state, period, action);
return s.start();
};
/**
* Schedules an action to be executed after dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleRelative = function (state, dueTime, action) {
var runAt = this.add(this.clock, dueTime);
return this.scheduleAbsolute(state, runAt, action);
};
/**
* Starts the virtual time scheduler.
*/
VirtualTimeSchedulerPrototype.start = function () {
if (!this.isEnabled) {
this.isEnabled = true;
do {
var next = this.getNext();
if (next !== null) {
this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime);
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
}
};
/**
* Stops the virtual time scheduler.
*/
VirtualTimeSchedulerPrototype.stop = function () {
this.isEnabled = false;
};
/**
* Advances the scheduler's clock to the specified time, running all work till that point.
* @param {Number} time Absolute time to advance the scheduler's clock to.
*/
VirtualTimeSchedulerPrototype.advanceTo = function (time) {
var dueToClock = this.comparer(this.clock, time);
if (this.comparer(this.clock, time) > 0) { throw new ArgumentOutOfRangeError(); }
if (dueToClock === 0) { return; }
if (!this.isEnabled) {
this.isEnabled = true;
do {
var next = this.getNext();
if (next !== null && this.comparer(next.dueTime, time) <= 0) {
this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime);
next.invoke();
} else {
this.isEnabled = false;
}
} while (this.isEnabled);
this.clock = time;
}
};
/**
* Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan.
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.advanceBy = function (time) {
var dt = this.add(this.clock, time),
dueToClock = this.comparer(this.clock, dt);
if (dueToClock > 0) { throw new ArgumentOutOfRangeError(); }
if (dueToClock === 0) { return; }
this.advanceTo(dt);
};
/**
* Advances the scheduler's clock by the specified relative time.
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.sleep = function (time) {
var dt = this.add(this.clock, time);
if (this.comparer(this.clock, dt) >= 0) { throw new ArgumentOutOfRangeError(); }
this.clock = dt;
};
/**
* Gets the next scheduled item to be executed.
* @returns {ScheduledItem} The next scheduled item.
*/
VirtualTimeSchedulerPrototype.getNext = function () {
while (this.queue.length > 0) {
var next = this.queue.peek();
if (next.isCancelled()) {
this.queue.dequeue();
} else {
return next;
}
}
return null;
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Number} dueTime Absolute time at which to execute the action.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
VirtualTimeSchedulerPrototype.scheduleAbsolute = function (state, dueTime, action) {
var self = this;
function run(scheduler, state1) {
self.queue.remove(si);
return action(scheduler, state1);
}
var si = new ScheduledItem(this, state, run, dueTime, this.comparer);
this.queue.enqueue(si);
return si.disposable;
};
return VirtualTimeScheduler;
}(Scheduler));
/** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */
Rx.HistoricalScheduler = (function (__super__) {
inherits(HistoricalScheduler, __super__);
/**
* Creates a new historical scheduler with the specified initial clock value.
* @constructor
* @param {Number} initialClock Initial value for the clock.
* @param {Function} comparer Comparer to determine causality of events based on absolute time.
*/
function HistoricalScheduler(initialClock, comparer) {
var clock = initialClock == null ? 0 : initialClock;
var cmp = comparer || defaultSubComparer;
__super__.call(this, clock, cmp);
}
var HistoricalSchedulerProto = HistoricalScheduler.prototype;
/**
* Adds a relative time value to an absolute time value.
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
HistoricalSchedulerProto.add = function (absolute, relative) {
return absolute + relative;
};
HistoricalSchedulerProto.toAbsoluteTime = function (absolute) {
return new Date(absolute).getTime();
};
/**
* Converts the TimeSpan value to a relative virtual time value.
* @memberOf HistoricalScheduler
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
HistoricalSchedulerProto.toRelativeTime = function (timeSpan) {
return timeSpan;
};
return HistoricalScheduler;
}(Rx.VirtualTimeScheduler));
function OnNextPredicate(predicate) {
this.predicate = predicate;
}
OnNextPredicate.prototype.equals = function (other) {
if (other === this) { return true; }
if (other == null) { return false; }
if (other.kind !== 'N') { return false; }
return this.predicate(other.value);
};
function OnErrorPredicate(predicate) {
this.predicate = predicate;
}
OnErrorPredicate.prototype.equals = function (other) {
if (other === this) { return true; }
if (other == null) { return false; }
if (other.kind !== 'E') { return false; }
return this.predicate(other.error);
};
var ReactiveTest = Rx.ReactiveTest = {
/** Default virtual time used for creation of observable sequences in unit tests. */
created: 100,
/** Default virtual time used to subscribe to observable sequences in unit tests. */
subscribed: 200,
/** Default virtual time used to dispose subscriptions in unit tests. */
disposed: 1000,
/**
* Factory method for an OnNext notification record at a given time with a given value or a predicate function.
*
* 1 - ReactiveTest.onNext(200, 42);
* 2 - ReactiveTest.onNext(200, function (x) { return x.length == 2; });
*
* @param ticks Recorded virtual time the OnNext notification occurs.
* @param value Recorded value stored in the OnNext notification or a predicate.
* @return Recorded OnNext notification.
*/
onNext: function (ticks, value) {
return typeof value === 'function' ?
new Recorded(ticks, new OnNextPredicate(value)) :
new Recorded(ticks, Notification.createOnNext(value));
},
/**
* Factory method for an OnError notification record at a given time with a given error.
*
* 1 - ReactiveTest.onNext(200, new Error('error'));
* 2 - ReactiveTest.onNext(200, function (e) { return e.message === 'error'; });
*
* @param ticks Recorded virtual time the OnError notification occurs.
* @param exception Recorded exception stored in the OnError notification.
* @return Recorded OnError notification.
*/
onError: function (ticks, error) {
return typeof error === 'function' ?
new Recorded(ticks, new OnErrorPredicate(error)) :
new Recorded(ticks, Notification.createOnError(error));
},
/**
* Factory method for an OnCompleted notification record at a given time.
*
* @param ticks Recorded virtual time the OnCompleted notification occurs.
* @return Recorded OnCompleted notification.
*/
onCompleted: function (ticks) {
return new Recorded(ticks, Notification.createOnCompleted());
},
/**
* Factory method for a subscription record based on a given subscription and disposal time.
*
* @param start Virtual time indicating when the subscription was created.
* @param end Virtual time indicating when the subscription was disposed.
* @return Subscription object.
*/
subscribe: function (start, end) {
return new Subscription(start, end);
}
};
/**
* Creates a new object recording the production of the specified value at the given virtual time.
*
* @constructor
* @param {Number} time Virtual time the value was produced on.
* @param {Mixed} value Value that was produced.
* @param {Function} comparer An optional comparer.
*/
var Recorded = Rx.Recorded = function (time, value, comparer) {
this.time = time;
this.value = value;
this.comparer = comparer || defaultComparer;
};
/**
* Checks whether the given recorded object is equal to the current instance.
*
* @param {Recorded} other Recorded object to check for equality.
* @returns {Boolean} true if both objects are equal; false otherwise.
*/
Recorded.prototype.equals = function (other) {
return this.time === other.time && this.comparer(this.value, other.value);
};
/**
* Returns a string representation of the current Recorded value.
*
* @returns {String} String representation of the current Recorded value.
*/
Recorded.prototype.toString = function () {
return this.value.toString() + '@' + this.time;
};
/**
* Creates a new subscription object with the given virtual subscription and unsubscription time.
*
* @constructor
* @param {Number} subscribe Virtual time at which the subscription occurred.
* @param {Number} unsubscribe Virtual time at which the unsubscription occurred.
*/
var Subscription = Rx.Subscription = function (start, end) {
this.subscribe = start;
this.unsubscribe = end || Number.MAX_VALUE;
};
/**
* Checks whether the given subscription is equal to the current instance.
* @param other Subscription object to check for equality.
* @returns {Boolean} true if both objects are equal; false otherwise.
*/
Subscription.prototype.equals = function (other) {
return this.subscribe === other.subscribe && this.unsubscribe === other.unsubscribe;
};
/**
* Returns a string representation of the current Subscription value.
* @returns {String} String representation of the current Subscription value.
*/
Subscription.prototype.toString = function () {
return '(' + this.subscribe + ', ' + (this.unsubscribe === Number.MAX_VALUE ? 'Infinite' : this.unsubscribe) + ')';
};
var MockDisposable = Rx.MockDisposable = function (scheduler) {
this.scheduler = scheduler;
this.disposes = [];
this.disposes.push(this.scheduler.clock);
};
MockDisposable.prototype.dispose = function () {
this.disposes.push(this.scheduler.clock);
};
var MockObserver = (function (__super__) {
inherits(MockObserver, __super__);
function MockObserver(scheduler) {
__super__.call(this);
this.scheduler = scheduler;
this.messages = [];
}
var MockObserverPrototype = MockObserver.prototype;
MockObserverPrototype.onNext = function (value) {
this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnNext(value)));
};
MockObserverPrototype.onError = function (e) {
this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnError(e)));
};
MockObserverPrototype.onCompleted = function () {
this.messages.push(new Recorded(this.scheduler.clock, Notification.createOnCompleted()));
};
return MockObserver;
})(Observer);
function MockPromise(scheduler, messages) {
var self = this;
this.scheduler = scheduler;
this.messages = messages;
this.subscriptions = [];
this.observers = [];
for (var i = 0, len = this.messages.length; i < len; i++) {
var message = this.messages[i],
notification = message.value;
(function (innerNotification) {
scheduler.scheduleAbsolute(null, message.time, function () {
var obs = self.observers.slice(0);
for (var j = 0, jLen = obs.length; j < jLen; j++) {
innerNotification.accept(obs[j]);
}
return disposableEmpty;
});
})(notification);
}
}
MockPromise.prototype.then = function (onResolved, onRejected) {
var self = this;
this.subscriptions.push(new Subscription(this.scheduler.clock));
var index = this.subscriptions.length - 1;
var newPromise;
var observer = Rx.Observer.create(
function (x) {
var retValue = onResolved(x);
if (retValue && typeof retValue.then === 'function') {
newPromise = retValue;
} else {
var ticks = self.scheduler.clock;
newPromise = new MockPromise(self.scheduler, [Rx.ReactiveTest.onNext(ticks, undefined), Rx.ReactiveTest.onCompleted(ticks)]);
}
var idx = self.observers.indexOf(observer);
self.observers.splice(idx, 1);
self.subscriptions[index] = new Subscription(self.subscriptions[index].subscribe, self.scheduler.clock);
},
function (err) {
onRejected(err);
var idx = self.observers.indexOf(observer);
self.observers.splice(idx, 1);
self.subscriptions[index] = new Subscription(self.subscriptions[index].subscribe, self.scheduler.clock);
}
);
this.observers.push(observer);
return newPromise || new MockPromise(this.scheduler, this.messages);
};
var HotObservable = (function (__super__) {
inherits(HotObservable, __super__);
function HotObservable(scheduler, messages) {
__super__.call(this);
var message, notification, observable = this;
this.scheduler = scheduler;
this.messages = messages;
this.subscriptions = [];
this.observers = [];
for (var i = 0, len = this.messages.length; i < len; i++) {
message = this.messages[i];
notification = message.value;
(function (innerNotification) {
scheduler.scheduleAbsolute(null, message.time, function () {
var obs = observable.observers.slice(0);
for (var j = 0, jLen = obs.length; j < jLen; j++) {
innerNotification.accept(obs[j]);
}
return disposableEmpty;
});
})(notification);
}
}
HotObservable.prototype._subscribe = function (o) {
var observable = this;
this.observers.push(o);
this.subscriptions.push(new Subscription(this.scheduler.clock));
var index = this.subscriptions.length - 1;
return disposableCreate(function () {
var idx = observable.observers.indexOf(o);
observable.observers.splice(idx, 1);
observable.subscriptions[index] = new Subscription(observable.subscriptions[index].subscribe, observable.scheduler.clock);
});
};
return HotObservable;
})(Observable);
var ColdObservable = (function (__super__) {
inherits(ColdObservable, __super__);
function ColdObservable(scheduler, messages) {
__super__.call(this);
this.scheduler = scheduler;
this.messages = messages;
this.subscriptions = [];
}
ColdObservable.prototype._subscribe = function (o) {
var message, notification, observable = this;
this.subscriptions.push(new Subscription(this.scheduler.clock));
var index = this.subscriptions.length - 1;
var d = new CompositeDisposable();
for (var i = 0, len = this.messages.length; i < len; i++) {
message = this.messages[i];
notification = message.value;
(function (innerNotification) {
d.add(observable.scheduler.scheduleRelative(null, message.time, function () {
innerNotification.accept(o);
return disposableEmpty;
}));
})(notification);
}
return disposableCreate(function () {
observable.subscriptions[index] = new Subscription(observable.subscriptions[index].subscribe, observable.scheduler.clock);
d.dispose();
});
};
return ColdObservable;
})(Observable);
/** Virtual time scheduler used for testing applications and libraries built using Reactive Extensions. */
Rx.TestScheduler = (function (__super__) {
inherits(TestScheduler, __super__);
function baseComparer(x, y) {
return x > y ? 1 : (x < y ? -1 : 0);
}
function TestScheduler() {
__super__.call(this, 0, baseComparer);
}
/**
* Schedules an action to be executed at the specified virtual time.
*
* @param state State passed to the action to be executed.
* @param dueTime Absolute virtual time at which to execute the action.
* @param action Action to be executed.
* @return Disposable object used to cancel the scheduled action (best effort).
*/
TestScheduler.prototype.scheduleAbsolute = function (state, dueTime, action) {
dueTime <= this.clock && (dueTime = this.clock + 1);
return __super__.prototype.scheduleAbsolute.call(this, state, dueTime, action);
};
/**
* Adds a relative virtual time to an absolute virtual time value.
*
* @param absolute Absolute virtual time value.
* @param relative Relative virtual time value to add.
* @return Resulting absolute virtual time sum value.
*/
TestScheduler.prototype.add = function (absolute, relative) {
return absolute + relative;
};
/**
* Converts the absolute virtual time value to a DateTimeOffset value.
*
* @param absolute Absolute virtual time value to convert.
* @return Corresponding DateTimeOffset value.
*/
TestScheduler.prototype.toAbsoluteTime = function (absolute) {
return new Date(absolute).getTime();
};
/**
* Converts the TimeSpan value to a relative virtual time value.
*
* @param timeSpan TimeSpan value to convert.
* @return Corresponding relative virtual time value.
*/
TestScheduler.prototype.toRelativeTime = function (timeSpan) {
return timeSpan;
};
/**
* Starts the test scheduler and uses the specified virtual times to invoke the factory function, subscribe to the resulting sequence, and dispose the subscription.
*
* @param create Factory method to create an observable sequence.
* @param created Virtual time at which to invoke the factory to create an observable sequence.
* @param subscribed Virtual time at which to subscribe to the created observable sequence.
* @param disposed Virtual time at which to dispose the subscription.
* @return Observer with timestamped recordings of notification messages that were received during the virtual time window when the subscription to the source sequence was active.
*/
TestScheduler.prototype.startScheduler = function (createFn, settings) {
settings || (settings = {});
settings.created == null && (settings.created = ReactiveTest.created);
settings.subscribed == null && (settings.subscribed = ReactiveTest.subscribed);
settings.disposed == null && (settings.disposed = ReactiveTest.disposed);
var observer = this.createObserver(), source, subscription;
this.scheduleAbsolute(null, settings.created, function () {
source = createFn();
return disposableEmpty;
});
this.scheduleAbsolute(null, settings.subscribed, function () {
subscription = source.subscribe(observer);
return disposableEmpty;
});
this.scheduleAbsolute(null, settings.disposed, function () {
subscription.dispose();
return disposableEmpty;
});
this.start();
return observer;
};
/**
* Creates a hot observable using the specified timestamped notification messages either as an array or arguments.
* @param messages Notifications to surface through the created sequence at their specified absolute virtual times.
* @return Hot observable sequence that can be used to assert the timing of subscriptions and notifications.
*/
TestScheduler.prototype.createHotObservable = function () {
var len = arguments.length, args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
args = new Array(len);
for (var i = 0; i < len; i++) { args[i] = arguments[i]; }
}
return new HotObservable(this, args);
};
/**
* Creates a cold observable using the specified timestamped notification messages either as an array or arguments.
* @param messages Notifications to surface through the created sequence at their specified virtual time offsets from the sequence subscription time.
* @return Cold observable sequence that can be used to assert the timing of subscriptions and notifications.
*/
TestScheduler.prototype.createColdObservable = function () {
var len = arguments.length, args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
args = new Array(len);
for (var i = 0; i < len; i++) { args[i] = arguments[i]; }
}
return new ColdObservable(this, args);
};
/**
* Creates a resolved promise with the given value and ticks
* @param {Number} ticks The absolute time of the resolution.
* @param {Any} value The value to yield at the given tick.
* @returns {MockPromise} A mock Promise which fulfills with the given value.
*/
TestScheduler.prototype.createResolvedPromise = function (ticks, value) {
return new MockPromise(this, [Rx.ReactiveTest.onNext(ticks, value), Rx.ReactiveTest.onCompleted(ticks)]);
};
/**
* Creates a rejected promise with the given reason and ticks
* @param {Number} ticks The absolute time of the resolution.
* @param {Any} reason The reason for rejection to yield at the given tick.
* @returns {MockPromise} A mock Promise which rejects with the given reason.
*/
TestScheduler.prototype.createRejectedPromise = function (ticks, reason) {
return new MockPromise(this, [Rx.ReactiveTest.onError(ticks, reason)]);
};
/**
* Creates an observer that records received notification messages and timestamps those.
* @return Observer that can be used to assert the timing of received notifications.
*/
TestScheduler.prototype.createObserver = function () {
return new MockObserver(this);
};
return TestScheduler;
})(VirtualTimeScheduler);
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
return subscriber && isFunction(subscriber.dispose) ? subscriber :
isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
}
function setDisposable(s, state) {
var ado = state[0], self = state[1];
var sub = tryCatch(self.__subscribe).call(self, ado);
if (sub === errorObj && !ado.fail(errorObj.e)) { thrower(errorObj.e); }
ado.setDisposable(fixSubscriber(sub));
}
function AnonymousObservable(subscribe, parent) {
this.source = parent;
this.__subscribe = subscribe;
__super__.call(this);
}
AnonymousObservable.prototype._subscribe = function (o) {
var ado = new AutoDetachObserver(o), state = [ado, this];
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.schedule(state, setDisposable);
} else {
setDisposable(null, state);
}
return ado;
};
return AnonymousObservable;
}(Observable));
var AutoDetachObserver = (function (__super__) {
inherits(AutoDetachObserver, __super__);
function AutoDetachObserver(observer) {
__super__.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var result = tryCatch(this.observer.onNext).call(this.observer, value);
if (result === errorObj) {
this.dispose();
thrower(result.e);
}
};
AutoDetachObserverPrototype.error = function (err) {
var result = tryCatch(this.observer.onError).call(this.observer, err);
this.dispose();
result === errorObj && thrower(result.e);
};
AutoDetachObserverPrototype.completed = function () {
var result = tryCatch(this.observer.onCompleted).call(this.observer);
this.dispose();
result === errorObj && thrower(result.e);
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); };
AutoDetachObserverPrototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
var UnderlyingObservable = (function (__super__) {
inherits(UnderlyingObservable, __super__);
function UnderlyingObservable(m, u) {
this._m = m;
this._u = u;
__super__.call(this);
}
UnderlyingObservable.prototype.subscribeCore = function (o) {
return new BinaryDisposable(this._m.getDisposable(), this._u.subscribe(o));
};
return UnderlyingObservable;
}(ObservableBase));
var GroupedObservable = (function (__super__) {
inherits(GroupedObservable, __super__);
function GroupedObservable(key, underlyingObservable, mergedDisposable) {
__super__.call(this);
this.key = key;
this.underlyingObservable = !mergedDisposable ?
underlyingObservable :
new UnderlyingObservable(mergedDisposable, underlyingObservable);
}
GroupedObservable.prototype._subscribe = function (o) {
return this.underlyingObservable.subscribe(o);
};
return GroupedObservable;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (__super__) {
inherits(Subject, __super__);
function Subject() {
__super__.call(this);
this.isDisposed = false;
this.isStopped = false;
this.observers = [];
this.hasError = false;
}
addProperties(Subject.prototype, Observer.prototype, {
_subscribe: function (o) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(o);
return new InnerSubscription(this, o);
}
if (this.hasError) {
o.onError(this.error);
return disposableEmpty;
}
o.onCompleted();
return disposableEmpty;
},
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () { checkDisposed(this); return this.observers.length > 0; },
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
this.error = error;
this.hasError = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (!this.isStopped) {
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (__super__) {
inherits(AsyncSubject, __super__);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
__super__.call(this);
this.isDisposed = false;
this.isStopped = false;
this.hasValue = false;
this.observers = [];
this.hasError = false;
}
addProperties(AsyncSubject.prototype, Observer.prototype, {
_subscribe: function (o) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(o);
return new InnerSubscription(this, o);
}
if (this.hasError) {
o.onError(this.error);
} else if (this.hasValue) {
o.onNext(this.value);
o.onCompleted();
} else {
o.onCompleted();
}
return disposableEmpty;
},
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () { checkDisposed(this); return this.observers.length > 0; },
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var i, len;
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
var os = cloneArray(this.observers), len = os.length;
if (this.hasValue) {
for (i = 0; i < len; i++) {
var o = os[i];
o.onNext(this.value);
o.onCompleted();
}
} else {
for (i = 0; i < len; i++) {
os[i].onCompleted();
}
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the error.
* @param {Mixed} error The Error to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
this.value = value;
this.hasValue = true;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.error = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
inherits(AnonymousSubject, __super__);
function AnonymousSubject(observer, observable) {
this.observer = observer;
this.observable = observable;
__super__.call(this);
}
addProperties(AnonymousSubject.prototype, Observer.prototype, {
_subscribe: function (o) {
return this.observable.subscribe(o);
},
onCompleted: function () {
this.observer.onCompleted();
},
onError: function (error) {
this.observer.onError(error);
},
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
/**
* Represents a value that changes over time.
* Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
*/
var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) {
inherits(BehaviorSubject, __super__);
function BehaviorSubject(value) {
__super__.call(this);
this.value = value;
this.observers = [];
this.isDisposed = false;
this.isStopped = false;
this.hasError = false;
}
addProperties(BehaviorSubject.prototype, Observer.prototype, {
_subscribe: function (o) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(o);
o.onNext(this.value);
return new InnerSubscription(this, o);
}
if (this.hasError) {
o.onError(this.error);
} else {
o.onCompleted();
}
return disposableEmpty;
},
/**
* Gets the current value or throws an exception.
* Value is frozen after onCompleted is called.
* After onError is called always throws the specified exception.
* An exception is always thrown after dispose is called.
* @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext.
*/
getValue: function () {
checkDisposed(this);
if (this.hasError) { thrower(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 () { checkDisposed(this); return this.observers.length > 0; },
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
this.value = value;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onNext(value);
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.value = null;
this.error = null;
}
});
return BehaviorSubject;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
var ReplaySubject = Rx.ReplaySubject = (function (__super__) {
var maxSafeInteger = Math.pow(2, 53) - 1;
function createRemovableDisposable(subject, observer) {
return disposableCreate(function () {
observer.dispose();
!subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1);
});
}
inherits(ReplaySubject, __super__);
/**
* Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
* @param {Number} [bufferSize] Maximum element count of the replay buffer.
* @param {Number} [windowSize] Maximum time length of the replay buffer.
* @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
*/
function ReplaySubject(bufferSize, windowSize, scheduler) {
this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize;
this.windowSize = windowSize == null ? maxSafeInteger : windowSize;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopped = false;
this.isDisposed = false;
this.hasError = false;
this.error = null;
__super__.call(this);
}
addProperties(ReplaySubject.prototype, Observer.prototype, {
_subscribe: function (o) {
checkDisposed(this);
var so = new ScheduledObserver(this.scheduler, o), subscription = createRemovableDisposable(this, so);
this._trim(this.scheduler.now());
this.observers.push(so);
for (var i = 0, len = this.q.length; i < len; i++) {
so.onNext(this.q[i].value);
}
if (this.hasError) {
so.onError(this.error);
} else if (this.isStopped) {
so.onCompleted();
}
so.ensureActive();
return subscription;
},
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () { checkDisposed(this); 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));
/**
* 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));
|
app/javascript/mastodon/containers/account_container.js | clworld/mastodon | import React from 'react';
import { connect } from 'react-redux';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { makeGetAccount } from '../selectors';
import Account from '../components/account';
import {
followAccount,
unfollowAccount,
blockAccount,
unblockAccount,
muteAccount,
unmuteAccount,
} from '../actions/accounts';
import { openModal } from '../actions/modal';
import { initMuteModal } from '../actions/mutes';
import { unfollowModal } from '../initial_state';
const messages = defineMessages({
unfollowConfirm: { id: 'confirmations.unfollow.confirm', defaultMessage: 'Unfollow' },
});
const makeMapStateToProps = () => {
const getAccount = makeGetAccount();
const mapStateToProps = (state, props) => ({
account: getAccount(state, props.id),
});
return mapStateToProps;
};
const mapDispatchToProps = (dispatch, { intl }) => ({
onFollow (account) {
if (account.getIn(['relationship', 'following']) || account.getIn(['relationship', 'requested'])) {
if (unfollowModal) {
dispatch(openModal('CONFIRM', {
message: <FormattedMessage id='confirmations.unfollow.message' defaultMessage='Are you sure you want to unfollow {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} />,
confirm: intl.formatMessage(messages.unfollowConfirm),
onConfirm: () => dispatch(unfollowAccount(account.get('id'))),
}));
} else {
dispatch(unfollowAccount(account.get('id')));
}
} else {
dispatch(followAccount(account.get('id')));
}
},
onBlock (account) {
if (account.getIn(['relationship', 'blocking'])) {
dispatch(unblockAccount(account.get('id')));
} else {
dispatch(blockAccount(account.get('id')));
}
},
onMute (account) {
if (account.getIn(['relationship', 'muting'])) {
dispatch(unmuteAccount(account.get('id')));
} else {
dispatch(initMuteModal(account));
}
},
onMuteNotifications (account, notifications) {
dispatch(muteAccount(account.get('id'), notifications));
},
});
export default injectIntl(connect(makeMapStateToProps, mapDispatchToProps)(Account));
|
reloby-app-client/src/containers/NotFound.js | hwclass/reloby | import React from 'react';
import './NotFound.css';
const NotFound = () => (
<div className="NotFound">
<h3>Sorry, page not found!</h3>
</div>
);
export default NotFound; |
src/components/panels/index.js | Menternship/client-web | // @flow
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { Panel } from 'ui-kit';
import { getPathname } from '@client/selectors/router';
import { getPanel } from '@client/selectors/panel';
import panelRoutes from './panelRoutes';
import { close } from './actions';
class PanelContainer extends Component {
render() {
const { onClose, panel, params } = this.props;
const { Route } = panelRoutes(panel.location, { params });
return <Panel onClose={onClose}>{Route}</Panel>;
}
}
const mapStateToProps = createStructuredSelector({
panel: getPanel(),
pathname: getPathname,
});
function mapDispatchToProps(dispatch: $$dispatch) {
return {
onClose() {
dispatch(close());
},
};
}
export default connect(mapStateToProps, mapDispatchToProps)(PanelContainer);
|
node_modules/react-bootstrap/es/ButtonGroup.js | superKaigon/TheCave | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import all from 'prop-types-extra/lib/all';
import Button from './Button';
import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
vertical: PropTypes.bool,
justified: PropTypes.bool,
/**
* Display block buttons; only useful when used with the "vertical" prop.
* @type {bool}
*/
block: all(PropTypes.bool, function (_ref) {
var block = _ref.block,
vertical = _ref.vertical;
return block && !vertical ? new Error('`block` requires `vertical` to be set to have any effect') : null;
})
};
var defaultProps = {
block: false,
justified: false,
vertical: false
};
var ButtonGroup = function (_React$Component) {
_inherits(ButtonGroup, _React$Component);
function ButtonGroup() {
_classCallCheck(this, ButtonGroup);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
ButtonGroup.prototype.render = function render() {
var _extends2;
var _props = this.props,
block = _props.block,
justified = _props.justified,
vertical = _props.vertical,
className = _props.className,
props = _objectWithoutProperties(_props, ['block', 'justified', 'vertical', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps)] = !vertical, _extends2[prefix(bsProps, 'vertical')] = vertical, _extends2[prefix(bsProps, 'justified')] = justified, _extends2[prefix(Button.defaultProps, 'block')] = block, _extends2));
return React.createElement('div', _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return ButtonGroup;
}(React.Component);
ButtonGroup.propTypes = propTypes;
ButtonGroup.defaultProps = defaultProps;
export default bsClass('btn-group', ButtonGroup); |
examples/huge-apps/routes/Course/routes/Assignments/components/Sidebar.js | emmenko/react-router | import React from 'react';
import { Link } from 'react-router';
class Sidebar extends React.Component {
//static loadProps (params, cb) {
//cb(null, {
//assignments: COURSES[params.courseId].assignments
//});
//}
render () {
//var { assignments } = this.props;
var assignments = COURSES[this.props.params.courseId].assignments
return (
<div>
<h3>Sidebar Assignments</h3>
<ul>
{assignments.map(assignment => (
<li key={assignment.id}>
<Link to={`/course/${this.props.params.courseId}/assignments/${assignment.id}`}>
{assignment.title}
</Link>
</li>
))}
</ul>
</div>
);
}
}
export default Sidebar;
|
ajax/libs/vkui/4.27.0/cjs/hooks/useAppearance.js | cdnjs/cdnjs | "use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useAppearance = void 0;
var React = _interopRequireWildcard(require("react"));
var _ConfigProviderContext = require("../components/ConfigProvider/ConfigProviderContext");
var useAppearance = function useAppearance() {
return React.useContext(_ConfigProviderContext.ConfigProviderContext).appearance;
};
exports.useAppearance = useAppearance;
//# sourceMappingURL=useAppearance.js.map |
ajax/libs/react-data-grid/1.0.68/react-data-grid.js | dakshshah96/cdnjs | (function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"), require("react-dom"));
else if(typeof define === 'function' && define.amd)
define(["react", "react-dom"], factory);
else if(typeof exports === 'object')
exports["ReactDataGrid"] = factory(require("react"), require("react-dom"));
else
root["ReactDataGrid"] = factory(root["React"], root["ReactDOM"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_1__, __WEBPACK_EXTERNAL_MODULE_2__) {
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';
var Grid = __webpack_require__(54);
var Row = __webpack_require__(18);
var Cell = __webpack_require__(24);
module.exports = Grid;
module.exports.Row = Row;
module.exports.Cell = Cell;
/***/ },
/* 1 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_1__;
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_2__;
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
var freeGlobal = __webpack_require__(31);
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
module.exports = root;
/***/ },
/* 4 */
/***/ function(module, exports) {
'use strict';
module.exports = {
getColumn: function getColumn(columns, idx) {
if (Array.isArray(columns)) {
return columns[idx];
} else if (typeof Immutable !== 'undefined') {
return columns.get(idx);
}
},
spliceColumn: function spliceColumn(metrics, idx, column) {
if (Array.isArray(metrics.columns)) {
metrics.columns.splice(idx, 1, column);
} else if (typeof Immutable !== 'undefined') {
metrics.columns = metrics.columns.splice(idx, 1, column);
}
return metrics;
},
getSize: function getSize(columns) {
if (Array.isArray(columns)) {
return columns.length;
} else if (typeof Immutable !== 'undefined') {
return columns.size;
}
},
// Logic extented to allow for functions to be passed down in column.editable
// this allows us to deicde whether we can be edting from a cell level
canEdit: function canEdit(col, rowData, enableCellSelect) {
if (col.editable != null && typeof col.editable === 'function') {
return enableCellSelect === true && col.editable(rowData);
}
return enableCellSelect === true && (!!col.editor || !!col.editable);
}
};
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2015 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
function classNames() {
var classes = '';
var arg;
for (var i = 0; i < arguments.length; i++) {
arg = arguments[i];
if (!arg) {
continue;
}
if ('string' === typeof arg || 'number' === typeof arg) {
classes += ' ' + arg;
} else if (Object.prototype.toString.call(arg) === '[object Array]') {
classes += ' ' + classNames.apply(null, arg);
} else if ('object' === typeof arg) {
for (var key in arg) {
if (!arg.hasOwnProperty(key) || !arg[key]) {
continue;
}
classes += ' ' + key;
}
}
}
return classes.substr(1);
}
// safely export classNames for node / browserify
if (typeof module !== 'undefined' && module.exports) {
module.exports = classNames;
}
// safely export classNames for RequireJS
if (true) {
!(__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__));
}
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var ExcelColumnShape = {
name: React.PropTypes.node.isRequired,
key: React.PropTypes.string.isRequired,
width: React.PropTypes.number.isRequired,
filterable: React.PropTypes.bool
};
module.exports = ExcelColumnShape;
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
var baseIsNative = __webpack_require__(86),
getValue = __webpack_require__(97);
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = getValue(object, key);
return baseIsNative(value) ? value : undefined;
}
module.exports = getNative;
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var PropTypes = __webpack_require__(1).PropTypes;
module.exports = {
selected: PropTypes.object.isRequired,
copied: PropTypes.object,
dragged: PropTypes.object,
onCellClick: PropTypes.func.isRequired,
onCellDoubleClick: PropTypes.func.isRequired,
onCommit: PropTypes.func.isRequired,
onCommitCancel: PropTypes.func.isRequired,
handleDragEnterRow: PropTypes.func.isRequired,
handleTerminateDrag: PropTypes.func.isRequired
};
/***/ },
/* 9 */
/***/ function(module, exports) {
"use strict";
function createObjectWithProperties(originalObj, properties) {
var result = {};
for (var _iterator = properties, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var property = _ref;
if (originalObj[property]) {
result[property] = originalObj[property];
}
}
return result;
}
module.exports = createObjectWithProperties;
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var shallowCloneObject = __webpack_require__(19);
var contextTypes = {
metricsComputator: React.PropTypes.object
};
var MetricsComputatorMixin = {
childContextTypes: contextTypes,
getChildContext: function getChildContext() {
return { metricsComputator: this };
},
getMetricImpl: function getMetricImpl(name) {
return this._DOMMetrics.metrics[name].value;
},
registerMetricsImpl: function registerMetricsImpl(component, metrics) {
var getters = {};
var s = this._DOMMetrics;
for (var name in metrics) {
if (s.metrics[name] !== undefined) {
throw new Error('DOM metric ' + name + ' is already defined');
}
s.metrics[name] = { component: component, computator: metrics[name].bind(component) };
getters[name] = this.getMetricImpl.bind(null, name);
}
if (s.components.indexOf(component) === -1) {
s.components.push(component);
}
return getters;
},
unregisterMetricsFor: function unregisterMetricsFor(component) {
var s = this._DOMMetrics;
var idx = s.components.indexOf(component);
if (idx > -1) {
s.components.splice(idx, 1);
var name = void 0;
var metricsToDelete = {};
for (name in s.metrics) {
if (s.metrics[name].component === component) {
metricsToDelete[name] = true;
}
}
for (name in metricsToDelete) {
if (metricsToDelete.hasOwnProperty(name)) {
delete s.metrics[name];
}
}
}
},
updateMetrics: function updateMetrics() {
var s = this._DOMMetrics;
var needUpdate = false;
for (var name in s.metrics) {
if (!s.metrics.hasOwnProperty(name)) continue;
var newMetric = s.metrics[name].computator();
if (newMetric !== s.metrics[name].value) {
needUpdate = true;
}
s.metrics[name].value = newMetric;
}
if (needUpdate) {
for (var i = 0, len = s.components.length; i < len; i++) {
if (s.components[i].metricsUpdated) {
s.components[i].metricsUpdated();
}
}
}
},
componentWillMount: function componentWillMount() {
this._DOMMetrics = {
metrics: {},
components: []
};
},
componentDidMount: function componentDidMount() {
if (window.addEventListener) {
window.addEventListener('resize', this.updateMetrics);
} else {
window.attachEvent('resize', this.updateMetrics);
}
this.updateMetrics();
},
componentWillUnmount: function componentWillUnmount() {
window.removeEventListener('resize', this.updateMetrics);
}
};
var MetricsMixin = {
contextTypes: contextTypes,
componentWillMount: function componentWillMount() {
if (this.DOMMetrics) {
this._DOMMetricsDefs = shallowCloneObject(this.DOMMetrics);
this.DOMMetrics = {};
for (var name in this._DOMMetricsDefs) {
if (!this._DOMMetricsDefs.hasOwnProperty(name)) continue;
this.DOMMetrics[name] = function () {};
}
}
},
componentDidMount: function componentDidMount() {
if (this.DOMMetrics) {
this.DOMMetrics = this.registerMetrics(this._DOMMetricsDefs);
}
},
componentWillUnmount: function componentWillUnmount() {
if (!this.registerMetricsImpl) {
return this.context.metricsComputator.unregisterMetricsFor(this);
}
if (this.hasOwnProperty('DOMMetrics')) {
delete this.DOMMetrics;
}
},
registerMetrics: function registerMetrics(metrics) {
if (this.registerMetricsImpl) {
return this.registerMetricsImpl(this, metrics);
}
return this.context.metricsComputator.registerMetricsImpl(this, metrics);
},
getMetric: function getMetric(name) {
if (this.getMetricImpl) {
return this.getMetricImpl(name);
}
return this.context.metricsComputator.getMetricImpl(name);
}
};
module.exports = {
MetricsComputatorMixin: MetricsComputatorMixin,
MetricsMixin: MetricsMixin
};
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
var listCacheClear = __webpack_require__(107),
listCacheDelete = __webpack_require__(108),
listCacheGet = __webpack_require__(109),
listCacheHas = __webpack_require__(110),
listCacheSet = __webpack_require__(111);
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
module.exports = ListCache;
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
var eq = __webpack_require__(33);
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
module.exports = assocIndexOf;
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(22),
getRawTag = __webpack_require__(95),
objectToString = __webpack_require__(120);
/** `Object#toString` result references. */
var nullTag = '[object Null]',
undefinedTag = '[object Undefined]';
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
value = Object(value);
return (symToStringTag && symToStringTag in value)
? getRawTag(value)
: objectToString(value);
}
module.exports = baseGetTag;
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
var isKeyable = __webpack_require__(104);
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
module.exports = getMapData;
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(7);
/* Built-in method references that are verified to be native. */
var nativeCreate = getNative(Object, 'create');
module.exports = nativeCreate;
/***/ },
/* 16 */
/***/ function(module, exports) {
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
module.exports = isObjectLike;
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var shallowCloneObject = __webpack_require__(19);
var sameColumn = __webpack_require__(43);
var ColumnUtils = __webpack_require__(4);
var getScrollbarSize = __webpack_require__(28);
var isColumnsImmutable = __webpack_require__(70);
function setColumnWidths(columns, totalWidth) {
return columns.map(function (column) {
var colInfo = Object.assign({}, column);
if (column.width) {
if (/^([0-9]+)%$/.exec(column.width.toString())) {
colInfo.width = Math.floor(column.width / 100 * totalWidth);
}
}
return colInfo;
});
}
function setDefferedColumnWidths(columns, unallocatedWidth, minColumnWidth) {
var defferedColumns = columns.filter(function (c) {
return !c.width;
});
return columns.map(function (column) {
if (!column.width) {
if (unallocatedWidth <= 0) {
column.width = minColumnWidth;
} else {
column.width = Math.floor(unallocatedWidth / ColumnUtils.getSize(defferedColumns));
}
}
return column;
});
}
function setColumnOffsets(columns) {
var left = 0;
return columns.map(function (column) {
column.left = left;
left += column.width;
return column;
});
}
/**
* Update column metrics calculation.
*
* @param {ColumnMetricsType} metrics
*/
function recalculate(metrics) {
// compute width for columns which specify width
var columns = setColumnWidths(metrics.columns, metrics.totalWidth);
var unallocatedWidth = columns.filter(function (c) {
return c.width;
}).reduce(function (w, column) {
return w - column.width;
}, metrics.totalWidth);
unallocatedWidth -= getScrollbarSize();
var width = columns.filter(function (c) {
return c.width;
}).reduce(function (w, column) {
return w + column.width;
}, 0);
// compute width for columns which doesn't specify width
columns = setDefferedColumnWidths(columns, unallocatedWidth, metrics.minColumnWidth);
// compute left offset
columns = setColumnOffsets(columns);
return {
columns: columns,
width: width,
totalWidth: metrics.totalWidth,
minColumnWidth: metrics.minColumnWidth
};
}
/**
* Update column metrics calculation by resizing a column.
*
* @param {ColumnMetricsType} metrics
* @param {Column} column
* @param {number} width
*/
function resizeColumn(metrics, index, width) {
var column = ColumnUtils.getColumn(metrics.columns, index);
var metricsClone = shallowCloneObject(metrics);
metricsClone.columns = metrics.columns.slice(0);
var updatedColumn = shallowCloneObject(column);
updatedColumn.width = Math.max(width, metricsClone.minColumnWidth);
metricsClone = ColumnUtils.spliceColumn(metricsClone, index, updatedColumn);
return recalculate(metricsClone);
}
function areColumnsImmutable(prevColumns, nextColumns) {
return isColumnsImmutable(prevColumns) && isColumnsImmutable(nextColumns);
}
function compareEachColumn(prevColumns, nextColumns, isSameColumn) {
var i = void 0;
var len = void 0;
var column = void 0;
var prevColumnsByKey = {};
var nextColumnsByKey = {};
if (ColumnUtils.getSize(prevColumns) !== ColumnUtils.getSize(nextColumns)) {
return false;
}
for (i = 0, len = ColumnUtils.getSize(prevColumns); i < len; i++) {
column = prevColumns[i];
prevColumnsByKey[column.key] = column;
}
for (i = 0, len = ColumnUtils.getSize(nextColumns); i < len; i++) {
column = nextColumns[i];
nextColumnsByKey[column.key] = column;
var prevColumn = prevColumnsByKey[column.key];
if (prevColumn === undefined || !isSameColumn(prevColumn, column)) {
return false;
}
}
for (i = 0, len = ColumnUtils.getSize(prevColumns); i < len; i++) {
column = prevColumns[i];
var nextColumn = nextColumnsByKey[column.key];
if (nextColumn === undefined) {
return false;
}
}
return true;
}
function sameColumns(prevColumns, nextColumns, isSameColumn) {
if (areColumnsImmutable(prevColumns, nextColumns)) {
return prevColumns === nextColumns;
}
return compareEachColumn(prevColumns, nextColumns, isSameColumn);
}
module.exports = { recalculate: recalculate, resizeColumn: resizeColumn, sameColumn: sameColumn, sameColumns: sameColumns };
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _OverflowCell = __webpack_require__(53);
var _OverflowCell2 = _interopRequireDefault(_OverflowCell);
var _RowComparer = __webpack_require__(56);
var _RowComparer2 = _interopRequireDefault(_RowComparer);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var React = __webpack_require__(1);
var joinClasses = __webpack_require__(5);
var Cell = __webpack_require__(24);
var ColumnUtilsMixin = __webpack_require__(4);
var cellMetaDataShape = __webpack_require__(8);
var PropTypes = React.PropTypes;
var createObjectWithProperties = __webpack_require__(9);
var CellExpander = React.createClass({
displayName: 'CellExpander',
render: function render() {
return React.createElement(Cell, this.props);
}
});
// The list of the propTypes that we want to include in the Row div
var knownDivPropertyKeys = ['height'];
var Row = React.createClass({
displayName: 'Row',
propTypes: {
height: PropTypes.number.isRequired,
columns: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired,
row: PropTypes.any.isRequired,
cellRenderer: PropTypes.func,
cellMetaData: PropTypes.shape(cellMetaDataShape),
isSelected: PropTypes.bool,
idx: PropTypes.number.isRequired,
expandedRows: PropTypes.arrayOf(PropTypes.object),
extraClasses: PropTypes.string,
forceUpdate: PropTypes.bool,
subRowDetails: PropTypes.object,
isRowHovered: PropTypes.bool,
colVisibleStart: PropTypes.number.isRequired,
colVisibleEnd: PropTypes.number.isRequired,
colDisplayStart: PropTypes.number.isRequired,
colDisplayEnd: PropTypes.number.isRequired,
isScrolling: React.PropTypes.bool.isRequired
},
mixins: [ColumnUtilsMixin],
getDefaultProps: function getDefaultProps() {
return {
cellRenderer: Cell,
isSelected: false,
height: 35
};
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps) {
return (0, _RowComparer2['default'])(nextProps, this.props);
},
handleDragEnter: function handleDragEnter() {
var handleDragEnterRow = this.props.cellMetaData.handleDragEnterRow;
if (handleDragEnterRow) {
handleDragEnterRow(this.props.idx);
}
},
getSelectedColumn: function getSelectedColumn() {
if (this.props.cellMetaData) {
var selected = this.props.cellMetaData.selected;
if (selected && selected.idx) {
return this.getColumn(this.props.columns, selected.idx);
}
}
},
getCellRenderer: function getCellRenderer(columnKey) {
var CellRenderer = this.props.cellRenderer;
if (this.props.subRowDetails && this.props.subRowDetails.field === columnKey) {
return CellExpander;
}
return CellRenderer;
},
getCell: function getCell(column, i, selectedColumn) {
var CellRenderer = this.props.cellRenderer;
var _props = this.props,
colVisibleStart = _props.colVisibleStart,
colVisibleEnd = _props.colVisibleEnd,
idx = _props.idx,
cellMetaData = _props.cellMetaData;
var key = column.key,
formatter = column.formatter;
var baseCellProps = { key: key + '-' + idx, idx: i, rowIdx: idx, height: this.getRowHeight(), column: column, cellMetaData: cellMetaData };
if (i < colVisibleStart || i > colVisibleEnd) {
return React.createElement(_OverflowCell2['default'], _extends({ ref: key }, baseCellProps));
}
var _props2 = this.props,
row = _props2.row,
isSelected = _props2.isSelected;
var cellProps = {
ref: key,
value: this.getCellValue(key || i),
rowData: row,
isRowSelected: isSelected,
expandableOptions: this.getExpandableOptions(key),
selectedColumn: selectedColumn,
formatter: formatter,
isScrolling: this.props.isScrolling
};
return React.createElement(CellRenderer, _extends({}, baseCellProps, cellProps));
},
getCells: function getCells() {
var _this = this;
var cells = [];
var lockedCells = [];
var selectedColumn = this.getSelectedColumn();
if (this.props.columns) {
this.props.columns.forEach(function (column, i) {
var cell = _this.getCell(column, i, selectedColumn);
if (column.locked) {
lockedCells.push(cell);
} else {
cells.push(cell);
}
});
}
return cells.concat(lockedCells);
},
getRowHeight: function getRowHeight() {
var rows = this.props.expandedRows || null;
if (rows && this.props.idx) {
var row = rows[this.props.idx] || null;
if (row) {
return row.height;
}
}
return this.props.height;
},
getCellValue: function getCellValue(key) {
var val = void 0;
if (key === 'select-row') {
return this.props.isSelected;
} else if (typeof this.props.row.get === 'function') {
val = this.props.row.get(key);
} else {
val = this.props.row[key];
}
return val;
},
isContextMenuDisplayed: function isContextMenuDisplayed() {
if (this.props.cellMetaData) {
var selected = this.props.cellMetaData.selected;
if (selected && selected.contextMenuDisplayed && selected.rowIdx === this.props.idx) {
return true;
}
}
return false;
},
getExpandableOptions: function getExpandableOptions(columnKey) {
return { canExpand: this.props.subRowDetails && this.props.subRowDetails.field === columnKey, expanded: this.props.subRowDetails && this.props.subRowDetails.expanded, children: this.props.subRowDetails && this.props.subRowDetails.children, treeDepth: this.props.subRowDetails ? this.props.subRowDetails.treeDepth : 0 };
},
setScrollLeft: function setScrollLeft(scrollLeft) {
var _this2 = this;
this.props.columns.forEach(function (column, i) {
if (column.locked) {
if (!_this2.refs['cell-' + i]) return;
_this2.refs['cell-' + i].setScrollLeft(scrollLeft);
}
});
},
getKnownDivProps: function getKnownDivProps() {
return createObjectWithProperties(this.props, knownDivPropertyKeys);
},
renderCell: function renderCell(props) {
if (typeof this.props.cellRenderer === 'function') {
this.props.cellRenderer.call(this, props);
}
if (React.isValidElement(this.props.cellRenderer)) {
return React.cloneElement(this.props.cellRenderer, props);
}
return this.props.cellRenderer(props);
},
render: function render() {
var className = joinClasses('react-grid-Row', 'react-grid-Row--' + (this.props.idx % 2 === 0 ? 'even' : 'odd'), {
'row-selected': this.props.isSelected,
'row-context-menu': this.isContextMenuDisplayed()
}, this.props.extraClasses);
var style = {
height: this.getRowHeight(this.props),
overflow: 'hidden',
contain: 'layout'
};
var cells = this.getCells();
return React.createElement(
'div',
_extends({}, this.getKnownDivProps(), { className: className, style: style, onDragEnter: this.handleDragEnter }),
React.isValidElement(this.props.row) ? this.props.row : cells
);
}
});
module.exports = Row;
/***/ },
/* 19 */
/***/ function(module, exports) {
"use strict";
function shallowCloneObject(obj) {
var result = {};
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
result[k] = obj[k];
}
}
return result;
}
module.exports = shallowCloneObject;
/***/ },
/* 20 */
/***/ 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;
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(7),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var Map = getNative(root, 'Map');
module.exports = Map;
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
var root = __webpack_require__(3);
/** Built-in value references. */
var Symbol = root.Symbol;
module.exports = Symbol;
/***/ },
/* 23 */
/***/ function(module, exports) {
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
module.exports = isObject;
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _isEqual = __webpack_require__(132);
var _isEqual2 = _interopRequireDefault(_isEqual);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(2);
var joinClasses = __webpack_require__(5);
var EditorContainer = __webpack_require__(66);
var ExcelColumn = __webpack_require__(6);
var isFunction = __webpack_require__(27);
var CellMetaDataShape = __webpack_require__(8);
var SimpleCellFormatter = __webpack_require__(68);
var ColumnUtils = __webpack_require__(4);
var createObjectWithProperties = __webpack_require__(9);
// The list of the propTypes that we want to include in the Cell div
var knownDivPropertyKeys = ['height', 'tabIndex', 'value'];
var Cell = React.createClass({
displayName: 'Cell',
propTypes: {
rowIdx: React.PropTypes.number.isRequired,
idx: React.PropTypes.number.isRequired,
selected: React.PropTypes.shape({
idx: React.PropTypes.number.isRequired
}),
selectedColumn: React.PropTypes.object,
height: React.PropTypes.number,
tabIndex: React.PropTypes.number,
ref: React.PropTypes.string,
column: React.PropTypes.shape(ExcelColumn).isRequired,
value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired,
isExpanded: React.PropTypes.bool,
isRowSelected: React.PropTypes.bool,
cellMetaData: React.PropTypes.shape(CellMetaDataShape).isRequired,
handleDragStart: React.PropTypes.func,
className: React.PropTypes.string,
cellControls: React.PropTypes.any,
rowData: React.PropTypes.object.isRequired,
forceUpdate: React.PropTypes.bool,
expandableOptions: React.PropTypes.object.isRequired,
isScrolling: React.PropTypes.bool.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
tabIndex: -1,
isExpanded: false,
value: ''
};
},
getInitialState: function getInitialState() {
return {
isCellValueChanging: false
};
},
componentDidMount: function componentDidMount() {
this.checkFocus();
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
this.setState({
isCellValueChanging: this.props.value !== nextProps.value
});
},
componentDidUpdate: function componentDidUpdate() {
this.checkFocus();
var dragged = this.props.cellMetaData.dragged;
if (dragged && dragged.complete === true) {
this.props.cellMetaData.handleTerminateDrag();
}
if (this.state.isCellValueChanging && this.props.selectedColumn != null) {
this.applyUpdateClass();
}
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps) {
var shouldUpdate = this.props.column.width !== nextProps.column.width || this.props.column.left !== nextProps.column.left || this.props.column.cellClass !== nextProps.column.cellClass || this.props.height !== nextProps.height || this.props.rowIdx !== nextProps.rowIdx || this.isCellSelectionChanging(nextProps) || this.isDraggedCellChanging(nextProps) || this.isCopyCellChanging(nextProps) || this.props.isRowSelected !== nextProps.isRowSelected || this.isSelected() || this.props.value !== nextProps.value || this.props.forceUpdate === true || this.props.className !== nextProps.className || this.hasChangedDependentValues(nextProps);
return shouldUpdate;
},
onCellClick: function onCellClick(e) {
var meta = this.props.cellMetaData;
if (meta != null && meta.onCellClick && typeof meta.onCellClick === 'function') {
meta.onCellClick({ rowIdx: this.props.rowIdx, idx: this.props.idx }, e);
}
},
onCellContextMenu: function onCellContextMenu() {
var meta = this.props.cellMetaData;
if (meta != null && meta.onCellContextMenu && typeof meta.onCellContextMenu === 'function') {
meta.onCellContextMenu({ rowIdx: this.props.rowIdx, idx: this.props.idx });
}
},
onCellDoubleClick: function onCellDoubleClick(e) {
var meta = this.props.cellMetaData;
if (meta != null && meta.onCellDoubleClick && typeof meta.onCellDoubleClick === 'function') {
meta.onCellDoubleClick({ rowIdx: this.props.rowIdx, idx: this.props.idx }, e);
}
},
onCellExpand: function onCellExpand(e) {
e.stopPropagation();
var meta = this.props.cellMetaData;
if (meta != null && meta.onCellExpand != null) {
meta.onCellExpand({ rowIdx: this.props.rowIdx, idx: this.props.idx, rowData: this.props.rowData, expandArgs: this.props.expandableOptions });
}
},
onCellKeyDown: function onCellKeyDown(e) {
if (this.canExpand() && e.key === 'Enter') {
this.onCellExpand(e);
}
},
onDragHandleDoubleClick: function onDragHandleDoubleClick(e) {
e.stopPropagation();
var meta = this.props.cellMetaData;
if (meta != null && meta.onDragHandleDoubleClick && typeof meta.onDragHandleDoubleClick === 'function') {
meta.onDragHandleDoubleClick({ rowIdx: this.props.rowIdx, idx: this.props.idx, rowData: this.getRowData(), e: e });
}
},
onDragOver: function onDragOver(e) {
e.preventDefault();
},
getStyle: function getStyle() {
var style = {
position: 'absolute',
width: this.props.column.width,
height: this.props.height,
left: this.props.column.left,
contain: 'layout'
};
return style;
},
getFormatter: function getFormatter() {
var col = this.props.column;
if (this.isActive()) {
return React.createElement(EditorContainer, { rowData: this.getRowData(), rowIdx: this.props.rowIdx, value: this.props.value, idx: this.props.idx, cellMetaData: this.props.cellMetaData, column: col, height: this.props.height });
}
return this.props.column.formatter;
},
getRowData: function getRowData() {
var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props;
return props.rowData.toJSON ? props.rowData.toJSON() : props.rowData;
},
getFormatterDependencies: function getFormatterDependencies() {
// convention based method to get corresponding Id or Name of any Name or Id property
if (typeof this.props.column.getRowMetaData === 'function') {
return this.props.column.getRowMetaData(this.getRowData(), this.props.column);
}
},
getCellClass: function getCellClass() {
var className = joinClasses(this.props.column.cellClass, 'react-grid-Cell', this.props.className, this.props.column.locked ? 'react-grid-Cell--locked' : null);
var extraClasses = joinClasses({
'row-selected': this.props.isRowSelected,
editing: this.isActive(),
copied: this.isCopied() || this.wasDraggedOver() || this.isDraggedOverUpwards() || this.isDraggedOverDownwards(),
'is-dragged-over-up': this.isDraggedOverUpwards(),
'is-dragged-over-down': this.isDraggedOverDownwards(),
'was-dragged-over': this.wasDraggedOver()
});
return joinClasses(className, extraClasses);
},
getUpdateCellClass: function getUpdateCellClass() {
return this.props.column.getUpdateCellClass ? this.props.column.getUpdateCellClass(this.props.selectedColumn, this.props.column, this.state.isCellValueChanging) : '';
},
isColumnSelected: function isColumnSelected() {
var meta = this.props.cellMetaData;
if (meta == null) {
return false;
}
return meta.selected && meta.selected.idx === this.props.idx;
},
isSelected: function isSelected() {
var meta = this.props.cellMetaData;
if (meta == null) {
return false;
}
return meta.selected && meta.selected.rowIdx === this.props.rowIdx && meta.selected.idx === this.props.idx;
},
isActive: function isActive() {
var meta = this.props.cellMetaData;
if (meta == null) {
return false;
}
return this.isSelected() && meta.selected.active === true;
},
isCellSelectionChanging: function isCellSelectionChanging(nextProps) {
var meta = this.props.cellMetaData;
if (meta == null) {
return false;
}
var nextSelected = nextProps.cellMetaData.selected;
if (meta.selected && nextSelected) {
return this.props.idx === nextSelected.idx || this.props.idx === meta.selected.idx;
}
return true;
},
isCellSelectEnabled: function isCellSelectEnabled() {
var meta = this.props.cellMetaData;
if (meta == null) {
return false;
}
return meta.enableCellSelect;
},
hasChangedDependentValues: function hasChangedDependentValues(nextProps) {
var currentColumn = this.props.column;
var hasChangedDependentValues = false;
if (currentColumn.getRowMetaData) {
var currentRowMetaData = currentColumn.getRowMetaData(this.getRowData(), currentColumn);
var nextColumn = nextProps.column;
var nextRowMetaData = nextColumn.getRowMetaData(this.getRowData(nextProps), nextColumn);
hasChangedDependentValues = !(0, _isEqual2['default'])(currentRowMetaData, nextRowMetaData);
}
return hasChangedDependentValues;
},
applyUpdateClass: function applyUpdateClass() {
var updateCellClass = this.getUpdateCellClass();
// -> removing the class
if (updateCellClass != null && updateCellClass !== '') {
var cellDOMNode = ReactDOM.findDOMNode(this);
if (cellDOMNode.classList) {
cellDOMNode.classList.remove(updateCellClass);
// -> and re-adding the class
cellDOMNode.classList.add(updateCellClass);
} else if (cellDOMNode.className.indexOf(updateCellClass) === -1) {
// IE9 doesn't support classList, nor (I think) altering element.className
// without replacing it wholesale.
cellDOMNode.className = cellDOMNode.className + ' ' + updateCellClass;
}
}
},
setScrollLeft: function setScrollLeft(scrollLeft) {
var ctrl = this; // flow on windows has an outdated react declaration, once that gets updated, we can remove this
if (ctrl.isMounted()) {
var node = ReactDOM.findDOMNode(this);
var transform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)';
node.style.webkitTransform = transform;
node.style.transform = transform;
}
},
isCopied: function isCopied() {
var copied = this.props.cellMetaData.copied;
return copied && copied.rowIdx === this.props.rowIdx && copied.idx === this.props.idx;
},
isDraggedOver: function isDraggedOver() {
var dragged = this.props.cellMetaData.dragged;
return dragged && dragged.overRowIdx === this.props.rowIdx && dragged.idx === this.props.idx;
},
wasDraggedOver: function wasDraggedOver() {
var dragged = this.props.cellMetaData.dragged;
return dragged && (dragged.overRowIdx < this.props.rowIdx && this.props.rowIdx < dragged.rowIdx || dragged.overRowIdx > this.props.rowIdx && this.props.rowIdx > dragged.rowIdx) && dragged.idx === this.props.idx;
},
isDraggedCellChanging: function isDraggedCellChanging(nextProps) {
var isChanging = void 0;
var dragged = this.props.cellMetaData.dragged;
var nextDragged = nextProps.cellMetaData.dragged;
if (dragged) {
isChanging = nextDragged && this.props.idx === nextDragged.idx || dragged && this.props.idx === dragged.idx;
return isChanging;
}
return false;
},
isCopyCellChanging: function isCopyCellChanging(nextProps) {
var isChanging = void 0;
var copied = this.props.cellMetaData.copied;
var nextCopied = nextProps.cellMetaData.copied;
if (copied) {
isChanging = nextCopied && this.props.idx === nextCopied.idx || copied && this.props.idx === copied.idx;
return isChanging;
}
return false;
},
isDraggedOverUpwards: function isDraggedOverUpwards() {
var dragged = this.props.cellMetaData.dragged;
return !this.isSelected() && this.isDraggedOver() && this.props.rowIdx < dragged.rowIdx;
},
isDraggedOverDownwards: function isDraggedOverDownwards() {
var dragged = this.props.cellMetaData.dragged;
return !this.isSelected() && this.isDraggedOver() && this.props.rowIdx > dragged.rowIdx;
},
isFocusedOnBody: function isFocusedOnBody() {
return document.activeElement == null || document.activeElement.nodeName && typeof document.activeElement.nodeName === 'string' && document.activeElement.nodeName.toLowerCase() === 'body';
},
checkFocus: function checkFocus() {
if (this.isSelected() && !this.isActive()) {
if (this.props.isScrolling && !this.props.cellMetaData.isScrollingVerticallyWithKeyboard && !this.props.cellMetaData.isScrollingHorizontallyWithKeyboard) {
return;
}
// Only focus to the current cell if the currently active node in the document is within the data grid.
// Meaning focus should not be stolen from elements that the grid doesnt control.
var dataGridDOMNode = this.props.cellMetaData && this.props.cellMetaData.getDataGridDOMNode ? this.props.cellMetaData.getDataGridDOMNode() : null;
if (document.activeElement.className === 'react-grid-Cell' || this.isFocusedOnBody() || dataGridDOMNode && dataGridDOMNode.contains(document.activeElement)) {
var cellDOMNode = ReactDOM.findDOMNode(this);
if (cellDOMNode) {
cellDOMNode.focus();
}
}
}
},
canEdit: function canEdit() {
return this.props.column.editor != null || this.props.column.editable;
},
canExpand: function canExpand() {
return this.props.expandableOptions && this.props.expandableOptions.canExpand;
},
createColumEventCallBack: function createColumEventCallBack(onColumnEvent, info) {
return function (e) {
onColumnEvent(e, info);
};
},
createCellEventCallBack: function createCellEventCallBack(gridEvent, columnEvent) {
return function (e) {
gridEvent(e);
columnEvent(e);
};
},
createEventDTO: function createEventDTO(gridEvents, columnEvents, onColumnEvent) {
var allEvents = Object.assign({}, gridEvents);
for (var eventKey in columnEvents) {
if (columnEvents.hasOwnProperty(eventKey)) {
var event = columnEvents[event];
var eventInfo = { rowIdx: this.props.rowIdx, idx: this.props.idx, name: eventKey };
var eventCallback = this.createColumEventCallBack(onColumnEvent, eventInfo);
if (allEvents.hasOwnProperty(eventKey)) {
var currentEvent = allEvents[eventKey];
allEvents[eventKey] = this.createCellEventCallBack(currentEvent, eventCallback);
} else {
allEvents[eventKey] = eventCallback;
}
}
}
return allEvents;
},
getEvents: function getEvents() {
var columnEvents = this.props.column ? Object.assign({}, this.props.column.events) : undefined;
var onColumnEvent = this.props.cellMetaData ? this.props.cellMetaData.onColumnEvent : undefined;
var gridEvents = {
onClick: this.onCellClick,
onDoubleClick: this.onCellDoubleClick,
onContextMenu: this.onCellContextMenu,
onDragOver: this.onDragOver
};
if (!columnEvents || !onColumnEvent) {
return gridEvents;
}
return this.createEventDTO(gridEvents, columnEvents, onColumnEvent);
},
getKnownDivProps: function getKnownDivProps() {
return createObjectWithProperties(this.props, knownDivPropertyKeys);
},
renderCellContent: function renderCellContent(props) {
var CellContent = void 0;
var Formatter = this.getFormatter();
if (React.isValidElement(Formatter)) {
props.dependentValues = this.getFormatterDependencies();
CellContent = React.cloneElement(Formatter, props);
} else if (isFunction(Formatter)) {
CellContent = React.createElement(Formatter, { value: this.props.value, dependentValues: this.getFormatterDependencies() });
} else {
CellContent = React.createElement(SimpleCellFormatter, { value: this.props.value });
}
var cellExpander = void 0;
var marginLeft = this.props.expandableOptions ? this.props.expandableOptions.treeDepth * 30 : 0;
if (this.canExpand()) {
cellExpander = React.createElement(
'span',
{ style: { float: 'left', marginLeft: marginLeft }, onClick: this.onCellExpand },
this.props.expandableOptions.expanded ? String.fromCharCode('9660') : String.fromCharCode('9658')
);
}
return React.createElement(
'div',
{ className: 'react-grid-Cell__value' },
cellExpander,
React.createElement(
'span',
null,
CellContent
),
' ',
this.props.cellControls,
' '
);
},
render: function render() {
if (this.props.column.hidden) {
return null;
}
var style = this.getStyle();
var className = this.getCellClass();
var cellContent = this.renderCellContent({
value: this.props.value,
column: this.props.column,
rowIdx: this.props.rowIdx,
isExpanded: this.props.isExpanded
});
var dragHandle = !this.isActive() && ColumnUtils.canEdit(this.props.column, this.props.rowData, this.props.cellMetaData.enableCellSelect) ? React.createElement(
'div',
{ className: 'drag-handle', draggable: 'true', onDoubleClick: this.onDragHandleDoubleClick },
React.createElement('span', { style: { display: 'none' } })
) : null;
var events = this.getEvents();
return React.createElement(
'div',
_extends({}, this.getKnownDivProps(), { className: className, style: style }, events),
cellContent,
dragHandle
);
}
});
module.exports = Cell;
/***/ },
/* 25 */
/***/ function(module, exports) {
'use strict';
var KeyboardHandlerMixin = {
onKeyDown: function onKeyDown(e) {
if (this.isCtrlKeyHeldDown(e)) {
this.checkAndCall('onPressKeyWithCtrl', e);
} else if (this.isKeyExplicitlyHandled(e.key)) {
// break up individual keyPress events to have their own specific callbacks
// this allows multiple mixins to listen to onKeyDown events and somewhat reduces methodName clashing
var callBack = 'onPress' + e.key;
this.checkAndCall(callBack, e);
} else if (this.isKeyPrintable(e.keyCode)) {
this.checkAndCall('onPressChar', e);
}
// Track which keys are currently down for shift clicking etc
this._keysDown = this._keysDown || {};
this._keysDown[e.keyCode] = true;
if (this.props.onGridKeyDown && typeof this.props.onGridKeyDown === 'function') {
this.props.onGridKeyDown(e);
}
},
onKeyUp: function onKeyUp(e) {
// Track which keys are currently down for shift clicking etc
this._keysDown = this._keysDown || {};
delete this._keysDown[e.keyCode];
if (this.props.onGridKeyUp && typeof this.props.onGridKeyUp === 'function') {
this.props.onGridKeyUp(e);
}
},
isKeyDown: function isKeyDown(keyCode) {
if (!this._keysDown) return false;
return keyCode in this._keysDown;
},
isSingleKeyDown: function isSingleKeyDown(keyCode) {
if (!this._keysDown) return false;
return keyCode in this._keysDown && Object.keys(this._keysDown).length === 1;
},
// taken from http://stackoverflow.com/questions/12467240/determine-if-javascript-e-keycode-is-a-printable-non-control-character
isKeyPrintable: function isKeyPrintable(keycode) {
var valid = keycode > 47 && keycode < 58 || // number keys
keycode === 32 || keycode === 13 || // spacebar & return key(s) (if you want to allow carriage returns)
keycode > 64 && keycode < 91 || // letter keys
keycode > 95 && keycode < 112 || // numpad keys
keycode > 185 && keycode < 193 || // ;=,-./` (in order)
keycode > 218 && keycode < 223; // [\]' (in order)
return valid;
},
isKeyExplicitlyHandled: function isKeyExplicitlyHandled(key) {
return typeof this['onPress' + key] === 'function';
},
isCtrlKeyHeldDown: function isCtrlKeyHeldDown(e) {
return e.ctrlKey === true && e.key !== 'Control';
},
checkAndCall: function checkAndCall(methodName, args) {
if (typeof this[methodName] === 'function') {
this[methodName](args);
}
}
};
module.exports = KeyboardHandlerMixin;
/***/ },
/* 26 */
/***/ function(module, exports) {
'use strict';
var RowUtils = {
get: function get(row, property) {
if (typeof row.get === 'function') {
return row.get(property);
}
return row[property];
},
isRowSelected: function isRowSelected(keys, indexes, isSelectedKey, rowData, rowIdx) {
if (indexes && Object.prototype.toString.call(indexes) === '[object Array]') {
return indexes.indexOf(rowIdx) > -1;
} else if (keys && keys.rowKey && keys.values && Object.prototype.toString.call(keys.values) === '[object Array]') {
return keys.values.indexOf(rowData[keys.rowKey]) > -1;
} else if (isSelectedKey && rowData && typeof isSelectedKey === 'string') {
return rowData[isSelectedKey];
}
return false;
}
};
module.exports = RowUtils;
/***/ },
/* 27 */
/***/ function(module, exports) {
'use strict';
var isFunction = function isFunction(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
};
module.exports = isFunction;
/***/ },
/* 28 */
/***/ function(module, exports) {
'use strict';
var size = void 0;
function getScrollbarSize() {
if (size === undefined) {
var outer = document.createElement('div');
outer.style.width = '50px';
outer.style.height = '50px';
outer.style.position = 'absolute';
outer.style.top = '-200px';
outer.style.left = '-200px';
var inner = document.createElement('div');
inner.style.height = '100px';
inner.style.width = '100%';
outer.appendChild(inner);
document.body.appendChild(outer);
var outerWidth = outer.clientWidth;
outer.style.overflowY = 'scroll';
var innerWidth = inner.clientWidth;
document.body.removeChild(outer);
size = outerWidth - innerWidth;
}
return size;
}
module.exports = getScrollbarSize;
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
var mapCacheClear = __webpack_require__(112),
mapCacheDelete = __webpack_require__(113),
mapCacheGet = __webpack_require__(114),
mapCacheHas = __webpack_require__(115),
mapCacheSet = __webpack_require__(116);
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
module.exports = MapCache;
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
var SetCache = __webpack_require__(77),
arraySome = __webpack_require__(82),
cacheHas = __webpack_require__(91);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(array);
if (stacked && stack.get(other)) {
return stacked == other;
}
var index = -1,
result = true,
seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
stack.set(array, other);
stack.set(other, array);
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
if (customizer) {
var compared = isPartial
? customizer(othValue, arrValue, index, other, array, stack)
: customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== undefined) {
if (compared) {
continue;
}
result = false;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (seen) {
if (!arraySome(other, function(othValue, othIndex) {
if (!cacheHas(seen, othIndex) &&
(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
return seen.push(othIndex);
}
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, bitmask, customizer, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
stack['delete'](other);
return result;
}
module.exports = equalArrays;
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof (window) == 'object' && (window) && (window).Object === Object && (window);
module.exports = freeGlobal;
/***/ },
/* 32 */
/***/ function(module, exports) {
/** Used for built-in method references. */
var funcProto = Function.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
module.exports = toSource;
/***/ },
/* 33 */
/***/ function(module, exports) {
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
module.exports = eq;
/***/ },
/* 34 */
/***/ function(module, exports) {
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
module.exports = isArray;
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(3),
stubFalse = __webpack_require__(134);
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse;
module.exports = isBuffer;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(40)(module)))
/***/ },
/* 36 */
/***/ function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(13),
isObject = __webpack_require__(23);
/** `Object#toString` result references. */
var asyncTag = '[object AsyncFunction]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
proxyTag = '[object Proxy]';
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
if (!isObject(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
module.exports = isFunction;
/***/ },
/* 37 */
/***/ function(module, exports) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
module.exports = isLength;
/***/ },
/* 38 */
/***/ function(module, exports, __webpack_require__) {
var baseIsTypedArray = __webpack_require__(87),
baseUnary = __webpack_require__(90),
nodeUtil = __webpack_require__(119);
/* Node.js helper references. */
var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
module.exports = isTypedArray;
/***/ },
/* 39 */
/***/ function(module, exports) {
'use strict';
function ToObject(val) {
if (val == null) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
module.exports = Object.assign || function (target, source) {
var from;
var keys;
var to = ToObject(target);
for (var s = 1; s < arguments.length; s++) {
from = arguments[s];
keys = Object.keys(Object(from));
for (var i = 0; i < keys.length; i++) {
to[keys[i]] = from[keys[i]];
}
}
return to;
};
/***/ },
/* 40 */
/***/ function(module, exports) {
module.exports = function(module) {
if(!module.webpackPolyfill) {
module.deprecate = function() {};
module.paths = [];
// module.parent = undefined by default
module.children = [];
module.webpackPolyfill = 1;
}
return module;
}
/***/ },
/* 41 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _keyMirror = __webpack_require__(72);
var _keyMirror2 = _interopRequireDefault(_keyMirror);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var constants = {
UpdateActions: (0, _keyMirror2['default'])({
CELL_UPDATE: null,
COLUMN_FILL: null,
COPY_PASTE: null,
CELL_DRAG: null
})
};
exports['default'] = constants;
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _shallowEqual = __webpack_require__(20);
var _shallowEqual2 = _interopRequireDefault(_shallowEqual);
var _RowsContainer = __webpack_require__(58);
var _RowsContainer2 = _interopRequireDefault(_RowsContainer);
var _RowGroup = __webpack_require__(57);
var _RowGroup2 = _interopRequireDefault(_RowGroup);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(2);
var joinClasses = __webpack_require__(5);
var PropTypes = React.PropTypes;
var ScrollShim = __webpack_require__(59);
var Row = __webpack_require__(18);
var cellMetaDataShape = __webpack_require__(8);
var RowUtils = __webpack_require__(26);
var Canvas = React.createClass({
displayName: 'Canvas',
mixins: [ScrollShim],
propTypes: {
rowRenderer: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
rowHeight: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
width: PropTypes.number,
totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
style: PropTypes.string,
className: PropTypes.string,
displayStart: PropTypes.number.isRequired,
displayEnd: PropTypes.number.isRequired,
visibleStart: PropTypes.number.isRequired,
visibleEnd: PropTypes.number.isRequired,
colVisibleStart: PropTypes.number.isRequired,
colVisibleEnd: PropTypes.number.isRequired,
colDisplayStart: PropTypes.number.isRequired,
colDisplayEnd: PropTypes.number.isRequired,
rowsCount: PropTypes.number.isRequired,
rowGetter: PropTypes.oneOfType([PropTypes.func.isRequired, PropTypes.array.isRequired]),
expandedRows: PropTypes.array,
onRows: PropTypes.func,
onScroll: PropTypes.func,
columns: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired,
cellMetaData: PropTypes.shape(cellMetaDataShape).isRequired,
selectedRows: PropTypes.array,
rowKey: React.PropTypes.string,
rowScrollTimeout: React.PropTypes.number,
contextMenu: PropTypes.element,
getSubRowDetails: PropTypes.func,
rowSelection: React.PropTypes.oneOfType([React.PropTypes.shape({
indexes: React.PropTypes.arrayOf(React.PropTypes.number).isRequired
}), React.PropTypes.shape({
isSelectedKey: React.PropTypes.string.isRequired
}), React.PropTypes.shape({
keys: React.PropTypes.shape({
values: React.PropTypes.array.isRequired,
rowKey: React.PropTypes.string.isRequired
}).isRequired
})]),
rowGroupRenderer: React.PropTypes.func,
isScrolling: React.PropTypes.bool
},
getDefaultProps: function getDefaultProps() {
return {
rowRenderer: Row,
onRows: function onRows() {},
selectedRows: [],
rowScrollTimeout: 0
};
},
getInitialState: function getInitialState() {
return {
displayStart: this.props.displayStart,
displayEnd: this.props.displayEnd,
scrollingTimeout: null
};
},
componentWillMount: function componentWillMount() {
this._currentRowsLength = 0;
this._currentRowsRange = { start: 0, end: 0 };
this._scroll = { scrollTop: 0, scrollLeft: 0 };
},
componentDidMount: function componentDidMount() {
this.onRows();
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if (nextProps.displayStart !== this.state.displayStart || nextProps.displayEnd !== this.state.displayEnd) {
this.setState({
displayStart: nextProps.displayStart,
displayEnd: nextProps.displayEnd
});
}
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) {
var shouldUpdate = nextState.displayStart !== this.state.displayStart || nextState.displayEnd !== this.state.displayEnd || nextState.scrollingTimeout !== this.state.scrollingTimeout || nextProps.rowsCount !== this.props.rowsCount || nextProps.rowHeight !== this.props.rowHeight || nextProps.columns !== this.props.columns || nextProps.width !== this.props.width || nextProps.cellMetaData !== this.props.cellMetaData || this.props.colDisplayStart !== nextProps.colDisplayStart || this.props.colDisplayEnd !== nextProps.colDisplayEnd || this.props.colVisibleStart !== nextProps.colVisibleStart || this.props.colVisibleEnd !== nextProps.colVisibleEnd || !(0, _shallowEqual2['default'])(nextProps.style, this.props.style);
return shouldUpdate;
},
componentWillUnmount: function componentWillUnmount() {
this._currentRowsLength = 0;
this._currentRowsRange = { start: 0, end: 0 };
this._scroll = { scrollTop: 0, scrollLeft: 0 };
},
componentDidUpdate: function componentDidUpdate() {
if (this._scroll.scrollTop !== 0 && this._scroll.scrollLeft !== 0) {
this.setScrollLeft(this._scroll.scrollLeft);
}
this.onRows();
},
onRows: function onRows() {
if (this._currentRowsRange !== { start: 0, end: 0 }) {
this.props.onRows(this._currentRowsRange);
this._currentRowsRange = { start: 0, end: 0 };
}
},
onScroll: function onScroll(e) {
if (ReactDOM.findDOMNode(this) !== e.target) {
return;
}
this.appendScrollShim();
var scrollLeft = e.target.scrollLeft;
var scrollTop = e.target.scrollTop;
var scroll = { scrollTop: scrollTop, scrollLeft: scrollLeft };
this._scroll = scroll;
this.props.onScroll(scroll);
},
getSubRows: function getSubRows(row) {
var subRowDetails = this.props.getSubRowDetails(row);
if (subRowDetails.expanded === true) {
return subRowDetails.children.map(function (r) {
return { row: r };
});
}
},
addSubRows: function addSubRows(rowsInput, row, i, displayEnd, treeDepth) {
var _this = this;
var subRowDetails = this.props.getSubRowDetails(row) || {};
var rows = rowsInput;
var increment = i;
if (increment < displayEnd) {
subRowDetails.treeDepth = treeDepth;
rows.push({ row: row, subRowDetails: subRowDetails });
increment++;
}
if (subRowDetails && subRowDetails.expanded) {
var subRows = this.getSubRows(row);
subRows.forEach(function (sr) {
var result = _this.addSubRows(rows, sr.row, increment, displayEnd, treeDepth + 1);
rows = result.rows;
increment = result.increment;
});
}
return { rows: rows, increment: increment };
},
getRows: function getRows(displayStart, displayEnd) {
this._currentRowsRange = { start: displayStart, end: displayEnd };
if (Array.isArray(this.props.rowGetter)) {
return this.props.rowGetter.slice(displayStart, displayEnd);
}
var rows = [];
var rowFetchIndex = displayStart;
var i = displayStart;
while (i < displayEnd) {
var row = this.props.rowGetter(rowFetchIndex);
if (this.props.getSubRowDetails) {
var treeDepth = 0;
var result = this.addSubRows(rows, row, i, displayEnd, treeDepth);
rows = result.rows;
i = result.increment;
} else {
rows.push({ row: row });
i++;
}
rowFetchIndex++;
}
return rows;
},
getScrollbarWidth: function getScrollbarWidth() {
var scrollbarWidth = 0;
// Get the scrollbar width
var canvas = ReactDOM.findDOMNode(this);
scrollbarWidth = canvas.offsetWidth - canvas.clientWidth;
return scrollbarWidth;
},
getScroll: function getScroll() {
var _ReactDOM$findDOMNode = ReactDOM.findDOMNode(this),
scrollTop = _ReactDOM$findDOMNode.scrollTop,
scrollLeft = _ReactDOM$findDOMNode.scrollLeft;
return { scrollTop: scrollTop, scrollLeft: scrollLeft };
},
isRowSelected: function isRowSelected(idx, row) {
var _this2 = this;
// Use selectedRows if set
if (this.props.selectedRows !== null) {
var selectedRows = this.props.selectedRows.filter(function (r) {
var rowKeyValue = row.get ? row.get(_this2.props.rowKey) : row[_this2.props.rowKey];
return r[_this2.props.rowKey] === rowKeyValue;
});
return selectedRows.length > 0 && selectedRows[0].isSelected;
}
// Else use new rowSelection props
if (this.props.rowSelection) {
var _props$rowSelection = this.props.rowSelection,
keys = _props$rowSelection.keys,
indexes = _props$rowSelection.indexes,
isSelectedKey = _props$rowSelection.isSelectedKey;
return RowUtils.isRowSelected(keys, indexes, isSelectedKey, row, idx);
}
return false;
},
_currentRowsLength: 0,
_currentRowsRange: { start: 0, end: 0 },
_scroll: { scrollTop: 0, scrollLeft: 0 },
setScrollLeft: function setScrollLeft(scrollLeft) {
if (this._currentRowsLength !== 0) {
if (!this.refs) return;
for (var i = 0, len = this._currentRowsLength; i < len; i++) {
if (this.refs[i]) {
var row = this.getRowByRef(i);
if (row && row.setScrollLeft) {
row.setScrollLeft(scrollLeft);
}
}
}
}
},
getRowByRef: function getRowByRef(i) {
// check if wrapped with React DND drop target
var wrappedRow = this.refs[i].getDecoratedComponentInstance ? this.refs[i].getDecoratedComponentInstance(i) : null;
if (wrappedRow) {
return wrappedRow.refs.row;
}
return this.refs[i];
},
renderRow: function renderRow(props) {
var row = props.row;
if (row.__metaData && row.__metaData.isGroup) {
return React.createElement(_RowGroup2['default'], _extends({
key: props.key,
name: row.name
}, row.__metaData, {
row: props.row,
idx: props.idx,
height: props.height,
cellMetaData: this.props.cellMetaData,
renderer: this.props.rowGroupRenderer
}));
}
var RowsRenderer = this.props.rowRenderer;
if (typeof RowsRenderer === 'function') {
return React.createElement(RowsRenderer, props);
}
if (React.isValidElement(this.props.rowRenderer)) {
return React.cloneElement(this.props.rowRenderer, props);
}
},
renderPlaceholder: function renderPlaceholder(key, height) {
// just renders empty cells
// if we wanted to show gridlines, we'd need classes and position as with renderScrollingPlaceholder
return React.createElement(
'div',
{ key: key, style: { height: height } },
this.props.columns.map(function (column, idx) {
return React.createElement('div', { style: { width: column.width }, key: idx });
})
);
},
render: function render() {
var _this3 = this;
var _state = this.state,
displayStart = _state.displayStart,
displayEnd = _state.displayEnd;
var _props = this.props,
rowHeight = _props.rowHeight,
rowsCount = _props.rowsCount;
var rows = this.getRows(displayStart, displayEnd).map(function (r, idx) {
return _this3.renderRow({
key: 'row-' + (displayStart + idx),
ref: idx,
idx: displayStart + idx,
visibleStart: _this3.props.visibleStart,
visibleEnd: _this3.props.visibleEnd,
row: r.row,
height: rowHeight,
onMouseOver: _this3.onMouseOver,
columns: _this3.props.columns,
isSelected: _this3.isRowSelected(displayStart + idx, r.row, displayStart, displayEnd),
expandedRows: _this3.props.expandedRows,
cellMetaData: _this3.props.cellMetaData,
subRowDetails: r.subRowDetails,
colVisibleStart: _this3.props.colVisibleStart,
colVisibleEnd: _this3.props.colVisibleEnd,
colDisplayStart: _this3.props.colDisplayStart,
colDisplayEnd: _this3.props.colDisplayEnd,
isScrolling: _this3.props.isScrolling
});
});
this._currentRowsLength = rows.length;
if (displayStart > 0) {
rows.unshift(this.renderPlaceholder('top', displayStart * rowHeight));
}
if (rowsCount - displayEnd > 0) {
rows.push(this.renderPlaceholder('bottom', (rowsCount - displayEnd) * rowHeight));
}
var style = {
position: 'absolute',
top: 0,
left: 0,
overflowX: 'auto',
overflowY: 'scroll',
width: this.props.totalWidth,
height: this.props.height
};
return React.createElement(
'div',
{
style: style,
onScroll: this.onScroll,
className: joinClasses('react-grid-Canvas', this.props.className, { opaque: this.props.cellMetaData.selected && this.props.cellMetaData.selected.active }) },
React.createElement(_RowsContainer2['default'], {
width: this.props.width,
rows: rows,
contextMenu: this.props.contextMenu,
rowIdx: this.props.cellMetaData.selected.rowIdx,
idx: this.props.cellMetaData.selected.idx })
);
}
});
module.exports = Canvas;
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var isValidElement = __webpack_require__(1).isValidElement;
module.exports = function sameColumn(a, b) {
var k = void 0;
for (k in a) {
if (a.hasOwnProperty(k)) {
if (typeof a[k] === 'function' && typeof b[k] === 'function' || isValidElement(a[k]) && isValidElement(b[k])) {
continue;
}
if (!b.hasOwnProperty(k) || a[k] !== b[k]) {
return false;
}
}
}
for (k in b) {
if (b.hasOwnProperty(k) && !a.hasOwnProperty(k)) {
return false;
}
}
return true;
};
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
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"); } }
var ColumnMetrics = __webpack_require__(17);
var DOMMetrics = __webpack_require__(10);
Object.assign = __webpack_require__(39);
var PropTypes = __webpack_require__(1).PropTypes;
var ColumnUtils = __webpack_require__(4);
var Column = function Column() {
_classCallCheck(this, Column);
};
module.exports = {
mixins: [DOMMetrics.MetricsMixin],
propTypes: {
columns: PropTypes.arrayOf(Column),
minColumnWidth: PropTypes.number,
columnEquality: PropTypes.func,
onColumnResize: PropTypes.func
},
DOMMetrics: {
gridWidth: function gridWidth() {
return _reactDom2['default'].findDOMNode(this).parentElement.offsetWidth;
}
},
getDefaultProps: function getDefaultProps() {
return {
minColumnWidth: 80,
columnEquality: ColumnMetrics.sameColumn
};
},
componentWillMount: function componentWillMount() {
this._mounted = true;
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if (nextProps.columns) {
if (!ColumnMetrics.sameColumns(this.props.columns, nextProps.columns, this.props.columnEquality) || nextProps.minWidth !== this.props.minWidth) {
var columnMetrics = this.createColumnMetrics(nextProps);
this.setState({ columnMetrics: columnMetrics });
}
}
},
getTotalWidth: function getTotalWidth() {
var totalWidth = 0;
if (this._mounted) {
totalWidth = this.DOMMetrics.gridWidth();
} else {
totalWidth = ColumnUtils.getSize(this.props.columns) * this.props.minColumnWidth;
}
return totalWidth;
},
getColumnMetricsType: function getColumnMetricsType(metrics) {
var totalWidth = metrics.totalWidth || this.getTotalWidth();
var currentMetrics = {
columns: metrics.columns,
totalWidth: totalWidth,
minColumnWidth: metrics.minColumnWidth
};
var updatedMetrics = ColumnMetrics.recalculate(currentMetrics);
return updatedMetrics;
},
getColumn: function getColumn(idx) {
var columns = this.state.columnMetrics.columns;
if (Array.isArray(columns)) {
return columns[idx];
} else if (typeof Immutable !== 'undefined') {
return columns.get(idx);
}
},
getSize: function getSize() {
var columns = this.state.columnMetrics.columns;
if (Array.isArray(columns)) {
return columns.length;
} else if (typeof Immutable !== 'undefined') {
return columns.size;
}
},
metricsUpdated: function metricsUpdated() {
var columnMetrics = this.createColumnMetrics();
this.setState({ columnMetrics: columnMetrics });
},
createColumnMetrics: function createColumnMetrics() {
var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props;
var gridColumns = this.setupGridColumns(props);
return this.getColumnMetricsType({
columns: gridColumns,
minColumnWidth: this.props.minColumnWidth,
totalWidth: props.minWidth
});
},
onColumnResize: function onColumnResize(index, width) {
var columnMetrics = ColumnMetrics.resizeColumn(this.state.columnMetrics, index, width);
this.setState({ columnMetrics: columnMetrics });
if (this.props.onColumnResize) {
this.props.onColumnResize(index, width);
}
}
};
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(1);
var PropTypes = React.PropTypes;
var createObjectWithProperties = __webpack_require__(9);
// The list of the propTypes that we want to include in the Draggable div
var knownDivPropertyKeys = ['onDragStart', 'onDragEnd', 'onDrag', 'style'];
var Draggable = React.createClass({
displayName: 'Draggable',
propTypes: {
onDragStart: PropTypes.func,
onDragEnd: PropTypes.func,
onDrag: PropTypes.func,
component: PropTypes.oneOfType([PropTypes.func, PropTypes.constructor]),
style: PropTypes.object
},
getDefaultProps: function getDefaultProps() {
return {
onDragStart: function onDragStart() {
return true;
},
onDragEnd: function onDragEnd() {},
onDrag: function onDrag() {}
};
},
getInitialState: function getInitialState() {
return {
drag: null
};
},
componentWillUnmount: function componentWillUnmount() {
this.cleanUp();
},
onMouseDown: function onMouseDown(e) {
var drag = this.props.onDragStart(e);
if (drag === null && e.button !== 0) {
return;
}
window.addEventListener('mouseup', this.onMouseUp);
window.addEventListener('mousemove', this.onMouseMove);
window.addEventListener('touchend', this.onMouseUp);
window.addEventListener('touchmove', this.onMouseMove);
this.setState({ drag: drag });
},
onMouseMove: function onMouseMove(e) {
if (this.state.drag === null) {
return;
}
if (e.preventDefault) {
e.preventDefault();
}
this.props.onDrag(e);
},
onMouseUp: function onMouseUp(e) {
this.cleanUp();
this.props.onDragEnd(e, this.state.drag);
this.setState({ drag: null });
},
cleanUp: function cleanUp() {
window.removeEventListener('mouseup', this.onMouseUp);
window.removeEventListener('mousemove', this.onMouseMove);
window.removeEventListener('touchend', this.onMouseUp);
window.removeEventListener('touchmove', this.onMouseMove);
},
getKnownDivProps: function getKnownDivProps() {
return createObjectWithProperties(this.props, knownDivPropertyKeys);
},
render: function render() {
return React.createElement('div', _extends({}, this.getKnownDivProps(), {
onMouseDown: this.onMouseDown,
onTouchStart: this.onMouseDown,
className: 'react-grid-HeaderCell__draggable' }));
}
});
module.exports = Draggable;
/***/ },
/* 46 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var PropTypes = React.PropTypes;
var Header = __webpack_require__(48);
var Viewport = __webpack_require__(60);
var GridScrollMixin = __webpack_require__(47);
var DOMMetrics = __webpack_require__(10);
var cellMetaDataShape = __webpack_require__(8);
var Grid = React.createClass({
displayName: 'Grid',
propTypes: {
rowGetter: PropTypes.oneOfType([PropTypes.array, PropTypes.func]).isRequired,
columns: PropTypes.oneOfType([PropTypes.array, PropTypes.object]),
columnMetrics: PropTypes.object,
minHeight: PropTypes.number,
totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
headerRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]),
rowHeight: PropTypes.number,
rowRenderer: PropTypes.oneOfType([PropTypes.element, PropTypes.func]),
emptyRowsView: PropTypes.func,
expandedRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]),
selectedRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]),
rowSelection: React.PropTypes.oneOfType([React.PropTypes.shape({
indexes: React.PropTypes.arrayOf(React.PropTypes.number).isRequired
}), React.PropTypes.shape({
isSelectedKey: React.PropTypes.string.isRequired
}), React.PropTypes.shape({
keys: React.PropTypes.shape({
values: React.PropTypes.array.isRequired,
rowKey: React.PropTypes.string.isRequired
}).isRequired
})]),
rowsCount: PropTypes.number,
onRows: PropTypes.func,
sortColumn: React.PropTypes.string,
sortDirection: React.PropTypes.oneOf(['ASC', 'DESC', 'NONE']),
rowOffsetHeight: PropTypes.number.isRequired,
onViewportKeydown: PropTypes.func.isRequired,
onViewportKeyup: PropTypes.func,
onViewportDragStart: PropTypes.func.isRequired,
onViewportDragEnd: PropTypes.func.isRequired,
onViewportDoubleClick: PropTypes.func.isRequired,
onColumnResize: PropTypes.func,
onSort: PropTypes.func,
cellMetaData: PropTypes.shape(cellMetaDataShape),
rowKey: PropTypes.string.isRequired,
rowScrollTimeout: PropTypes.number,
contextMenu: PropTypes.element,
getSubRowDetails: PropTypes.func,
draggableHeaderCell: PropTypes.func,
getValidFilterValues: PropTypes.func,
rowGroupRenderer: PropTypes.func,
overScan: PropTypes.object
},
mixins: [GridScrollMixin, DOMMetrics.MetricsComputatorMixin],
getDefaultProps: function getDefaultProps() {
return {
rowHeight: 35,
minHeight: 350
};
},
getStyle: function getStyle() {
return {
overflow: 'hidden',
outline: 0,
position: 'relative',
minHeight: this.props.minHeight
};
},
render: function render() {
var headerRows = this.props.headerRows || [{ ref: 'row' }];
var EmptyRowsView = this.props.emptyRowsView;
return React.createElement(
'div',
{ style: this.getStyle(), className: 'react-grid-Grid' },
React.createElement(Header, {
ref: 'header',
columnMetrics: this.props.columnMetrics,
onColumnResize: this.props.onColumnResize,
height: this.props.rowHeight,
totalWidth: this.props.totalWidth,
headerRows: headerRows,
sortColumn: this.props.sortColumn,
sortDirection: this.props.sortDirection,
draggableHeaderCell: this.props.draggableHeaderCell,
onSort: this.props.onSort,
onScroll: this.onHeaderScroll,
getValidFilterValues: this.props.getValidFilterValues
}),
this.props.rowsCount >= 1 || this.props.rowsCount === 0 && !this.props.emptyRowsView ? React.createElement(
'div',
{ ref: 'viewPortContainer', tabIndex: '0', onKeyDown: this.props.onViewportKeydown, onKeyUp: this.props.onViewportKeyup, onDoubleClick: this.props.onViewportDoubleClick, onDragStart: this.props.onViewportDragStart, onDragEnd: this.props.onViewportDragEnd },
React.createElement(Viewport, {
ref: 'viewport',
rowKey: this.props.rowKey,
width: this.props.columnMetrics.width,
rowHeight: this.props.rowHeight,
rowRenderer: this.props.rowRenderer,
rowGetter: this.props.rowGetter,
rowsCount: this.props.rowsCount,
selectedRows: this.props.selectedRows,
expandedRows: this.props.expandedRows,
columnMetrics: this.props.columnMetrics,
totalWidth: this.props.totalWidth,
onScroll: this.onScroll,
onRows: this.props.onRows,
cellMetaData: this.props.cellMetaData,
rowOffsetHeight: this.props.rowOffsetHeight || this.props.rowHeight * headerRows.length,
minHeight: this.props.minHeight,
rowScrollTimeout: this.props.rowScrollTimeout,
contextMenu: this.props.contextMenu,
rowSelection: this.props.rowSelection,
getSubRowDetails: this.props.getSubRowDetails,
rowGroupRenderer: this.props.rowGroupRenderer,
overScan: this.props.overScan
})
) : React.createElement(
'div',
{ ref: 'emptyView', className: 'react-grid-Empty' },
React.createElement(EmptyRowsView, null)
)
);
}
});
module.exports = Grid;
/***/ },
/* 47 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ReactDOM = __webpack_require__(2);
module.exports = {
componentDidMount: function componentDidMount() {
this._scrollLeft = this.refs.viewport ? this.refs.viewport.getScroll().scrollLeft : 0;
this._onScroll();
},
componentDidUpdate: function componentDidUpdate() {
this._onScroll();
},
componentWillMount: function componentWillMount() {
this._scrollLeft = undefined;
},
componentWillUnmount: function componentWillUnmount() {
this._scrollLeft = undefined;
},
onScroll: function onScroll(props) {
if (this._scrollLeft !== props.scrollLeft) {
this._scrollLeft = props.scrollLeft;
this._onScroll();
}
},
onHeaderScroll: function onHeaderScroll(e) {
var scrollLeft = e.target.scrollLeft;
if (this._scrollLeft !== scrollLeft) {
this._scrollLeft = scrollLeft;
this.refs.header.setScrollLeft(scrollLeft);
var canvas = ReactDOM.findDOMNode(this.refs.viewport.refs.canvas);
canvas.scrollLeft = scrollLeft;
this.refs.viewport.refs.canvas.setScrollLeft(scrollLeft);
}
},
_onScroll: function _onScroll() {
if (this._scrollLeft !== undefined) {
this.refs.header.setScrollLeft(this._scrollLeft);
if (this.refs.viewport) {
this.refs.viewport.setScrollLeft(this._scrollLeft);
}
}
}
};
/***/ },
/* 48 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(2);
var joinClasses = __webpack_require__(5);
var shallowCloneObject = __webpack_require__(19);
var ColumnMetrics = __webpack_require__(17);
var ColumnUtils = __webpack_require__(4);
var HeaderRow = __webpack_require__(51);
var PropTypes = React.PropTypes;
var createObjectWithProperties = __webpack_require__(9);
// The list of the propTypes that we want to include in the Header div
var knownDivPropertyKeys = ['height', 'onScroll'];
var Header = React.createClass({
displayName: 'Header',
propTypes: {
columnMetrics: PropTypes.shape({ width: PropTypes.number.isRequired, columns: PropTypes.any }).isRequired,
totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
height: PropTypes.number.isRequired,
headerRows: PropTypes.array.isRequired,
sortColumn: PropTypes.string,
sortDirection: PropTypes.oneOf(['ASC', 'DESC', 'NONE']),
onSort: PropTypes.func,
onColumnResize: PropTypes.func,
onScroll: PropTypes.func,
draggableHeaderCell: PropTypes.func,
getValidFilterValues: PropTypes.func
},
getInitialState: function getInitialState() {
return { resizing: null };
},
componentWillReceiveProps: function componentWillReceiveProps() {
this.setState({ resizing: null });
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) {
var update = !ColumnMetrics.sameColumns(this.props.columnMetrics.columns, nextProps.columnMetrics.columns, ColumnMetrics.sameColumn) || this.props.totalWidth !== nextProps.totalWidth || this.props.headerRows.length !== nextProps.headerRows.length || this.state.resizing !== nextState.resizing || this.props.sortColumn !== nextProps.sortColumn || this.props.sortDirection !== nextProps.sortDirection;
return update;
},
onColumnResize: function onColumnResize(column, width) {
var state = this.state.resizing || this.props;
var pos = this.getColumnPosition(column);
if (pos != null) {
var _resizing = {
columnMetrics: shallowCloneObject(state.columnMetrics)
};
_resizing.columnMetrics = ColumnMetrics.resizeColumn(_resizing.columnMetrics, pos, width);
// we don't want to influence scrollLeft while resizing
if (_resizing.columnMetrics.totalWidth < state.columnMetrics.totalWidth) {
_resizing.columnMetrics.totalWidth = state.columnMetrics.totalWidth;
}
_resizing.column = ColumnUtils.getColumn(_resizing.columnMetrics.columns, pos);
this.setState({ resizing: _resizing });
}
},
onColumnResizeEnd: function onColumnResizeEnd(column, width) {
var pos = this.getColumnPosition(column);
if (pos !== null && this.props.onColumnResize) {
this.props.onColumnResize(pos, width || column.width);
}
},
getHeaderRows: function getHeaderRows() {
var _this = this;
var columnMetrics = this.getColumnMetrics();
var resizeColumn = void 0;
if (this.state.resizing) {
resizeColumn = this.state.resizing.column;
}
var headerRows = [];
this.props.headerRows.forEach(function (row, index) {
// To allow header filters to be visible
var rowHeight = 'auto';
if (row.rowType === 'filter') {
rowHeight = '500px';
}
var headerRowStyle = {
position: 'absolute',
top: _this.getCombinedHeaderHeights(index),
left: 0,
width: _this.props.totalWidth,
overflowX: 'hidden',
minHeight: rowHeight
};
headerRows.push(React.createElement(HeaderRow, {
key: row.ref,
ref: row.ref,
rowType: row.rowType,
style: headerRowStyle,
onColumnResize: _this.onColumnResize,
onColumnResizeEnd: _this.onColumnResizeEnd,
width: columnMetrics.width,
height: row.height || _this.props.height,
columns: columnMetrics.columns,
resizing: resizeColumn,
draggableHeaderCell: _this.props.draggableHeaderCell,
filterable: row.filterable,
onFilterChange: row.onFilterChange,
sortColumn: _this.props.sortColumn,
sortDirection: _this.props.sortDirection,
onSort: _this.props.onSort,
onScroll: _this.props.onScroll,
getValidFilterValues: _this.props.getValidFilterValues
}));
});
return headerRows;
},
getColumnMetrics: function getColumnMetrics() {
var columnMetrics = void 0;
if (this.state.resizing) {
columnMetrics = this.state.resizing.columnMetrics;
} else {
columnMetrics = this.props.columnMetrics;
}
return columnMetrics;
},
getColumnPosition: function getColumnPosition(column) {
var columnMetrics = this.getColumnMetrics();
var pos = -1;
columnMetrics.columns.forEach(function (c, idx) {
if (c.key === column.key) {
pos = idx;
}
});
return pos === -1 ? null : pos;
},
getCombinedHeaderHeights: function getCombinedHeaderHeights(until) {
var stopAt = this.props.headerRows.length;
if (typeof until !== 'undefined') {
stopAt = until;
}
var height = 0;
for (var index = 0; index < stopAt; index++) {
height += this.props.headerRows[index].height || this.props.height;
}
return height;
},
getStyle: function getStyle() {
return {
position: 'relative',
height: this.getCombinedHeaderHeights()
};
},
setScrollLeft: function setScrollLeft(scrollLeft) {
var node = ReactDOM.findDOMNode(this.refs.row);
node.scrollLeft = scrollLeft;
this.refs.row.setScrollLeft(scrollLeft);
if (this.refs.filterRow) {
var nodeFilters = ReactDOM.findDOMNode(this.refs.filterRow);
nodeFilters.scrollLeft = scrollLeft;
this.refs.filterRow.setScrollLeft(scrollLeft);
}
},
getKnownDivProps: function getKnownDivProps() {
return createObjectWithProperties(this.props, knownDivPropertyKeys);
},
render: function render() {
var className = joinClasses({
'react-grid-Header': true,
'react-grid-Header--resizing': !!this.state.resizing
});
var headerRows = this.getHeaderRows();
return React.createElement(
'div',
_extends({}, this.getKnownDivProps(), { style: this.getStyle(), className: className }),
headerRows
);
}
});
module.exports = Header;
/***/ },
/* 49 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _reactAddonsShallowCompare = __webpack_require__(135);
var _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(2);
var joinClasses = __webpack_require__(5);
var ExcelColumn = __webpack_require__(6);
var ResizeHandle = __webpack_require__(55);
var PropTypes = React.PropTypes;
function simpleCellRenderer(objArgs) {
return React.createElement(
'div',
{ className: 'widget-HeaderCell__value' },
objArgs.column.name
);
}
var HeaderCell = React.createClass({
displayName: 'HeaderCell',
propTypes: {
renderer: PropTypes.oneOfType([PropTypes.func, PropTypes.element]).isRequired,
column: PropTypes.shape(ExcelColumn).isRequired,
onResize: PropTypes.func.isRequired,
height: PropTypes.number.isRequired,
onResizeEnd: PropTypes.func.isRequired,
className: PropTypes.string
},
getDefaultProps: function getDefaultProps() {
return {
renderer: simpleCellRenderer
};
},
getInitialState: function getInitialState() {
return { resizing: false };
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) {
return (0, _reactAddonsShallowCompare2['default'])(this, nextProps, nextState) && (this.props.column.width !== nextProps.column.width || this.props.column.left !== nextProps.column.left || this.props.column.name !== nextProps.column.name || this.props.column.cellClass !== nextProps.column.cellClass);
},
onDragStart: function onDragStart(e) {
this.setState({ resizing: true });
// need to set dummy data for FF
if (e && e.dataTransfer && e.dataTransfer.setData) e.dataTransfer.setData('text/plain', 'dummy');
},
onDrag: function onDrag(e) {
var resize = this.props.onResize || null; // for flows sake, doesnt recognise a null check direct
if (resize) {
var _width = this.getWidthFromMouseEvent(e);
if (_width > 0) {
resize(this.props.column, _width);
}
}
},
onDragEnd: function onDragEnd(e) {
var width = this.getWidthFromMouseEvent(e);
this.props.onResizeEnd(this.props.column, width);
this.setState({ resizing: false });
},
getWidthFromMouseEvent: function getWidthFromMouseEvent(e) {
var right = e.pageX || e.touches && e.touches[0] && e.touches[0].pageX || e.changedTouches && e.changedTouches[e.changedTouches.length - 1].pageX;
var left = ReactDOM.findDOMNode(this).getBoundingClientRect().left;
return right - left;
},
getCell: function getCell() {
if (React.isValidElement(this.props.renderer)) {
// if it is a string, it's an HTML element, and column is not a valid property, so only pass height
if (typeof this.props.renderer.type === 'string') {
return React.cloneElement(this.props.renderer, { height: this.props.height });
}
return React.cloneElement(this.props.renderer, { column: this.props.column, height: this.props.height });
}
return this.props.renderer({ column: this.props.column });
},
getStyle: function getStyle() {
return {
width: this.props.column.width,
left: this.props.column.left,
display: 'inline-block',
position: 'absolute',
height: this.props.height,
margin: 0,
textOverflow: 'ellipsis',
whiteSpace: 'nowrap'
};
},
setScrollLeft: function setScrollLeft(scrollLeft) {
var node = ReactDOM.findDOMNode(this);
node.style.webkitTransform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)';
node.style.transform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)';
},
render: function render() {
var resizeHandle = void 0;
if (this.props.column.resizable) {
resizeHandle = React.createElement(ResizeHandle, {
onDrag: this.onDrag,
onDragStart: this.onDragStart,
onDragEnd: this.onDragEnd
});
}
var className = joinClasses({
'react-grid-HeaderCell': true,
'react-grid-HeaderCell--resizing': this.state.resizing,
'react-grid-HeaderCell--locked': this.props.column.locked
});
className = joinClasses(className, this.props.className, this.props.column.cellClass);
var cell = this.getCell();
return React.createElement(
'div',
{ className: className, style: this.getStyle() },
cell,
resizeHandle
);
}
});
module.exports = HeaderCell;
/***/ },
/* 50 */
/***/ function(module, exports) {
"use strict";
var HeaderCellType = {
SORTABLE: 0,
FILTERABLE: 1,
NONE: 2,
CHECKBOX: 3
};
module.exports = HeaderCellType;
/***/ },
/* 51 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(1);
var shallowEqual = __webpack_require__(20);
var BaseHeaderCell = __webpack_require__(49);
var getScrollbarSize = __webpack_require__(28);
var ExcelColumn = __webpack_require__(6);
var ColumnUtilsMixin = __webpack_require__(4);
var SortableHeaderCell = __webpack_require__(63);
var FilterableHeaderCell = __webpack_require__(62);
var HeaderCellType = __webpack_require__(50);
var createObjectWithProperties = __webpack_require__(9);
var PropTypes = React.PropTypes;
var HeaderRowStyle = {
overflow: React.PropTypes.string,
width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
height: React.PropTypes.number,
position: React.PropTypes.string
};
var DEFINE_SORT = ['ASC', 'DESC', 'NONE'];
// The list of the propTypes that we want to include in the HeaderRow div
var knownDivPropertyKeys = ['width', 'height', 'style', 'onScroll'];
var HeaderRow = React.createClass({
displayName: 'HeaderRow',
propTypes: {
width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
height: PropTypes.number.isRequired,
columns: PropTypes.oneOfType([PropTypes.array, PropTypes.object]).isRequired,
onColumnResize: PropTypes.func,
onSort: PropTypes.func.isRequired,
onColumnResizeEnd: PropTypes.func,
style: PropTypes.shape(HeaderRowStyle),
sortColumn: PropTypes.string,
sortDirection: React.PropTypes.oneOf(DEFINE_SORT),
cellRenderer: PropTypes.func,
headerCellRenderer: PropTypes.func,
filterable: PropTypes.bool,
onFilterChange: PropTypes.func,
resizing: PropTypes.object,
onScroll: PropTypes.func,
rowType: PropTypes.string,
draggableHeaderCell: PropTypes.func
},
mixins: [ColumnUtilsMixin],
shouldComponentUpdate: function shouldComponentUpdate(nextProps) {
return nextProps.width !== this.props.width || nextProps.height !== this.props.height || nextProps.columns !== this.props.columns || !shallowEqual(nextProps.style, this.props.style) || this.props.sortColumn !== nextProps.sortColumn || this.props.sortDirection !== nextProps.sortDirection;
},
getHeaderCellType: function getHeaderCellType(column) {
if (column.filterable) {
if (this.props.filterable) return HeaderCellType.FILTERABLE;
}
if (column.sortable) return HeaderCellType.SORTABLE;
return HeaderCellType.NONE;
},
getFilterableHeaderCell: function getFilterableHeaderCell(column) {
var FilterRenderer = FilterableHeaderCell;
if (column.filterRenderer !== undefined) {
FilterRenderer = column.filterRenderer;
}
return React.createElement(FilterRenderer, _extends({}, this.props, { onChange: this.props.onFilterChange }));
},
getSortableHeaderCell: function getSortableHeaderCell(column) {
var sortDirection = this.props.sortColumn === column.key ? this.props.sortDirection : DEFINE_SORT.NONE;
return React.createElement(SortableHeaderCell, { columnKey: column.key, onSort: this.props.onSort, sortDirection: sortDirection });
},
getHeaderRenderer: function getHeaderRenderer(column) {
var renderer = void 0;
if (column.headerRenderer) {
renderer = column.headerRenderer;
} else {
var headerCellType = this.getHeaderCellType(column);
switch (headerCellType) {
case HeaderCellType.SORTABLE:
renderer = this.getSortableHeaderCell(column);
break;
case HeaderCellType.FILTERABLE:
renderer = this.getFilterableHeaderCell(column);
break;
default:
break;
}
}
return renderer;
},
getStyle: function getStyle() {
return {
overflow: 'hidden',
width: '100%',
height: this.props.height,
position: 'absolute'
};
},
getCells: function getCells() {
var cells = [];
var lockedCells = [];
for (var i = 0, len = this.getSize(this.props.columns); i < len; i++) {
var column = this.getColumn(this.props.columns, i);
var _renderer = this.getHeaderRenderer(column);
if (column.key === 'select-row' && this.props.rowType === 'filter') {
_renderer = React.createElement('div', null);
}
var _HeaderCell = column.draggable ? this.props.draggableHeaderCell : BaseHeaderCell;
var cell = React.createElement(_HeaderCell, {
ref: i,
key: i,
height: this.props.height,
column: column,
renderer: _renderer,
resizing: this.props.resizing === column,
onResize: this.props.onColumnResize,
onResizeEnd: this.props.onColumnResizeEnd
});
if (column.locked) {
lockedCells.push(cell);
} else {
cells.push(cell);
}
}
return cells.concat(lockedCells);
},
setScrollLeft: function setScrollLeft(scrollLeft) {
var _this = this;
this.props.columns.forEach(function (column, i) {
if (column.locked) {
_this.refs[i].setScrollLeft(scrollLeft);
}
});
},
getKnownDivProps: function getKnownDivProps() {
return createObjectWithProperties(this.props, knownDivPropertyKeys);
},
render: function render() {
var cellsStyle = {
width: this.props.width ? this.props.width + getScrollbarSize() : '100%',
height: this.props.height,
whiteSpace: 'nowrap',
overflowX: 'hidden',
overflowY: 'hidden'
};
var cells = this.getCells();
return React.createElement(
'div',
_extends({}, this.getKnownDivProps(), { className: 'react-grid-HeaderRow' }),
React.createElement(
'div',
{ style: cellsStyle },
cells
)
);
}
});
module.exports = HeaderRow;
/***/ },
/* 52 */
/***/ function(module, exports) {
"use strict";
module.exports = {
Backspace: 8,
Tab: 9,
Enter: 13,
Shift: 16,
Ctrl: 17,
Alt: 18,
PauseBreak: 19,
CapsLock: 20,
Escape: 27,
PageUp: 33,
PageDown: 34,
End: 35,
Home: 36,
LeftArrow: 37,
UpArrow: 38,
RightArrow: 39,
DownArrow: 40,
Insert: 45,
Delete: 46,
0: 48,
1: 49,
2: 50,
3: 51,
4: 52,
5: 53,
6: 54,
7: 55,
8: 56,
9: 57,
a: 65,
b: 66,
c: 67,
d: 68,
e: 69,
f: 70,
g: 71,
h: 72,
i: 73,
j: 74,
k: 75,
l: 76,
m: 77,
n: 78,
o: 79,
p: 80,
q: 81,
r: 82,
s: 83,
t: 84,
u: 85,
v: 86,
w: 87,
x: 88,
y: 89,
z: 90,
LeftWindowKey: 91,
RightWindowKey: 92,
SelectKey: 93,
NumPad0: 96,
NumPad1: 97,
NumPad2: 98,
NumPad3: 99,
NumPad4: 100,
NumPad5: 101,
NumPad6: 102,
NumPad7: 103,
NumPad8: 104,
NumPad9: 105,
Multiply: 106,
Add: 107,
Subtract: 109,
DecimalPoint: 110,
Divide: 111,
F1: 112,
F2: 113,
F3: 114,
F4: 115,
F5: 116,
F6: 117,
F7: 118,
F8: 119,
F9: 120,
F10: 121,
F12: 123,
NumLock: 144,
ScrollLock: 145,
SemiColon: 186,
EqualSign: 187,
Comma: 188,
Dash: 189,
Period: 190,
ForwardSlash: 191,
GraveAccent: 192,
OpenBracket: 219,
BackSlash: 220,
CloseBracket: 221,
SingleQuote: 222
};
/***/ },
/* 53 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.OverflowCellComponent = undefined;
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _focusableComponentWrapper = __webpack_require__(69);
var _focusableComponentWrapper2 = _interopRequireDefault(_focusableComponentWrapper);
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 OverflowCell = function (_React$Component) {
_inherits(OverflowCell, _React$Component);
function OverflowCell() {
_classCallCheck(this, OverflowCell);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
OverflowCell.prototype.getStyle = function getStyle() {
var style = {
position: 'absolute',
width: this.props.column.width,
height: this.props.height,
left: this.props.column.left,
border: '1px solid #eee'
};
return style;
};
OverflowCell.prototype.render = function render() {
return _react2['default'].createElement('div', { tabIndex: '-1', style: this.getStyle(), width: '100%', className: 'react-grid-Cell' });
};
return OverflowCell;
}(_react2['default'].Component);
OverflowCell.isSelected = function (props) {
var cellMetaData = props.cellMetaData,
rowIdx = props.rowIdx,
idx = props.idx;
if (cellMetaData == null) {
return false;
}
var selected = cellMetaData.selected;
return selected && selected.rowIdx === rowIdx && selected.idx === idx;
};
OverflowCell.isScrolling = function (props) {
return props.cellMetaData.isScrollingHorizontallyWithKeyboard;
};
OverflowCell.propTypes = {
rowIdx: _react2['default'].PropTypes.number,
idx: _react2['default'].PropTypes.number,
height: _react2['default'].PropTypes.number,
column: _react2['default'].PropTypes.object,
cellMetaData: _react2['default'].PropTypes.object
};
OverflowCell.displayName = 'Cell';
var OverflowCellComponent = OverflowCell;
exports['default'] = (0, _focusableComponentWrapper2['default'])(OverflowCell);
exports.OverflowCellComponent = OverflowCellComponent;
/***/ },
/* 54 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _AppConstants = __webpack_require__(41);
var _AppConstants2 = _interopRequireDefault(_AppConstants);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(2);
var BaseGrid = __webpack_require__(46);
var Row = __webpack_require__(18);
var ExcelColumn = __webpack_require__(6);
var KeyboardHandlerMixin = __webpack_require__(25);
var CheckboxEditor = __webpack_require__(64);
var DOMMetrics = __webpack_require__(10);
var ColumnMetricsMixin = __webpack_require__(44);
var RowUtils = __webpack_require__(26);
var ColumnUtils = __webpack_require__(4);
var KeyCodes = __webpack_require__(52);
if (!Object.assign) {
Object.assign = __webpack_require__(39);
}
var ReactDataGrid = React.createClass({
displayName: 'ReactDataGrid',
mixins: [ColumnMetricsMixin, DOMMetrics.MetricsComputatorMixin, KeyboardHandlerMixin],
propTypes: {
rowHeight: React.PropTypes.number.isRequired,
headerRowHeight: React.PropTypes.number,
minHeight: React.PropTypes.number.isRequired,
minWidth: React.PropTypes.number,
enableRowSelect: React.PropTypes.oneOfType([React.PropTypes.bool, React.PropTypes.string]),
onRowUpdated: React.PropTypes.func,
rowGetter: React.PropTypes.func.isRequired,
rowsCount: React.PropTypes.number.isRequired,
toolbar: React.PropTypes.element,
enableCellSelect: React.PropTypes.bool,
columns: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]).isRequired,
onFilter: React.PropTypes.func,
onCellCopyPaste: React.PropTypes.func,
onCellsDragged: React.PropTypes.func,
onAddFilter: React.PropTypes.func,
onGridSort: React.PropTypes.func,
onDragHandleDoubleClick: React.PropTypes.func,
onGridRowsUpdated: React.PropTypes.func,
onRowSelect: React.PropTypes.func,
rowKey: React.PropTypes.string,
rowScrollTimeout: React.PropTypes.number,
onClearFilters: React.PropTypes.func,
contextMenu: React.PropTypes.element,
cellNavigationMode: React.PropTypes.oneOf(['none', 'loopOverRow', 'changeRow']),
onCellSelected: React.PropTypes.func,
onCellDeSelected: React.PropTypes.func,
onCellExpand: React.PropTypes.func,
enableDragAndDrop: React.PropTypes.bool,
onRowExpandToggle: React.PropTypes.func,
draggableHeaderCell: React.PropTypes.func,
getValidFilterValues: React.PropTypes.func,
rowSelection: React.PropTypes.shape({
enableShiftSelect: React.PropTypes.bool,
onRowsSelected: React.PropTypes.func,
onRowsDeselected: React.PropTypes.func,
showCheckbox: React.PropTypes.bool,
selectBy: React.PropTypes.oneOfType([React.PropTypes.shape({
indexes: React.PropTypes.arrayOf(React.PropTypes.number).isRequired
}), React.PropTypes.shape({
isSelectedKey: React.PropTypes.string.isRequired
}), React.PropTypes.shape({
keys: React.PropTypes.shape({
values: React.PropTypes.array.isRequired,
rowKey: React.PropTypes.string.isRequired
}).isRequired
})]).isRequired
}),
onRowClick: React.PropTypes.func,
onGridKeyUp: React.PropTypes.func,
onGridKeyDown: React.PropTypes.func,
rowGroupRenderer: React.PropTypes.func,
rowActionsCell: React.PropTypes.func,
onCheckCellIsEditable: React.PropTypes.func,
/* called before cell is set active, returns a boolean to determine whether cell is editable */
overScan: React.PropTypes.object
},
getDefaultProps: function getDefaultProps() {
return {
enableCellSelect: false,
tabIndex: -1,
rowHeight: 35,
enableRowSelect: false,
minHeight: 350,
rowKey: 'id',
rowScrollTimeout: 0,
cellNavigationMode: 'none',
overScan: {
colsStart: 5,
colsEnd: 5,
rowsStart: 5,
rowsEnd: 5
}
};
},
getInitialState: function getInitialState() {
var columnMetrics = this.createColumnMetrics();
var initialState = { columnMetrics: columnMetrics, selectedRows: [], copied: null, expandedRows: [], canFilter: false, columnFilters: {}, sortDirection: null, sortColumn: null, dragged: null, scrollOffset: 0, lastRowIdxUiSelected: -1 };
if (this.props.enableCellSelect) {
initialState.selected = { rowIdx: 0, idx: 0 };
} else {
initialState.selected = { rowIdx: -1, idx: -1 };
}
return initialState;
},
hasSelectedCellChanged: function hasSelectedCellChanged(selected) {
var previouslySelected = Object.assign({}, this.state.selected);
return previouslySelected.rowIdx !== selected.rowIdx || previouslySelected.idx !== selected.idx || previouslySelected.active === false;
},
onContextMenuHide: function onContextMenuHide() {
document.removeEventListener('click', this.onContextMenuHide);
var newSelected = Object.assign({}, this.state.selected, { contextMenuDisplayed: false });
this.setState({ selected: newSelected });
},
onColumnEvent: function onColumnEvent(ev, columnEvent) {
var idx = columnEvent.idx,
name = columnEvent.name;
if (name && typeof idx !== 'undefined') {
var column = this.getColumn(idx);
if (column && column.events && column.events[name] && typeof column.events[name] === 'function') {
var eventArgs = {
rowIdx: columnEvent.rowIdx,
idx: idx,
column: column
};
column.events[name](ev, eventArgs);
}
}
},
onSelect: function onSelect(selected) {
var _this = this;
if (this.state.selected.rowIdx !== selected.rowIdx || this.state.selected.idx !== selected.idx || this.state.selected.active === false) {
var _idx = selected.idx;
var _rowIdx = selected.rowIdx;
if (_idx >= 0 && _rowIdx >= 0 && _idx < ColumnUtils.getSize(this.state.columnMetrics.columns) && _rowIdx < this.props.rowsCount) {
(function () {
var oldSelection = _this.state.selected;
_this.setState({ selected: selected }, function () {
if (typeof _this.props.onCellDeSelected === 'function') {
_this.props.onCellDeSelected(oldSelection);
}
if (typeof _this.props.onCellSelected === 'function') {
_this.props.onCellSelected(selected);
}
});
})();
}
}
},
onCellClick: function onCellClick(cell) {
this.onSelect({ rowIdx: cell.rowIdx, idx: cell.idx });
if (this.props.onRowClick && typeof this.props.onRowClick === 'function') {
this.props.onRowClick(cell.rowIdx, this.props.rowGetter(cell.rowIdx));
}
},
onCellContextMenu: function onCellContextMenu(cell) {
this.onSelect({ rowIdx: cell.rowIdx, idx: cell.idx, contextMenuDisplayed: this.props.contextMenu });
if (this.props.contextMenu) {
document.addEventListener('click', this.onContextMenuHide);
}
},
onCellDoubleClick: function onCellDoubleClick(cell) {
this.onSelect({ rowIdx: cell.rowIdx, idx: cell.idx });
this.setActive('Enter');
},
onViewportDoubleClick: function onViewportDoubleClick() {
this.setActive();
},
onPressArrowUp: function onPressArrowUp(e) {
this.moveSelectedCell(e, -1, 0);
},
onPressArrowDown: function onPressArrowDown(e) {
this.moveSelectedCell(e, 1, 0);
},
onPressArrowLeft: function onPressArrowLeft(e) {
this.moveSelectedCell(e, 0, -1);
},
onPressArrowRight: function onPressArrowRight(e) {
this.moveSelectedCell(e, 0, 1);
},
onPressTab: function onPressTab(e) {
this.moveSelectedCell(e, 0, e.shiftKey ? -1 : 1);
},
onPressEnter: function onPressEnter(e) {
this.setActive(e.key);
},
onPressDelete: function onPressDelete(e) {
this.setActive(e.key);
},
onPressEscape: function onPressEscape(e) {
this.setInactive(e.key);
this.handleCancelCopy();
},
onPressBackspace: function onPressBackspace(e) {
this.setActive(e.key);
},
onPressChar: function onPressChar(e) {
if (this.isKeyPrintable(e.keyCode)) {
this.setActive(e.keyCode);
}
},
onPressKeyWithCtrl: function onPressKeyWithCtrl(e) {
var keys = {
KeyCode_c: 99,
KeyCode_C: 67,
KeyCode_V: 86,
KeyCode_v: 118
};
var rowIdx = this.state.selected.rowIdx;
var row = this.props.rowGetter(rowIdx);
var idx = this.state.selected.idx;
var col = this.getColumn(idx);
if (ColumnUtils.canEdit(col, row, this.props.enableCellSelect)) {
if (e.keyCode === keys.KeyCode_c || e.keyCode === keys.KeyCode_C) {
var _value = this.getSelectedValue();
this.handleCopy({ value: _value });
} else if (e.keyCode === keys.KeyCode_v || e.keyCode === keys.KeyCode_V) {
this.handlePaste();
}
}
},
onGridRowsUpdated: function onGridRowsUpdated(cellKey, fromRow, toRow, updated, action) {
var rowIds = [];
for (var i = fromRow; i <= toRow; i++) {
rowIds.push(this.props.rowGetter(i)[this.props.rowKey]);
}
this.props.onGridRowsUpdated({ cellKey: cellKey, fromRow: fromRow, toRow: toRow, rowIds: rowIds, updated: updated, action: action });
},
onCellCommit: function onCellCommit(commit) {
var selected = Object.assign({}, this.state.selected);
selected.active = false;
if (commit.key === 'Tab') {
selected.idx += 1;
}
var expandedRows = this.state.expandedRows;
// if(commit.changed && commit.changed.expandedHeight){
// expandedRows = this.expandRow(commit.rowIdx, commit.changed.expandedHeight);
// }
this.setState({ selected: selected, expandedRows: expandedRows });
if (this.props.onRowUpdated) {
this.props.onRowUpdated(commit);
}
var targetRow = commit.rowIdx;
if (this.props.onGridRowsUpdated) {
this.onGridRowsUpdated(commit.cellKey, targetRow, targetRow, commit.updated, _AppConstants2['default'].UpdateActions.CELL_UPDATE);
}
},
onDragStart: function onDragStart(e) {
var idx = this.state.selected.idx;
if (idx > -1) {
var _value2 = this.getSelectedValue();
this.handleDragStart({ idx: this.state.selected.idx, rowIdx: this.state.selected.rowIdx, value: _value2 });
// need to set dummy data for FF
if (e && e.dataTransfer) {
if (e.dataTransfer.setData) {
e.dataTransfer.dropEffect = 'move';
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', 'dummy');
}
}
}
},
onToggleFilter: function onToggleFilter() {
var _this2 = this;
// setState() does not immediately mutate this.state but creates a pending state transition.
// Therefore if you want to do something after the state change occurs, pass it in as a callback function.
this.setState({ canFilter: !this.state.canFilter }, function () {
if (_this2.state.canFilter === false && _this2.props.onClearFilters) {
_this2.props.onClearFilters();
}
});
},
onDragHandleDoubleClick: function onDragHandleDoubleClick(e) {
if (this.props.onDragHandleDoubleClick) {
this.props.onDragHandleDoubleClick(e);
}
if (this.props.onGridRowsUpdated) {
var _onGridRowsUpdated;
var cellKey = this.getColumn(e.idx).key;
this.onGridRowsUpdated(cellKey, e.rowIdx, this.props.rowsCount - 1, (_onGridRowsUpdated = {}, _onGridRowsUpdated[cellKey] = e.rowData[cellKey], _onGridRowsUpdated), _AppConstants2['default'].UpdateActions.COLUMN_FILL);
}
},
onCellExpand: function onCellExpand(args) {
if (this.props.onCellExpand) {
this.props.onCellExpand(args);
}
},
onRowExpandToggle: function onRowExpandToggle(args) {
if (typeof this.props.onRowExpandToggle === 'function') {
this.props.onRowExpandToggle(args);
}
},
handleDragStart: function handleDragStart(dragged) {
if (!this.dragEnabled()) {
return;
}
var idx = dragged.idx;
var rowIdx = dragged.rowIdx;
if (idx >= 0 && rowIdx >= 0 && idx < this.getSize() && rowIdx < this.props.rowsCount) {
this.setState({ dragged: dragged });
}
},
handleDragEnd: function handleDragEnd() {
if (!this.dragEnabled()) {
return;
}
var selected = this.state.selected;
var dragged = this.state.dragged;
var cellKey = this.getColumn(this.state.selected.idx).key;
var fromRow = selected.rowIdx < dragged.overRowIdx ? selected.rowIdx : dragged.overRowIdx;
var toRow = selected.rowIdx > dragged.overRowIdx ? selected.rowIdx : dragged.overRowIdx;
if (this.props.onCellsDragged) {
this.props.onCellsDragged({ cellKey: cellKey, fromRow: fromRow, toRow: toRow, value: dragged.value });
}
if (this.props.onGridRowsUpdated) {
var _onGridRowsUpdated2;
this.onGridRowsUpdated(cellKey, fromRow, toRow, (_onGridRowsUpdated2 = {}, _onGridRowsUpdated2[cellKey] = dragged.value, _onGridRowsUpdated2), _AppConstants2['default'].UpdateActions.CELL_DRAG);
}
this.setState({ dragged: { complete: true } });
},
handleDragEnter: function handleDragEnter(row) {
if (!this.dragEnabled() || this.state.dragged == null) {
return;
}
var dragged = this.state.dragged;
dragged.overRowIdx = row;
this.setState({ dragged: dragged });
},
handleTerminateDrag: function handleTerminateDrag() {
if (!this.dragEnabled()) {
return;
}
this.setState({ dragged: null });
},
handlePaste: function handlePaste() {
if (!this.copyPasteEnabled() || !this.state.copied) {
return;
}
var selected = this.state.selected;
var cellKey = this.getColumn(this.state.selected.idx).key;
var textToCopy = this.state.textToCopy;
var fromRow = this.state.copied.rowIdx;
var toRow = selected.rowIdx;
if (this.props.onCellCopyPaste) {
this.props.onCellCopyPaste({ cellKey: cellKey, rowIdx: toRow, value: textToCopy, fromRow: fromRow, toRow: toRow });
}
if (this.props.onGridRowsUpdated) {
var _onGridRowsUpdated3;
this.onGridRowsUpdated(cellKey, toRow, toRow, (_onGridRowsUpdated3 = {}, _onGridRowsUpdated3[cellKey] = textToCopy, _onGridRowsUpdated3), _AppConstants2['default'].UpdateActions.COPY_PASTE);
}
},
handleCancelCopy: function handleCancelCopy() {
this.setState({ copied: null });
},
handleCopy: function handleCopy(args) {
if (!this.copyPasteEnabled()) {
return;
}
var textToCopy = args.value;
var selected = this.state.selected;
var copied = { idx: selected.idx, rowIdx: selected.rowIdx };
this.setState({ textToCopy: textToCopy, copied: copied });
},
handleSort: function handleSort(columnKey, direction) {
this.setState({ sortDirection: direction, sortColumn: columnKey }, function () {
this.props.onGridSort(columnKey, direction);
});
},
getSelectedRow: function getSelectedRow(rows, key) {
var _this3 = this;
var selectedRow = rows.filter(function (r) {
if (r[_this3.props.rowKey] === key) {
return true;
}
return false;
});
if (selectedRow.length > 0) {
return selectedRow[0];
}
},
useNewRowSelection: function useNewRowSelection() {
return this.props.rowSelection && this.props.rowSelection.selectBy;
},
// return false if not a shift select so can be handled as normal row selection
handleShiftSelect: function handleShiftSelect(rowIdx) {
if (this.state.lastRowIdxUiSelected > -1 && this.isSingleKeyDown(KeyCodes.Shift)) {
var _props$rowSelection$s = this.props.rowSelection.selectBy,
keys = _props$rowSelection$s.keys,
indexes = _props$rowSelection$s.indexes,
isSelectedKey = _props$rowSelection$s.isSelectedKey;
var isPreviouslySelected = RowUtils.isRowSelected(keys, indexes, isSelectedKey, this.props.rowGetter(rowIdx), rowIdx);
if (isPreviouslySelected) return false;
var handled = false;
if (rowIdx > this.state.lastRowIdxUiSelected) {
var rowsSelected = [];
for (var i = this.state.lastRowIdxUiSelected + 1; i <= rowIdx; i++) {
rowsSelected.push({ rowIdx: i, row: this.props.rowGetter(i) });
}
if (typeof this.props.rowSelection.onRowsSelected === 'function') {
this.props.rowSelection.onRowsSelected(rowsSelected);
}
handled = true;
} else if (rowIdx < this.state.lastRowIdxUiSelected) {
var _rowsSelected = [];
for (var _i = rowIdx; _i <= this.state.lastRowIdxUiSelected - 1; _i++) {
_rowsSelected.push({ rowIdx: _i, row: this.props.rowGetter(_i) });
}
if (typeof this.props.rowSelection.onRowsSelected === 'function') {
this.props.rowSelection.onRowsSelected(_rowsSelected);
}
handled = true;
}
if (handled) {
this.setState({ lastRowIdxUiSelected: rowIdx });
}
return handled;
}
return false;
},
handleNewRowSelect: function handleNewRowSelect(rowIdx, rowData) {
var _props$rowSelection$s2 = this.props.rowSelection.selectBy,
keys = _props$rowSelection$s2.keys,
indexes = _props$rowSelection$s2.indexes,
isSelectedKey = _props$rowSelection$s2.isSelectedKey;
var isPreviouslySelected = RowUtils.isRowSelected(keys, indexes, isSelectedKey, rowData, rowIdx);
this.setState({ lastRowIdxUiSelected: isPreviouslySelected ? -1 : rowIdx, selected: { rowIdx: rowIdx, idx: 0 } });
if (isPreviouslySelected && typeof this.props.rowSelection.onRowsDeselected === 'function') {
this.props.rowSelection.onRowsDeselected([{ rowIdx: rowIdx, row: rowData }]);
} else if (!isPreviouslySelected && typeof this.props.rowSelection.onRowsSelected === 'function') {
this.props.rowSelection.onRowsSelected([{ rowIdx: rowIdx, row: rowData }]);
}
},
// columnKey not used here as this function will select the whole row,
// but needed to match the function signature in the CheckboxEditor
handleRowSelect: function handleRowSelect(rowIdx, columnKey, rowData, e) {
e.stopPropagation();
if (this.useNewRowSelection()) {
if (this.props.rowSelection.enableShiftSelect === true) {
if (!this.handleShiftSelect(rowIdx)) {
this.handleNewRowSelect(rowIdx, rowData);
}
} else {
this.handleNewRowSelect(rowIdx, rowData);
}
} else {
// Fallback to old onRowSelect handler
var _selectedRows = this.props.enableRowSelect === 'single' ? [] : this.state.selectedRows.slice(0);
var selectedRow = this.getSelectedRow(_selectedRows, rowData[this.props.rowKey]);
if (selectedRow) {
selectedRow.isSelected = !selectedRow.isSelected;
} else {
rowData.isSelected = true;
_selectedRows.push(rowData);
}
this.setState({ selectedRows: _selectedRows, selected: { rowIdx: rowIdx, idx: 0 } });
if (this.props.onRowSelect) {
this.props.onRowSelect(_selectedRows.filter(function (r) {
return r.isSelected === true;
}));
}
}
},
handleCheckboxChange: function handleCheckboxChange(e) {
var allRowsSelected = void 0;
if (e.currentTarget instanceof HTMLInputElement && e.currentTarget.checked === true) {
allRowsSelected = true;
} else {
allRowsSelected = false;
}
if (this.useNewRowSelection()) {
var _props$rowSelection$s3 = this.props.rowSelection.selectBy,
keys = _props$rowSelection$s3.keys,
indexes = _props$rowSelection$s3.indexes,
isSelectedKey = _props$rowSelection$s3.isSelectedKey;
if (allRowsSelected && typeof this.props.rowSelection.onRowsSelected === 'function') {
var _selectedRows2 = [];
for (var i = 0; i < this.props.rowsCount; i++) {
var rowData = this.props.rowGetter(i);
if (!RowUtils.isRowSelected(keys, indexes, isSelectedKey, rowData, i)) {
_selectedRows2.push({ rowIdx: i, row: rowData });
}
}
if (_selectedRows2.length > 0) {
this.props.rowSelection.onRowsSelected(_selectedRows2);
}
} else if (!allRowsSelected && typeof this.props.rowSelection.onRowsDeselected === 'function') {
var deselectedRows = [];
for (var _i2 = 0; _i2 < this.props.rowsCount; _i2++) {
var _rowData = this.props.rowGetter(_i2);
if (RowUtils.isRowSelected(keys, indexes, isSelectedKey, _rowData, _i2)) {
deselectedRows.push({ rowIdx: _i2, row: _rowData });
}
}
if (deselectedRows.length > 0) {
this.props.rowSelection.onRowsDeselected(deselectedRows);
}
}
} else {
var _selectedRows3 = [];
for (var _i3 = 0; _i3 < this.props.rowsCount; _i3++) {
var row = Object.assign({}, this.props.rowGetter(_i3), { isSelected: allRowsSelected });
_selectedRows3.push(row);
}
this.setState({ selectedRows: _selectedRows3 });
if (typeof this.props.onRowSelect === 'function') {
this.props.onRowSelect(_selectedRows3.filter(function (r) {
return r.isSelected === true;
}));
}
}
},
getScrollOffSet: function getScrollOffSet() {
var scrollOffset = 0;
var canvas = ReactDOM.findDOMNode(this).querySelector('.react-grid-Canvas');
if (canvas) {
scrollOffset = canvas.offsetWidth - canvas.clientWidth;
}
this.setState({ scrollOffset: scrollOffset });
},
getRowOffsetHeight: function getRowOffsetHeight() {
var offsetHeight = 0;
this.getHeaderRows().forEach(function (row) {
return offsetHeight += parseFloat(row.height, 10);
});
return offsetHeight;
},
getHeaderRows: function getHeaderRows() {
var rows = [{ ref: 'row', height: this.props.headerRowHeight || this.props.rowHeight, rowType: 'header' }];
if (this.state.canFilter === true) {
rows.push({
ref: 'filterRow',
filterable: true,
onFilterChange: this.props.onAddFilter,
height: 45,
rowType: 'filter'
});
}
return rows;
},
getInitialSelectedRows: function getInitialSelectedRows() {
var selectedRows = [];
for (var i = 0; i < this.props.rowsCount; i++) {
selectedRows.push(false);
}
return selectedRows;
},
getRowSelectionProps: function getRowSelectionProps() {
if (this.props.rowSelection) {
return this.props.rowSelection.selectBy;
}
return null;
},
getSelectedRows: function getSelectedRows() {
if (this.props.rowSelection) {
return null;
}
return this.state.selectedRows.filter(function (r) {
return r.isSelected === true;
});
},
getSelectedValue: function getSelectedValue() {
var rowIdx = this.state.selected.rowIdx;
var idx = this.state.selected.idx;
var cellKey = this.getColumn(idx).key;
var row = this.props.rowGetter(rowIdx);
return RowUtils.get(row, cellKey);
},
moveSelectedCell: function moveSelectedCell(e, rowDelta, cellDelta) {
// we need to prevent default as we control grid scroll
// otherwise it moves every time you left/right which is janky
e.preventDefault();
var rowIdx = void 0;
var idx = void 0;
var cellNavigationMode = this.props.cellNavigationMode;
if (cellNavigationMode !== 'none') {
var _calculateNextSelecti = this.calculateNextSelectionPosition(cellNavigationMode, cellDelta, rowDelta);
idx = _calculateNextSelecti.idx;
rowIdx = _calculateNextSelecti.rowIdx;
} else {
rowIdx = this.state.selected.rowIdx + rowDelta;
idx = this.state.selected.idx + cellDelta;
}
this.onSelect({ idx: idx, rowIdx: rowIdx });
},
getNbrColumns: function getNbrColumns() {
var _props = this.props,
columns = _props.columns,
enableRowSelect = _props.enableRowSelect;
return enableRowSelect ? columns.length + 1 : columns.length;
},
getDataGridDOMNode: function getDataGridDOMNode() {
if (!this._gridNode) {
this._gridNode = ReactDOM.findDOMNode(this);
}
return this._gridNode;
},
calculateNextSelectionPosition: function calculateNextSelectionPosition(cellNavigationMode, cellDelta, rowDelta) {
var _rowDelta = rowDelta;
var idx = this.state.selected.idx + cellDelta;
var nbrColumns = this.getNbrColumns();
if (cellDelta > 0) {
if (this.isAtLastCellInRow(nbrColumns)) {
if (cellNavigationMode === 'changeRow') {
_rowDelta = this.isAtLastRow() ? rowDelta : rowDelta + 1;
idx = this.isAtLastRow() ? idx : 0;
} else {
idx = 0;
}
}
} else if (cellDelta < 0) {
if (this.isAtFirstCellInRow()) {
if (cellNavigationMode === 'changeRow') {
_rowDelta = this.isAtFirstRow() ? rowDelta : rowDelta - 1;
idx = this.isAtFirstRow() ? 0 : nbrColumns - 1;
} else {
idx = nbrColumns - 1;
}
}
}
var rowIdx = this.state.selected.rowIdx + _rowDelta;
return { idx: idx, rowIdx: rowIdx };
},
isAtLastCellInRow: function isAtLastCellInRow(nbrColumns) {
return this.state.selected.idx === nbrColumns - 1;
},
isAtLastRow: function isAtLastRow() {
return this.state.selected.rowIdx === this.props.rowsCount - 1;
},
isAtFirstCellInRow: function isAtFirstCellInRow() {
return this.state.selected.idx === 0;
},
isAtFirstRow: function isAtFirstRow() {
return this.state.selected.rowIdx === 0;
},
openCellEditor: function openCellEditor(rowIdx, idx) {
var _this4 = this;
var row = this.props.rowGetter(rowIdx);
var col = this.getColumn(idx);
if (!ColumnUtils.canEdit(col, row, this.props.enableCellSelect)) {
return;
}
var selected = { rowIdx: rowIdx, idx: idx };
if (this.hasSelectedCellChanged(selected)) {
this.setState({ selected: selected }, function () {
_this4.setActive('Enter');
});
} else {
this.setActive('Enter');
}
},
scrollToColumn: function scrollToColumn(colIdx) {
var canvas = ReactDOM.findDOMNode(this).querySelector('.react-grid-Canvas');
if (canvas) {
var left = 0;
var locked = 0;
for (var i = 0; i < colIdx; i++) {
var column = this.getColumn(i);
if (column) {
if (column.width) {
left += column.width;
}
if (column.locked) {
locked += column.width;
}
}
}
var selectedColumn = this.getColumn(colIdx);
if (selectedColumn) {
var scrollLeft = left - locked - canvas.scrollLeft;
var scrollRight = left + selectedColumn.width - canvas.scrollLeft;
if (scrollLeft < 0) {
canvas.scrollLeft += scrollLeft;
} else if (scrollRight > canvas.clientWidth) {
var scrollAmount = scrollRight - canvas.clientWidth;
canvas.scrollLeft += scrollAmount;
}
}
}
},
setActive: function setActive(keyPressed) {
var rowIdx = this.state.selected.rowIdx;
var row = this.props.rowGetter(rowIdx);
var idx = this.state.selected.idx;
var column = this.getColumn(idx);
if (ColumnUtils.canEdit(column, row, this.props.enableCellSelect) && !this.isActive()) {
var _selected = Object.assign(this.state.selected, { idx: idx, rowIdx: rowIdx, active: true, initialKeyCode: keyPressed });
var showEditor = true;
if (typeof this.props.onCheckCellIsEditable === 'function') {
var args = Object.assign({}, { row: row, column: column }, _selected);
showEditor = this.props.onCheckCellIsEditable(args);
}
if (showEditor !== false) {
this.setState({ selected: _selected }, this.scrollToColumn(idx));
this.handleCancelCopy();
}
}
},
setInactive: function setInactive() {
var rowIdx = this.state.selected.rowIdx;
var row = this.props.rowGetter(rowIdx);
var idx = this.state.selected.idx;
var col = this.getColumn(idx);
if (ColumnUtils.canEdit(col, row, this.props.enableCellSelect) && this.isActive()) {
var _selected2 = Object.assign(this.state.selected, { idx: idx, rowIdx: rowIdx, active: false });
this.setState({ selected: _selected2 });
}
},
isActive: function isActive() {
return this.state.selected.active === true;
},
setupGridColumns: function setupGridColumns() {
var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props;
var columns = props.columns;
if (this._cachedColumns === columns) {
return this._cachedComputedColumns;
}
this._cachedColumns = columns;
var cols = columns.slice(0);
var unshiftedCols = {};
if (this.props.rowActionsCell || props.enableRowSelect && !this.props.rowSelection || props.rowSelection && props.rowSelection.showCheckbox !== false) {
var headerRenderer = props.enableRowSelect === 'single' ? null : React.createElement(
'div',
{ className: 'react-grid-checkbox-container' },
React.createElement('input', { className: 'react-grid-checkbox', type: 'checkbox', name: 'select-all-checkbox', id: 'select-all-checkbox', onChange: this.handleCheckboxChange }),
React.createElement('label', { htmlFor: 'select-all-checkbox', className: 'react-grid-checkbox-label' })
);
var Formatter = this.props.rowActionsCell ? this.props.rowActionsCell : CheckboxEditor;
var selectColumn = {
key: 'select-row',
name: '',
formatter: React.createElement(Formatter, { rowSelection: this.props.rowSelection }),
onCellChange: this.handleRowSelect,
filterable: false,
headerRenderer: headerRenderer,
width: 60,
locked: true,
getRowMetaData: function getRowMetaData(rowData) {
return rowData;
},
cellClass: this.props.rowActionsCell ? 'rdg-row-actions-cell' : ''
};
unshiftedCols = cols.unshift(selectColumn);
cols = unshiftedCols > 0 ? cols : unshiftedCols;
}
this._cachedComputedColumns = cols;
return this._cachedComputedColumns;
},
copyPasteEnabled: function copyPasteEnabled() {
return this.props.onCellCopyPaste !== null;
},
dragEnabled: function dragEnabled() {
return this.props.onGridRowsUpdated !== undefined || this.props.onCellsDragged !== undefined;
},
renderToolbar: function renderToolbar() {
var Toolbar = this.props.toolbar;
if (React.isValidElement(Toolbar)) {
return React.cloneElement(Toolbar, { columns: this.props.columns, onToggleFilter: this.onToggleFilter, numberOfRows: this.props.rowsCount });
}
},
render: function render() {
var cellMetaData = {
selected: this.state.selected,
dragged: this.state.dragged,
hoveredRowIdx: this.state.hoveredRowIdx,
onCellClick: this.onCellClick,
onCellContextMenu: this.onCellContextMenu,
onCellDoubleClick: this.onCellDoubleClick,
onCommit: this.onCellCommit,
onCommitCancel: this.setInactive,
copied: this.state.copied,
handleDragEnterRow: this.handleDragEnter,
handleTerminateDrag: this.handleTerminateDrag,
enableCellSelect: this.props.enableCellSelect,
onColumnEvent: this.onColumnEvent,
openCellEditor: this.openCellEditor,
onDragHandleDoubleClick: this.onDragHandleDoubleClick,
onCellExpand: this.onCellExpand,
onRowExpandToggle: this.onRowExpandToggle,
onRowHover: this.onRowHover,
getDataGridDOMNode: this.getDataGridDOMNode,
isScrollingVerticallyWithKeyboard: this.isKeyDown(40) || this.isKeyDown(38), // up or down
isScrollingHorizontallyWithKeyboard: this.isKeyDown(37) || this.isKeyDown(39) // left or right
};
var toolbar = this.renderToolbar();
var containerWidth = this.props.minWidth || this.DOMMetrics.gridWidth();
var gridWidth = containerWidth - this.state.scrollOffset;
// depending on the current lifecycle stage, gridWidth() may not initialize correctly
// this also handles cases where it always returns undefined -- such as when inside a div with display:none
// eg Bootstrap tabs and collapses
if (typeof containerWidth === 'undefined' || isNaN(containerWidth) || containerWidth === 0) {
containerWidth = '100%';
}
if (typeof gridWidth === 'undefined' || isNaN(gridWidth) || gridWidth === 0) {
gridWidth = '100%';
}
return React.createElement(
'div',
{ className: 'react-grid-Container', style: { width: containerWidth } },
toolbar,
React.createElement(
'div',
{ className: 'react-grid-Main' },
React.createElement(BaseGrid, _extends({
ref: 'base'
}, this.props, {
rowKey: this.props.rowKey,
headerRows: this.getHeaderRows(),
columnMetrics: this.state.columnMetrics,
rowGetter: this.props.rowGetter,
rowsCount: this.props.rowsCount,
rowHeight: this.props.rowHeight,
cellMetaData: cellMetaData,
selectedRows: this.getSelectedRows(),
rowSelection: this.getRowSelectionProps(),
expandedRows: this.state.expandedRows,
rowOffsetHeight: this.getRowOffsetHeight(),
sortColumn: this.state.sortColumn,
sortDirection: this.state.sortDirection,
onSort: this.handleSort,
minHeight: this.props.minHeight,
totalWidth: gridWidth,
onViewportKeydown: this.onKeyDown,
onViewportKeyup: this.onKeyUp,
onViewportDragStart: this.onDragStart,
onViewportDragEnd: this.handleDragEnd,
onViewportDoubleClick: this.onViewportDoubleClick,
onColumnResize: this.onColumnResize,
rowScrollTimeout: this.props.rowScrollTimeout,
contextMenu: this.props.contextMenu,
overScan: this.props.overScan }))
)
);
}
});
module.exports = ReactDataGrid;
/***/ },
/* 55 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(1);
var Draggable = __webpack_require__(45);
var ResizeHandle = React.createClass({
displayName: 'ResizeHandle',
style: {
position: 'absolute',
top: 0,
right: 0,
width: 6,
height: '100%'
},
render: function render() {
return React.createElement(Draggable, _extends({}, this.props, {
className: 'react-grid-HeaderCell__resizeHandle',
style: this.style
}));
}
});
module.exports = ResizeHandle;
/***/ },
/* 56 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.shouldRowUpdate = undefined;
var _ColumnMetrics = __webpack_require__(17);
var _ColumnMetrics2 = _interopRequireDefault(_ColumnMetrics);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function doesRowContainSelectedCell(props) {
var selected = props.cellMetaData.selected;
if (selected && selected.rowIdx === props.idx) {
return true;
}
return false;
}
function willRowBeDraggedOver(props) {
var dragged = props.cellMetaData.dragged;
return dragged != null && (dragged.rowIdx >= 0 || dragged.complete === true);
}
function hasRowBeenCopied(props) {
var copied = props.cellMetaData.copied;
return copied != null && copied.rowIdx === props.idx;
}
var shouldRowUpdate = exports.shouldRowUpdate = function shouldRowUpdate(nextProps, currentProps) {
return !_ColumnMetrics2['default'].sameColumns(currentProps.columns, nextProps.columns, _ColumnMetrics2['default'].sameColumn) || doesRowContainSelectedCell(currentProps) || doesRowContainSelectedCell(nextProps) || willRowBeDraggedOver(nextProps) || nextProps.row !== currentProps.row || currentProps.colDisplayStart !== nextProps.colDisplayStart || currentProps.colDisplayEnd !== nextProps.colDisplayEnd || currentProps.colVisibleStart !== nextProps.colVisibleStart || currentProps.colVisibleEnd !== nextProps.colVisibleEnd || hasRowBeenCopied(currentProps) || currentProps.isSelected !== nextProps.isSelected || nextProps.height !== currentProps.height || currentProps.isOver !== nextProps.isOver || currentProps.canDrop !== nextProps.canDrop || currentProps.forceUpdate === true;
};
exports['default'] = shouldRowUpdate;
/***/ },
/* 57 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _classnames = __webpack_require__(5);
var _classnames2 = _interopRequireDefault(_classnames);
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 RowGroup = function (_Component) {
_inherits(RowGroup, _Component);
function RowGroup() {
_classCallCheck(this, RowGroup);
var _this = _possibleConstructorReturn(this, _Component.call(this));
_this.checkFocus = _this.checkFocus.bind(_this);
_this.isSelected = _this.isSelected.bind(_this);
_this.onClick = _this.onClick.bind(_this);
_this.onRowExpandToggle = _this.onRowExpandToggle.bind(_this);
_this.onKeyDown = _this.onKeyDown.bind(_this);
_this.onRowExpandClick = _this.onRowExpandClick.bind(_this);
return _this;
}
RowGroup.prototype.componentDidMount = function componentDidMount() {
this.checkFocus();
};
RowGroup.prototype.componentDidUpdate = function componentDidUpdate() {
this.checkFocus();
};
RowGroup.prototype.isSelected = function isSelected() {
var meta = this.props.cellMetaData;
if (meta == null) {
return false;
}
return meta.selected && meta.selected.rowIdx === this.props.idx;
};
RowGroup.prototype.onClick = function onClick(e) {
var meta = this.props.cellMetaData;
if (meta != null && meta.onCellClick && typeof meta.onCellClick === 'function') {
meta.onCellClick({ rowIdx: this.props.idx, idx: 0 }, e);
}
};
RowGroup.prototype.onKeyDown = function onKeyDown(e) {
if (e.key === 'ArrowLeft') {
this.onRowExpandToggle(false);
}
if (e.key === 'ArrowRight') {
this.onRowExpandToggle(true);
}
if (e.key === 'Enter') {
this.onRowExpandToggle(!this.props.isExpanded);
}
};
RowGroup.prototype.onRowExpandClick = function onRowExpandClick() {
this.onRowExpandToggle(!this.props.isExpanded);
};
RowGroup.prototype.onRowExpandToggle = function onRowExpandToggle(expand) {
var shouldExpand = expand == null ? !this.props.isExpanded : expand;
var meta = this.props.cellMetaData;
if (meta != null && meta.onRowExpandToggle && typeof meta.onRowExpandToggle === 'function') {
meta.onRowExpandToggle({ rowIdx: this.props.idx, shouldExpand: shouldExpand, columnGroupName: this.props.columnGroupName, name: this.props.name });
}
};
RowGroup.prototype.getClassName = function getClassName() {
return (0, _classnames2['default'])('react-grid-row-group', 'react-grid-Row', { 'row-selected': this.isSelected() });
};
RowGroup.prototype.checkFocus = function checkFocus() {
if (this.isSelected()) {
_reactDom2['default'].findDOMNode(this).focus();
}
};
RowGroup.prototype.render = function render() {
var style = {
height: '50px',
overflow: 'hidden',
border: '1px solid #dddddd',
paddingTop: '15px',
paddingLeft: '5px'
};
var rowGroupRendererProps = Object.assign({ onRowExpandClick: this.onRowExpandClick }, this.props);
return _react2['default'].createElement(
'div',
{ style: style, className: this.getClassName(), onClick: this.onClick, onKeyDown: this.onKeyDown, tabIndex: -1 },
_react2['default'].createElement(this.props.renderer, rowGroupRendererProps)
);
};
return RowGroup;
}(_react.Component);
RowGroup.propTypes = {
name: _react.PropTypes.string.isRequired,
columnGroupName: _react.PropTypes.string.isRequired,
isExpanded: _react.PropTypes.bool.isRequired,
treeDepth: _react.PropTypes.number.isRequired,
height: _react.PropTypes.number.isRequired,
cellMetaData: _react.PropTypes.object,
idx: _react.PropTypes.number.isRequired,
renderer: _react.PropTypes.func
};
var DefaultRowGroupRenderer = function DefaultRowGroupRenderer(props) {
var treeDepth = props.treeDepth || 0;
var marginLeft = treeDepth * 20;
return _react2['default'].createElement(
'div',
null,
_react2['default'].createElement(
'span',
{ className: 'row-expand-icon', style: { float: 'left', marginLeft: marginLeft, cursor: 'pointer' }, onClick: props.onRowExpandClick },
props.isExpanded ? String.fromCharCode('9660') : String.fromCharCode('9658')
),
_react2['default'].createElement(
'strong',
null,
props.columnGroupName,
' : ',
props.name
)
);
};
DefaultRowGroupRenderer.propTypes = {
onRowExpandClick: _react.PropTypes.func.isRequired,
isExpanded: _react.PropTypes.bool.isRequired,
treeDepth: _react.PropTypes.number.isRequired,
name: _react.PropTypes.string.isRequired,
columnGroupName: _react.PropTypes.string.isRequired
};
RowGroup.defaultProps = {
renderer: DefaultRowGroupRenderer
};
exports['default'] = RowGroup;
/***/ },
/* 58 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.SimpleRowsContainer = undefined;
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
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 SimpleRowsContainer = function SimpleRowsContainer(props) {
return _react2['default'].createElement(
'div',
{ key: 'rows-container', style: { overflow: 'hidden' } },
props.rows
);
};
SimpleRowsContainer.propTypes = {
width: _react.PropTypes.number,
rows: _react.PropTypes.array
};
var RowsContainer = function (_React$Component) {
_inherits(RowsContainer, _React$Component);
function RowsContainer(props) {
_classCallCheck(this, RowsContainer);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));
_this.plugins = props.window ? props.window.ReactDataGridPlugins : window.ReactDataGridPlugins;
_this.hasContextMenu = _this.hasContextMenu.bind(_this);
_this.renderRowsWithContextMenu = _this.renderRowsWithContextMenu.bind(_this);
_this.getContextMenuContainer = _this.getContextMenuContainer.bind(_this);
_this.state = { ContextMenuContainer: _this.getContextMenuContainer(props) };
return _this;
}
RowsContainer.prototype.getContextMenuContainer = function getContextMenuContainer() {
if (this.hasContextMenu()) {
if (!this.plugins) {
throw new Error('You need to include ReactDataGrid UiPlugins in order to initialise context menu');
}
return this.plugins.Menu.ContextMenuLayer('reactDataGridContextMenu')(SimpleRowsContainer);
}
};
RowsContainer.prototype.hasContextMenu = function hasContextMenu() {
return this.props.contextMenu && _react2['default'].isValidElement(this.props.contextMenu);
};
RowsContainer.prototype.renderRowsWithContextMenu = function renderRowsWithContextMenu() {
var ContextMenuRowsContainer = this.state.ContextMenuContainer;
var newProps = { rowIdx: this.props.rowIdx, idx: this.props.idx };
var contextMenu = _react2['default'].cloneElement(this.props.contextMenu, newProps);
// Initialise the context menu if it is available
return _react2['default'].createElement(
'div',
null,
_react2['default'].createElement(ContextMenuRowsContainer, this.props),
contextMenu
);
};
RowsContainer.prototype.render = function render() {
return this.hasContextMenu() ? this.renderRowsWithContextMenu() : _react2['default'].createElement(SimpleRowsContainer, this.props);
};
return RowsContainer;
}(_react2['default'].Component);
RowsContainer.propTypes = {
contextMenu: _react.PropTypes.element,
rowIdx: _react.PropTypes.number,
idx: _react.PropTypes.number,
window: _react.PropTypes.object
};
exports['default'] = RowsContainer;
exports.SimpleRowsContainer = SimpleRowsContainer;
/***/ },
/* 59 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var ScrollShim = {
appendScrollShim: function appendScrollShim() {
if (!this._scrollShim) {
var size = this._scrollShimSize();
var shim = document.createElement('div');
if (shim.classList) {
shim.classList.add('react-grid-ScrollShim'); // flow - not compatible with HTMLElement
} else {
shim.className += ' react-grid-ScrollShim';
}
shim.style.position = 'absolute';
shim.style.top = 0;
shim.style.left = 0;
shim.style.width = size.width + 'px';
shim.style.height = size.height + 'px';
_reactDom2['default'].findDOMNode(this).appendChild(shim);
this._scrollShim = shim;
}
this._scheduleRemoveScrollShim();
},
_scrollShimSize: function _scrollShimSize() {
return {
width: this.props.width,
height: this.props.length * this.props.rowHeight
};
},
_scheduleRemoveScrollShim: function _scheduleRemoveScrollShim() {
if (this._scheduleRemoveScrollShimTimer) {
clearTimeout(this._scheduleRemoveScrollShimTimer);
}
this._scheduleRemoveScrollShimTimer = setTimeout(this._removeScrollShim, 200);
},
_removeScrollShim: function _removeScrollShim() {
if (this._scrollShim) {
this._scrollShim.parentNode.removeChild(this._scrollShim);
this._scrollShim = undefined;
}
}
};
module.exports = ScrollShim;
/***/ },
/* 60 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var Canvas = __webpack_require__(42);
var ViewportScroll = __webpack_require__(61);
var cellMetaDataShape = __webpack_require__(8);
var PropTypes = React.PropTypes;
var Viewport = React.createClass({
displayName: 'Viewport',
mixins: [ViewportScroll],
propTypes: {
rowOffsetHeight: PropTypes.number.isRequired,
totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
columnMetrics: PropTypes.object.isRequired,
rowGetter: PropTypes.oneOfType([PropTypes.array, PropTypes.func]).isRequired,
selectedRows: PropTypes.array,
rowSelection: React.PropTypes.oneOfType([React.PropTypes.shape({
indexes: React.PropTypes.arrayOf(React.PropTypes.number).isRequired
}), React.PropTypes.shape({
isSelectedKey: React.PropTypes.string.isRequired
}), React.PropTypes.shape({
keys: React.PropTypes.shape({
values: React.PropTypes.array.isRequired,
rowKey: React.PropTypes.string.isRequired
}).isRequired
})]),
expandedRows: PropTypes.array,
rowRenderer: PropTypes.oneOfType([PropTypes.element, PropTypes.func]),
rowsCount: PropTypes.number.isRequired,
rowHeight: PropTypes.number.isRequired,
onRows: PropTypes.func,
onScroll: PropTypes.func,
minHeight: PropTypes.number,
cellMetaData: PropTypes.shape(cellMetaDataShape),
rowKey: PropTypes.string.isRequired,
rowScrollTimeout: PropTypes.number,
contextMenu: PropTypes.element,
getSubRowDetails: PropTypes.func,
rowGroupRenderer: PropTypes.func
},
onScroll: function onScroll(scroll) {
this.updateScroll(scroll.scrollTop, scroll.scrollLeft, this.state.height, this.props.rowHeight, this.props.rowsCount);
if (this.props.onScroll) {
this.props.onScroll({ scrollTop: scroll.scrollTop, scrollLeft: scroll.scrollLeft });
}
},
getScroll: function getScroll() {
return this.refs.canvas.getScroll();
},
setScrollLeft: function setScrollLeft(scrollLeft) {
this.refs.canvas.setScrollLeft(scrollLeft);
},
render: function render() {
var style = {
padding: 0,
bottom: 0,
left: 0,
right: 0,
overflow: 'hidden',
position: 'absolute',
top: this.props.rowOffsetHeight
};
return React.createElement(
'div',
{
className: 'react-grid-Viewport',
style: style },
React.createElement(Canvas, {
ref: 'canvas',
rowKey: this.props.rowKey,
totalWidth: this.props.totalWidth,
width: this.props.columnMetrics.width,
rowGetter: this.props.rowGetter,
rowsCount: this.props.rowsCount,
selectedRows: this.props.selectedRows,
expandedRows: this.props.expandedRows,
columns: this.props.columnMetrics.columns,
rowRenderer: this.props.rowRenderer,
displayStart: this.state.displayStart,
displayEnd: this.state.displayEnd,
visibleStart: this.state.visibleStart,
visibleEnd: this.state.visibleEnd,
colVisibleStart: this.state.colVisibleStart,
colVisibleEnd: this.state.colVisibleEnd,
colDisplayStart: this.state.colDisplayStart,
colDisplayEnd: this.state.colDisplayEnd,
cellMetaData: this.props.cellMetaData,
height: this.state.height,
rowHeight: this.props.rowHeight,
onScroll: this.onScroll,
onRows: this.props.onRows,
rowScrollTimeout: this.props.rowScrollTimeout,
contextMenu: this.props.contextMenu,
rowSelection: this.props.rowSelection,
getSubRowDetails: this.props.getSubRowDetails,
rowGroupRenderer: this.props.rowGroupRenderer,
isScrolling: this.state.isScrolling
})
);
}
});
module.exports = Viewport;
/***/ },
/* 61 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _ColumnUtils = __webpack_require__(4);
var _ColumnUtils2 = _interopRequireDefault(_ColumnUtils);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(2);
var DOMMetrics = __webpack_require__(10);
var min = Math.min;
var max = Math.max;
var floor = Math.floor;
var ceil = Math.ceil;
module.exports = {
mixins: [DOMMetrics.MetricsMixin],
DOMMetrics: {
viewportHeight: function viewportHeight() {
return ReactDOM.findDOMNode(this).offsetHeight;
},
viewportWidth: function viewportWidth() {
return ReactDOM.findDOMNode(this).offsetWidth;
}
},
propTypes: {
rowHeight: React.PropTypes.number,
rowsCount: React.PropTypes.number.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
rowHeight: 30
};
},
getInitialState: function getInitialState() {
return this.getGridState(this.props);
},
getGridState: function getGridState(props) {
var totalNumberColumns = _ColumnUtils2['default'].getSize(props.columnMetrics.columns);
var canvasHeight = props.minHeight - props.rowOffsetHeight;
var renderedRowsCount = ceil((props.minHeight - props.rowHeight) / props.rowHeight);
var totalRowCount = min(renderedRowsCount * 4, props.rowsCount);
return {
displayStart: 0,
displayEnd: totalRowCount,
visibleStart: 0,
visibleEnd: totalRowCount,
height: canvasHeight,
scrollTop: 0,
scrollLeft: 0,
colVisibleStart: 0,
colVisibleEnd: totalNumberColumns,
colDisplayStart: 0,
colDisplayEnd: totalNumberColumns
};
},
getRenderedColumnCount: function getRenderedColumnCount(displayStart, width) {
var remainingWidth = width > 0 ? width : this.props.columnMetrics.totalWidth;
if (remainingWidth === 0) {
remainingWidth = ReactDOM.findDOMNode(this).offsetWidth;
}
var columnIndex = displayStart;
var columnCount = 0;
while (remainingWidth > 0) {
var column = _ColumnUtils2['default'].getColumn(this.props.columnMetrics.columns, columnIndex);
if (!column) {
break;
}
columnCount++;
columnIndex++;
remainingWidth -= column.width;
}
return columnCount;
},
getVisibleColStart: function getVisibleColStart(scrollLeft) {
var remainingScroll = scrollLeft;
var columnIndex = -1;
while (remainingScroll >= 0) {
columnIndex++;
remainingScroll -= _ColumnUtils2['default'].getColumn(this.props.columnMetrics.columns, columnIndex).width;
}
return columnIndex;
},
resetScrollStateAfterDelay: function resetScrollStateAfterDelay() {
if (this.resetScrollStateTimeoutId) {
clearTimeout(this.resetScrollStateTimeoutId);
}
this.resetScrollStateTimeoutId = setTimeout(this.resetScrollStateAfterDelayCallback, 500);
},
resetScrollStateAfterDelayCallback: function resetScrollStateAfterDelayCallback() {
this.resetScrollStateTimeoutId = null;
this.setState({
isScrolling: false
});
},
updateScroll: function updateScroll(scrollTop, scrollLeft, height, rowHeight, length, width) {
var isScrolling = true;
this.resetScrollStateAfterDelay();
var renderedRowsCount = ceil(height / rowHeight);
var visibleStart = max(0, floor(scrollTop / rowHeight));
var visibleEnd = min(visibleStart + renderedRowsCount, length);
var displayStart = max(0, visibleStart - this.props.overScan.rowsStart);
var displayEnd = min(visibleEnd + this.props.overScan.rowsEnd, length);
var totalNumberColumns = _ColumnUtils2['default'].getSize(this.props.columnMetrics.columns);
var colVisibleStart = max(0, this.getVisibleColStart(scrollLeft));
var renderedColumnCount = this.getRenderedColumnCount(colVisibleStart, width);
var colVisibleEnd = colVisibleStart + renderedColumnCount;
var colDisplayStart = max(0, colVisibleStart - this.props.overScan.colsStart);
var colDisplayEnd = min(colVisibleEnd + this.props.overScan.colsEnd, totalNumberColumns);
var nextScrollState = {
visibleStart: visibleStart,
visibleEnd: visibleEnd,
displayStart: displayStart,
displayEnd: displayEnd,
height: height,
scrollTop: scrollTop,
scrollLeft: scrollLeft,
colVisibleStart: colVisibleStart,
colVisibleEnd: colVisibleEnd,
colDisplayStart: colDisplayStart,
colDisplayEnd: colDisplayEnd,
isScrolling: isScrolling
};
this.setState(nextScrollState);
},
metricsUpdated: function metricsUpdated() {
var height = this.DOMMetrics.viewportHeight();
var width = this.DOMMetrics.viewportWidth();
if (height) {
this.updateScroll(this.state.scrollTop, this.state.scrollLeft, height, this.props.rowHeight, this.props.rowsCount, width);
}
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if (this.props.rowHeight !== nextProps.rowHeight || this.props.minHeight !== nextProps.minHeight || _ColumnUtils2['default'].getSize(this.props.columnMetrics.columns) !== _ColumnUtils2['default'].getSize(nextProps.columnMetrics.columns)) {
this.setState(this.getGridState(nextProps));
} else if (this.props.rowsCount !== nextProps.rowsCount) {
this.updateScroll(this.state.scrollTop, this.state.scrollLeft, this.state.height, nextProps.rowHeight, nextProps.rowsCount);
// Added to fix the hiding of the bottom scrollbar when showing the filters.
} else if (this.props.rowOffsetHeight !== nextProps.rowOffsetHeight) {
// The value of height can be positive or negative and will be added to the current height to cater for changes in the header height (due to the filer)
var _height = this.props.rowOffsetHeight - nextProps.rowOffsetHeight;
this.updateScroll(this.state.scrollTop, this.state.scrollLeft, this.state.height + _height, nextProps.rowHeight, nextProps.rowsCount);
}
}
};
/***/ },
/* 62 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var ExcelColumn = __webpack_require__(6);
var FilterableHeaderCell = React.createClass({
displayName: 'FilterableHeaderCell',
propTypes: {
onChange: React.PropTypes.func.isRequired,
column: React.PropTypes.shape(ExcelColumn)
},
getInitialState: function getInitialState() {
return { filterTerm: '' };
},
handleChange: function handleChange(e) {
var val = e.target.value;
this.setState({ filterTerm: val });
this.props.onChange({ filterTerm: val, column: this.props.column });
},
renderInput: function renderInput() {
if (this.props.column.filterable === false) {
return React.createElement('span', null);
}
var inputKey = 'header-filter-' + this.props.column.key;
return React.createElement('input', { key: inputKey, type: 'text', className: 'form-control input-sm', placeholder: 'Search', value: this.state.filterTerm, onChange: this.handleChange });
},
render: function render() {
return React.createElement(
'div',
null,
React.createElement(
'div',
{ className: 'form-group' },
this.renderInput()
)
);
}
});
module.exports = FilterableHeaderCell;
/***/ },
/* 63 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var joinClasses = __webpack_require__(5);
var DEFINE_SORT = {
ASC: 'ASC',
DESC: 'DESC',
NONE: 'NONE'
};
var SortableHeaderCell = React.createClass({
displayName: 'SortableHeaderCell',
propTypes: {
columnKey: React.PropTypes.string.isRequired,
column: React.PropTypes.shape({ name: React.PropTypes.node }),
onSort: React.PropTypes.func.isRequired,
sortDirection: React.PropTypes.oneOf(['ASC', 'DESC', 'NONE'])
},
onClick: function onClick() {
var direction = void 0;
switch (this.props.sortDirection) {
default:
case null:
case undefined:
case DEFINE_SORT.NONE:
direction = DEFINE_SORT.ASC;
break;
case DEFINE_SORT.ASC:
direction = DEFINE_SORT.DESC;
break;
case DEFINE_SORT.DESC:
direction = DEFINE_SORT.NONE;
break;
}
this.props.onSort(this.props.columnKey, direction);
},
getSortByText: function getSortByText() {
var unicodeKeys = {
ASC: '9650',
DESC: '9660',
NONE: ''
};
return String.fromCharCode(unicodeKeys[this.props.sortDirection]);
},
render: function render() {
var className = joinClasses({
'react-grid-HeaderCell-sortable': true,
'react-grid-HeaderCell-sortable--ascending': this.props.sortDirection === 'ASC',
'react-grid-HeaderCell-sortable--descending': this.props.sortDirection === 'DESC'
});
return React.createElement(
'div',
{ className: className,
onClick: this.onClick,
style: { cursor: 'pointer' } },
this.props.column.name,
React.createElement(
'span',
{ className: 'pull-right' },
this.getSortByText()
)
);
}
});
module.exports = SortableHeaderCell;
/***/ },
/* 64 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var CheckboxEditor = React.createClass({
displayName: 'CheckboxEditor',
propTypes: {
value: React.PropTypes.bool,
rowIdx: React.PropTypes.number,
column: React.PropTypes.shape({
key: React.PropTypes.string,
onCellChange: React.PropTypes.func
}),
dependentValues: React.PropTypes.object
},
handleChange: function handleChange(e) {
this.props.column.onCellChange(this.props.rowIdx, this.props.column.key, this.props.dependentValues, e);
},
render: function render() {
var checked = this.props.value != null ? this.props.value : false;
var checkboxName = 'checkbox' + this.props.rowIdx;
return React.createElement(
'div',
{ className: 'react-grid-checkbox-container', onClick: this.handleChange },
React.createElement('input', { className: 'react-grid-checkbox', type: 'checkbox', name: checkboxName, checked: checked }),
React.createElement('label', { htmlFor: checkboxName, className: 'react-grid-checkbox-label' })
);
}
});
module.exports = CheckboxEditor;
/***/ },
/* 65 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
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 React = __webpack_require__(1);
var ReactDOM = __webpack_require__(2);
var ExcelColumn = __webpack_require__(6);
var EditorBase = function (_React$Component) {
_inherits(EditorBase, _React$Component);
function EditorBase() {
_classCallCheck(this, EditorBase);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
EditorBase.prototype.getStyle = function getStyle() {
return {
width: '100%'
};
};
EditorBase.prototype.getValue = function getValue() {
var updated = {};
updated[this.props.column.key] = this.getInputNode().value;
return updated;
};
EditorBase.prototype.getInputNode = function getInputNode() {
var domNode = ReactDOM.findDOMNode(this);
if (domNode.tagName === 'INPUT') {
return domNode;
}
return domNode.querySelector('input:not([type=hidden])');
};
EditorBase.prototype.inheritContainerStyles = function inheritContainerStyles() {
return true;
};
return EditorBase;
}(React.Component);
EditorBase.propTypes = {
onKeyDown: React.PropTypes.func.isRequired,
value: React.PropTypes.any.isRequired,
onBlur: React.PropTypes.func.isRequired,
column: React.PropTypes.shape(ExcelColumn).isRequired,
commit: React.PropTypes.func.isRequired
};
module.exports = EditorBase;
/***/ },
/* 66 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = __webpack_require__(1);
var joinClasses = __webpack_require__(5);
var keyboardHandlerMixin = __webpack_require__(25);
var SimpleTextEditor = __webpack_require__(67);
var isFunction = __webpack_require__(27);
var EditorContainer = React.createClass({
displayName: 'EditorContainer',
mixins: [keyboardHandlerMixin],
propTypes: {
rowIdx: React.PropTypes.number,
rowData: React.PropTypes.object.isRequired,
value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired,
cellMetaData: React.PropTypes.shape({
selected: React.PropTypes.object.isRequired,
copied: React.PropTypes.object,
dragged: React.PropTypes.object,
onCellClick: React.PropTypes.func,
onCellDoubleClick: React.PropTypes.func,
onCommitCancel: React.PropTypes.func,
onCommit: React.PropTypes.func
}).isRequired,
column: React.PropTypes.object.isRequired,
height: React.PropTypes.number.isRequired
},
changeCommitted: false,
getInitialState: function getInitialState() {
return { isInvalid: false };
},
componentDidMount: function componentDidMount() {
var inputNode = this.getInputNode();
if (inputNode !== undefined) {
this.setTextInputFocus();
if (!this.getEditor().disableContainerStyles) {
inputNode.className += ' editor-main';
inputNode.style.height = this.props.height - 1 + 'px';
}
}
},
componentWillUnmount: function componentWillUnmount() {
if (!this.changeCommitted && !this.hasEscapeBeenPressed()) {
this.commit({ key: 'Enter' });
}
},
createEditor: function createEditor() {
var _this = this;
var editorRef = function editorRef(c) {
return _this.editor = c;
};
var editorProps = {
ref: editorRef,
column: this.props.column,
value: this.getInitialValue(),
onCommit: this.commit,
rowMetaData: this.getRowMetaData(),
rowData: this.props.rowData,
height: this.props.height,
onBlur: this.commit,
onOverrideKeyDown: this.onKeyDown
};
var CustomEditor = this.props.column.editor;
// return custom column editor or SimpleEditor if none specified
if (React.isValidElement(CustomEditor)) {
return React.cloneElement(CustomEditor, editorProps);
}
if (isFunction(CustomEditor)) {
return React.createElement(CustomEditor, _extends({ ref: editorRef }, editorProps));
}
return React.createElement(SimpleTextEditor, { ref: editorRef, column: this.props.column, value: this.getInitialValue(), onBlur: this.commit, rowMetaData: this.getRowMetaData(), onKeyDown: function onKeyDown() {}, commit: function commit() {} });
},
onPressEnter: function onPressEnter() {
this.commit({ key: 'Enter' });
},
onPressTab: function onPressTab() {
this.commit({ key: 'Tab' });
},
onPressEscape: function onPressEscape(e) {
if (!this.editorIsSelectOpen()) {
this.props.cellMetaData.onCommitCancel();
} else {
// prevent event from bubbling if editor has results to select
e.stopPropagation();
}
},
onPressArrowDown: function onPressArrowDown(e) {
if (this.editorHasResults()) {
// dont want to propogate as that then moves us round the grid
e.stopPropagation();
} else {
this.commit(e);
}
},
onPressArrowUp: function onPressArrowUp(e) {
if (this.editorHasResults()) {
// dont want to propogate as that then moves us round the grid
e.stopPropagation();
} else {
this.commit(e);
}
},
onPressArrowLeft: function onPressArrowLeft(e) {
// prevent event propogation. this disables left cell navigation
if (!this.isCaretAtBeginningOfInput()) {
e.stopPropagation();
} else {
this.commit(e);
}
},
onPressArrowRight: function onPressArrowRight(e) {
// prevent event propogation. this disables right cell navigation
if (!this.isCaretAtEndOfInput()) {
e.stopPropagation();
} else {
this.commit(e);
}
},
editorHasResults: function editorHasResults() {
if (isFunction(this.getEditor().hasResults)) {
return this.getEditor().hasResults();
}
return false;
},
editorIsSelectOpen: function editorIsSelectOpen() {
if (isFunction(this.getEditor().isSelectOpen)) {
return this.getEditor().isSelectOpen();
}
return false;
},
getRowMetaData: function getRowMetaData() {
// clone row data so editor cannot actually change this
// convention based method to get corresponding Id or Name of any Name or Id property
if (typeof this.props.column.getRowMetaData === 'function') {
return this.props.column.getRowMetaData(this.props.rowData, this.props.column);
}
},
getEditor: function getEditor() {
return this.editor;
},
getInputNode: function getInputNode() {
return this.getEditor().getInputNode();
},
getInitialValue: function getInitialValue() {
var selected = this.props.cellMetaData.selected;
var keyCode = selected.initialKeyCode;
if (keyCode === 'Delete' || keyCode === 'Backspace') {
return '';
} else if (keyCode === 'Enter') {
return this.props.value;
}
var text = keyCode ? String.fromCharCode(keyCode) : this.props.value;
return text;
},
getContainerClass: function getContainerClass() {
return joinClasses({
'has-error': this.state.isInvalid === true
});
},
commit: function commit(args) {
var opts = args || {};
var updated = this.getEditor().getValue();
if (this.isNewValueValid(updated)) {
this.changeCommitted = true;
var cellKey = this.props.column.key;
this.props.cellMetaData.onCommit({ cellKey: cellKey, rowIdx: this.props.rowIdx, updated: updated, key: opts.key });
}
},
isNewValueValid: function isNewValueValid(value) {
if (isFunction(this.getEditor().validate)) {
var isValid = this.getEditor().validate(value);
this.setState({ isInvalid: !isValid });
return isValid;
}
return true;
},
setCaretAtEndOfInput: function setCaretAtEndOfInput() {
var input = this.getInputNode();
// taken from http://stackoverflow.com/questions/511088/use-javascript-to-place-cursor-at-end-of-text-in-text-input-element
var txtLength = input.value.length;
if (input.setSelectionRange) {
input.setSelectionRange(txtLength, txtLength);
} else if (input.createTextRange) {
var fieldRange = input.createTextRange();
fieldRange.moveStart('character', txtLength);
fieldRange.collapse();
fieldRange.select();
}
},
isCaretAtBeginningOfInput: function isCaretAtBeginningOfInput() {
var inputNode = this.getInputNode();
return inputNode.selectionStart === inputNode.selectionEnd && inputNode.selectionStart === 0;
},
isCaretAtEndOfInput: function isCaretAtEndOfInput() {
var inputNode = this.getInputNode();
return inputNode.selectionStart === inputNode.value.length;
},
isBodyClicked: function isBodyClicked(e) {
return e.relatedTarget === null;
},
isViewportClicked: function isViewportClicked(e) {
return e.relatedTarget.classList.contains('react-grid-Viewport');
},
isClickInisdeEditor: function isClickInisdeEditor(e) {
return e.currentTarget.contains(e.relatedTarget) || e.relatedTarget.classList.contains('editing') || e.relatedTarget.classList.contains('react-grid-Cell');
},
handleBlur: function handleBlur(e) {
e.stopPropagation();
if (this.isBodyClicked(e)) {
this.commit(e);
}
if (!this.isBodyClicked(e)) {
// prevent null reference
if (this.isViewportClicked(e) || !this.isClickInisdeEditor(e)) {
this.commit(e);
}
}
},
setTextInputFocus: function setTextInputFocus() {
var selected = this.props.cellMetaData.selected;
var keyCode = selected.initialKeyCode;
var inputNode = this.getInputNode();
inputNode.focus();
if (inputNode.tagName === 'INPUT') {
if (!this.isKeyPrintable(keyCode)) {
inputNode.focus();
inputNode.select();
} else {
inputNode.select();
}
}
},
hasEscapeBeenPressed: function hasEscapeBeenPressed() {
var pressed = false;
var escapeKey = 27;
if (window.event) {
if (window.event.keyCode === escapeKey) {
pressed = true;
} else if (window.event.which === escapeKey) {
pressed = true;
}
}
return pressed;
},
renderStatusIcon: function renderStatusIcon() {
if (this.state.isInvalid === true) {
return React.createElement('span', { className: 'glyphicon glyphicon-remove form-control-feedback' });
}
},
render: function render() {
return React.createElement(
'div',
{ className: this.getContainerClass(), onBlur: this.handleBlur, onKeyDown: this.onKeyDown },
this.createEditor(),
this.renderStatusIcon()
);
}
});
module.exports = EditorContainer;
/***/ },
/* 67 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
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 React = __webpack_require__(1);
var EditorBase = __webpack_require__(65);
var SimpleTextEditor = function (_EditorBase) {
_inherits(SimpleTextEditor, _EditorBase);
function SimpleTextEditor() {
_classCallCheck(this, SimpleTextEditor);
return _possibleConstructorReturn(this, _EditorBase.apply(this, arguments));
}
SimpleTextEditor.prototype.render = function render() {
return React.createElement('input', { ref: 'input', type: 'text', onBlur: this.props.onBlur, className: 'form-control', defaultValue: this.props.value });
};
return SimpleTextEditor;
}(EditorBase);
module.exports = SimpleTextEditor;
/***/ },
/* 68 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var SimpleCellFormatter = React.createClass({
displayName: 'SimpleCellFormatter',
propTypes: {
value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps) {
return nextProps.value !== this.props.value;
},
render: function render() {
return React.createElement(
'div',
{ title: this.props.value },
this.props.value
);
}
});
module.exports = SimpleCellFormatter;
/***/ },
/* 69 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(1);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(2);
var _reactDom2 = _interopRequireDefault(_reactDom);
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; } /* eslint-disable react/prop-types */
var focusableComponentWrapper = function focusableComponentWrapper(WrappedComponent) {
return function (_Component) {
_inherits(ComponentWrapper, _Component);
function ComponentWrapper() {
_classCallCheck(this, ComponentWrapper);
var _this = _possibleConstructorReturn(this, _Component.call(this));
_this.checkFocus = _this.checkFocus.bind(_this);
return _this;
}
ComponentWrapper.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
return WrappedComponent.isSelected(this.props) !== WrappedComponent.isSelected(nextProps);
};
ComponentWrapper.prototype.componentDidMount = function componentDidMount() {
this.checkFocus();
};
ComponentWrapper.prototype.componentDidUpdate = function componentDidUpdate() {
this.checkFocus();
};
ComponentWrapper.prototype.checkFocus = function checkFocus() {
if (WrappedComponent.isSelected(this.props) && WrappedComponent.isScrolling(this.props)) {
this.focus();
}
};
ComponentWrapper.prototype.focus = function focus() {
_reactDom2['default'].findDOMNode(this).focus();
};
ComponentWrapper.prototype.render = function render() {
return _react2['default'].createElement(WrappedComponent, _extends({}, this.props, this.state));
};
return ComponentWrapper;
}(_react.Component);
};
exports['default'] = focusableComponentWrapper;
/***/ },
/* 70 */
/***/ function(module, exports) {
'use strict';
module.exports = function isColumnsImmutable(columns) {
return typeof Immutable !== 'undefined' && columns instanceof Immutable.List;
};
/***/ },
/* 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 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 (false) {
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;
/***/ },
/* 72 */
/***/ 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 keyMirror
* @typechecks static-only
*/
'use strict';
var invariant = __webpack_require__(71);
/**
* 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)) ? false ? 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;
/***/ },
/* 73 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(7),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView');
module.exports = DataView;
/***/ },
/* 74 */
/***/ function(module, exports, __webpack_require__) {
var hashClear = __webpack_require__(98),
hashDelete = __webpack_require__(99),
hashGet = __webpack_require__(100),
hashHas = __webpack_require__(101),
hashSet = __webpack_require__(102);
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
module.exports = Hash;
/***/ },
/* 75 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(7),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var Promise = getNative(root, 'Promise');
module.exports = Promise;
/***/ },
/* 76 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(7),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var Set = getNative(root, 'Set');
module.exports = Set;
/***/ },
/* 77 */
/***/ function(module, exports, __webpack_require__) {
var MapCache = __webpack_require__(29),
setCacheAdd = __webpack_require__(122),
setCacheHas = __webpack_require__(123);
/**
*
* Creates an array cache object to store unique values.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function SetCache(values) {
var index = -1,
length = values == null ? 0 : values.length;
this.__data__ = new MapCache;
while (++index < length) {
this.add(values[index]);
}
}
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;
module.exports = SetCache;
/***/ },
/* 78 */
/***/ function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(11),
stackClear = __webpack_require__(125),
stackDelete = __webpack_require__(126),
stackGet = __webpack_require__(127),
stackHas = __webpack_require__(128),
stackSet = __webpack_require__(129);
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
var data = this.__data__ = new ListCache(entries);
this.size = data.size;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
module.exports = Stack;
/***/ },
/* 79 */
/***/ function(module, exports, __webpack_require__) {
var root = __webpack_require__(3);
/** Built-in value references. */
var Uint8Array = root.Uint8Array;
module.exports = Uint8Array;
/***/ },
/* 80 */
/***/ function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(7),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var WeakMap = getNative(root, 'WeakMap');
module.exports = WeakMap;
/***/ },
/* 81 */
/***/ function(module, exports, __webpack_require__) {
var baseTimes = __webpack_require__(89),
isArguments = __webpack_require__(130),
isArray = __webpack_require__(34),
isBuffer = __webpack_require__(35),
isIndex = __webpack_require__(103),
isTypedArray = __webpack_require__(38);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray(value),
isArg = !isArr && isArguments(value),
isBuff = !isArr && !isArg && isBuffer(value),
isType = !isArr && !isArg && !isBuff && isTypedArray(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
module.exports = arrayLikeKeys;
/***/ },
/* 82 */
/***/ function(module, exports) {
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
module.exports = arraySome;
/***/ },
/* 83 */
/***/ function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(13),
isObjectLike = __webpack_require__(16);
/** `Object#toString` result references. */
var argsTag = '[object Arguments]';
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments(value) {
return isObjectLike(value) && baseGetTag(value) == argsTag;
}
module.exports = baseIsArguments;
/***/ },
/* 84 */
/***/ function(module, exports, __webpack_require__) {
var baseIsEqualDeep = __webpack_require__(85),
isObject = __webpack_require__(23),
isObjectLike = __webpack_require__(16);
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {boolean} bitmask The bitmask flags.
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Function} [customizer] The function to customize comparisons.
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}
module.exports = baseIsEqual;
/***/ },
/* 85 */
/***/ function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(78),
equalArrays = __webpack_require__(30),
equalByTag = __webpack_require__(93),
equalObjects = __webpack_require__(94),
getTag = __webpack_require__(96),
isArray = __webpack_require__(34),
isBuffer = __webpack_require__(35),
isTypedArray = __webpack_require__(38);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
objectTag = '[object Object]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = arrayTag,
othTag = arrayTag;
if (!objIsArr) {
objTag = getTag(object);
objTag = objTag == argsTag ? objectTag : objTag;
}
if (!othIsArr) {
othTag = getTag(other);
othTag = othTag == argsTag ? objectTag : othTag;
}
var objIsObj = objTag == objectTag,
othIsObj = othTag == objectTag,
isSameTag = objTag == othTag;
if (isSameTag && isBuffer(object)) {
if (!isBuffer(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack);
return (objIsArr || isTypedArray(object))
? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
: equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack);
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack);
return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
module.exports = baseIsEqualDeep;
/***/ },
/* 86 */
/***/ function(module, exports, __webpack_require__) {
var isFunction = __webpack_require__(36),
isMasked = __webpack_require__(105),
isObject = __webpack_require__(23),
toSource = __webpack_require__(32);
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for built-in method references. */
var funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
module.exports = baseIsNative;
/***/ },
/* 87 */
/***/ function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(13),
isLength = __webpack_require__(37),
isObjectLike = __webpack_require__(16);
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}
module.exports = baseIsTypedArray;
/***/ },
/* 88 */
/***/ function(module, exports, __webpack_require__) {
var isPrototype = __webpack_require__(106),
nativeKeys = __webpack_require__(118);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
module.exports = baseKeys;
/***/ },
/* 89 */
/***/ function(module, exports) {
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
module.exports = baseTimes;
/***/ },
/* 90 */
/***/ function(module, exports) {
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/
function baseUnary(func) {
return function(value) {
return func(value);
};
}
module.exports = baseUnary;
/***/ },
/* 91 */
/***/ function(module, exports) {
/**
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function cacheHas(cache, key) {
return cache.has(key);
}
module.exports = cacheHas;
/***/ },
/* 92 */
/***/ function(module, exports, __webpack_require__) {
var root = __webpack_require__(3);
/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];
module.exports = coreJsData;
/***/ },
/* 93 */
/***/ function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(22),
Uint8Array = __webpack_require__(79),
eq = __webpack_require__(33),
equalArrays = __webpack_require__(30),
mapToArray = __webpack_require__(117),
setToArray = __webpack_require__(124);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
mapTag = '[object Map]',
numberTag = '[object Number]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]';
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case dataViewTag:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new Uint8Array(object), new Uint8Array(other))) {
return false;
}
return true;
case boolTag:
case dateTag:
case numberTag:
// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq(+object, +other);
case errorTag:
return object.name == other.name && object.message == other.message;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
convert || (convert = setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= COMPARE_UNORDERED_FLAG;
// Recursively compare objects (susceptible to call stack limits).
stack.set(object, other);
var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
stack['delete'](object);
return result;
case symbolTag:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
module.exports = equalByTag;
/***/ },
/* 94 */
/***/ function(module, exports, __webpack_require__) {
var keys = __webpack_require__(133);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
objProps = keys(object),
objLength = objProps.length,
othProps = keys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
return false;
}
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked && stack.get(other)) {
return stacked == other;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
stack['delete'](other);
return result;
}
module.exports = equalObjects;
/***/ },
/* 95 */
/***/ function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(22);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
module.exports = getRawTag;
/***/ },
/* 96 */
/***/ function(module, exports, __webpack_require__) {
var DataView = __webpack_require__(73),
Map = __webpack_require__(21),
Promise = __webpack_require__(75),
Set = __webpack_require__(76),
WeakMap = __webpack_require__(80),
baseGetTag = __webpack_require__(13),
toSource = __webpack_require__(32);
/** `Object#toString` result references. */
var mapTag = '[object Map]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
setTag = '[object Set]',
weakMapTag = '[object WeakMap]';
var dataViewTag = '[object DataView]';
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
(Map && getTag(new Map) != mapTag) ||
(Promise && getTag(Promise.resolve()) != promiseTag) ||
(Set && getTag(new Set) != setTag) ||
(WeakMap && getTag(new WeakMap) != weakMapTag)) {
getTag = function(value) {
var result = baseGetTag(value),
Ctor = result == objectTag ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : '';
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag;
case mapCtorString: return mapTag;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag;
case weakMapCtorString: return weakMapTag;
}
}
return result;
};
}
module.exports = getTag;
/***/ },
/* 97 */
/***/ function(module, exports) {
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
module.exports = getValue;
/***/ },
/* 98 */
/***/ function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(15);
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
this.size = 0;
}
module.exports = hashClear;
/***/ },
/* 99 */
/***/ function(module, exports) {
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
module.exports = hashDelete;
/***/ },
/* 100 */
/***/ function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(15);
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(data, key) ? data[key] : undefined;
}
module.exports = hashGet;
/***/ },
/* 101 */
/***/ function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(15);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
}
module.exports = hashHas;
/***/ },
/* 102 */
/***/ function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(15);
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
return this;
}
module.exports = hashSet;
/***/ },
/* 103 */
/***/ function(module, exports) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(typeof value == 'number' || reIsUint.test(value)) &&
(value > -1 && value % 1 == 0 && value < length);
}
module.exports = isIndex;
/***/ },
/* 104 */
/***/ function(module, exports) {
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
module.exports = isKeyable;
/***/ },
/* 105 */
/***/ function(module, exports, __webpack_require__) {
var coreJsData = __webpack_require__(92);
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
module.exports = isMasked;
/***/ },
/* 106 */
/***/ function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
module.exports = isPrototype;
/***/ },
/* 107 */
/***/ function(module, exports) {
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
module.exports = listCacheClear;
/***/ },
/* 108 */
/***/ function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(12);
/** Used for built-in method references. */
var arrayProto = Array.prototype;
/** Built-in value references. */
var splice = arrayProto.splice;
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
module.exports = listCacheDelete;
/***/ },
/* 109 */
/***/ function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(12);
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
module.exports = listCacheGet;
/***/ },
/* 110 */
/***/ function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(12);
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return assocIndexOf(this.__data__, key) > -1;
}
module.exports = listCacheHas;
/***/ },
/* 111 */
/***/ function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(12);
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
module.exports = listCacheSet;
/***/ },
/* 112 */
/***/ function(module, exports, __webpack_require__) {
var Hash = __webpack_require__(74),
ListCache = __webpack_require__(11),
Map = __webpack_require__(21);
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.size = 0;
this.__data__ = {
'hash': new Hash,
'map': new (Map || ListCache),
'string': new Hash
};
}
module.exports = mapCacheClear;
/***/ },
/* 113 */
/***/ function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(14);
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
var result = getMapData(this, key)['delete'](key);
this.size -= result ? 1 : 0;
return result;
}
module.exports = mapCacheDelete;
/***/ },
/* 114 */
/***/ function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(14);
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return getMapData(this, key).get(key);
}
module.exports = mapCacheGet;
/***/ },
/* 115 */
/***/ function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(14);
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return getMapData(this, key).has(key);
}
module.exports = mapCacheHas;
/***/ },
/* 116 */
/***/ function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(14);
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
var data = getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
module.exports = mapCacheSet;
/***/ },
/* 117 */
/***/ function(module, exports) {
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
module.exports = mapToArray;
/***/ },
/* 118 */
/***/ function(module, exports, __webpack_require__) {
var overArg = __webpack_require__(121);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object);
module.exports = nativeKeys;
/***/ },
/* 119 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(31);
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}());
module.exports = nodeUtil;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(40)(module)))
/***/ },
/* 120 */
/***/ function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString.call(value);
}
module.exports = objectToString;
/***/ },
/* 121 */
/***/ function(module, exports) {
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
module.exports = overArg;
/***/ },
/* 122 */
/***/ function(module, exports) {
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
*/
function setCacheAdd(value) {
this.__data__.set(value, HASH_UNDEFINED);
return this;
}
module.exports = setCacheAdd;
/***/ },
/* 123 */
/***/ function(module, exports) {
/**
* Checks if `value` is in the array cache.
*
* @private
* @name has
* @memberOf SetCache
* @param {*} value The value to search for.
* @returns {number} Returns `true` if `value` is found, else `false`.
*/
function setCacheHas(value) {
return this.__data__.has(value);
}
module.exports = setCacheHas;
/***/ },
/* 124 */
/***/ function(module, exports) {
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
module.exports = setToArray;
/***/ },
/* 125 */
/***/ function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(11);
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache;
this.size = 0;
}
module.exports = stackClear;
/***/ },
/* 126 */
/***/ function(module, exports) {
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
result = data['delete'](key);
this.size = data.size;
return result;
}
module.exports = stackDelete;
/***/ },
/* 127 */
/***/ function(module, exports) {
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
module.exports = stackGet;
/***/ },
/* 128 */
/***/ function(module, exports) {
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
module.exports = stackHas;
/***/ },
/* 129 */
/***/ function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(11),
Map = __webpack_require__(21),
MapCache = __webpack_require__(29);
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache) {
var pairs = data.__data__;
if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new MapCache(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
module.exports = stackSet;
/***/ },
/* 130 */
/***/ function(module, exports, __webpack_require__) {
var baseIsArguments = __webpack_require__(83),
isObjectLike = __webpack_require__(16);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
!propertyIsEnumerable.call(value, 'callee');
};
module.exports = isArguments;
/***/ },
/* 131 */
/***/ function(module, exports, __webpack_require__) {
var isFunction = __webpack_require__(36),
isLength = __webpack_require__(37);
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
module.exports = isArrayLike;
/***/ },
/* 132 */
/***/ function(module, exports, __webpack_require__) {
var baseIsEqual = __webpack_require__(84);
/**
* Performs a deep comparison between two values to determine if they are
* equivalent.
*
* **Note:** This method supports comparing arrays, array buffers, booleans,
* date objects, error objects, maps, numbers, `Object` objects, regexes,
* sets, strings, symbols, and typed arrays. `Object` objects are compared
* by their own, not inherited, enumerable properties. Functions and DOM
* nodes are **not** supported.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.isEqual(object, other);
* // => true
*
* object === other;
* // => false
*/
function isEqual(value, other) {
return baseIsEqual(value, other);
}
module.exports = isEqual;
/***/ },
/* 133 */
/***/ function(module, exports, __webpack_require__) {
var arrayLikeKeys = __webpack_require__(81),
baseKeys = __webpack_require__(88),
isArrayLike = __webpack_require__(131);
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
module.exports = keys;
/***/ },
/* 134 */
/***/ function(module, exports) {
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
module.exports = stubFalse;
/***/ },
/* 135 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(136);
/***/ },
/* 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 shallowCompare
*/
'use strict';
var shallowEqual = __webpack_require__(20);
/**
* Does a shallow comparison for props and state.
* See ReactComponentWithPureRenderMixin
*/
function shallowCompare(instance, nextProps, nextState) {
return !shallowEqual(instance.props, nextProps) || !shallowEqual(instance.state, nextState);
}
module.exports = shallowCompare;
/***/ }
/******/ ])
});
; |
app/javascript/mastodon/features/follow_recommendations/components/account.js | glitch-soc/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { connect } from 'react-redux';
import { makeGetAccount } from 'mastodon/selectors';
import Avatar from 'mastodon/components/avatar';
import DisplayName from 'mastodon/components/display_name';
import Permalink from 'mastodon/components/permalink';
import IconButton from 'mastodon/components/icon_button';
import { injectIntl, defineMessages } from 'react-intl';
import { followAccount, unfollowAccount } from 'mastodon/actions/accounts';
const messages = defineMessages({
follow: { id: 'account.follow', defaultMessage: 'Follow' },
unfollow: { id: 'account.unfollow', defaultMessage: 'Unfollow' },
});
const makeMapStateToProps = () => {
const getAccount = makeGetAccount();
const mapStateToProps = (state, props) => ({
account: getAccount(state, props.id),
});
return mapStateToProps;
};
const getFirstSentence = str => {
const arr = str.split(/(([\.\?!]+\s)|[.。?!\n•])/);
return arr[0];
};
export default @connect(makeMapStateToProps)
@injectIntl
class Account extends ImmutablePureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
intl: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
};
handleFollow = () => {
const { account, dispatch } = this.props;
if (account.getIn(['relationship', 'following']) || account.getIn(['relationship', 'requested'])) {
dispatch(unfollowAccount(account.get('id')));
} else {
dispatch(followAccount(account.get('id')));
}
}
render () {
const { account, intl } = this.props;
let button;
if (account.getIn(['relationship', 'following'])) {
button = <IconButton icon='check' title={intl.formatMessage(messages.unfollow)} active onClick={this.handleFollow} />;
} else {
button = <IconButton icon='plus' title={intl.formatMessage(messages.follow)} onClick={this.handleFollow} />;
}
return (
<div className='account follow-recommendations-account'>
<div className='account__wrapper'>
<Permalink className='account__display-name account__display-name--with-note' title={account.get('acct')} href={account.get('url')} to={`/@${account.get('acct')}`}>
<div className='account__avatar-wrapper'><Avatar account={account} size={36} /></div>
<DisplayName account={account} />
<div className='account__note'>{getFirstSentence(account.get('note_plain'))}</div>
</Permalink>
<div className='account__relationship'>
{button}
</div>
</div>
</div>
);
}
}
|
src/components/SearchView/InfoView/index.js | JamesJin038801/CampID | import React, { Component } from 'react';
import I18n from 'react-native-i18n';
import { connect } from 'react-redux';
import { View, Text, TouchableOpacity, Image, Alert, ScrollView } from 'react-native';
import { Styles, Metrics, Images, Colors, Fonts } from '@theme/';
import styles from './styles';
import CommonWidgets from '@components/CommonWidgets';
import Utils from '@src/utils';
import MapView from 'react-native-maps';
class InfoView extends Component {
constructor(props) {
super(props);
this.state = {
coordinate: {
latitude: 37.78825,
longitude: -122.4324,
},
};
}
render() {
return (
<View>
{CommonWidgets.renderSpacer(18)}
<View style={styles.container} >
<TouchableOpacity>
<Image style={styles.listImg} source={Images.imgLoginLogo} />
</TouchableOpacity>
<View style={styles.rowContainer}>
<View style={styles.leftView}>
<Text style={styles.descTitle}>
{ this.props.txtTitle }
</Text>
<Text style={styles.descPeriod}>
{ this.props.txtSubTitle }
</Text>
<Text style={styles.descSubTitle}>
{ this.props.txtPeriod }
</Text>
</View>
<View style={styles.middleGap} />
<View style={styles.rightView}>
<Image style={styles.rateBar} source={Images.rateBar} >
<Text style={styles.rateText}>
{this.props.rate}
</Text>
</Image>
{CommonWidgets.renderTextButton(I18n.t('RATE_CAMP'), styles.rateCampBtn, () => Alert.alert('CAMP'))}
</View>
</View>
</View>
{CommonWidgets.renderSpacer(6, Colors.textSecondary)}
<View style={styles.container} >
<View style={styles.rowContainer}>
<View style={styles.leftView}>
<Text style={styles.stadium}>
{ this.props.txtStadium }
</Text>
<Text style={styles.university}>
{ this.props.txtUniversity }
</Text>
<Text style={styles.address}>
{ this.props.txtAddress }
</Text>
</View>
<View style={styles.middleGap} />
<View style={styles.rightView}>
<MapView
style={{ width: Metrics.rateBarWidth, height: Metrics.rateBarHeight }}
initialRegion={{
latitude: 37.78825,
longitude: -122.4324,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}>
<MapView.Marker
coordinate={this.state.coordinate}
/>
</MapView>
</View>
</View>
</View>
{CommonWidgets.renderSpacer(2, Colors.textSecondary)}
<View style={styles.container} >
<View style={styles.rowContainer}>
<View style={[...styles.leftView, { flex: 1, flexDirection: 'row', alignItems: 'center' }]}>
<View style={styles.priceView}>
<Text style={styles.descPrice}>
{ this.props.txtPrice }
</Text>
</View>
<View style={styles.middleTextView}>
<Text style={[styles.university, { marginLeft: 20 }]}>
{ I18n.t('NOT_REGISTERED_FOR_THIS_CAMP') }
</Text>
</View>
</View>
<View style={styles.middleGap} />
<View style={styles.rightView}>
{CommonWidgets.renderMaterialButton(I18n.t('REGISTER'), Colors.brandPrimary, () => Alert.alert('ss'), Metrics.rateBarWidth)}
</View>
</View>
</View>
{CommonWidgets.renderSpacer(6, Colors.textSecondary)}
</View>
);
}
}
InfoView.propTypes = {
txtTitle: React.PropTypes.string.isRequired,
txtSubTitle: React.PropTypes.string.isRequired,
txtPeriod: React.PropTypes.string.isRequired,
txtSchool: React.PropTypes.string.isRequired,
txtPrice: React.PropTypes.string.isRequired,
};
InfoView.defaultProps = {
txtTitle: "Women's Basketball",
txtSubTitle: 'All American Skills Development',
txtPeriod: 'June 21-27th 2017',
txtSchool: 'University of Connecticut - Storrs, CT',
txtPrice: '$199',
rate: '9.0',
txtStadium: 'Gampel Pavilion',
txtUniversity: 'University of Connecticut',
txtAddress: '2098 Hillside Rd, SSS, SSS 08232',
};
function mapStateToProps(state) {
const globals = state.get('globals');
return { globals };
}
export default connect(mapStateToProps, null)(InfoView);
|
Select/Select.spec.js | mmellado/airtame-gooey-react | import React from 'react';
import { render, shallow, mount } from 'enzyme';
import { spy } from 'sinon';
import Select from './Select';
const options = [
{
id: 'articuno',
label: 'Articuno',
value: 'Articuno',
},
{
id: 'zapdos',
label: 'El Zapdos',
value: 'Zapdos',
},
{
id: 'moltres',
label: 'Moltres',
value: 'Moltres',
isDisabled: true,
},
];
describe('<Select />', () => {
it('should render the select field', () => {
const wrapper = shallow(<Select options={options} />);
expect(wrapper).toHaveTagName('div');
});
it('should create a disabled select if requested', () => {
const wrapper = render(<Select options={options} isDisabled />);
expect(wrapper.find('select')[0].attribs.disabled).toEqual('');
});
it('should add an error className if is error', () => {
const wrapper = shallow(<Select options={options} isError />);
expect(wrapper.find('.gooey-select--error')).toHaveLength(1);
});
it('should mark the requested value as selected', () => {
const wrapper = shallow(<Select options={options} selected="zapdos" />);
expect(wrapper.state('selected')).toEqual('Zapdos');
});
it('should set a requested option as disabled', () => {
const wrapper = render(<Select options={options} />);
expect(wrapper.find('option')[2].attribs.disabled).toEqual('');
});
it('should set the first value as selected when no selected is specified', () => {
const wrapper = shallow(<Select options={options} />);
expect(wrapper.state('selected')).toEqual('Articuno');
});
it('should update the state when the select value changes', () => {
const o = options.slice(0);
delete o[2].isDisabled;
const wrapper = mount(<Select options={o} />);
wrapper.find('select').simulate('change', {
target: { value: 'Moltres' },
persist: () => {},
});
expect(wrapper.state('selected')).toEqual('Moltres');
});
it('should trigger a callback function when a callback is available', () => {
const onChangeCall = spy();
const wrapper = mount(<Select options={options} onChange={onChangeCall} />);
expect(onChangeCall).toHaveProperty('callCount', 0);
wrapper.find('select').simulate('change', {
target: { value: 'moltres' },
persist: () => {},
});
expect(onChangeCall).toHaveProperty('callCount', 1);
});
it('should properly create the ref for the select element', () => {
const wrapper = mount(<Select options={options} selectRef="selectEl" />);
expect(wrapper.ref('selectEl').tagName).toEqual('SELECT');
});
it('should propagate additional valid props to the select element', () => {
const focusCallback = spy();
const wrapper = shallow(<Select options={options} onFocus={focusCallback} />);
wrapper.find('select').simulate('focus');
expect(focusCallback).toHaveProperty('callCount', 1);
});
it('should set the proper state if the selected prop is updated', () => {
const wrapper = shallow(<Select options={options} selected="zapdos" />);
expect(wrapper.state('selected')).toEqual('Zapdos');
wrapper.setProps({ selected: 'articuno' });
expect(wrapper.state('selected')).toEqual('Articuno');
});
it('should set the proper state if the options prop is updated', () => {
const newOptions = [{ id: 'a', label: 'a', value: 'a' }, { id: 'b', label: 'b', value: 'b' }];
const wrapper = shallow(<Select options={options} />);
expect(wrapper.state('selected')).toEqual('Articuno');
wrapper.setProps({ options: newOptions });
expect(wrapper.state('selected')).toEqual('a');
});
it('should not touch the state if invalid props change', () => {
const stateSpy = spy(Select.prototype, 'setState');
const wrapper = shallow(<Select options={options} selected="zapdos" />);
expect(stateSpy.callCount).toEqual(0);
wrapper.setProps({ isError: true });
expect(stateSpy.callCount).toEqual(0);
});
it('should not touch the state if the options prop doesnt change', () => {
const newOptions = [
{
id: 'articuno',
label: 'Articuno',
value: 'Articuno',
},
{
id: 'zapdos',
label: 'El Zapdos',
value: 'Zapdos',
},
{
id: 'moltres',
label: 'Moltres',
value: 'Moltres',
isDisabled: true,
},
];
const wrapper = shallow(<Select options={options} selected="zapdos" />);
expect(wrapper.state('selected')).toEqual('Zapdos');
wrapper.setProps({ options: newOptions });
expect(wrapper.state('selected')).toEqual('Zapdos');
});
});
|
test/helpers/shallowRenderHelper.js | PaoCYB/two-by-react | /**
* Function to get the shallow output for a given component
* As we are using phantom.js, we also need to include the fn.proto.bind shim!
*
* @see http://simonsmith.io/unit-testing-react-components-without-a-dom/
* @author somonsmith
*/
import React from 'react';
import TestUtils from 'react-addons-test-utils';
/**
* Get the shallow rendered component
*
* @param {Object} component The component to return the output for
* @param {Object} props [optional] The components properties
* @param {Mixed} ...children [optional] List of children
* @return {Object} Shallow rendered output
*/
export default function createComponent(component, props = {}, ...children) {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0]));
return shallowRenderer.getRenderOutput();
}
|
index.ios.js | DrPandemic/TwiolioRN | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class TwilioRN 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('TwilioRN', () => TwilioRN);
|
src/svg-icons/maps/local-shipping.js | andrejunges/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalShipping = (props) => (
<SvgIcon {...props}>
<path d="M20 8h-3V4H3c-1.1 0-2 .9-2 2v11h2c0 1.66 1.34 3 3 3s3-1.34 3-3h6c0 1.66 1.34 3 3 3s3-1.34 3-3h2v-5l-3-4zM6 18.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm13.5-9l1.96 2.5H17V9.5h2.5zm-1.5 9c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/>
</SvgIcon>
);
MapsLocalShipping = pure(MapsLocalShipping);
MapsLocalShipping.displayName = 'MapsLocalShipping';
MapsLocalShipping.muiName = 'SvgIcon';
export default MapsLocalShipping;
|
files/wordpress/3.3/js/jquery/jquery.js | iMega/jsdelivr | /*! jQuery v1.7.1 jquery.com | jquery.org/license */
(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cv(a){if(!ck[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cl||(cl=c.createElement("iframe"),cl.frameBorder=cl.width=cl.height=0),b.appendChild(cl);if(!cm||!cl.createElement)cm=(cl.contentWindow||cl.contentDocument).document,cm.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),cm.close();d=cm.createElement(a),cm.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cl)}ck[a]=e}return ck[a]}function cu(a,b){var c={};f.each(cq.concat.apply([],cq.slice(0,b)),function(){c[this]=a});return c}function ct(){cr=b}function cs(){setTimeout(ct,0);return cr=f.now()}function cj(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ci(){try{return new a.XMLHttpRequest}catch(b){}}function cc(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function cb(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 ca(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bE.test(a)?d(a,e):ca(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)ca(a+"["+e+"]",b[e],c,d);else d(a,b)}function b_(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function b$(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===bT,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=b$(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=b$(a,c,d,e,"*",g));return l}function bZ(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bP),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bC(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bx:by,g=0,h=e.length;if(d>0){if(c!=="border")for(;g<h;g++)c||(d-=parseFloat(f.css(a,"padding"+e[g]))||0),c==="margin"?d+=parseFloat(f.css(a,c+e[g]))||0:d-=parseFloat(f.css(a,"border"+e[g]+"Width"))||0;return d+"px"}d=bz(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0;if(c)for(;g<h;g++)d+=parseFloat(f.css(a,"padding"+e[g]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+e[g]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+e[g]))||0);return d+"px"}function bp(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();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(f.expando)}}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c+(i[c][d].namespace?".":"")+i[c][d].namespace,i[c][d],i[c][d].data)}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.1",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)e.access(a,j,c[j],f,g,d);return a}if(d!==b){f=!h&&f&&e.isFunction(d);for(var k=0;k<i;k++)g(a[k],c,f?d.call(a[k],k,g(a[k],c)):d,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?m(g):h==="function"&&(!a.unique||!o.has(g))&&c.push(g)},n=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,l=j||0,j=0,k=c.length;for(;c&&l<k;l++)if(c[l].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}i=!1,c&&(a.once?e===!0?o.disable():c=[]:d&&d.length&&(e=d.shift(),o.fireWith(e[0],e[1])))},o={add:function(){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){i&&f<=k&&(k--,f<=l&&l--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&o.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(i?a.once||d.push([b,c]):(!a.once||!e)&&n(b,c));return this},fire:function(){o.fireWith(this,arguments);return this},fired:function(){return!!e}};return o};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p,q=c.createElement("div"),r=c.documentElement;q.setAttribute("className","t"),q.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=q.getElementsByTagName("*"),e=q.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=q.getElementsByTagName("input")[0],b={leadingWhitespace:q.firstChild.nodeType===3,tbody:!q.getElementsByTagName("tbody").length,htmlSerialize:!!q.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:q.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete q.test}catch(s){b.deleteExpando=!1}!q.addEventListener&&q.attachEvent&&q.fireEvent&&(q.attachEvent("onclick",function(){b.noCloneEvent=!1}),q.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),q.appendChild(i),k=c.createDocumentFragment(),k.appendChild(q.lastChild),b.checkClone=k.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,k.removeChild(i),k.appendChild(q),q.innerHTML="",a.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",q.style.width="2px",q.appendChild(j),b.reliableMarginRight=(parseInt((a.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(q.attachEvent)for(o in{submit:1,change:1,focusin:1})n="on"+o,p=n in q,p||(q.setAttribute(n,"return;"),p=typeof q[n]=="function"),b[o+"Bubbles"]=p;k.removeChild(q),k=g=h=j=q=i=null,f(function(){var a,d,e,g,h,i,j,k,m,n,o,r=c.getElementsByTagName("body")[0];!r||(j=1,k="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",m="visibility:hidden;border:0;",n="style='"+k+"border:5px solid #000;padding:0;'",o="<div "+n+"><div></div></div>"+"<table "+n+" cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",a=c.createElement("div"),a.style.cssText=m+"width:0;height:0;position:static;top:0;margin-top:"+j+"px",r.insertBefore(a,r.firstChild),q=c.createElement("div"),a.appendChild(q),q.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",l=q.getElementsByTagName("td"),p=l[0].offsetHeight===0,l[0].style.display="",l[1].style.display="none",b.reliableHiddenOffsets=p&&l[0].offsetHeight===0,q.innerHTML="",q.style.width=q.style.paddingLeft="1px",f.boxModel=b.boxModel=q.offsetWidth===2,typeof q.style.zoom!="undefined"&&(q.style.display="inline",q.style.zoom=1,b.inlineBlockNeedsLayout=q.offsetWidth===2,q.style.display="",q.innerHTML="<div style='width:4px;'></div>",b.shrinkWrapBlocks=q.offsetWidth!==2),q.style.cssText=k+m,q.innerHTML=o,d=q.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,i={doesNotAddBorder:e.offsetTop!==5,doesAddBorderForTableAndCells:h.offsetTop===5},e.style.position="fixed",e.style.top="20px",i.fixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",i.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,i.doesNotIncludeMarginInBodyOffset=r.offsetTop!==j,r.removeChild(a),q=a=null,f.extend(b,i))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h=null;if(typeof a=="undefined"){if(this.length){h=f.data(this[0]);if(this[0].nodeType===1&&!f._data(this[0],"parsedAttrs")){e=this[0].attributes;for(var i=0,j=e.length;i<j;i++)g=e[i].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),l(this[0],g,h[g]));f._data(this[0],"parsedAttrs",!0)}}return h}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split("."),d[1]=d[1]?"."+d[1]:"";if(c===b){h=this.triggerHandler("getData"+d[1]+"!",[d[0]]),h===b&&this.length&&(h=f.data(this[0],a),h=l(this[0],a,h));return h===b&&d[1]?this.data(d[0]):h}return this.each(function(){var b=f(this),e=[d[0],c];b.triggerHandler("setData"+d[1]+"!",e),f.data(this,a,c),b.triggerHandler("changeData"+d[1]+"!",e)})},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){typeof a!="string"&&(c=a,a="fx");if(c===b)return f.queue(this[0],a);return this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise()}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,a,b,!0,f.attr)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,a,b,!0,f.prop)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;h<g;h++)e=d[h],e&&(c=f.propFix[e]||e,f.attr(a,e,""),a.removeAttribute(v?e:c),u.test(e)&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]}},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/\bhover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function(a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};
f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=[],j,k,l,m,n,o,p,q,r,s,t;g[0]=c,c.delegateTarget=this;if(e&&!c.target.disabled&&(!c.button||c.type!=="click")){m=f(this),m.context=this.ownerDocument||this;for(l=c.target;l!=this;l=l.parentNode||this){o={},q=[],m[0]=l;for(j=0;j<e;j++)r=d[j],s=r.selector,o[s]===b&&(o[s]=r.quick?H(l,r.quick):m.is(s)),o[s]&&q.push(r);q.length&&i.push({elem:l,matches:q})}}d.length>e&&i.push({elem:this,matches:d.slice(e)});for(j=0;j<i.length&&!c.isPropagationStopped();j++){p=i[j],c.currentTarget=p.elem;for(k=0;k<p.matches.length&&!c.isImmediatePropagationStopped();k++){r=p.matches[k];if(h||!c.namespace&&!r.namespace||c.namespace_re&&c.namespace_re.test(r.namespace))c.data=r.data,c.handleObj=r,n=((f.event.special[r.origType]||{}).handle||r.handler).apply(p.elem,g),n!==b&&(c.result=n,n===!1&&(c.preventDefault(),c.stopPropagation()))}}return c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0)}),d._submit_attached=!0)})},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on.call(this,a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.type+"."+e.namespace:e.type,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.POS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(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 f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function()
{for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(var c=0,d=this.length;c<d;c++)this[c].nodeType===1&&(f.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(e){this.empty().append(a)}}else f.isFunction(a)?this.each(function(b){var c=f(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,bp)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||!bc.test("<"+a.nodeName)?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!_.test(k))k=b.createTextNode(k);else{k=k.replace(Y,"<$1></$2>");var l=(Z.exec(k)||["",""])[1].toLowerCase(),m=bg[l]||bg._default,n=m[0],o=b.createElement("div");b===c?bh.appendChild(o):U(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=$.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]==="<table>"&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&X.test(k)&&o.insertBefore(b.createTextNode(X.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i<r;i++)bn(k[i]);else bn(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||be.test(a.type)};for(j=0;h[j];j++)if(e&&f.nodeName(h[j],"script")&&(!h[j].type||h[j].type.toLowerCase()==="text/javascript"))e.push(h[j].parentNode?h[j].parentNode.removeChild(h[j]):h[j]);else{if(h[j].nodeType===1){var s=f.grep(h[j].getElementsByTagName("script"),g);h.splice.apply(h,[j+1,0].concat(s))}d.appendChild(h[j])}}return h},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bq=/alpha\([^)]*\)/i,br=/opacity=([^)]*)/,bs=/([A-Z]|^ms)/g,bt=/^-?\d+(?:px)?$/i,bu=/^-?\d/,bv=/^([\-+])=([\-+.\de]+)/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Left","Right"],by=["Top","Bottom"],bz,bA,bB;f.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return f.access(this,a,c,!0,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)})},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bz(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bv.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(bz)return bz(a,c)},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]}}),f.curCSS=f.css,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){var e;if(c){if(a.offsetWidth!==0)return bC(a,b,d);f.swap(a,bw,function(){e=bC(a,b,d)});return e}},set:function(a,b){if(!bt.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return br.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bq,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bq.test(g)?g.replace(bq,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bz(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bA=function(a,b){var c,d,e;b=b.replace(bs,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b)));return c}),c.documentElement.currentStyle&&(bB=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bt.test(f)&&bu.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bz=bA||bB,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bD=/%20/g,bE=/\[\]$/,bF=/\r?\n/g,bG=/#.*$/,bH=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bI=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bJ=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bK=/^(?:GET|HEAD)$/,bL=/^\/\//,bM=/\?/,bN=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bO=/^(?:select|textarea)/i,bP=/\s+/,bQ=/([?&])_=[^&]*/,bR=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bS=f.fn.load,bT={},bU={},bV,bW,bX=["*/"]+["*"];try{bV=e.href}catch(bY){bV=c.createElement("a"),bV.href="",bV=bV.href}bW=bR.exec(bV.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bS)return bS.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bN,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bO.test(this.nodeName)||bI.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bF,"\r\n")}}):{name:b.name,value:c.replace(bF,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b_(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b_(a,b);return a},ajaxSettings:{url:bV,isLocal:bJ.test(bW[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","*":bX},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bZ(bT),ajaxTransport:bZ(bU),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cb(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cc(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bH.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bG,"").replace(bL,bW[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bP),d.crossDomain==null&&(r=bR.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bW[1]&&r[2]==bW[2]&&(r[3]||(r[1]==="http:"?80:443))==(bW[3]||(bW[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),b$(bT,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bK.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bM.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bQ,"$1_="+x);d.url=y+(y===d.url?(bM.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bX+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=b$(bU,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)ca(g,a[g],c,e);return d.join("&").replace(bD,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cd=f.now(),ce=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cd++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(ce.test(b.url)||e&&ce.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(ce,l),b.url===j&&(e&&(k=k.replace(ce,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var cf=a.ActiveXObject?function(){for(var a in ch)ch[a](0,1)}:!1,cg=0,ch;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ci()||cj()}:ci,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,cf&&delete ch[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cg,cf&&(ch||(ch={},f(a).unload(cf)),ch[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var ck={},cl,cm,cn=/^(?:toggle|show|hide)$/,co=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cp,cq=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cr;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cu("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),e===""&&f.css(d,"display")==="none"&&f._data(d,"olddisplay",cv(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cu("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(cu("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]),h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cv(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cn.test(h)?(o=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),o?(f._data(this,"toggle"+i,o==="show"?"hide":"show"),j[o]()):j[h]()):(k=co.exec(h),l=j.cur(),k?(m=parseFloat(k[2]),n=k[3]||(f.cssNumber[i]?"":"px"),n!=="px"&&(f.style(this,i,(m||1)+n),l=(m||1)/j.cur()*l,f.style(this,i,l+n)),k[1]&&(m=(k[1]==="-="?-1:1)*m+l),j.custom(l,m,n)):j.custom(l,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:cu("show",1),slideUp:cu("hide",1),slideToggle:cu("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a,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||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cr||cs(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){e.options.hide&&f._data(e.elem,"fxshow"+e.prop)===b&&f._data(e.elem,"fxshow"+e.prop,e.start)},h()&&f.timers.push(h)&&!cp&&(cp=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cr||cs(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(cp),cp=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(["width","height"],function(a,b){f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?f.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(d){}var e=b.ownerDocument,g=e.documentElement;if(!c||!f.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=e.body,i=cy(e),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||f.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||f.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:f.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);var c,d=b.offsetParent,e=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(f.support.fixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===d&&(l+=b.offsetTop,m+=b.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.support.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;f.support.fixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cy(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cy(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window);
jQuery.noConflict();
|
src/OptionsButton.js | APSL/react-native-options-button | /* @flow */
import React from 'react';
import PropTypes from 'prop-types';
import {
ActivityIndicator,
Animated,
Easing,
View,
Text,
StyleSheet,
Dimensions,
InteractionManager
} from 'react-native';
import OptionButton from './OptionButton';
import Button from './Button';
const ALMOST_ZERO: number = 0.00000001;
export type OptionItem = {
title: string,
id: string | number,
onPress?: Function
};
type Props = {
items: Array<OptionItem>,
title: string,
openTitle: string,
onPress: Function,
color?: string,
openedColor?: string,
isLoading?: boolean,
containerStyle?: any,
buttonStyle?: any,
buttonTextStyle?: any,
optionsStyle?: any,
optionTextStyle?: any,
separatorStyle?: any
};
type State = {
isCollapsed: boolean,
height: Animated.Value,
width: Animated.Value,
saturation: Animated.Value
};
class OptionsButton extends React.PureComponent<Props, State> {
static defaultProps = {
color: 'hsla(192, 100%, 34%, 1)',
openedColor: 'hsla(179, 0%, 65%, 1)'
};
static propTypes = {
items: PropTypes.arrayOf(
PropTypes.shape({
title: PropTypes.string.isRequired,
id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
onPress: PropTypes.func
})
).isRequired,
title: PropTypes.string.isRequired,
openTitle: PropTypes.string.isRequired,
onPress: PropTypes.func.isRequired,
color: PropTypes.string,
openedColor: PropTypes.string,
isLoading: PropTypes.bool,
containerStyle: PropTypes.any,
buttonStyle: PropTypes.any,
buttonTextStyle: PropTypes.any,
optionsStyle: PropTypes.any,
optionTextStyle: PropTypes.any,
separatorStyle: PropTypes.any
};
constructor(props: Object) {
super(props);
this.state = {
isCollapsed: true,
height: new Animated.Value(0),
width: new Animated.Value(100),
saturation: new Animated.Value(100)
};
}
_startAnimation = (index: number) => {
let height = ALMOST_ZERO;
let saturation = 100;
let width = 100;
let collapseAnimation = Animated.timing(this.state.height, {
toValue: height,
duration: 200,
easing: Easing.inOut(Easing.bezier(1.0, 0.0, 0.915, 1.065))
});
if (this.state.isCollapsed) {
height = 44 * this.props.items.length + (this.props.items.length - 1);
saturation = 0;
width = 0;
collapseAnimation = Animated.spring(this.state.height, {
toValue: height,
tension: 260,
friction: 10
});
}
Animated.parallel([
Animated.timing(this.state.saturation, {
toValue: saturation,
duration: 200
}),
Animated.timing(this.state.width, {
toValue: width,
duration: 150
}),
collapseAnimation
]).start();
this.setState({ isCollapsed: !this.state.isCollapsed });
// Pass the option selected
InteractionManager.runAfterInteractions(() => {
if (Number.isInteger(index) && this.props.onPress) {
this.props.onPress(this.props.items[index], index);
}
});
};
_renderOptions() {
return (
<Animated.View
style={[
styles.options,
this.props.optionsStyle,
{ backgroundColor: this.props.color, height: this.state.height }
]}>
{this.props.items.map(
(
item: OptionItem,
index: number,
arr: Array<OptionItem>
): OptionButton => (
<OptionButton
key={`${item.title}-${index}`}
index={index}
style={[styles.option]}
renderSeparator={index < arr.length - 1}
separatorStyle={this.props.separatorStyle}
textStyle={[styles.optionText, this.props.optionTextStyle]}
onPress={this._startAnimation}>
{item.title}
</OptionButton>
)
)}
</Animated.View>
);
}
_renderButton(color: string, width: number, text: string) {
if (this.props.isLoading) {
return (
<Animated.View
style={[
styles.button,
styles.loader,
{ backgroundColor: this.props.color },
this.props.buttonStyle
]}>
<ActivityIndicator animating={true} color="white" />
</Animated.View>
);
}
return (
<Animated.View
activeOpacity={0.9}
style={[
styles.button,
this.props.buttonStyle,
{ backgroundColor: color, borderColor: color, width: width }
]}>
<Button
style={[styles.button, this.props.buttonStyle]}
textStyle={this.props.buttonTextStyle}
onPress={this._startAnimation}>
{text}
</Button>
</Animated.View>
);
}
render() {
const color = this.state.saturation.interpolate({
inputRange: [0, 100],
outputRange: [this.props.openedColor, this.props.color]
});
const width = this.state.width.interpolate({
inputRange: [0, 100],
outputRange: [74, Dimensions.get('window').width - 50]
});
const text = this.state.isCollapsed
? this.props.title
: this.props.openTitle;
return (
<View style={[styles.container, this.props.containerStyle]}>
{this._renderOptions()}
<View style={styles.buttonContainer}>
{this._renderButton(color, width, text)}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
position: 'absolute',
left: 0,
right: 0,
bottom: 0,
marginLeft: 25,
marginRight: 25
},
buttonContainer: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center'
},
button: {
borderRadius: 10,
height: 44,
marginBottom: 10
},
options: {
overflow: 'hidden',
borderRadius: 22,
marginBottom: 5
},
option: {
overflow: 'hidden',
marginLeft: 10,
marginRight: 10
},
separator: {
borderBottomWidth: 1,
borderBottomColor: 'white'
},
optionText: {
color: 'white'
},
loader: {
width: Dimensions.get('window').width - 50,
height: 44,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
marginBottom: 10
}
});
export default OptionsButton;
|
ajax/libs/mini-meteor/1.0.0/mini-meteor.min.js | noraesae/cdnjs | (function(){var a=this,b=a._,d=Array.prototype,f=Object.prototype,l=d.push,k=d.slice,n=d.concat,p=f.toString,C=f.hasOwnProperty,f=Array.isArray,D=Object.keys,w=Function.prototype.bind,c=function(e){return e instanceof c?e:this instanceof c?void(this._wrapped=e):new c(e)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=c),exports._=c):a._=c;c.VERSION="1.7.0";var t=function(e,a,c){if(void 0===a)return e;switch(null==c?3:c){case 1:return function(c){return e.call(a,
c)};case 2:return function(c,g){return e.call(a,c,g)};case 3:return function(c,g,b){return e.call(a,c,g,b)};case 4:return function(c,g,b,d){return e.call(a,c,g,b,d)}}return function(){return e.apply(a,arguments)}};c.iteratee=function(e,a,g){return null==e?c.identity:c.isFunction(e)?t(e,a,g):c.isObject(e)?c.matches(e):c.property(e)};c.each=c.forEach=function(e,a,g){if(null==e)return e;a=t(a,g);var q=e.length;if(q===+q)for(g=0;q>g;g++)a(e[g],g,e);else{var b=c.keys(e);g=0;for(q=b.length;q>g;g++)a(e[b[g]],
b[g],e)}return e};c.map=c.collect=function(e,a,g){if(null==e)return[];a=c.iteratee(a,g);for(var q=e.length!==+e.length&&c.keys(e),b=(q||e).length,d=Array(b),m=0;b>m;m++)g=q?q[m]:m,d[m]=a(e[g],g,e);return d};c.reduce=c.foldl=c.inject=function(e,a,g,q){null==e&&(e=[]);a=t(a,q,4);var b,d=e.length!==+e.length&&c.keys(e),m=(d||e).length,f=0;if(3>arguments.length){if(!m)throw new TypeError("Reduce of empty array with no initial value");g=e[d?d[f++]:f++]}for(;m>f;f++)b=d?d[f]:f,g=a(g,e[b],b,e);return g};
c.reduceRight=c.foldr=function(e,a,g,b){null==e&&(e=[]);a=t(a,b,4);var h,d=e.length!==+e.length&&c.keys(e),f=(d||e).length;if(3>arguments.length){if(!f)throw new TypeError("Reduce of empty array with no initial value");g=e[d?d[--f]:--f]}for(;f--;)h=d?d[f]:f,g=a(g,e[h],h,e);return g};c.find=c.detect=function(e,a,g){var b;return a=c.iteratee(a,g),c.some(e,function(e,c,g){return a(e,c,g)?(b=e,!0):void 0}),b};c.filter=c.select=function(e,a,g){var b=[];return null==e?b:(a=c.iteratee(a,g),c.each(e,function(e,
c,g){a(e,c,g)&&b.push(e)}),b)};c.reject=function(e,a,g){return c.filter(e,c.negate(c.iteratee(a)),g)};c.every=c.all=function(e,a,g){if(null==e)return!0;a=c.iteratee(a,g);var b,h=e.length!==+e.length&&c.keys(e),d=(h||e).length;for(g=0;d>g;g++)if(b=h?h[g]:g,!a(e[b],b,e))return!1;return!0};c.some=c.any=function(e,a,g){if(null==e)return!1;a=c.iteratee(a,g);var b,h=e.length!==+e.length&&c.keys(e),d=(h||e).length;for(g=0;d>g;g++)if(b=h?h[g]:g,a(e[b],b,e))return!0;return!1};c.contains=c.include=function(e,
a){return null==e?!1:(e.length!==+e.length&&(e=c.values(e)),0<=c.indexOf(e,a))};c.invoke=function(e,a){var g=k.call(arguments,2),b=c.isFunction(a);return c.map(e,function(e){return(b?a:e[a]).apply(e,g)})};c.pluck=function(e,a){return c.map(e,c.property(a))};c.where=function(e,a){return c.filter(e,c.matches(a))};c.findWhere=function(e,a){return c.find(e,c.matches(a))};c.max=function(e,a,g){var b,h=-1/0,d=-1/0;if(null==a&&null!=e){e=e.length===+e.length?e:c.values(e);for(var f=0,r=e.length;r>f;f++)g=
e[f],g>h&&(h=g)}else a=c.iteratee(a,g),c.each(e,function(e,c,g){b=a(e,c,g);(b>d||b===-1/0&&h===-1/0)&&(h=e,d=b)});return h};c.min=function(e,a,g){var b,h=1/0,d=1/0;if(null==a&&null!=e){e=e.length===+e.length?e:c.values(e);for(var f=0,r=e.length;r>f;f++)g=e[f],h>g&&(h=g)}else a=c.iteratee(a,g),c.each(e,function(e,c,g){b=a(e,c,g);(d>b||1/0===b&&1/0===h)&&(h=e,d=b)});return h};c.shuffle=function(e){for(var a=e&&e.length===+e.length?e:c.values(e),g=a.length,b=Array(g),h=0;g>h;h++)e=c.random(0,h),e!==
h&&(b[h]=b[e]),b[e]=a[h];return b};c.sample=function(e,a,g){return null==a||g?(e.length!==+e.length&&(e=c.values(e)),e[c.random(e.length-1)]):c.shuffle(e).slice(0,Math.max(0,a))};c.sortBy=function(e,a,g){return a=c.iteratee(a,g),c.pluck(c.map(e,function(e,c,g){return{value:e,index:c,criteria:a(e,c,g)}}).sort(function(e,a){var c=e.criteria,g=a.criteria;if(c!==g){if(c>g||void 0===c)return 1;if(g>c||void 0===g)return-1}return e.index-a.index}),"value")};var u=function(e){return function(a,g,b){var d=
{};return g=c.iteratee(g,b),c.each(a,function(c,b){var q=g(c,b,a);e(d,c,q)}),d}};c.groupBy=u(function(e,a,g){c.has(e,g)?e[g].push(a):e[g]=[a]});c.indexBy=u(function(e,a,c){e[c]=a});c.countBy=u(function(e,a,g){c.has(e,g)?e[g]++:e[g]=1});c.sortedIndex=function(e,a,g,b){g=c.iteratee(g,b,1);a=g(a);b=0;for(var d=e.length;d>b;){var f=b+d>>>1;g(e[f])<a?b=f+1:d=f}return b};c.toArray=function(e){return e?c.isArray(e)?k.call(e):e.length===+e.length?c.map(e,c.identity):c.values(e):[]};c.size=function(e){return null==
e?0:e.length===+e.length?e.length:c.keys(e).length};c.partition=function(e,a,g){a=c.iteratee(a,g);var b=[],d=[];return c.each(e,function(e,c,g){(a(e,c,g)?b:d).push(e)}),[b,d]};c.first=c.head=c.take=function(e,a,c){return null==e?void 0:null==a||c?e[0]:0>a?[]:k.call(e,0,a)};c.initial=function(e,a,c){return k.call(e,0,Math.max(0,e.length-(null==a||c?1:a)))};c.last=function(e,a,c){return null==e?void 0:null==a||c?e[e.length-1]:k.call(e,Math.max(e.length-a,0))};c.rest=c.tail=c.drop=function(e,a,c){return k.call(e,
null==a||c?1:a)};c.compact=function(e){return c.filter(e,c.identity)};var v=function(e,a,g,b){if(a&&c.every(e,c.isArray))return n.apply(b,e);for(var d=0,f=e.length;f>d;d++){var m=e[d];c.isArray(m)||c.isArguments(m)?a?l.apply(b,m):v(m,a,g,b):g||b.push(m)}return b};c.flatten=function(e,a){return v(e,a,!1,[])};c.without=function(e){return c.difference(e,k.call(arguments,1))};c.uniq=c.unique=function(e,a,b,d){if(null==e)return[];c.isBoolean(a)||(d=b,b=a,a=!1);null!=b&&(b=c.iteratee(b,d));d=[];for(var h=
[],f=0,m=e.length;m>f;f++){var r=e[f];if(a)f&&h===r||d.push(r),h=r;else if(b){var k=b(r,f,e);0>c.indexOf(h,k)&&(h.push(k),d.push(r))}else 0>c.indexOf(d,r)&&d.push(r)}return d};c.union=function(){return c.uniq(v(arguments,!0,!0,[]))};c.intersection=function(e){if(null==e)return[];for(var a=[],b=arguments.length,d=0,h=e.length;h>d;d++){var f=e[d];if(!c.contains(a,f)){for(var m=1;b>m&&c.contains(arguments[m],f);m++);m===b&&a.push(f)}}return a};c.difference=function(e){var a=v(k.call(arguments,1),!0,
!0,[]);return c.filter(e,function(e){return!c.contains(a,e)})};c.zip=function(e){if(null==e)return[];for(var a=c.max(arguments,"length").length,b=Array(a),d=0;a>d;d++)b[d]=c.pluck(arguments,d);return b};c.object=function(a,c){if(null==a)return{};for(var b={},d=0,h=a.length;h>d;d++)c?b[a[d]]=c[d]:b[a[d][0]]=a[d][1];return b};c.indexOf=function(a,b,g){if(null==a)return-1;var d=0,h=a.length;if(g){if("number"!=typeof g)return d=c.sortedIndex(a,b),a[d]===b?d:-1;d=0>g?Math.max(0,h+g):g}for(;h>d;d++)if(a[d]===
b)return d;return-1};c.lastIndexOf=function(a,c,b){if(null==a)return-1;var d=a.length;for("number"==typeof b&&(d=0>b?d+b+1:Math.min(d,b+1));0<=--d;)if(a[d]===c)return d;return-1};c.range=function(a,c,b){1>=arguments.length&&(c=a||0,a=0);b=b||1;for(var d=Math.max(Math.ceil((c-a)/b),0),h=Array(d),f=0;d>f;f++,a+=b)h[f]=a;return h};var y=function(){};c.bind=function(a,b){var g,d;if(w&&a.bind===w)return w.apply(a,k.call(arguments,1));if(!c.isFunction(a))throw new TypeError("Bind must be called on a function");
return g=k.call(arguments,2),d=function(){if(!(this instanceof d))return a.apply(b,g.concat(k.call(arguments)));y.prototype=a.prototype;var h=new y;y.prototype=null;var f=a.apply(h,g.concat(k.call(arguments)));return c.isObject(f)?f:h}};c.partial=function(a){var b=k.call(arguments,1);return function(){for(var g=0,d=b.slice(),h=0,f=d.length;f>h;h++)d[h]===c&&(d[h]=arguments[g++]);for(;g<arguments.length;)d.push(arguments[g++]);return a.apply(this,d)}};c.bindAll=function(a){var b,g,d=arguments.length;
if(1>=d)throw Error("bindAll must be passed function names");for(b=1;d>b;b++)g=arguments[b],a[g]=c.bind(a[g],a);return a};c.memoize=function(a,b){var g=function(d){var h=g.cache,f=b?b.apply(this,arguments):d;return c.has(h,f)||(h[f]=a.apply(this,arguments)),h[f]};return g.cache={},g};c.delay=function(a,c){var b=k.call(arguments,2);return setTimeout(function(){return a.apply(null,b)},c)};c.defer=function(a){return c.delay.apply(c,[a,1].concat(k.call(arguments,1)))};c.throttle=function(a,b,d){var f,
h,x,m=null,k=0;d||(d={});var l=function(){k=!1===d.leading?0:c.now();m=null;x=a.apply(f,h);m||(f=h=null)};return function(){var p=c.now();k||!1!==d.leading||(k=p);var n=b-(p-k);return f=this,h=arguments,0>=n||n>b?(clearTimeout(m),m=null,k=p,x=a.apply(f,h),m||(f=h=null)):m||!1===d.trailing||(m=setTimeout(l,n)),x}};c.debounce=function(a,b,d){var f,h,k,m,l,p=function(){var n=c.now()-m;b>n&&0<n?f=setTimeout(p,b-n):(f=null,d||(l=a.apply(k,h),f||(k=h=null)))};return function(){k=this;h=arguments;m=c.now();
var n=d&&!f;return f||(f=setTimeout(p,b)),n&&(l=a.apply(k,h),k=h=null),l}};c.wrap=function(a,b){return c.partial(b,a)};c.negate=function(a){return function(){return!a.apply(this,arguments)}};c.compose=function(){var a=arguments,c=a.length-1;return function(){for(var b=c,d=a[c].apply(this,arguments);b--;)d=a[b].call(this,d);return d}};c.after=function(a,c){return function(){return 1>--a?c.apply(this,arguments):void 0}};c.before=function(a,c){var b;return function(){return 0<--a?b=c.apply(this,arguments):
c=null,b}};c.once=c.partial(c.before,2);c.keys=function(a){if(!c.isObject(a))return[];if(D)return D(a);var b=[],d;for(d in a)c.has(a,d)&&b.push(d);return b};c.values=function(a){for(var b=c.keys(a),d=b.length,f=Array(d),h=0;d>h;h++)f[h]=a[b[h]];return f};c.pairs=function(a){for(var b=c.keys(a),d=b.length,f=Array(d),h=0;d>h;h++)f[h]=[b[h],a[b[h]]];return f};c.invert=function(a){for(var b={},d=c.keys(a),f=0,h=d.length;h>f;f++)b[a[d[f]]]=d[f];return b};c.functions=c.methods=function(a){var b=[],d;for(d in a)c.isFunction(a[d])&&
b.push(d);return b.sort()};c.extend=function(a){if(!c.isObject(a))return a;for(var b,d,f=1,h=arguments.length;h>f;f++)for(d in b=arguments[f],b)C.call(b,d)&&(a[d]=b[d]);return a};c.pick=function(a,b,d){var f,h={};if(null==a)return h;if(c.isFunction(b))for(f in b=t(b,d),a){var l=a[f];b(l,f,a)&&(h[f]=l)}else{l=n.apply([],k.call(arguments,1));a=Object(a);for(var m=0,p=l.length;p>m;m++)f=l[m],f in a&&(h[f]=a[f])}return h};c.omit=function(a,b,d){if(c.isFunction(b))b=c.negate(b);else{var f=c.map(n.apply([],
k.call(arguments,1)),String);b=function(a,e){return!c.contains(f,e)}}return c.pick(a,b,d)};c.defaults=function(a){if(!c.isObject(a))return a;for(var b=1,d=arguments.length;d>b;b++){var f=arguments[b],h;for(h in f)void 0===a[h]&&(a[h]=f[h])}return a};c.clone=function(a){return c.isObject(a)?c.isArray(a)?a.slice():c.extend({},a):a};c.tap=function(a,b){return b(a),a};var z=function(a,b,d,f){if(a===b)return 0!==a||1/a===1/b;if(null==a||null==b)return a===b;a instanceof c&&(a=a._wrapped);b instanceof c&&
(b=b._wrapped);var h=p.call(a);if(h!==p.call(b))return!1;switch(h){case "[object RegExp]":case "[object String]":return""+a==""+b;case "[object Number]":return+a!==+a?+b!==+b:0===+a?1/+a===1/b:+a===+b;case "[object Date]":case "[object Boolean]":return+a===+b}if("object"!=typeof a||"object"!=typeof b)return!1;for(var k=d.length;k--;)if(d[k]===a)return f[k]===b;var k=a.constructor,m=b.constructor;if(k!==m&&"constructor"in a&&"constructor"in b&&!(c.isFunction(k)&&k instanceof k&&c.isFunction(m)&&m instanceof
m))return!1;d.push(a);f.push(b);var l;if("[object Array]"===h){if(l=a.length,h=l===b.length)for(;l--&&(h=z(a[l],b[l],d,f)););}else{var n,k=c.keys(a);if(l=k.length,h=c.keys(b).length===l)for(;l--&&(n=k[l],h=c.has(b,n)&&z(a[n],b[n],d,f)););}return d.pop(),f.pop(),h};c.isEqual=function(a,b){return z(a,b,[],[])};c.isEmpty=function(a){if(null==a)return!0;if(c.isArray(a)||c.isString(a)||c.isArguments(a))return 0===a.length;for(var b in a)if(c.has(a,b))return!1;return!0};c.isElement=function(a){return!(!a||
1!==a.nodeType)};c.isArray=f||function(a){return"[object Array]"===p.call(a)};c.isObject=function(a){var b=typeof a;return"function"===b||"object"===b&&!!a};c.each("Arguments Function String Number Date RegExp".split(" "),function(a){c["is"+a]=function(b){return p.call(b)==="[object "+a+"]"}});c.isArguments(arguments)||(c.isArguments=function(a){return c.has(a,"callee")});"function"!=typeof/./&&(c.isFunction=function(a){return"function"==typeof a||!1});c.isFinite=function(a){return isFinite(a)&&!isNaN(parseFloat(a))};
c.isNaN=function(a){return c.isNumber(a)&&a!==+a};c.isBoolean=function(a){return!0===a||!1===a||"[object Boolean]"===p.call(a)};c.isNull=function(a){return null===a};c.isUndefined=function(a){return void 0===a};c.has=function(a,b){return null!=a&&C.call(a,b)};c.noConflict=function(){return a._=b,this};c.identity=function(a){return a};c.constant=function(a){return function(){return a}};c.noop=function(){};c.property=function(a){return function(b){return b[a]}};c.matches=function(a){var b=c.pairs(a),
d=b.length;return function(a){if(null==a)return!d;a=Object(a);for(var c=0;d>c;c++){var e=b[c],f=e[0];if(e[1]!==a[f]||!(f in a))return!1}return!0}};c.times=function(a,b,c){var d=Array(Math.max(0,a));b=t(b,c,1);for(c=0;a>c;c++)d[c]=b(c);return d};c.random=function(a,b){return null==b&&(b=a,a=0),a+Math.floor(Math.random()*(b-a+1))};c.now=Date.now||function(){return(new Date).getTime()};var f={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},u=c.invert(f),E=function(a){var b=
function(b){return a[b]},d="(?:"+c.keys(a).join("|")+")",f=RegExp(d),h=RegExp(d,"g");return function(a){return a=null==a?"":""+a,f.test(a)?a.replace(h,b):a}};c.escape=E(f);c.unescape=E(u);c.result=function(a,b){if(null!=a){var d=a[b];return c.isFunction(d)?a[b]():d}};var F=0;c.uniqueId=function(a){var b=++F+"";return a?a+b:b};c.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var A=/(.)^/,G={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028",
"\u2029":"u2029"},H=/\\|'|\r|\n|\u2028|\u2029/g,I=function(a){return"\\"+G[a]};c.template=function(a,b,d){!b&&d&&(b=d);b=c.defaults({},b,c.templateSettings);d=RegExp([(b.escape||A).source,(b.interpolate||A).source,(b.evaluate||A).source].join("|")+"|$","g");var f=0,h="__p+='";a.replace(d,function(b,c,d,g,k){return h+=a.slice(f,k).replace(H,I),f=k+b.length,c?h+="'+\n((__t=("+c+"))==null?'':_.escape(__t))+\n'":d?h+="'+\n((__t=("+d+"))==null?'':__t)+\n'":g&&(h+="';\n"+g+"\n__p+='"),b});h+="';\n";b.variable||
(h="with(obj||{}){\n"+h+"}\n");h="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+h+"return __p;\n";try{var k=new Function(b.variable||"obj","_",h)}catch(l){throw l.source=h,l;}d=function(a){return k.call(this,a,c)};return d.source="function("+(b.variable||"obj")+"){\n"+h+"}",d};c.chain=function(a){a=c(a);return a._chain=!0,a};var B=function(a){return this._chain?c(a).chain():a};c.mixin=function(a){c.each(c.functions(a),function(b){var d=c[b]=a[b];c.prototype[b]=
function(){var a=[this._wrapped];return l.apply(a,arguments),B.call(this,d.apply(c,a))}})};c.mixin(c);c.each("pop push reverse shift sort splice unshift".split(" "),function(a){var b=d[a];c.prototype[a]=function(){var c=this._wrapped;return b.apply(c,arguments),"shift"!==a&&"splice"!==a||0!==c.length||delete c[0],B.call(this,c)}});c.each(["concat","join","slice"],function(a){var b=d[a];c.prototype[a]=function(){return B.call(this,b.apply(this._wrapped,arguments))}});c.prototype.value=function(){return this._wrapped};
"function"==typeof define&&define.amd&&define("underscore",[],function(){return c})}).call(this);for(var BASE_64_CHARS="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",BASE_64_VALS={},i=0;i<BASE_64_CHARS.length;i++)BASE_64_VALS[BASE_64_CHARS.charAt(i)]=i;
Base64={encode:function(a){if("string"===typeof a){var b=a;a=Base64.newBinary(b.length);for(var d=0;d<b.length;d++){var f=b.charCodeAt(d);if(255<f)throw Error("Not ascii. Base64.encode can only take ascii strings.");a[d]=f}}for(var b=[],l=f=null,k=null,n=null,d=0;d<a.length;d++)switch(d%3){case 0:f=a[d]>>2&63;l=(a[d]&3)<<4;break;case 1:l|=a[d]>>4&15;k=(a[d]&15)<<2;break;case 2:k|=a[d]>>6&3,n=a[d]&63,b.push(getChar(f)),b.push(getChar(l)),b.push(getChar(k)),b.push(getChar(n)),n=k=l=f=null}null!=f&&
(b.push(getChar(f)),b.push(getChar(l)),null==k?b.push("="):b.push(getChar(k)),null==n&&b.push("="));return b.join("")}};var getChar=function(a){return BASE_64_CHARS.charAt(a)},getVal=function(a){return"="===a?-1:BASE_64_VALS[a]};Base64.newBinary=function(a){if("undefined"===typeof Uint8Array||"undefined"===typeof ArrayBuffer){for(var b=[],d=0;d<a;d++)b.push(0);b.$Uint8ArrayPolyfill=!0;return b}return new Uint8Array(new ArrayBuffer(a))};
Base64.decode=function(a){var b=Math.floor(3*a.length/4);"="==a.charAt(a.length-1)&&(b--,"="==a.charAt(a.length-2)&&b--);for(var b=Base64.newBinary(b),d=null,f=null,l=null,k=0,n=0;n<a.length;n++){var p=a.charAt(n),p=getVal(p);switch(n%4){case 0:if(0>p)throw Error("invalid base64 string");d=p<<2;break;case 1:if(0>p)throw Error("invalid base64 string");d|=p>>4;b[k++]=d;f=(p&15)<<4;break;case 2:0<=p&&(f|=p>>2,b[k++]=f,l=(p&3)<<6);break;case 3:0<=p&&(b[k++]=l|p)}}return b};EJSON={};EJSONTest={};
var customTypes={};EJSON.addType=function(a,b){if(_.has(customTypes,a))throw Error("Type "+a+" already present");customTypes[a]=b};
var isInfOrNan=function(a){return _.isNaN(a)||Infinity===a||-Infinity===a},builtinConverters=[{matchJSONValue:function(a){return _.has(a,"$date")&&1===_.size(a)},matchObject:function(a){return a instanceof Date},toJSONValue:function(a){return{$date:a.getTime()}},fromJSONValue:function(a){return new Date(a.$date)}},{matchJSONValue:function(a){return _.has(a,"$InfNaN")&&1===_.size(a)},matchObject:isInfOrNan,toJSONValue:function(a){return{$InfNaN:_.isNaN(a)?0:Infinity===a?1:-1}},fromJSONValue:function(a){return a.$InfNaN/
0}},{matchJSONValue:function(a){return _.has(a,"$binary")&&1===_.size(a)},matchObject:function(a){return"undefined"!==typeof Uint8Array&&a instanceof Uint8Array||a&&_.has(a,"$Uint8ArrayPolyfill")},toJSONValue:function(a){return{$binary:Base64.encode(a)}},fromJSONValue:function(a){return Base64.decode(a.$binary)}},{matchJSONValue:function(a){return _.has(a,"$escape")&&1===_.size(a)},matchObject:function(a){return _.isEmpty(a)||2<_.size(a)?!1:_.any(builtinConverters,function(b){return b.matchJSONValue(a)})},
toJSONValue:function(a){var b={};_.each(a,function(a,f){b[f]=EJSON.toJSONValue(a)});return{$escape:b}},fromJSONValue:function(a){var b={};_.each(a.$escape,function(a,f){b[f]=EJSON.fromJSONValue(a)});return b}},{matchJSONValue:function(a){return _.has(a,"$type")&&_.has(a,"$value")&&2===_.size(a)},matchObject:function(a){return EJSON._isCustomType(a)},toJSONValue:function(a){var b=Meteor._noYieldsAllowed(function(){return a.toJSONValue()});return{$type:a.typeName(),$value:b}},fromJSONValue:function(a){var b=
a.$type;if(!_.has(customTypes,b))throw Error("Custom EJSON type "+b+" is not defined");var d=customTypes[b];return Meteor._noYieldsAllowed(function(){return d(a.$value)})}}];EJSON._isCustomType=function(a){return a&&"function"===typeof a.toJSONValue&&"function"===typeof a.typeName&&_.has(customTypes,a.typeName())};
var adjustTypesToJSONValue=EJSON._adjustTypesToJSONValue=function(a){if(null===a)return null;var b=toJSONValueHelper(a);if(void 0!==b)return b;if("object"!==typeof a)return a;_.each(a,function(b,f){if("object"===typeof b||void 0===b||isInfOrNan(b)){var l=toJSONValueHelper(b);l?a[f]=l:adjustTypesToJSONValue(b)}});return a},toJSONValueHelper=function(a){for(var b=0;b<builtinConverters.length;b++){var d=builtinConverters[b];if(d.matchObject(a))return d.toJSONValue(a)}};
EJSON.toJSONValue=function(a){var b=toJSONValueHelper(a);if(void 0!==b)return b;"object"===typeof a&&(a=EJSON.clone(a),adjustTypesToJSONValue(a));return a};
var adjustTypesFromJSONValue=EJSON._adjustTypesFromJSONValue=function(a){if(null===a)return null;var b=fromJSONValueHelper(a);if(b!==a)return b;if("object"!==typeof a)return a;_.each(a,function(b,f){if("object"===typeof b){var l=fromJSONValueHelper(b);b!==l?a[f]=l:adjustTypesFromJSONValue(b)}});return a},fromJSONValueHelper=function(a){if("object"===typeof a&&null!==a&&2>=_.size(a)&&_.all(a,function(a,b){return"string"===typeof b&&"$"===b.substr(0,1)}))for(var b=0;b<builtinConverters.length;b++){var d=
builtinConverters[b];if(d.matchJSONValue(a))return d.fromJSONValue(a)}return a};EJSON.fromJSONValue=function(a){var b=fromJSONValueHelper(a);return b===a&&"object"===typeof a?(a=EJSON.clone(a),adjustTypesFromJSONValue(a),a):b};EJSON.stringify=function(a,b){var d=EJSON.toJSONValue(a);return b&&(b.canonical||b.indent)?EJSON._canonicalStringify(d,b):JSON.stringify(d)};EJSON.parse=function(a){if("string"!==typeof a)throw Error("EJSON.parse argument should be a string");return EJSON.fromJSONValue(JSON.parse(a))};
EJSON.isBinary=function(a){return!!("undefined"!==typeof Uint8Array&&a instanceof Uint8Array||a&&a.$Uint8ArrayPolyfill)};
EJSON.equals=function(a,b,d){var f,l=!(!d||!d.keyOrderSensitive);if(a===b||_.isNaN(a)&&_.isNaN(b))return!0;if(!a||!b||"object"!==typeof a||"object"!==typeof b)return!1;if(a instanceof Date&&b instanceof Date)return a.valueOf()===b.valueOf();if(EJSON.isBinary(a)&&EJSON.isBinary(b)){if(a.length!==b.length)return!1;for(f=0;f<a.length;f++)if(a[f]!==b[f])return!1;return!0}if("function"===typeof a.equals)return a.equals(b,d);if("function"===typeof b.equals)return b.equals(a,d);if(a instanceof Array){if(!(b instanceof
Array)||a.length!==b.length)return!1;for(f=0;f<a.length;f++)if(!EJSON.equals(a[f],b[f],d))return!1;return!0}switch(EJSON._isCustomType(a)+EJSON._isCustomType(b)){case 1:return!1;case 2:return EJSON.equals(EJSON.toJSONValue(a),EJSON.toJSONValue(b))}if(l){var k=[];_.each(b,function(a,b){k.push(b)});f=0;return(a=_.all(a,function(a,l){if(f>=k.length||l!==k[f]||!EJSON.equals(a,b[k[f]],d))return!1;f++;return!0}))&&f===k.length}f=0;return(a=_.all(a,function(a,k){if(!_.has(b,k)||!EJSON.equals(a,b[k],d))return!1;
f++;return!0}))&&_.size(b)===f};
EJSON.clone=function(a){var b;if("object"!==typeof a)return a;if(null===a)return null;if(a instanceof Date)return new Date(a.getTime());if(a instanceof RegExp)return a;if(EJSON.isBinary(a)){b=EJSON.newBinary(a.length);for(var d=0;d<a.length;d++)b[d]=a[d];return b}if(_.isArray(a)||_.isArguments(a)){b=[];for(d=0;d<a.length;d++)b[d]=EJSON.clone(a[d]);return b}if("function"===typeof a.clone)return a.clone();if(EJSON._isCustomType(a))return EJSON.fromJSONValue(EJSON.clone(EJSON.toJSONValue(a)),!0);b={};
_.each(a,function(a,d){b[d]=EJSON.clone(a)});return b};EJSON.newBinary=Base64.newBinary;Meteor={active:!1,currentComputation:null};
var setCurrentComputation=function(a){Meteor.currentComputation=a;Meteor.active=!!a},_debugFunc=function(){return"undefined"!==typeof Meteor?Meteor._debug:"undefined"!==typeof console&&console.log?function(){console.log.apply(console,arguments)}:function(){}},_throwOrLog=function(a,b){if(throwFirstError)throw b;var d;b.stack&&b.message?(d=b.stack.indexOf(b.message),d=0<=d&&10>=d?b.stack:b.message+("\n"===b.stack.charAt(0)?"":"\n")+b.stack):d=b.stack||b.message;_debugFunc()("Exception from Meteor "+
a+" function:",d)},withNoYieldsAllowed=function(a){return"undefined"===typeof Meteor||Meteor.isClient?a:function(){var b=arguments;Meteor._noYieldsAllowed(function(){a.apply(null,b)})}},nextId=1,pendingComputations=[],willFlush=!1,inFlush=!1,inCompute=!1,throwFirstError=!1,afterFlushCallbacks=[],requireFlush=function(){willFlush||(setTimeout(Meteor.flush,0),willFlush=!0)},constructingComputation=!1;
Meteor.Computation=function(a,b){if(!constructingComputation)throw Error("Meteor.Computation constructor is private; use Meteor.run");this.invalidated=this.stopped=constructingComputation=!1;this.firstRun=!0;this._id=nextId++;this._onInvalidateCallbacks=[];this._parent=b;this._func=a;this._recomputing=!1;var d=!0;try{this._compute(),d=!1}finally{this.firstRun=!1,d&&this.stop()}};
Meteor.Computation.prototype.onInvalidate=function(a){var b=this;if("function"!==typeof a)throw Error("onInvalidate requires a function");b.invalidated?Meteor.nonreactive(function(){withNoYieldsAllowed(a)(b)}):b._onInvalidateCallbacks.push(a)};
Meteor.Computation.prototype.invalidate=function(){var a=this;if(!a.invalidated){a._recomputing||a.stopped||(requireFlush(),pendingComputations.push(this));a.invalidated=!0;for(var b=0,d;d=a._onInvalidateCallbacks[b];b++)Meteor.nonreactive(function(){withNoYieldsAllowed(d)(a)});a._onInvalidateCallbacks=[]}};Meteor.Computation.prototype.stop=function(){this.stopped||(this.stopped=!0,this.invalidate())};
Meteor.Computation.prototype._compute=function(){this.invalidated=!1;var a=Meteor.currentComputation;setCurrentComputation(this);inCompute=!0;try{withNoYieldsAllowed(this._func)(this)}finally{setCurrentComputation(a),inCompute=!1}};Meteor.Computation.prototype._recompute=function(){this._recomputing=!0;try{for(;this.invalidated&&!this.stopped;)try{this._compute()}catch(a){_throwOrLog("recompute",a)}}finally{this._recomputing=!1}};Meteor.Dependency=function(){this._dependentsById={}};
Meteor.Dependency.prototype.depend=function(a){if(!a){if(!Meteor.active)return!1;a=Meteor.currentComputation}var b=this,d=a._id;return d in b._dependentsById?!1:(b._dependentsById[d]=a,a.onInvalidate(function(){delete b._dependentsById[d]}),!0)};Meteor.Dependency.prototype.changed=function(){for(var a in this._dependentsById)this._dependentsById[a].invalidate()};Meteor.Dependency.prototype.hasDependents=function(){for(var a in this._dependentsById)return!0;return!1};
Meteor.flush=function(a){if(inFlush)throw Error("Can't call Meteor.flush while flushing");if(inCompute)throw Error("Can't flush inside Meteor.run");willFlush=inFlush=!0;throwFirstError=!(!a||!a._throwFirstError);a=!1;try{for(;pendingComputations.length||afterFlushCallbacks.length;){for(;pendingComputations.length;)pendingComputations.shift()._recompute();if(afterFlushCallbacks.length){var b=afterFlushCallbacks.shift();try{b()}catch(d){_throwOrLog("afterFlush",d)}}}a=!0}finally{a||(inFlush=
!1,Meteor.flush({_throwFirstError:!1})),inFlush=willFlush=!1}};Meteor.run=function(a){if("function"!==typeof a)throw Error("Meteor.run requires a function argument");constructingComputation=!0;var b=new Meteor.Computation(a,Meteor.currentComputation);if(Meteor.active)Meteor.onInvalidate(function(){b.stop()});return b};Meteor.nonreactive=function(a){var b=Meteor.currentComputation;setCurrentComputation(null);try{return a()}finally{setCurrentComputation(b)}};
Meteor.onInvalidate=function(a){if(!Meteor.active)throw Error("Meteor.onInvalidate requires a currentComputation");Meteor.currentComputation.onInvalidate(a)};Meteor.afterFlush=function(a){afterFlushCallbacks.push(a);requireFlush()};var stringify=function(a){return void 0===a?"undefined":EJSON.stringify(a)},parse=function(a){return void 0===a||"undefined"===a?void 0:EJSON.parse(a)};ReactiveMap=function(a){this.keys=a||{};this.keyDeps={};this.keyValueDeps={}};
_.extend(ReactiveMap.prototype,{set:function(a,b){b=stringify(b);var d="undefined";_.has(this.keys,a)&&(d=this.keys[a]);if(b!==d){this.keys[a]=b;var f=this.keyDeps[a];f&&f.changed();this.keyValueDeps[a]&&((d=this.keyValueDeps[a][d])&&d.changed(),(d=this.keyValueDeps[a][b])&&d.changed())}},setDefault:function(a,b){void 0===this.keys[a]&&this.set(a,b)},get:function(a){this._ensureKey(a);this.keyDeps[a].depend();return parse(this.keys[a])},equals:function(a,b){var d=this,f=Package["mongo-livedata"]&&
Meteor.Collection.ObjectID;if(!("string"===typeof b||"number"===typeof b||"boolean"===typeof b||"undefined"===typeof b||b instanceof Date||f&&b instanceof f)&&null!==b)throw Error("ReactiveMap.equals: value must be scalar");var l=stringify(b);if(Meteor.active&&(d._ensureKey(a),_.has(d.keyValueDeps[a],l)||(d.keyValueDeps[a][l]=new Meteor.Dependency),d.keyValueDeps[a][l].depend()))Meteor.onInvalidate(function(){d.keyValueDeps[a][l].hasDependents()||delete d.keyValueDeps[a][l]});f=void 0;_.has(d.keys,
a)&&(f=parse(d.keys[a]));return EJSON.equals(f,b)},_ensureKey:function(a){a in this.keyDeps||(this.keyDeps[a]=new Meteor.Dependency,this.keyValueDeps[a]={})},getMigrationData:function(){return this.keys}});ReactiveVar=function(a,b){if(!(this instanceof ReactiveVar))return new ReactiveVar(a,b);this.curValue=a;this.equalsFunc=b;this.dep=new Meteor.Dependency};ReactiveVar._isEqual=function(a,b){return a!==b?!1:!a||"number"===typeof a||"boolean"===typeof a||"string"===typeof a};
ReactiveVar.prototype.get=function(){Meteor.active&&this.dep.depend();return this.curValue};ReactiveVar.prototype.set=function(a){(this.equalsFunc||ReactiveVar._isEqual)(this.curValue,a)||(this.curValue=a,this.dep.changed())};ReactiveVar.prototype.toString=function(){return"ReactiveVar{"+this.get()+"}"};ReactiveVar.prototype._numListeners=function(){var a=0,b;for(b in this.dep._dependentsById)a++;return a};
ReactiveObject=function(a){var b;this._definePrivateProperty("_items",{});this._definePrivateProperty("_itemsMeteor",{});b=this;_.isArray(a)&&_.each(a,function(a){return b.defineProperty(a,void 0)});_.isObject(a)&&_.each(a,function(a,f){return b.defineProperty(f,a)})};
ReactiveObject.prototype.wrapArrayMethods=function(a,b){var d=this;_.each("pop push reverse shift sort slice unshift splice".split(" "),function(f){b[f]=function(){d._itemsMeteor[a].changed();return Array.prototype[f].apply(this,arguments)}});b.clean=function(){return _.filter(this,function(a){return!Match.test(a,Function)})};return b};
ReactiveObject.prototype.defineProperty=function(a,b){Object.defineProperty(this,a,{configurable:!0,enumerable:!0,get:_.bind(this._propertyGet,this,a),set:_.bind(this._propertySet,this,a)});this[a]=b;return this};ReactiveObject.prototype.undefineProperty=function(a){var b;b=this._itemsMeteor[a];delete this[a];delete this._items[a];delete this._itemsMeteor[a];b&&b.changed();return this};ReactiveObject.prototype.clone=function(){return new ReactiveObject(_.clone(this._items))};
ReactiveObject.prototype.equals=function(a){return null!=a&&a instanceof ReactiveObject&&_.isEqual(a._items,this._items)};ReactiveObject.prototype.typeName=function(){return"reactive-object"};ReactiveObject.prototype.toJSONValue=function(){return EJSON.toJSONValue(this._items)};
ReactiveObject.prototype._propertySet=function(a,b){var d,f;_.isArray(b)&&(b=this.wrapArrayMethods(a,b));this._items[a]=b;null==(d=this._itemsMeteor)[a]&&(d[a]=new Meteor.Dependency);null!=(f=this._itemsMeteor[a])&&f.changed();return this._items[a]};ReactiveObject.prototype._propertyGet=function(a){this._itemsMeteor[a].depend();return this._items[a]};
ReactiveObject.prototype._definePrivateProperty=function(a,b){return Object.defineProperty(this,a,{configurable:!0,enumerable:!1,writable:!0,value:b})};EJSON.addType("reactive-object",function(a){return new ReactiveObject(a)});
|
src/views/Logos.js | scarescrow/react-resource-center | import React, { Component } from 'react';
class Logos extends Component {
state = {}
render () {
return <h1>Logos</h1>
}
}
export default Logos; |
src/cli.js | noodle-learns-programming/react-templates | #!/usr/bin/env node
/**
* Created by idok on 11/10/14.
*/
'use strict';
var _ = require('lodash');
var path = require('path');
var api = require('./api');
var context = require('./context');
var shell = require('./shell');
var pkg = require('../package.json');
var options = require('./options');
var reactDOMSupport = require('./reactDOMSupport');
var reactTemplates = require('./reactTemplates');
function executeOptions(currentOptions) {
var ret = 0;
var files = currentOptions._;
context.options.format = currentOptions.format || 'stylish';
if (currentOptions.version) {
console.log('v' + pkg.version);
} else if (currentOptions.help) {
if (files.length) {
console.log(options.generateHelpForOption(files[0]));
} else {
console.log(options.generateHelp());
}
} else if (currentOptions.listTargetVersion) {
printVersions(currentOptions);
} else if (!files.length) {
console.log(options.generateHelp());
} else {
_.forEach(files, handleSingleFile.bind(this, currentOptions));
ret = shell.printResults(context);
}
return ret;
}
function printVersions(currentOptions) {
var ret = Object.keys(reactDOMSupport);
if (currentOptions.format === 'json') {
console.log(JSON.stringify(ret, undefined, 2));
} else {
console.log(ret.join(', '));
}
}
/**
* @param {CONTEXT} context
* @param {*} currentOptions
* @param {string} filename file name to process
*/
function handleSingleFile(currentOptions, filename) {
try {
var sourceExt = path.extname(filename);
var outputFilename;
if (sourceExt === '.rt') {
if (currentOptions.modules !== 'typescript') {
outputFilename = filename + '.js';
} else {
outputFilename = filename + '.ts';
}
} else if (sourceExt === '.jsrt') {
outputFilename = filename.replace(/\.jsrt$/, '.js');
currentOptions = _.assign({}, currentOptions, {modules: 'jsrt'});
} else {
context.error('invalid file, only handle rt/jsrt files', filename);
return;
}
api.convertFile(filename, outputFilename, currentOptions, context);
} catch (e) {
context.error(e.message, filename, e.line, e.column, e.startOffset, e.endOffset);
}
}
/**
* Executes the CLI based on an array of arguments that is passed in.
* @param {string|Array|Object} args The arguments to process.
* @returns {int} The exit code for the operation.
*/
function execute(args) {
var currentOptions;
try {
currentOptions = options.parse(args);
} catch (error) {
console.error(error.message);
return 1;
}
return executeOptions(currentOptions);
}
module.exports = {
context: context,
execute: execute,
executeOptions: executeOptions,
handleSingleFile: handleSingleFile,
convertTemplateToReact: reactTemplates.convertTemplateToReact
}; |
packages/react-scripts/fixtures/kitchensink/src/features/webpack/UnknownExtInclusion.js | CodingZeal/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import aFileWithExtUnknown from './assets/aFileWithExt.unknown';
const text = aFileWithExtUnknown.includes('base64')
? atob(aFileWithExtUnknown.split('base64,')[1]).trim()
: aFileWithExtUnknown;
export default () => (
<a id="feature-unknown-ext-inclusion" href={text}>
aFileWithExtUnknown
</a>
);
|
packages/component/src/text-field-macro.js | Pinecast/encoder | import React from 'react';
export default (inputProps) =>
<label>
<span>{inputProps.title}</span>
<input
{...inputProps}
type='text'
/>
</label>;
|
stories/landing/index.js | NestorSegura/operationcode_frontend | import React from 'react';
import { Router } from 'react-router-dom';
import createHistory from 'history/createBrowserHistory';
import { storiesOf } from '@storybook/react';
import Landing from 'scenes/home/landing/landing';
const history = createHistory();
storiesOf('Landing', module)
.add('Basic', () => (
<Router history={history}>
<Landing />
</Router>
));
|